python - 如何在 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
字符串传递给服务器?
解决方案
根据文件:
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 请求的一部分发送
推荐阅读
- python - 如何挑选出每 n 个刻度标签以显示在图上?
- javascript - Firefox 和 Safari 下 HTML/CSS/JS 元球的性能问题
- scala - 在 Spark 中访问数据集中的每一行时未找到适用的构造函数/方法
- user-interface - 从用户输入变量开始一个 for 循环
- node.js - NodeJS - 调用反序列化用户后,应用程序在身份验证期间挂起(passport.js)
- firefox - 跨不同端口的 CORS 请求在 Firefox 上未成功,但在 Chrome 上有效
- python - 如何使用'set'保持有序列表?
- android - 如何在 android 的启动画面中使用除应用程序图标之外的图像
- android - Android Studio 找不到我的虚拟设备
- scala - 在 Spark Scala 中找不到错误值