圣杯框架:请求未指定接受 header 和 image/jpeg

Chalice Framework: Request did not specify an Accept header with image/jpeg

我想 return 来自 Chalice/python 应用程序的图像。我的整个应用程序代码粘贴在下面:

from chalice import Chalice, Response
import base64

app = Chalice(app_name='hello')

@app.route('/makeImage', methods=['GET'])
def makeImage():
    return Response(
        base64.b64decode(
            "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
        ),
        headers={
            'Content-Type': 'image/jpeg'
        },
        status_code=200)

结果...

{"Code":"BadRequest","Message":"Request did not specify an Accept header with image/jpeg, The response has a Content-Type of image/jpeg. If a response has a binary Content-Type then the request must specify an Accept header that matches."}

为什么会这样?

我已经翻阅了大量文档,其中大部分已经过时,因为最近 Chalice 添加了二进制支持:

仅出于故障排除目的,我可以使用 curl -H "accept: image/jpeg" 获得响应,但这没有用,因为浏览器无法以这种方式工作,我需要在浏览器中使用响应 (HTML IMG 标签).

更新

我也试过了@app.route('/makeImage', methods=['GET'], content_types=['image/jpeg'])

结果变成了{"Code":"UnsupportedMediaType","Message":"Unsupported media type: application/json"}

Chalice 中存在一个错误,已于 2019 年 5 月 14 日修复并记录在此处:

https://github.com/aws/chalice/issues/1095

除了直接从 GitHub 安装最新的 Chalice 外,我还必须添加:

app.api.binary_types =['*/*']

app.py.

最终的工作代码如下所示:

from chalice import Chalice, Response
import base64

app = Chalice(app_name='hello')
app.api.binary_types =['*/*']

@app.route('/makeImage', methods=['GET'])
def makeImage():
    return Response(
        base64.b64decode(
            "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
        ),
        headers={
            'Content-Type': 'image/jpeg'
        },
        status_code=200)

我遇到了同样的问题。

如果不存在 header 接受,AWS 将其设置为默认值 application/json 并且我收到 base64 响应。如果我将接受设置为 images/jpeg 或 header 中的任何二进制内容类型,那么我就得到了图像。很好,但是网络浏览器没有设置接受 header.

但是如果我添加

app.api.binary_types =['*/*']

那么好的,我的图像 api 现在可以使用了。 很好,但现在 json 失败了。

目前我没有看到任何解决方案,除了有两个 API 网关:一个用于 json 和一个用于图像。如果您真的只想要一个 API 网关,我认为您必须对所有 json 响应使用 gzip 压缩以将它们转换为二进制文件。

更多的是 AWS API 网关如何与 lambda 代理一起工作,而不是圣杯问题。但我同意,这是一个很大的限制