python - 尝试从 S3 发送文件作为电子邮件附件时,字节类型的对象不是 JSON 可序列化的
问题描述
错误信息:
"errorMessage": "bytes 类型的对象不是 JSON 可序列化的"
def _get_file():
s3 = boto3.resource('s3')
obj = s3.Object(S3_BUCKET_NAME, S3_ITEM_NAME)
return obj.get()['Body'].read()
def _send_email_with_ebook(email):
data = {
...
"attachments": [
{
"content": _get_ebook_file(),
"type": "application/pdf",
"filename": "my_file.pdf"
}
]
}
headers = {'Authorization': 'Bearer {}'.format(SENDGRID_API_KEY), 'Content-Type': 'application/json'}
r = requests.post(SENDGRID_API_URL, json=data, headers=headers)
解决方案
您需要对您的文件内容进行 base64 编码,例如:
import base64
def _get_file():
s3 = boto3.resource('s3')
obj = s3.Object(S3_BUCKET_NAME, S3_ITEM_NAME)
return obj.get()['Body'].read()
def _send_email_with_ebook(email):
data = {
...
"attachments": [
{
"content": base64.b64encode(_get_ebook_file()),
"type": "application/pdf",
"filename": "my_file.pdf"
}
]
}
headers = {'Authorization': 'Bearer {}'.format(SENDGRID_API_KEY), 'Content-Type': 'application/json'}
r = requests.post(SENDGRID_API_URL, json=data, headers=headers)
推荐阅读
- vue.js - Vue 组件中没有听到 $emit 事件
- c# - 如何使用查询在表中选择最新日期
- python - 哪个多项式回归次数显着?取决于点数或其他参数?
- java - 原因:java.lang.RuntimeException:java.lang.String 不是日期模式的有效外部类型
- javascript - 通过传递一些数据来响应本机深度链接和回退到网页
- r - glmnet 出错?说我有 NA 但我删除了那些?
- php - 什么时候根据 woocomerce 事件触发我的发布请求,以及如何控制台我的 php 代码以便我可以调试
- python - 在导入中包含包层次结构
- mule - 从 Mule Dataweave 过滤 Json 数组
- python - “ImageField”字段中的默认图像 - Django