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开发的nosql数据库CodernityDB介绍和使用实例
Oct 23 Python
python定时检查某个进程是否已经关闭的方法
May 20 Python
简单介绍使用Python解析并修改XML文档的方法
Oct 15 Python
pycharm下打开、执行并调试scrapy爬虫程序的方法
Nov 29 Python
DataFrame:通过SparkSql将scala类转为DataFrame的方法
Jan 29 Python
Tensorflow实现神经网络拟合线性回归
Jul 19 Python
python+pygame实现坦克大战
Sep 10 Python
利用python实现AR教程
Nov 20 Python
win10安装python3.6的常见问题
Jul 01 Python
python定义具名元组实例操作
Feb 28 Python
Python 实现劳拉游戏的实例代码(四连环、重力四子棋)
Mar 03 Python
python通配符之glob模块的使用详解
Apr 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
使用sockets:从新闻组中获取文章(三)
2006/10/09 PHP
php变量范围介绍
2012/10/15 PHP
基于php导出到Excel或CSV的详解(附utf8、gbk 编码转换)
2013/06/25 PHP
用js实现计算代码行数的简单方法附代码
2007/08/13 Javascript
jquery 学习之二 属性相关
2010/11/23 Javascript
js中的值类型和引用类型小结 文字说明与实例
2010/12/12 Javascript
JavaScript把数组作为堆栈使用的方法
2015/03/20 Javascript
浅析BootStrap Treeview的简单使用
2016/10/12 Javascript
JS添加或修改控件的样式(Class)实现方法
2016/10/15 Javascript
基于JavaScript实现多级菜单效果
2017/07/25 Javascript
详解React native全局变量的使用(跨组件的通信)
2017/09/07 Javascript
VUE+elementui面包屑实现动态路由详解
2019/11/04 Javascript
javascript实现雪花飘落效果
2020/08/19 Javascript
Win7上搭建Cocos2d-x 3.1.1开发环境
2014/07/03 Python
python实现的生成随机迷宫算法核心代码分享(含游戏完整代码)
2014/07/11 Python
python中scikit-learn机器代码实例
2018/08/05 Python
python字典值排序并取出前n个key值的方法
2018/10/17 Python
Linux CentOS Python开发环境搭建教程
2018/11/28 Python
python利用小波分析进行特征提取的实例
2019/01/09 Python
解决python文件双击运行秒退的问题
2019/06/24 Python
关于Flask项目无法使用公网IP访问的解决方式
2019/11/19 Python
Pytorch自己加载单通道图片用作数据集训练的实例
2020/01/18 Python
Python Numpy,mask图像的生成详解
2020/02/19 Python
Python virtualenv虚拟环境实现过程解析
2020/04/18 Python
python不同版本的_new_不同点总结
2020/12/09 Python
俄罗斯第一家篮球店:StreetBall
2020/07/30 全球购物
init进程的作用
2015/08/20 面试题
医药工作者的求职信范文
2013/09/21 职场文书
优秀毕业生求职信范文
2014/01/02 职场文书
测量员岗位职责
2015/02/14 职场文书
创业计划书之DIY自助厨房
2019/09/06 职场文书
导游词之西湖雷峰塔
2019/09/18 职场文书
导游词之太原天龙山
2020/01/02 职场文书
安装harbor作为docker镜像仓库的问题
2022/06/14 Servers
python数字图像处理之对比度与亮度调整示例
2022/06/28 Python
MySQL事务的ACID特性以及并发问题方案
2022/07/15 MySQL