且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用python将json和文件发送到flask

更新时间:2023-11-27 14:25:40

我建议同时发送JSON和文件作为多部分表单的一部分.在这种情况下,您可以从服务器上的request.files中读取它们. (一个警告:我使用Python 3,请求2.18.4和Flask 0.12.2测试了所有示例,您可能需要更改代码以匹配您的环境.)

I would recommend sending both the JSON and the file as parts of the multipart form. In that case you would read them from request.files on the server. (One caveat: I tested all my examples with Python 3, requests 2.18.4, and Flask 0.12.2 -- you might need to change the code around to match your environment).

来自 https://***.com/a/35940980/2415176 (以及 http://docs.python-requests.org /en/latest/user/advanced/#post-multiple-multipart-encoded-files ),则无需指定标头或其他任何内容.您可以让requests为您处理它:

From https://***.com/a/35940980/2415176 (and the Flask docs at http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files), you don't need to specify headers or anything. You can just let requests handle it for you:

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读取(请参阅 http://flask.pocoo.org/docs/0.12/api/#flask.Request.files ,但请注意,request.file的工作方式有所不同,请参见

Then on the server you can read from request.files (see http://flask.pocoo.org/docs/0.12/api/#flask.Request.files but note that request.files used to work a little differently, see https://***.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)