Python Flask:发送文件和变量 [英] Python Flask: Send file and variable

查看:230
本文介绍了Python Flask:发送文件和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两台服务器,其中一台试图从另一台获取文件.我正在使用Flask get请求来回发送简单数据(字符串,列表,JSON对象等).

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.).

我也知道如何仅发送文件,但是我需要将错误代码与数据一起发送.

I also know how to send just a file, but I need to send an error code with my data.

我正在使用以下内容:

服务器1:

req = requests.post('https://www.otherserver.com/_download_file', data = {'filename':filename})

服务器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

服务器1:

with codecs.open('new_file.xyz', 'w') as f:
    f.write(req.content)

...所有这些都可以正常工作.但是,我想与file_data一起发送错误代码变量,以便服务器1知道状态(而不是HTTP状态,而是内部状态代码).

...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).

感谢您的帮助.

推荐答案

我想到的一个解决方案是使用自定义HTTP标头.

One solution that comes to my mind is to use a custom HTTP header.

这是服务器和客户端实现的示例.

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.

服务器

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)

客户

import requests

r = requests.post(url)

status = r.headers['my-custom-header']

# do what you want with status

更新

这是根据您的实现的服务器的另一个版本

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)

这篇关于Python Flask:发送文件和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆