如何在同一圣杯应用程序中从不同的路由返回图像和json?

时间:2019-05-18 18:46:37

标签: python chalice

我有一个最小的,可验证的示例圣杯应用程序:

from chalice import Chalice, Response
from urllib.request import Request, urlopen
from urllib.parse import unquote
import io

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

@app.route('/get-photo/{url}/{maxWidth}/{maxHeight}', methods=['GET'])
def getPhoto(url, maxWidth, maxHeight):
     return Response(
        load(unquote(url), int(maxWidth), int(maxHeight)),
        headers={ 'Content-Type': 'image/jpeg' },
        status_code=200)

def load(url, maxWidth, maxHeight):
    print(url)
    req = Request(url)
    req.add_header('accept', 'image/jpeg')
    image = urlopen(req).read()
    return thumbnail(image, maxWidth, maxHeight)

from PIL import Image

def thumbnail(image, maxWidth, maxHeight):

    im = Image.open(io.BytesIO(image))
    im.thumbnail((maxWidth,maxHeight), Image.ANTIALIAS)

    with io.BytesIO() as output:
        im.save(output, format="JPEG")
        return output.getvalue()

@app.route('/echo', methods=['POST'])
def preload():
    # MCVE
    return Response(app.current_request.json_body, status_code=200)

按现状,/get-photo路由可以正常工作,但是/echo端点在用curl -H "Content-Type: application/json" -X POST -d '{"test":1}' https://...调用时失败了

[ERROR] ValueError: Expected bytes type for body with binary Content-Type. Got <class 'str'> type body instead.
Traceback (most recent call last):
  File "/var/task/chalice/app.py", line 836, in __call__
    response = response.to_dict(self.api.binary_types)
  File "/var/task/chalice/app.py", line 375, in to_dict
    self._b64encode_body_if_needed(response, binary_types)
  File "/var/task/chalice/app.py", line 392, in _b64encode_body_if_needed
    body = self._base64encode(body)
  File "/var/task/chalice/app.py", line 400, in _base64encode
    % type(data))

如果我移除了app.api.binary_types =['*/*'],那么/echo可以正常工作,但是我遇到了Chalice Framework: Request did not specify an Accept header with image/jpeg中描述的问题

如何在同一应用程序中同时使用这两个路由?

1 个答案:

答案 0 :(得分:0)

通过将最后一行更改为

来解决
return Response(json.dumps(app.current_request.json_body).encode('utf-8'), status_code=200)

更新

这工作了一段时间,直到遇到其他问题。然后,我根据返回类型将应用程序一分为二。