python requests提交表單問(wèn)題
問(wèn)題描述
有些name是重復(fù)的,以及有些value是空的,比如sel_title,如何解決?我是這樣寫的form,不知道錯(cuò)在哪里,結(jié)果是400 Bad Requests.
form={’begin_ap’: ’a’, ’begin_hh’: ’0’, ’begin_mi’: ’0’, ’end_ap’: ’a’, ’end_hh’: ’0’, ’end_mi’: ’0’, ’sel_attr’: [’dummy’, ’%’], ’sel_camp’: [’dummy’, ’%’], ’sel_crse’: ’512’, ’sel_day’: ’dummy’, ’sel_from_cred’: ’’, ’sel_insm’: [’dummy’, ’%’], ’sel_instr’: [’dummy’, ’ED2E4E78451EB376949C4166DC00AFAF’], ’sel_levl’: ’dummy’, ’sel_ptrm’: [’dummy’, ’%’], ’sel_schd’: [’dummy’, ’%’], ’sel_sess’: [’%’, ’dummy’], ’sel_subj’: [’dummy’, ’STAT’], ’sel_title’: ’’, ’sel_to_cred’: ’’, ’term_in’: ’201810’}
問(wèn)題解答
回答1:你對(duì)http協(xié)議的內(nèi)容類型和結(jié)構(gòu)了解的不夠
首先, 你的表單數(shù)據(jù)比較復(fù)雜, 所以信息頭 Content-Type:application/json 最為合適, 前提是接收post請(qǐng)求的服務(wù)端, 對(duì)body的json解析是支持的
服務(wù)端通常的只支持或不支持body解析:application/x-www-form-urlencoded 和multipart/form-data(nodejs express需要加body-parser和multer插件)
application/x-www-form-urlencoded 就是 k1=v1&k2=v2...這樣的key=>str_val結(jié)構(gòu), 所以不適合你的多級(jí)字典form數(shù)據(jù)
關(guān)于表單的發(fā)送,body部分為json數(shù)據(jù)
import jsonimport requestsurl = ’https://api.github.com/some/endpoint’# 聲明數(shù)據(jù)類型, 有些框架會(huì)自動(dòng)識(shí)別并解析jsonheaders = {’Content-Type’: ’application/json; charset=utf-8’}# form = {’begin_ap’: ’a’, ...}r = requests.post(url, data=json.dumps(form), headers=headers)# 接收請(qǐng)求的服務(wù)端, 如果是flask框架(python)# 則request.json 即可取到字典結(jié)構(gòu)的form數(shù)據(jù)# request.form 則取不到form數(shù)據(jù)(需要 application/x-www-form-urlencoded 或 multipart/form-data)
如果你的框架默認(rèn)不支持對(duì)POST application/json 的解析, 則你需要自己對(duì)請(qǐng)求的body raw數(shù)據(jù)進(jìn)行一次json解析, 即可得到想要的數(shù)據(jù)
回答2:代碼如下:
import requestsurl = ’http://httpbin.org/post’r = requests.post(url, data=[(’interests’, ’football’), (’interests’, ’basketball’)])r.request.bodyr.json()[’form’]r = requests.post(url, data={’interests’: [’football’, ’basketball’]})r.request.bodyr.json()[’form’]
結(jié)果如下:
Out[100]:’interests=football&interests=basketball’Out[100]:{u’interests’: [u’football’, u’basketball’]}Out[100]:’interests=football&interests=basketball’Out[100]:{u’interests’: [u’football’, u’basketball’]}
為空的情況要看你和后臺(tái)的定義,是傳空字符串 ’’ 還是 key 也不傳, value 寫 None
回答3:推薦postman,寫代碼前可以先用postman測(cè)試請(qǐng)求表單
相關(guān)文章:
1. mac連接阿里云docker集群,已經(jīng)卡了2天了,求問(wèn)?2. ddos - apache日志很多其它網(wǎng)址,什么情況?3. 上傳圖片老是失敗是什么原因?SAE_TMP_PATH.后面跟的路徑在哪看4. javascript - 關(guān)于jquery的ajax post數(shù)據(jù)的問(wèn)題5. 前端 - 我有一個(gè)建站程序,但是多個(gè)文件夾下的HTML模板代碼沒(méi)有進(jìn)行縮進(jìn)格式化,請(qǐng)問(wèn)用什么軟件可以批量格式化一下代碼?6. android-studio - Win10下修改Windows用戶文件夾名user,導(dǎo)致Android Studio報(bào)錯(cuò)無(wú)法使用7. phpstudy pro小皮面板經(jīng)常報(bào)這個(gè)nginx: [emerg] CreateFile【急】8. thinkphp5.1學(xué)習(xí)時(shí)遇到session問(wèn)題9. angular.js - angular 路由為什么一直請(qǐng)求css和js文件10. javascript - setTimeout的延遲時(shí)間,是從什么時(shí)間段開(kāi)始算起的?
