我建议将 JSON 和文件作为多部分表单的一部分发送。在这种情况下,您将从中读取它们request.files
在服务器上。 (需要注意的是:我使用 Python 3、requests 2.18.4 和 Flask 0.12.2 测试了所有示例——您可能需要更改代码以匹配您的环境)。
From https://stackoverflow.com/a/35940980/2415176 https://stackoverflow.com/a/35940980/2415176(以及 Flask 文档位于http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files),您不需要指定标头或任何内容。你可以让requests
为您处理:
import json
import requests
# Ton to be sent
datas = {'var1' : 'var1','var2' : 'var2',}
#my file to be sent
local_file_to_send = 'tmpfile.txt'
with open(local_file_to_send, 'w') as f:
f.write('I am a file\n')
url = "http://127.0.0.1:3000/customerupdate"
files = [
('document', (local_file_to_send, open(local_file_to_send, 'rb'), 'application/octet')),
('datas', ('datas', json.dumps(datas), 'application/json')),
]
r = requests.post(url, files=files)
print(str(r.content, 'utf-8'))
然后在服务器上您可以读取request.files
(see http://flask.pocoo.org/docs/0.12/api/#flask.Request.files http://flask.pocoo.org/docs/0.12/api/#flask.Request.files但请注意 request.files 过去的工作方式略有不同,请参阅https://stackoverflow.com/a/11817318/2415176 https://stackoverflow.com/a/11817318/2415176):
import json
from flask import Flask, request
app = Flask(__name__)
@app.route('/',methods=['GET'])
def hello_world():
return 'Hello World!'
@app.route('/customerupdate',methods=['GET','POST'])
def customerupdate():
posted_file = str(request.files['document'].read(), 'utf-8')
posted_data = json.load(request.files['datas'])
print(posted_file)
print(posted_data)
return '{}\n{}\n'.format(posted_file, posted_data)