首页 > 解决方案 > 客户端通过 send_file 命令调用服务器的 FLASK 端点时无法查看图像

问题描述

我有一个在 python 中运行的 Flask 应用程序。有一个客户端正在从磁盘提供图像。我希望服务器到达终点并检索图像。

在客户端:

@app.route('/api/get_image')
def get(self, id):
   # Map id to filename.
   return send_file(filename)

当我从浏览器调用客户端的端点时,这有效。

在服务器端,我有一个类似的函数应该调用上述端点。

@app.route('/api/get_image')
def get(self, id):
    return requests.get(client_url + '/api/get_image')

当我调用服务器端点时,我得到:

TypeError: <Response [200]> is not JSON serializable

但即使我尝试 .json() 也不起作用。如何返回图像有效负载?

标签: pythonflasksendfile

解决方案


Don't return the object from requests.get() directly, instead retrieve the .raw or .content object from it

r = requests.get(url)
r.raise_for_status()  # raise an Exception if the request failed
return r.content

推荐阅读