繁体   English   中英

如何使用 Flask 在 1 个响应中将 send_file() 与另一个信息(例如,int)结合起来

[英]How can combine send_file() with another information (E.g., int) in 1 response using Flask

我的问题是我正在尝试使用 Python 和 Flask 向客户端和图像发送另一个附加信息。

我尝试使用 send_file(),但问题是我只能发送图像,我找不到其他方法来发送附加信息。 我还尝试将图像和信息组合到 JSON 中,但似乎 send_file() 无法序列化为 JSON

def post(self):
    img_path, score = self.get_result()
    final_image = send_file(
        img_path,
        mimetype='image/jpg'
    )
    output = {'img': final_image, 'score': score}
    return output

有什么方法可以在客户的 1 个请求中接收到带有附加结果的图像?

您可以考虑以下任一方法:

  • 将额外信息设置为 cookie。
response = send_file(
                img_path,
                mimetype='image/jpg'
           )
response.set_cookies('score', score)
  • 设置其他响应标头以包含额外信息。
response = send_file(
                img_path,
                mimetype='image/jpg'
           )
response.set_header('x-myapp-score', score)
from base64 import b64encode
import logging

logger = logging.getLogger(__name__)

def post(self):
    # ...
    output = {
       'score': score
    }
    try:
        with open(final_image, 'rb') as f:
            content = f.read()
            output['img'] = b64encode(content)
    except TypeError, FileNotFoundError:
           # handle default image ¯\_(ツ)_/¯
           logger.exception('Failed to encode image file')
    return output

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM