Python requests.post方法中data與json參數(shù)區(qū)別詳解
在通過requests.post()進(jìn)行POST請求時,傳入報文的參數(shù)有兩個,一個是data,一個是json。
data與json既可以是str類型,也可以是dict類型。
區(qū)別:
1、不管json是str還是dict,如果不指定headers中的content-type,默認(rèn)為application/json
2、data為dict時,如果不指定content-type,默認(rèn)為application/x-www-form-urlencoded,相當(dāng)于普通form表單提交的形式
3、data為str時,如果不指定content-type,默認(rèn)為text/plain
4、json為dict時,如果不指定content-type,默認(rèn)為application/json
5、json為str時,如果不指定content-type,默認(rèn)為application/json
6、用data參數(shù)提交數(shù)據(jù)時,request.body的內(nèi)容則為a=1&b=2的這種形式,用json參數(shù)提交數(shù)據(jù)時,request.body的內(nèi)容則為'{"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)
"""
當(dāng)post請求的請求體以data為參數(shù),發(fā)送過來的數(shù)據(jù)格式為:b'username=amy&password=123'
當(dāng)post請求的請求體以json為參數(shù),發(fā)送過來的數(shù)據(jù)格式為:b'{"username": "amy", "password": "123"}'
"""
print(request.headers)
"""
當(dāng)post請求的請求體以data為參數(shù),Content-Type為:application/x-www-form-urlencoded
當(dāng)post請求的請求體以json為參數(shù),Content-Type為:application/json
"""
return HttpResponse("ok")
在另一個Python程序中向http://127.0.0.1:8080/index/發(fā)送post請求,打印request.body觀察data參數(shù)和json參數(shù)發(fā)送數(shù)據(jù)的格式是不同的。
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參數(shù)區(qū)別詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python實現(xiàn)自動發(fā)送報警監(jiān)控郵件
這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)自動發(fā)送報警監(jiān)控郵件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06
python計算階乘和的方法(1!+2!+3!+...+n!)
今天小編就為大家分享一篇python計算階乘和的方法(1!+2!+3!+...+n!),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02
Python讀取Word文檔中的Excel嵌入文件的方法詳解
這篇文章主要為大家詳細(xì)介紹了Python讀取Word文檔中的Excel嵌入文件的方法,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,需要的可以參考一下2022-12-12
python pyecharts 實現(xiàn)一個文件繪制多張圖
這篇文章主要介紹了python pyecharts 實現(xiàn)一個文件繪制多張圖,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05

