django API 中接口的互相调用实例


Posted in Python onApril 01, 2020

我就废话不多说了,还是直接上代码吧!

url = "http://%s:%s/api-token-auth/" % (ip, port)
 query_args = {
  "username": username,
  "password": password
 }
 resp = requests.post(url=url, data=query_args)
 token = json.loads(resp.text)["token"]
 headers = {"Authorization": "JWT" + " " + token}  # 拿到token,拼成headers


 post_url = "http://%s:%s/message/message-level-two/"% (ip, port)
 data = {
  "app": app,
  "url": url,
  "message_id": message_id,
  "head": head,
  "title": title,
  "userprofile_id_list": userprofile_id_list
 }
 headers = self.headers
 requests.post(url=post_url, data=data, headers=headers)

获取当前请求的ip和端口

host_ip, host_port = self.request.META.get("HTTP_HOST").split(':')[0], \
        self.request.META.get("HTTP_HOST").split(':')[1]

常见的请求头如下:

CONTENT_LENGTH ? The length of the request body (as a string).
CONTENT_TYPE ? The MIME type of the request body.
HTTP_ACCEPT ? Acceptable content types for the response.
HTTP_ACCEPT_ENCODING ? Acceptable encodings for the response.
HTTP_ACCEPT_LANGUAGE ? Acceptable languages for the response.
HTTP_HOST ? The HTTP Host header sent by the client.
HTTP_REFERER ? The referring page, if any.
HTTP_USER_AGENT ? The client's user-agent string.
QUERY_STRING ? The query string, as a single (unparsed) string.
REMOTE_ADDR ? The IP address of the client.
REMOTE_HOST ? The hostname of the client.
REMOTE_USER ? The user authenticated by the Web server, if any.
REQUEST_METHOD ? A string such as "GET" or "POST".
SERVER_NAME ? The hostname of the server.
SERVER_PORT ? The port of the server (as a string).

获取请求头内容的用META

示例:

def index(request):
 ip = request.META.get("REMOTE_ADDR")
 return HttpResponse("你的ip地址是%s"%ip)

http://10.254.30.27/1
self.kwargs[‘pk'] # 可以拿到后边的 1

补充知识:django 使用requests请求相关接口

1、如果是get请求接口,并且需要带相关参数的话,可以借鉴下面的代码:

import requests
 
from django.http import JsonResponse
 
def get_info(request):
 url = 'http://www.baidu.com'
 params = {'id': 1, 'user': 'lin'}
 response = requests.get(url=url, params=params)
 return JsonResponse(response.text, safe=False)

这样将会返回一串json的字符串数据。

2、如果是post请求接口,并且需要带相关参数的话,可以借鉴下面的代码:

import requests
 
from json import dumps
from django.http import JsonResponse
 
def get_info(request):
 url = 'http://www.baidu.com'
 data = {'id': 1, 'user': 'lin'}
 response = requests.post(url=url, data=dumps(data))
 return JsonResponse(response.text, safe=False)

注:

(1)、其中必须注意的为data这个参数,必须要用dumps(data)转换一下,不然会报错,response状态码为400,bad request error 400 while using python requests.post function。

(2)、如果需要在post请求底下加相关请求头的话,可以借鉴下面的代码:

import requests
 
from json import dumps
from django.http import JsonResponse
 
def get_info(request):
 url = 'http://www.baidu.com'
 data = {'id': 1, 'user': 'lin'}
 headers = {'content-Type': 'application/json', 'Accept': '*/*'}
 response = requests.post(url=url, data=dumps(data), headers=headers)
 return JsonResponse(response.text, safe=False)

这里如果response的状态码报415错误的话,即HTTP请求415错误 ? 不支持的媒体类型(Unsupported media type),这就是content-Type可能写错了,就要注意一下了,因为通常接口会封装一些参数到请求头底下。

以上这篇django API 中接口的互相调用实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python快速查找算法应用实例
Sep 26 Python
实例讲解Python设计模式编程之工厂方法模式的使用
Mar 02 Python
Python制作Windows系统服务
Mar 25 Python
Python实现PS图像调整颜色梯度效果示例
Jan 25 Python
利用python为运维人员写一个监控脚本
Mar 25 Python
Python实现处理逆波兰表达式示例
Jul 30 Python
Python拼接字符串的7种方法总结
Nov 01 Python
PyCharm配置mongo插件的方法
Nov 30 Python
Python语言进阶知识点总结
May 28 Python
selenium 安装与chromedriver安装的方法步骤
Jun 12 Python
django的聚合函数和aggregate、annotate方法使用详解
Jul 23 Python
使用Python的datetime库处理时间(RPA流程)
Nov 24 Python
完美解决pyinstaller打包报错找不到依赖pypiwin32或pywin32-ctypes的错误
Apr 01 #Python
Python greenlet和gevent使用代码示例解析
Apr 01 #Python
Django-rest-framework中过滤器的定制实例
Apr 01 #Python
Python如何操作office实现自动化及win32com.client的运用
Apr 01 #Python
Django之choices选项和富文本编辑器的使用详解
Apr 01 #Python
Python AutoCAD 系统设置的实现方法
Apr 01 #Python
django实现模型字段动态choice的操作
Apr 01 #Python
You might like
一个高ai的分页函数和一个url函数
2006/10/09 PHP
php 无法载入mysql扩展
2010/03/12 PHP
深入理解PHP几个算法:PHP冒泡、PHP二分法、PHP求素数、PHP乘法表
2013/06/06 PHP
yii2.0整合阿里云oss的示例代码
2017/09/19 PHP
PHP+Ajax实现的博客文章添加类别功能示例
2018/03/29 PHP
PHP parse_ini_file函数的应用与扩展操作示例
2019/01/07 PHP
javascript add event remove event
2008/04/07 Javascript
Javascript 键盘keyCode键码值表
2009/12/24 Javascript
通过pjax实现无刷新翻页(兼容新版jquery)
2014/01/31 Javascript
jquery实现右键菜单插件
2015/03/29 Javascript
学习JavaScript设计模式之模板方法模式
2016/01/20 Javascript
AngularJS ng-bind-template 指令详解
2016/07/30 Javascript
React Js 微信禁止复制链接分享禁止隐藏右上角菜单功能
2017/05/26 Javascript
JQuery 获取多个select标签option的text内容(实例)
2017/09/07 jQuery
详解ES6 Fetch API HTTP请求实用指南
2018/11/14 Javascript
vue中的使用token的方法示例
2020/03/10 Javascript
Vue实现input宽度随文字长度自适应操作
2020/07/29 Javascript
[05:02]2014DOTA2 TI中国区预选赛精彩TOPPLAY第三弹
2014/06/25 DOTA
Python模拟登录12306的方法
2014/12/30 Python
详解python的数字类型变量与其方法
2016/11/20 Python
解决python3 安装完Pycurl在import pycurl时报错的问题
2018/10/15 Python
用Python读取几十万行文本数据
2018/12/24 Python
pyinstaller打包多个py文件和去除cmd黑框的方法
2019/06/21 Python
python实现人工智能Ai抠图功能
2019/09/05 Python
python 的 openpyxl模块 读取 Excel文件的方法
2019/09/09 Python
浅析Python requests 模块
2020/10/09 Python
python excel多行合并的方法
2020/12/09 Python
介绍一下write命令
2014/08/10 面试题
高三地理教学反思
2014/01/11 职场文书
经典团队口号大全
2014/06/21 职场文书
加强作风建设工作总结
2014/10/23 职场文书
乌镇导游词
2015/02/02 职场文书
第二次离婚起诉书
2015/05/18 职场文书
力克胡哲观后感
2015/06/10 职场文书
html5实现点击弹出图片功能
2021/07/16 HTML / CSS
redis的list数据类型相关命令介绍及使用
2022/01/18 Redis