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 爬虫出现403禁止访问错误详解
Mar 11 Python
Python双精度浮点数运算并分行显示操作示例
Jul 21 Python
Python三种遍历文件目录的方法实例代码
Jan 19 Python
Python multiprocessing多进程原理与应用示例
Feb 28 Python
python pygame实现五子棋小游戏
Oct 26 Python
flask框架单元测试原理与用法实例分析
Jul 23 Python
详解Django admin高级用法
Nov 06 Python
python、PyTorch图像读取与numpy转换实例
Jan 13 Python
opencv python 图片读取与显示图片窗口未响应问题的解决
Apr 24 Python
Python 利用flask搭建一个共享服务器的步骤
Dec 05 Python
Python图像处理之膨胀与腐蚀的操作
Feb 07 Python
django注册用邮箱发送验证码的实现
Apr 18 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
Gregarius中文日期格式问题解决办法
2008/04/22 PHP
php 文件夹删除、php清除缓存程序
2009/08/25 PHP
PHP gbk环境下json_dencode传送来的汉字
2012/11/13 PHP
PHP OPP机制和模式简介(抽象类、接口和契约式编程)
2014/06/09 PHP
用PHP解决的一个栈的面试题
2014/07/02 PHP
php curl 获取https请求的2种方法
2015/04/27 PHP
封装的原生javascript弹出层代码
2010/09/24 Javascript
html5+javascript制作简易画板附图
2014/04/25 Javascript
jQuery回调函数的定义及用法实例
2014/12/23 Javascript
JavaScript事件类型中焦点、鼠标和滚轮事件详解
2016/01/25 Javascript
举例说明JavaScript中的实例对象与原型对象
2016/03/11 Javascript
JS hashMap实例详解
2016/05/26 Javascript
Bootstrap学习笔记之css样式设计(2)
2016/06/07 Javascript
微信JS接口大全
2016/08/25 Javascript
js点击按钮实现水波纹效果代码(CSS3和Canves)
2016/09/15 Javascript
vue开发调试神器vue-devtools使用详解
2017/07/13 Javascript
Vue项目引进ElementUI组件的方法
2018/11/11 Javascript
VUE前后端学习tab写法实例
2019/08/06 Javascript
JavaScript进阶(四)原型与原型链用法实例分析
2020/05/09 Javascript
解决vue-pdf查看pdf文件及打印乱码的问题
2020/11/04 Javascript
vue项目中使用rem,在入口文件添加内容操作
2020/11/11 Javascript
[00:37]DOTA2上海特级锦标赛 Secert 战队宣传片
2016/03/03 DOTA
[01:04:09]DOTA2-DPC中国联赛 正赛 iG vs VG BO3 第二场 2月2日
2021/03/11 DOTA
Python 过滤字符串的技巧,map与itertools.imap
2008/09/06 Python
python操作数据库之sqlite3打开数据库、删除、修改示例
2014/03/13 Python
python清除函数占用的内存方法
2018/06/25 Python
英国最大的邮寄种子和植物公司:Thompson & Morgan
2017/09/21 全球购物
PHP面试题-$message和$$message的区别
2015/12/08 面试题
办公室文员工作自我评价
2013/12/01 职场文书
幼师求职自荐信范文
2014/01/26 职场文书
财政专业求职信范文
2014/02/19 职场文书
计算机应用专业自荐信
2014/07/05 职场文书
战友聚会致辞
2015/07/28 职场文书
公司新员工欢迎词
2015/09/30 职场文书
vue3语法糖内的defineProps及defineEmits
2022/04/14 Vue.js
Nginx静态压缩和代码压缩提高访问速度详解
2022/05/30 Servers