亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python requests.post方法中data與json參數(shù)區(qū)別詳解

 更新時(shí)間:2020年04月30日 10:07:41   作者:隨風(fēng)飄-挨刀刀  
這篇文章主要介紹了Python requests.post方法中data與json參數(shù)區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

在通過(guò)requests.post()進(jìn)行POST請(qǐng)求時(shí),傳入報(bào)文的參數(shù)有兩個(gè),一個(gè)是data,一個(gè)是json。

data與json既可以是str類型,也可以是dict類型。

區(qū)別:

1、不管json是str還是dict,如果不指定headers中的content-type,默認(rèn)為application/json

2、data為dict時(shí),如果不指定content-type,默認(rèn)為application/x-www-form-urlencoded,相當(dāng)于普通form表單提交的形式

3、data為str時(shí),如果不指定content-type,默認(rèn)為text/plain

4、json為dict時(shí),如果不指定content-type,默認(rèn)為application/json

5、json為str時(shí),如果不指定content-type,默認(rèn)為application/json

6、用data參數(shù)提交數(shù)據(jù)時(shí),request.body的內(nèi)容則為a=1&b=2的這種形式,用json參數(shù)提交數(shù)據(jù)時(shí),request.body的內(nèi)容則為'{"a": 1, "b": 2}'的這種形式

示例

Django項(xiàng)目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請(qǐng)求的請(qǐng)求體以data為參數(shù),發(fā)送過(guò)來(lái)的數(shù)據(jù)格式為:b'username=amy&password=123'
 當(dāng)post請(qǐng)求的請(qǐng)求體以json為參數(shù),發(fā)送過(guò)來(lái)的數(shù)據(jù)格式為:b'{"username": "amy", "password": "123"}'
 """
 print(request.headers)
 """
 當(dāng)post請(qǐng)求的請(qǐng)求體以data為參數(shù),Content-Type為:application/x-www-form-urlencoded
 當(dāng)post請(qǐng)求的請(qǐng)求體以json為參數(shù),Content-Type為:application/json
 """
 return HttpResponse("ok")

在另一個(gè)Python程序中向http://127.0.0.1:8080/index/發(fā)送post請(qǐng)求,打印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ū)別詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論