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中的floor()方法
May 15 Python
构建Python包的五个简单准则简介
Jun 15 Python
Python安装使用命令行交互模块pexpect的基础教程
May 12 Python
将字典转换为DataFrame并进行频次统计的方法
Apr 08 Python
python通过微信发送邮件实现电脑关机
Jun 20 Python
Python 判断奇数偶数的方法
Dec 20 Python
Python正则表达式匹配日期与时间的方法
Jul 07 Python
Python编译成.so文件进行加密后调用的实现
Dec 23 Python
python求一个字符串的所有排列的实现方法
Feb 04 Python
Python实现企业微信机器人每天定时发消息实例
Feb 25 Python
python学生管理系统的实现
Apr 05 Python
python中slice参数过长的处理方法及实例
Dec 15 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 has encountered an Access Violation 错误的解决方法
2010/01/17 PHP
ThinkPHP实现递归无级分类――代码少
2015/07/29 PHP
Yii2.0多文件上传实例说明
2017/07/24 PHP
PHP中quotemeta()函数的用法讲解
2019/04/04 PHP
javascript JSON操作入门实例
2010/04/16 Javascript
jQuery写的日历(包括日历的样式及功能)
2013/04/23 Javascript
jquery的live使用注意事项
2014/02/18 Javascript
JS实现简易图片轮播效果的方法
2015/03/25 Javascript
表单元素值获取方式js及java方式的简单实例
2016/10/15 Javascript
Bootstrap里的文件分别代表什么意思及其引用方法
2017/05/01 Javascript
Vue render深入开发讲解
2018/04/13 Javascript
详解webpack打包时排除其中一个css、js文件或单独打包一个css、js文件(两种方法)
2018/10/26 Javascript
WebGL three.js学习笔记之阴影与实现物体的动画效果
2019/04/25 Javascript
解决vue组件中click事件失效的问题
2019/11/09 Javascript
[02:25]DOTA2英雄基础教程 生死判决瘟疫法师
2013/12/06 DOTA
[01:35]2014DOTA2西雅图邀请赛 专访狐狸妈青春献给刀塔
2014/07/08 DOTA
Python下线程之间的共享和释放示例
2015/05/04 Python
python fabric实现远程部署
2017/01/05 Python
python 使用plt画图,去除图片四周的白边方法
2019/07/09 Python
用Python将Excel数据导入到SQL Server的例子
2019/08/24 Python
python manage.py runserver流程解析
2019/11/08 Python
解决Python pip 自动更新升级失败的问题
2020/02/21 Python
详解Python中的编码问题(encoding与decode、str与bytes)
2020/09/30 Python
详解Django ORM引发的数据库N+1性能问题
2020/10/12 Python
Ariat官网:美国马靴和服装品牌
2019/12/16 全球购物
宿舍卫生检讨书
2014/01/16 职场文书
2014年十一国庆节活动方案
2014/09/16 职场文书
上班迟到检讨书范文300字
2014/11/02 职场文书
2014年学生会部门工作总结
2014/11/07 职场文书
2014年司机工作总结
2014/11/21 职场文书
体育教师个人总结
2015/02/09 职场文书
高三毕业感言
2015/07/30 职场文书
2016年秋季运动会广播稿
2015/12/21 职场文书
导游词之山西祁县乔家大院
2019/10/14 职场文书
react antd实现动态增减表单
2021/06/03 Javascript
Nginx下SSL证书安装部署步骤介绍
2021/12/06 Servers