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中的多线程编程
Apr 09 Python
在Python中使用cookielib和urllib2配合PyQuery抓取网页信息
Apr 25 Python
python实现将pvr格式转换成pvr.ccz的方法
Apr 28 Python
Windows下为Python安装Matplotlib模块
Nov 06 Python
在Mac OS上搭建Python的开发环境
Dec 24 Python
Sanic框架请求与响应实例分析
Jul 16 Python
在python中安装basemap的教程
Sep 20 Python
python多线程共享变量的使用和效率方法
Jul 16 Python
Django中modelform组件实例用法总结
Feb 10 Python
Python结合Window计划任务监测邮件的示例代码
Aug 05 Python
用Python自动清理电脑内重复文件,只要10行代码(自动脚本)
Jan 09 Python
详解Python 中的 defaultdict 数据类型
Feb 22 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
提问的智慧
2006/10/09 PHP
比较strtr, str_replace和preg_replace三个函数的效率
2013/06/26 PHP
PHP封装分页函数实现文本分页和数字分页
2014/10/23 PHP
浅谈php命令行用法
2015/02/04 PHP
Twig模板引擎用法入门教程
2016/01/20 PHP
PHP简单获取上月、本月、近15天、近30天的方法示例
2017/07/03 PHP
laravel自定义分页效果
2017/07/23 PHP
让焦点自动跳转
2006/07/01 Javascript
js获取浏览器的可视区域尺寸的实现代码
2011/11/30 Javascript
jquery中的查找parents与closest方法之间的区别
2013/12/02 Javascript
js动态往表格的td中添加图片并注册事件
2014/06/12 Javascript
jQuery插件jFade实现鼠标经过的图片高亮其它变暗
2015/03/14 Javascript
JavaScript控制listbox列表框的项目上下移动的方法
2015/03/18 Javascript
详解JavaScript中Hash Map映射结构的实现
2016/05/21 Javascript
浅谈Cookie的生命周期问题
2016/08/02 Javascript
servlet+jquery实现文件上传进度条示例代码
2017/01/25 Javascript
vue过渡和animate.css结合使用详解
2017/06/14 Javascript
jQuery接受后台传递的List的实例详解
2017/08/02 jQuery
AngularJS集合数据遍历显示的实例
2017/12/27 Javascript
p5.js入门教程之小球动画示例代码
2018/03/15 Javascript
Vue项目分环境打包的实现步骤
2018/04/02 Javascript
JavaScript数据结构之栈实例用法
2019/01/18 Javascript
ES6中的class是如何实现的(附Babel编译的ES5代码详解)
2019/05/17 Javascript
js实现页面图片消除效果
2020/03/24 Javascript
virtualenv实现多个版本Python共存
2017/08/21 Python
python添加模块搜索路径和包的导入方法
2019/01/19 Python
解决pyqt5中QToolButton无法使用的问题
2019/06/21 Python
tensorflow对图像进行拼接的例子
2020/02/05 Python
Python如何测试stdout输出
2020/08/10 Python
慕尼黑山地运动、户外服装和体育用品专家:Sporthaus Schuster
2019/08/27 全球购物
会计毕业生求职简历的自我评价
2013/10/20 职场文书
国际经济贸易专业推荐信
2013/11/06 职场文书
学校运动会霸气口号
2014/06/07 职场文书
求职简历自我评价怎么写
2015/03/10 职场文书
预备党员考察表党小组意见
2015/06/01 职场文书
《詹天佑》教学反思
2016/02/20 职场文书