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编程中namedtuple类的用法
Jun 21 Python
itchat和matplotlib的结合使用爬取微信信息的实例
Aug 25 Python
django项目搭建与Session使用详解
Oct 10 Python
python django 原生sql 获取数据的例子
Aug 14 Python
python下载库的步骤方法
Oct 12 Python
selenium+Chrome滑动验证码破解二(某某网站)
Dec 17 Python
Python datetime 格式化 明天,昨天实例
Mar 02 Python
python判断一个变量是否已经设置的方法
Aug 13 Python
详解用Python把PDF转为Word方法总结
Apr 27 Python
Python自动化爬取天眼查数据的实现
Jun 15 Python
Python pandas读取CSV文件的注意事项(适合新手)
Jun 20 Python
详解Python类和对象内容
Jun 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
PHP与SQL注入攻击防范小技巧
2011/09/16 PHP
PHP-Java-Bridge使用笔记
2014/09/22 PHP
PHP实现HTML页面静态化的方法
2015/11/04 PHP
PHP中大括号'{}'用法实例总结
2017/02/08 PHP
javascript入门·动态的时钟,显示完整的一些方法,新年倒计时
2007/10/01 Javascript
JQuery 引发两次$(document.ready)事件
2010/01/15 Javascript
按钮JS复制文本框和表格的代码
2011/04/01 Javascript
jquery选择符快速提取web表单数据示例
2014/03/27 Javascript
JS判断浏览器是否支持某一个CSS3属性的方法
2014/10/17 Javascript
jQuery实现防止提交按钮被双击的方法
2015/03/24 Javascript
深入解析JavaScript中的数字对象与字符串对象
2015/10/21 Javascript
jQuery+canvas实现简单的球体斜抛及颜色动态变换效果
2016/01/28 Javascript
BootStrap日期控件在模态框中选择时间下拉菜单无效的原因及解决办法(火狐下不能点击)
2016/08/18 Javascript
jQuery解析XML 详解及方法总结
2016/09/28 Javascript
浅述Javascript的外部对象
2016/12/07 Javascript
原生Javascript插件开发实践
2017/01/09 Javascript
jQuery插件echarts实现的去掉X轴、Y轴和网格线效果示例【附demo源码下载】
2017/03/04 Javascript
激动人心的 Angular HttpClient的源码解析
2017/07/10 Javascript
微信小程序使用request网络请求操作实例
2017/12/15 Javascript
独立部署小程序基于nodejs的服务器过程详解
2019/06/24 NodeJs
解决vue项目刷新后,导航菜单高亮显示的位置不对问题
2019/11/01 Javascript
微信小程序连接服务器展示MQTT数据信息的实现
2020/07/14 Javascript
python开发简易版在线音乐播放器
2017/03/03 Python
Python中垃圾回收和del语句详解
2018/11/15 Python
python实现扫描ip地址的小程序
2019/04/16 Python
python 默认参数相关知识详解
2019/09/18 Python
北京华建集团SQL面试题
2014/06/03 面试题
什么是makefile? 如何编写makefile?
2013/01/02 面试题
关于迟到的检讨书
2014/01/26 职场文书
小学生成长感言
2014/01/30 职场文书
法律系毕业生自荐信范文
2014/03/27 职场文书
心理健康活动总结
2014/04/30 职场文书
无子女夫妻离婚协议书(4篇)
2014/10/20 职场文书
浅谈redis的过期时间设置和过期删除机制
2022/03/18 MySQL
「回转企鹅罐」10周年纪念展「輪るピングドラム展」海报公开
2022/03/22 日漫
Win11无法访问设备和打印机 如何解决页面空白
2022/04/09 数码科技