我的问题是我正在尝试使用 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 个请求内收到包含附加结果的图像?
您可以考虑以下任一方法:
\n\nresponse = send_file(\n img_path,\n mimetype=\'image/jpg\'\n )\nresponse.set_cookies(\'score\', score)\nRun Code Online (Sandbox Code Playgroud)\n\nresponse = send_file(\n img_path,\n mimetype=\'image/jpg\'\n )\nresponse.set_header(\'x-myapp-score\', score)\nRun Code Online (Sandbox Code Playgroud)\n\nfrom 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\nRun Code Online (Sandbox Code Playgroud)\n