使用API Gateway和Lambda向Smartsheet附加PDF的Base64解码问题
问题描述
通过API Gateway和Lambda向Smartsheet的行附加PDF文件时,请求体包含疑似Unicode格式的字符串,执行以下代码时触发Non-base64 digit found错误:
temp = tempfile.NamedTemporaryFile() with open(temp.name, "wb") as file: file_content = base64.b64decode(bytes(event['body'], 'utf-8'), validate=True) file.write(file_content) response = smartsheet_client.Attachments.attach_file_to_row(1234, 1234, ( 'test.pdf', open(temp.name, "rb"), "application/pdf" ))
将validate=True改为False后错误消失,但希望找到正确的解码方式,确保PDF能正常写入并发送到Smartsheet。
解决方案
问题出在哪
请求体里的字符串不是纯Base64格式,主要两个原因:
- API Gateway可能把原始请求体做了Unicode转义,变成带
\uXXXX的字符串 - 字符串里混了换行、空格这类非Base64允许的字符,
validate=True时就会报错
正确处理步骤
- 转义回正常字符串:如果
event['body']是带\uXXXX的格式,先把它转成真实的Base64字符串 - 清理无效字符:把所有Base64不允许的字符(仅保留
A-Za-z0-9+/=)都删掉 - 安全解码写文件:用清理后的字符串解码,保留
validate=True提前发现无效数据
修正后的代码
import tempfile import base64 import re import os def lambda_handler(event, context): # 处理Unicode转义的请求体 raw_body = event['body'] decoded_body = raw_body.encode('utf-8').decode('unicode-escape') # 清理Base64字符串,移除非法字符 clean_base64 = re.sub(r'[^A-Za-z0-9+/=]', '', decoded_body) # 创建临时文件(设delete=False避免自动删除) temp = tempfile.NamedTemporaryFile(delete=False) try: with open(temp.name, "wb") as file: file_content = base64.b64decode(clean_base64, validate=True) file.write(file_content) # 附加PDF到Smartsheet行 response = smartsheet_client.Attachments.attach_file_to_row( 1234, 1234, ('test.pdf', open(temp.name, "rb"), "application/pdf") ) return {'statusCode': 200, 'body': 'Attachment successful'} finally: # 清理临时文件 os.unlink(temp.name)
额外提示
如果API Gateway用了Lambda Proxy Integration,可以先检查event['isBase64Encoded']字段:如果值为True,直接用base64.b64decode(event['body'], validate=True)即可,无需处理Unicode转义。
内容的提问来源于stack exchange,提问作者Justin Domingo
相关产品推荐
相关产品推荐

