[英]Python Flask: Send file and variable
I have two servers where one is trying to get a file from the other. 我有两台服务器,其中一台试图从另一台获取文件。 I am using Flask get requests to send simple data back and forth (strings, lists, JSON objects, etc.).
我正在使用Flask get请求来回发送简单数据(字符串,列表,JSON对象等)。
I also know how to send just a file, but I need to send an error code with my data. 我也知道如何仅发送文件,但是我需要随数据发送错误代码。
I'm using something along the following lines: 我正在使用以下内容:
Server 1: 服务器1:
req = requests.post('https://www.otherserver.com/_download_file', data = {'filename':filename})
Server 2: 服务器2:
@app.route('/_download_file', methods = ['POST'])
def download_file():
filename = requests.form.get('filename')
file_data = codecs.open(filename, 'rb').read()
return file_data
Server 1: 服务器1:
with codecs.open('new_file.xyz', 'w') as f:
f.write(req.content)
...all of which works fine. ...一切都很好。 However, I want to send an error code variable along with
file_data
so that Server 1 knows the status (and not the HTTP status, but an internal status code). 但是,我想与
file_data
一起发送错误代码变量,以便服务器1知道状态(而不是HTTP状态,而是内部状态代码)。
Any help is appreciated. 任何帮助表示赞赏。
One solution that comes to my mind is to use a custom HTTP header. 我想到的一种解决方案是使用自定义HTTP标头。
Here is an example server and client implementation. 这是服务器和客户端实现的示例。
Of course, you are free to change the name and the value of the custom header as you need. 当然,您可以根据需要随意更改自定义标头的名称和值。
server 服务器
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/', methods=['POST'])
def index():
response = send_from_directory(directory='your-directory', filename='your-file-name')
response.headers['my-custom-header'] = 'my-custom-status-0'
return response
if __name__ == '__main__':
app.run(debug=True)
client 客户
import requests
r = requests.post(url)
status = r.headers['my-custom-header']
# do what you want with status
UPDATE 更新
Here is another version of the server based on your implementation 这是根据您的实现的服务器的另一个版本
import codecs
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/', methods=['POST'])
def index():
filename = request.form.get('filename')
file_data = codecs.open(filename, 'rb').read()
response = make_response()
response.headers['my-custom-header'] = 'my-custom-status-0'
response.data = file_data
return response
if __name__ == '__main__':
app.run(debug=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.