温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python requests.post方法中data与json参数有什么区别

发布时间:2020-07-29 11:10:56 来源:亿速云 阅读:844 作者:小猪 栏目:开发技术

小编这次要给大家分享的是Python requests.post方法中data与json参数有什么区别,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

在通过requests.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json。

data与json既可以是str类型,也可以是dict类型。

区别:

1、不管json是str还是dict,如果不指定headers中的content-type,默认为application/json

2、data为dict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式

3、data为str时,如果不指定content-type,默认为text/plain

4、json为dict时,如果不指定content-type,默认为application/json

5、json为str时,如果不指定content-type,默认为application/json

6、用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式

示例

Django项目pro_1如下:

urls.py:

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
 url(r'^admin/', admin.site.urls),
 url(r'^index/', views.index),
]

views.py :

from django.shortcuts import render, HttpResponse

def index(request):
 print(request.body)
 """
 当post请求的请求体以data为参数,发送过来的数据格式为:b'username=amy&password=123'
 当post请求的请求体以json为参数,发送过来的数据格式为:b'{"username": "amy", "password": "123"}'
 """
 print(request.headers)
 """
 当post请求的请求体以data为参数,Content-Type为:application/x-www-form-urlencoded
 当post请求的请求体以json为参数,Content-Type为:application/json
 """
 return HttpResponse("ok")

在另一个Python程序中向http://127.0.0.1:8080/index/发送post请求,打印request.body观察data参数和json参数发送数据的格式是不同的。

example1.py :

import requests

r1 = requests.post(
 url="http://127.0.0.1:8089/index/",
 data={
  "username": "amy",
  "password": "123"
 }

 # data='username=amy&password=123'

 # json={
 #  "username": "amy",
 #  "password": "123"
 # }

 # json='username=amy&password=123'
)
print(r1.text)

看完这篇关于Python requests.post方法中data与json参数有什么区别的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI