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 相关文章推荐
linux系统使用python获取内存使用信息脚本分享
Jan 15 Python
用C++封装MySQL的API的教程
May 06 Python
python 基础教程之Map使用方法
Jan 17 Python
python虚拟环境迁移方法
Jan 03 Python
Python实现操纵控制windows注册表的方法分析
May 24 Python
python地震数据可视化详解
Jun 18 Python
解决Tensorboard 不显示计算图graph的问题
Feb 15 Python
从多个tfrecord文件中无限读取文件的例子
Feb 17 Python
Python中的sys.stdout.write实现打印刷新功能
Feb 21 Python
关于tf.matmul() 和tf.multiply() 的区别说明
Jun 18 Python
Selenium alert 弹窗处理的示例代码
Aug 06 Python
python读取并查看npz/npy文件数据以及数据显示方法
Apr 14 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和ACCESS写聊天室(二)
2006/10/09 PHP
Symfony2安装第三方Bundles实例详解
2016/02/04 PHP
使用ltrace工具跟踪PHP库函数调用的方法
2016/04/25 PHP
PHP多维数组指定多字段排序的示例代码
2018/05/16 PHP
PHP利用缓存处理用户注册时的邮箱验证,成功后用户数据存入数据库操作示例
2019/12/31 PHP
js禁止页面复制功能禁用页面右键菜单示例代码
2013/08/29 Javascript
javascript的动态加载、缓存、更新以及复用(一)
2014/06/09 Javascript
jQuery遍历对象、数组、集合实例
2014/11/08 Javascript
解决jQuery使用JSONP时产生的错误
2015/12/02 Javascript
基于jquery插件实现拖拽删除图片功能
2020/08/27 Javascript
教你如何在Node.js中使用jQuery
2016/08/28 Javascript
js实现获取鼠标当前的位置
2016/12/14 Javascript
bootstrap实现每隔5秒自动轮播效果
2016/12/20 Javascript
JS 实现 ajax 异步浏览器兼容问题
2017/01/21 Javascript
原生和jQuery的ajax用法详解
2017/01/23 Javascript
关于Angular2 + node接口调试的解决方案
2017/05/28 Javascript
vue.js系列中的vue-fontawesome使用
2018/02/10 Javascript
js实现百度淘宝搜索功能
2020/02/17 Javascript
JS函数本身的作用域实例分析
2020/03/16 Javascript
详谈Vue.js框架下main.js,App.vue,page/index.vue之间的区别
2020/08/12 Javascript
[58:32]EG vs Liquid 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
Python Django使用forms来实现评论功能
2016/08/17 Python
Python 转义字符详细介绍
2017/03/21 Python
Atom的python插件和常用插件说明
2018/07/08 Python
Python 数值区间处理_对interval 库的快速入门详解
2018/11/16 Python
细说CSS3中的选择符
2008/10/17 HTML / CSS
怀俄明州飞钓:Platte River Fly Shop
2017/12/28 全球购物
Perfume’s Club美国官网:西班牙第一家在线美容店
2020/06/10 全球购物
一年级学生期末评语
2014/04/21 职场文书
广告艺术设计专业自荐书
2014/07/08 职场文书
2014物价局民主生活会对照检查材料思想汇报
2014/09/24 职场文书
2014红色之旅心得体会
2014/10/07 职场文书
全国爱眼日活动总结
2015/02/27 职场文书
面试通知邮件
2015/04/20 职场文书
nginx.conf配置文件结构小结
2022/04/08 Servers
Vue OpenLayer 为地图绘制风场效果
2022/04/24 Vue.js