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 17 Python
python通过elixir包操作mysql数据库实例代码
Jan 31 Python
pandas把dataframe转成Series,改变列中值的类型方法
Apr 10 Python
python matlibplot绘制多条曲线图
Feb 19 Python
python 调用有道api接口的方法
Jan 03 Python
python求最大值,不使用内置函数的实现方法
Jul 09 Python
Python及Pycharm安装方法图文教程
Aug 05 Python
关于Python中的向量相加和numpy中的向量相加效率对比
Aug 26 Python
Pycharm debug调试时带参数过程解析
Feb 03 Python
python实现udp聊天窗口
Mar 31 Python
pyinstaller打包找不到文件的问题解决
Apr 15 Python
关于python3.7安装matplotlib始终无法成功的问题的解决
Jul 28 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
PHP脚本的10个技巧(6)
2006/10/09 PHP
PHP $_SERVER详解
2009/01/16 PHP
ThinkPHP3.1.3版本新特性概述
2014/06/19 PHP
推荐一款MAC OS X 下php集成开发环境mamp
2014/11/08 PHP
php上传大文件失败的原因及应对策略
2015/10/20 PHP
WordPress中调试缩略图的相关PHP函数使用解析
2016/01/07 PHP
php利用gd库为图片添加水印
2016/11/09 PHP
javascript数组的扩展实现代码集合
2008/06/01 Javascript
数组Array进行原型prototype扩展后带来的for in遍历问题
2010/02/07 Javascript
jquery向.ashx文件post中文乱码问题的解决方法
2011/03/28 Javascript
JQuery操作tr和td内容的方法实例
2013/03/06 Javascript
JavaScript驾驭网页-获取网页元素
2016/03/24 Javascript
JavaScript SHA1加密算法实现详细代码
2016/10/06 Javascript
基于bootstrap按钮式下拉菜单组件的搜索建议插件
2017/03/25 Javascript
vue中的非父子间的通讯问题简单的实例代码
2017/07/19 Javascript
Angular将填入表单的数据渲染到表格的方法
2017/09/22 Javascript
详解Vue Elementui中的Tag与页面其它元素相互交互的两三事
2018/09/25 Javascript
[02:02]DOTA2英雄基础教程 斯拉达
2013/12/11 DOTA
python实现彩票系统
2020/06/28 Python
python Selenium实现付费音乐批量下载的实现方法
2019/01/24 Python
Django框架自定义session处理操作示例
2019/05/27 Python
Kears+Opencv实现简单人脸识别
2019/08/28 Python
深入了解python中元类的相关知识
2019/08/29 Python
Python paramiko模块使用解析(实现ssh)
2019/08/30 Python
如何基于Python获取图片的物理尺寸
2019/11/25 Python
Elasticsearch py客户端库安装及使用方法解析
2020/09/14 Python
利用html5 canvas动态画饼状图的示例代码
2018/04/02 HTML / CSS
雅高酒店中国:Accorhotels.com China
2018/03/26 全球购物
什么样的创业计划书可行性高?
2014/02/01 职场文书
公务员培训自我鉴定
2014/02/01 职场文书
六查六看自查报告
2014/10/14 职场文书
2015年领导干部廉洁自律工作总结
2015/05/26 职场文书
导游词之西湖雷峰塔
2019/09/18 职场文书
python 提取html文本的方法
2021/05/20 Python
Matplotlib可视化之添加让统计图变得简单易懂的注释
2021/06/11 Python
深入解读Java三大集合之map list set的用法
2021/11/11 Java/Android