python - 如何在 Flask 中返回图像作为 GET 请求响应的一部分?

标签 python api flask python-imaging-library

我已经设置了一个基本的 Python Flask API,它没有将 ID 作为 GET 请求的参数。在 get 请求逻辑中,我正在对另一个资源执行 get 请求,以检索与传入的 ID 关联的图像:

image = requests.get(url = image_url)
image = Image.open(BytesIO(image.content))
print(image.format)

它以 JPEG 形式返回的图像格式。

我想将其添加为 API 响应的一部分。这是我的 GET 端点的定义:

@app.route('/getmsg/', methods=['GET']) 
def respond():

这就是我尝试返回从其他资源获得的图像的方式:

return {"image": send_file(image, mimetype='image/jpeg'), "data": jsonify(return_list)}

我已经尝试遵循这个 stackoverflow 问题:How to return images in flask response?

这就是我如何到达现在的位置。我通过此端点发出获取请求:http://localhost:5000/getmsg/?id=7187167507933759112

我也尝试过只返回图像,如下所示:

return send_file(image, mimetype='image/jpeg')

但它给了我同样的错误。

除了返回图像之外,一切正常。

我希望能够在 get 请求的响应中看到图像,但现在它给出 500 内部服务器错误。

这是我在终端中得到的响应:

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

任何有关我做错的事情的指导将不胜感激。谢谢。

最佳答案

摘自send_file()的文档:

Sends the contents of a file to the client. This will use the most efficient method available and configured.

这意味着send_file本身就是一个响应。这就是您收到此错误的原因:Response 693 bytes [200 OK]

发送图像的一种可能的解决方案是对文件进行 base64 编码。像这样的事情:

with open("yourfile.ext", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

然后发送如下响应:

return {"image": encoded_string, "data": jsonify(return_list)}

并在另一端解码字符串,如下所示:

base64.b64decode(coded_string)

这也使响应的大小更小,从而提高了性能。

希望这有帮助。祝你好运。

关于python - 如何在 Flask 中返回图像作为 GET 请求响应的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58494586/

相关文章:

python - DRF- Django Rest Framework re_path 查询参数 - "Method\"GET\"not allowed."

python - Emacs 中对 Python 的 Doxygen 支持?

python - 安全错误 : Permission denied to access property "document" on cross-origin object error clicking on download link in iframe using Selenium Python

javascript - Google Contact API 错误 : Request via script load timed out. 可能原因:Feed URL 不正确;提要需要身份验证

python - 将不在模型中的字段添加到 Django REST 框架中的序列化程序

python - 如何使用 python、Flask 和命令行传递 URL 参数

python - 如何在不同的端口上运行 Python Eve 应用程序

python - 使用 Python 的 matplotlib 3D API 绘制轮廓的问题

python - 导入错误 : Plotly express requires pandas to be installed

php - 如何拥有一个由 Apache 提供服务的 Flask 网站以及位于/blog 的 WordPress 博客?