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

Dyl*_*yen 3 python 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
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以让我在客户的 1 个请求内收到包含附加结果的图像?

Olu*_*ule 6

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

\n\n
    \n
  • 将额外信息设置为 cookie。
  • \n
\n\n
response = send_file(\n                img_path,\n                mimetype=\'image/jpg\'\n           )\nresponse.set_cookies(\'score\', score)\n
Run Code Online (Sandbox Code Playgroud)\n\n
    \n
  • 设置附加响应标头以包含额外信息。
  • \n
\n\n
response = send_file(\n                img_path,\n                mimetype=\'image/jpg\'\n           )\nresponse.set_header(\'x-myapp-score\', score)\n
Run Code Online (Sandbox Code Playgroud)\n\n\n\n
from base64 import b64encode\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ndef post(self):\n    # ...\n    output = {\n       \'score\': score\n    }\n    try:\n        with open(final_image, \'rb\') as f:\n            content = f.read()\n            output[\'img\'] = b64encode(content)\n    except TypeError, FileNotFoundError:\n           # handle default image \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf\n           logger.exception(\'Failed to encode image file\')\n    return output\n
Run Code Online (Sandbox Code Playgroud)\n