我有这个最低限度完整的、可验证的示例 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 中描述的问题:请求没有指定带有 image/jpeg 的 Accept 标头
我怎样才能让这两条路线在同一个应用程序中工作?