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的几种开发工具介绍
Mar 07 Python
在Python中使用lambda高效操作列表的教程
Apr 24 Python
Python3遍历目录树实现方法
May 22 Python
Python中getattr函数和hasattr函数作用详解
Jun 14 Python
python 判断是否为正小数和正整数的实例
Jul 23 Python
Python随机生成均匀分布在单位圆内的点代码示例
Nov 13 Python
如何在sae中设置django,让sae的工作环境跟本地python环境一致
Nov 21 Python
详解Django中间件的5种自定义方法
Jul 26 Python
使用PYTHON解析Wireshark的PCAP文件方法
Jul 23 Python
Python TKinter如何自动关闭主窗口
Feb 26 Python
python学习将数据写入文件并保存方法
Jun 07 Python
Python3.9.1中使用match方法详解
Feb 08 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
执行、获取远程代码返回:file_get_contents 超时处理的问题详解
2013/06/25 PHP
php json_encode值中大括号与花括号区别
2013/09/30 PHP
windows7下安装php的imagick和imagemagick扩展教程
2014/07/04 PHP
php实现的mongodb操作类实例
2015/04/03 PHP
PHP编程实现计算抽奖概率算法完整实例
2017/08/09 PHP
php报错502badgateway解决方法
2019/10/11 PHP
PHP查找一列有序数组是否包含某值的方法
2020/02/07 PHP
php反序列化长度变化尾部字符串逃逸(0CTF-2016-piapiapia)
2020/02/15 PHP
基于JavaScript自定义构造函数的详解说明
2013/04/24 Javascript
利用div+jquery自定义滚动条样式的2种方法
2013/07/18 Javascript
使用GruntJS构建Web程序之合并压缩篇
2014/06/06 Javascript
jQuery选择器全集详解
2014/11/24 Javascript
JavaScript 异常处理 详解
2015/02/06 Javascript
Jquery全屏相册插件zoomvisualizer具有调节放大与缩小功能
2015/11/02 Javascript
浅谈jquery的html方法里包含特殊字符的处理
2016/11/30 Javascript
浅谈react.js中实现tab吸顶效果的问题
2017/09/06 Javascript
js Dom实现换肤效果
2017/10/21 Javascript
Vue组件之单向数据流的解决方法
2018/11/10 Javascript
Vue 实现前进刷新后退不刷新的效果
2019/06/14 Javascript
[00:44]TI7不朽珍藏III——军团指挥官不朽展示
2017/07/15 DOTA
python中OrderedDict的使用方法详解
2017/05/05 Python
在PyCharm下打包*.py程序成.exe的方法
2018/11/29 Python
python读取几个G的csv文件方法
2019/01/07 Python
Pyqt5如何让QMessageBox按钮显示中文示例代码
2019/04/11 Python
在Python中使用filter去除列表中值为假及空字符串的例子
2019/11/18 Python
python绘制汉诺塔
2021/03/01 Python
Maisons du Monde德国:法国家具和装饰的市场领导者
2019/07/26 全球购物
阿迪达斯印尼官方网站:adidas印尼
2020/02/10 全球购物
this关键字的含义
2015/04/08 面试题
行政文秘岗位职责范本
2014/02/10 职场文书
2014年党员自我剖析材料
2014/10/07 职场文书
2015年车间主任工作总结
2015/05/21 职场文书
网吧员工管理制度
2015/08/05 职场文书
使用Nginx搭载rtmp直播服务器的方法
2021/10/16 Servers
Python实现位图分割的效果
2021/11/20 Python
基于Python实现射击小游戏的制作
2022/04/06 Python