python requests form submission problem
迷茫
迷茫 2017-05-18 10:57:52
0
3
985

Some names are repeated, and some values ​​are empty, such as sel_title. How to solve it?
I wrote the form like this. I don’t know what’s wrong. The result is 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'}

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
阿神

You don’t know enough about the content type and structure of the http protocol

First of all, your form data is relatively complex, so the information header Content-Type: application/json is most suitable. The premise is that the server that receives the post request supports json parsing of the body

The server usually only supports or does not support body parsing:
application/x-www-form-urlencoded and
multipart/form-data
(nodejs express needs to add body-parser and multer plug-ins)

application/x-www-form-urlencoded is k1=v1&k2=v2...such a key=>str_val structure, so it is not suitable for your multi-level dictionary form data

About sending the form, the body part is json data

import json
import requests

url = 'https://api.github.com/some/endpoint'
# 声明数据类型, 有些框架会自动识别并解析json
headers = {'Content-Type': 'application/json; charset=utf-8'}
# form = {'begin_ap': 'a', ...}
r = requests.post(url, data=json.dumps(form), headers=headers)

# 接收请求的服务端, 如果是flask框架(python)
# 则request.json 即可取到字典结构的form数据
# request.form 则取不到form数据(需要 application/x-www-form-urlencoded 或 multipart/form-data)

If your framework does not support parsing POST application/json by default, you need to perform a json parsing on the requested body raw data yourself to get the desired data

刘奇

The code is as follows:

import requests
url = 'http://httpbin.org/post'
r = requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])
r.request.body
r.json()['form']
r = requests.post(url, data={'interests': ['football', 'basketball']})
r.request.body
r.json()['form']

The results are as follows:

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']}

If it is empty, it depends on the definition of you and the background. It means passing an empty string '' 还是 key 也不传, valueNone

世界只因有你

Postman is recommended. You can use Postman to test the request form before writing code

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template