Python requests.post方法中data與json參數(shù)區(qū)別詳解
在通過requests.post()進行POST請求時,傳入報文的參數(shù)有兩個,一個是data,一個是json。
data與json既可以是str類型,也可以是dict類型。
區(qū)別:
1、不管json是str還是dict,如果不指定headers中的content-type,默認為application/json
2、data為dict時,如果不指定content-type,默認為application/x-www-form-urlencoded,相當(dāng)于普通form表單提交的形式
3、data為str時,如果不指定content-type,默認為text/plain
4、json為dict時,如果不指定content-type,默認為application/json
5、json為str時,如果不指定content-type,默認為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 urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r’^admin/’, admin.site.urls), url(r’^index/’, views.index),]
views.py :
from django.shortcuts import render, HttpResponsedef 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 requestsr1 = 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)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
