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 相关文章推荐
400多行Python代码实现了一个FTP服务器
May 10 Python
Python3.x中自定义比较函数
Apr 24 Python
Python实现PS滤镜特效之扇形变换效果示例
Jan 26 Python
python安装pywin32clipboard的操作方法
Jan 24 Python
python中正则表达式与模式匹配
May 07 Python
Pandas_cum累积计算和rolling滚动计算的用法详解
Jul 04 Python
python3 字符串知识点学习笔记
Feb 08 Python
django为Form生成的label标签添加class方式
May 20 Python
Python csv文件记录流程代码解析
Jul 16 Python
分享一个python的aes加密代码
Dec 22 Python
关于PySnooper 永远不要使用print进行调试的问题
Mar 04 Python
Pytorch可视化的几种实现方法
Jun 10 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
dede3.1分页文字采集过滤规则详说(图文教程)续二
2007/04/03 PHP
php Mysql日期和时间函数集合
2007/11/16 PHP
PHP 危险函数全解析
2009/09/09 PHP
php join函数应用
2011/05/04 PHP
PHP时间格式控制符对照表分享
2013/07/23 PHP
php类的自动加载操作实例详解
2016/09/28 PHP
url地址自动加#号问题说明
2010/08/21 Javascript
基于jQuery的前端数据通用验证库
2011/08/08 Javascript
基于jQuery实现图片的前进与后退功能
2013/04/24 Javascript
js获取URL的参数的方法(getQueryString)示例
2013/09/29 Javascript
jQuery循环滚动新闻列表示例代码
2014/06/17 Javascript
jquery ajax请求方式与提示用户正在处理请稍等
2014/09/01 Javascript
js实现兼容IE和FF的上下层的移动
2015/05/04 Javascript
jQuery ajax时间差导致的变量赋值问题分析
2016/01/22 Javascript
AngularJS基础 ng-keyup 指令简单示例
2016/08/02 Javascript
jQuery给指定的table动态添加删除行的操作方法
2016/10/12 Javascript
JavaScript与JQUERY获取元素的宽、高和位置
2017/02/26 Javascript
微信公众号菜单配置微信小程序实例详解
2017/03/31 Javascript
Vue学习笔记进阶篇之过渡状态详解
2017/07/14 Javascript
JS库 Highlightjs 添加代码行号的实现代码
2017/09/13 Javascript
JS中的一些常用的函数式编程术语
2019/06/15 Javascript
详解Python图像处理库Pillow常用使用方法
2019/09/02 Python
澳大利亚旅游网站:Lastminute
2017/08/07 全球购物
微软日本官方网站:Microsoft日本
2017/11/26 全球购物
德国珠宝和配件商店:Styleserver
2021/02/23 全球购物
网页设计个人找工作求职信
2013/11/28 职场文书
旷课检讨书2000字
2014/01/14 职场文书
宝宝周岁宴答谢词
2014/01/26 职场文书
告诉你怎样写创业计划书
2014/01/27 职场文书
超市促销活动总结
2014/07/01 职场文书
同意离婚答辩状
2015/05/22 职场文书
演讲稿之我的初心我的成长
2019/08/12 职场文书
在校大学生才艺比赛策划书怎么写?
2019/08/26 职场文书
教你解决往mysql数据库中存入汉字报错的方法
2021/05/06 MySQL
用Python编写简单的gRPC服务的详细过程
2021/07/04 Python
如何基于python实现单目三维重建详解
2022/06/25 Python