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实现的简单万年历例子分享
Apr 25 Python
python实现进程间通信简单实例
Jul 23 Python
学习Python3 Dlib19.7进行人脸面部识别
Jan 24 Python
详解Django+Uwsgi+Nginx的生产环境部署
Jun 25 Python
Python判断两个文件是否相同与两个文本进行相同项筛选的方法
Mar 01 Python
Python基础学习之类与实例基本用法与注意事项详解
Jun 17 Python
python读csv文件时指定行为表头或无表头的方法
Jun 26 Python
如何基于Python获取图片的物理尺寸
Nov 25 Python
python实现提取str字符串/json中多级目录下的某个值
Feb 27 Python
使用Python三角函数公式计算三角形的夹角案例
Apr 15 Python
tensorflow与numpy的版本兼容性问题的解决
Jan 08 Python
python爬虫实现爬取同一个网站的多页数据的实例讲解
Jan 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
PHP 危险函数解释 分析
2009/04/22 PHP
PHP实现把数字ID转字母ID
2013/08/12 PHP
超强多功能php绿色集成环境详解
2017/01/25 PHP
php中错误处理操作实例分析
2019/08/23 PHP
PHP常见的序列化与反序列化操作实例分析
2019/10/28 PHP
jQuery 过滤not()与filter()实例代码
2012/05/10 Javascript
一个判断抢购时间是否到达的简单的js函数
2014/06/23 Javascript
jQuery网页选项卡插件rTabs用法实例分析
2015/08/26 Javascript
SublimeText自带格式化代码功能之reindent
2015/12/27 Javascript
详解vue的数据binding绑定原理
2017/04/12 Javascript
JS与HTML结合实现流程进度展示条思路详解
2017/09/03 Javascript
Angular 容器部署的方法
2018/04/17 Javascript
QRCode.js二维码生成并能长按识别
2018/10/16 Javascript
详解TypeScript+Vue 插件 vue-class-component的使用总结
2019/02/18 Javascript
小程序开发踩坑:页面窗口定位(相对于浏览器定位)(推荐)
2019/04/25 Javascript
微信小程序自定义toast组件的方法详解【含动画】
2019/05/11 Javascript
详解jenkins自动化部署vue
2019/05/14 Javascript
浅谈VUE中演示v-for为什么要加key
2020/01/16 Javascript
原生js中运算符及流程控制示例详解
2021/01/05 Javascript
Python多线程编程(四):使用Lock互斥锁
2015/04/05 Python
python简单分割文件的方法
2015/07/30 Python
详解django中自定义标签和过滤器
2017/07/03 Python
Python2.7读取PDF文件的方法示例
2017/07/13 Python
python正则表达式及使用正则表达式的例子
2018/01/22 Python
python 重命名轴索引的方法
2018/11/10 Python
Python assert语句的简单使用示例
2019/07/28 Python
python 控制Asterisk AMI接口外呼电话的例子
2019/08/08 Python
Pyinstaller加密打包应用的示例代码
2020/06/11 Python
canvas裁剪clip()函数的具体使用
2018/03/01 HTML / CSS
费用会计岗位职责
2014/01/01 职场文书
主持人婚宴答谢词
2014/01/28 职场文书
2014小学植树节活动总结
2014/03/10 职场文书
预备党员自我批评思想汇报
2014/10/10 职场文书
婚前财产协议书范本
2014/10/19 职场文书
文书工作总结(范文)
2019/07/11 职场文书
标准版个人借条怎么写?以及什么是借条?
2019/08/28 职场文书