How to have image and json returned from separate routes in same Chalice application?

让人想犯罪 __ 提交于 2019-12-13 03:01:24

问题


I have this minimally complete, verifiable example Chalice application:

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)

As it stands, the /get-photo route works fine, but the /echo endpoint fails when invoked with 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))

If I remove the app.api.binary_types =['*/*'], then the /echo works fine but I run instead into the issue described in Chalice Framework: Request did not specify an Accept header with image/jpeg

How can I get both of these routes working in the same application?


回答1:


Fixed by changing the last line to

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

UPDATE

This worked for a while until I ran into additional issues. Then I ended up splitting the application into two based on the return type.



来源:https://stackoverflow.com/questions/56201915/how-to-have-image-and-json-returned-from-separate-routes-in-same-chalice-applica

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!