同样是 POST,表单和 JSON 在 Flask 里分别从哪读?Content-Type 不对会怎样?JSON 非法是 400 还是 415?表单太大会被拒吗?这篇逐个试。
application/x-www-form-urlencoded form={'a': ['1'], 'b': ['x', 'y']} files=[] json=None data_len=0
multipart/form-data form={'a': ['1']} files=['f'] json=None data_len=0
application/json form={} files=[] json={'a': 1} data_len=8
text/plain form={} files=[] json=None data_len=12
(data_len 为 0 表示请求体已经被 form / files 解析消耗了,get_data() 拿不到)上一篇:Query String 参数解析;下一篇:request.args、request.form、request.json。
Content-Type: application/json + 合法 JSON → 200 {'json': {'a': 1}}
Content-Type: application/json + 非法 JSON → 400 {'error': 'BadRequest', 'msg': '400 Bad Request: The browser (or proxy) sent a request that this server could not understand.'}
Content-Type: text/plain + 合法 JSON → 415 {'error': 'UnsupportedMediaType', 'msg': "415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json"}
没有 Content-Type → 415 {'error': 'UnsupportedMediaType', 'msg': "415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json"}
application/json + 空正文 → 400 {'error': 'BadRequest', 'msg': '400 Bad Request: The browser (or proxy) sent a request that this server could not understand.'}
application/vnd.api+json → 200 {'json': {'a': 1}}
application/json; charset=utf-8 + 中文 → 200 {'json': {'名': '张三'}}
text/plain + force=True → {'force': {'a': 1}, 'silent_after_force': {'a': 1}, 'silent_first': None} form = {'single': ['x'], 'tags': ['a', 'b', 'c']}
form["tags"] = a | form.getlist("tags") = ['a', 'b'] | form.get("none") = None默认值:MAX_FORM_MEMORY_SIZE = 500000 | MAX_FORM_PARTS = 1000 MAX_FORM_PARTS=5 时发 10 个 multipart 字段 → 413 MAX_FORM_MEMORY_SIZE=100 时发 500 字节的表单字段 → 200 同样 500 字节,multipart 形式 → 413
JSON 往返: {'n': 1, 'nested': {'a': [1, 2]}, 'none': None, 'ok': True} | 类型: {'n': 'int', 'nested': 'dict', 'none': 'NoneType', 'ok': 'bool'}