zl程序教程

您现在的位置是:首页 >  后端

当前栏目

requests.post 方法 json 和 data 参数的区别

方法JSONJSON 区别 参数 Data post requests
2023-06-13 09:16:00 时间

背景

import requests

requests.post("http://127.0.0.1:8000/", data={'name':'tom'})

requests.post("http://127.0.0.1:8000/", json={'name':'tom'})

最近用 requests 调用一些开放平台的 WEB-API ,从它们的官方文档上看有如上两种参数传递的风格;一开始我以为这两个是可以互换的,后来发现并不是这样,这是两种传参方法,在后台对应着完全不同的处理方式。

针对这个问题,在服务端直接打印 request.headersrequest.body 可以非常快地看出两者的不同。


实现一个简单的后台

写一个简单的后台处理程序,用它来打印请求对象的 header 和 body 。

def index(request, *args, **kwargs):
    logger.info(f"request.headers = {request.headers} .")
    logger.info(f"request.body = {request.body} .")
    return JsonResponse({})

通过 data 传参数

这种传参方式就是传统的表单提交;这此情况下 Content-Type 会被设置为 application/x-www-form-urlencoded , 数据以 name=value 的形式编码在 body 中。

[INFO] request.headers = {'Content-Length': '8', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': '127.0.0.1:8000', 'User-Agent': 'python-requests/2.26.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} .

[INFO] request.body = b'name=tom' .

通过 json 传参数

这种方式的话 requests 会把 Content-Type 设置为 application/json,并且 body 里面的值就是字典序列化后的值。

[INFO] request.headers = {'Content-Length': '15', 'Content-Type': 'application/json', 'Host': '127.0.0.1:8000', 'User-Agent': 'python-requests/2.26.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} .

[INFO] request.body = b'{"name": "tom"}' .