You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用awsgi部署Flask到AWS Lambda时遭遇UnicodeDecodeError问题

AWS Lambda部署Flask PDF解密程序的UnicodeDecodeError问题及解决

问题场景

用Flask结合PyPDF2开发了一个PDF解密程序,本地运行完全正常,能正确返回解密后的PDF文件,但部署到AWS Lambda后,日志抛出如下编码错误:

[ERROR] UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 69, in lambda_handler
    return awsgi.response(app, event, context)
  File "/opt/python/awsgi/__init__.py", line 173, in response
    return sr.response(output)
  File "/opt/python/awsgi/__init__.py", line 95, in response
    rv = super(StartResponse_GW, self).response(output)
  File "/opt/python/awsgi/__init__.py", line 89, in response
    rv.update(self.build_body(headers, output))
  File "/opt/python/awsgi/__init__.py", line 75, in build_body
    converted_output = convert_str(totalbody)
  File "/opt/python/awsgi/__init__.py", line 12, in convert_str
    return s.decode('utf-8') if isinstance(s, bytes) else s

尝试过将awsgi/init.py中的utf-8替换为ISO-8859-1,虽然不再报错,但返回的是两页空白PDF(原加密文件为两页)。原程序逻辑为:解密文件后生成临时NamedTemporaryFile对象,再通过send_from_directory返回文件。

解决方法

放弃使用send_from_directory返回文件,改为对解密后的PDF内容进行base64编码后传输,在接收端(Laravel应用)解码还原为PDF文件。该方法解决了问题,推测是awsgi不支持原方式直接返回二进制文件。

内容的提问来源于stack exchange,提问作者if_loop98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 22:05:02