首页 > 解决方案 > 如何在 request.post 方法中使用 json 和 files 参数上传文件

问题描述

使用 Flask 服务器:

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    print('get_json: %s get_data: %s' % (type(request.get_json()), type(request.get_data())) )
    return 'OK', 200

app.run('0.0.0.0', 80)

json客户端使用和files参数发送请求:

import requests 
files_data = {"dirname/file,name": bytearray(4)}
response = requests.post('http://127.0.0.1:80/', json = 'hello world', files = files_data)

服务器打印request.get_json()返回None.

get_json: <type 'NoneType'> get_data: <type 'str'>

如何将hello world字符串传递给服务器?

标签: pythonflaskrequest

解决方案


根据文件

Note, the json parameter is ignored if either data or files is passed.

您的 json 参数必须是json类型,如下所示:

import requests 
json_data = {'data': 'hello world'}
files_data = {"dirname/file_name": bytearray(4)}
response = requests.post('http://127.0.0.1:80/', json = 'hello world')

如果您想同时使用文件和 json,则不要使用 json 进行编码。

也不要Content-type自己设置标题,将其留给 pyrequests 生成

payload = {"param_1": "value_1", "param_2": "value_2"}
    files = {
         'json': (None, json.dumps(payload), 'application/json'),
         'file': (os.path.basename(file), open(file, 'rb'), 'application/octet-stream')
    }

    r = requests.post(url, files=files)

有关更多信息,请参阅此线程如何将 JSON 作为多部分 POST 请求的一部分发送


推荐阅读