如何在同一圣杯应用程序中从不同的路由返回图像和json? [英] How to have image and json returned from separate routes in same Chalice application?

查看:66
本文介绍了如何在同一圣杯应用程序中从不同的路由返回图像和json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

就目前而言,/get-photo路由可以正常工作,但是/echo端点在用curl -H "Content-Type: application/json" -X POST -d '{"test":1}' https://...

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))

如果删除app.api.binary_types =['*/*'],则/echo可以正常工作,但我遇到了

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?

推荐答案

通过将最后一行更改为

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

更新

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

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.

这篇关于如何在同一圣杯应用程序中从不同的路由返回图像和json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆