gpt4 book ai didi

python - 如何在 Django 中将 S3 文件附加到电子邮件

转载 作者:行者123 更新时间:2023-12-01 00:23:39 29 4
gpt4 key购买 nike

我正在尝试将保存在 S3 存储桶中的媒体文件附加到电子邮件,我正在使用这行代码执行此操作:

email.attach_file(standard.download.url)

模型定义如下:

class Standard(models.Model):
name = models.CharField(max_length = 51)
download = models.FileField(upload_to="standard_downloads/", null=True, blank=True)

def __str__(self):
return self.name

settings.py中,我定义了我的媒体文件,如下所示:

AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
DEFAULT_FILE_STORAGE = 'sme.storage_backends.MediaStorage'
MEDIA_ROOT = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME

当尝试运行我得到的代码时

No such file or directory: 'https:/bucket-name.s3.amazonaws.com/media/standard_downloads/filename.ext

请注意,它显示为 https:// (单个/)。我该如何纠正这个问题?

最佳答案

这是 Django 的 attach_file 源代码。它清楚地表明 - 从文件系统附加文件。它不适用于远程 URL。当你给它一个 url 时,它认为你指的是本地文件,因此它将所有双斜杠转义为单斜杠。

def attach_file(self, path, mimetype=None):
"""
Attach a file from the filesystem.

Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified
and cannot be guessed.

For a text/* mimetype (guessed or specified), decode the file's content
as UTF-8. If that fails, set the mimetype to
DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
"""
path = Path(path)
with path.open('rb') as file:
content = file.read()
self.attach(path.name, content, mimetype)

Django 没有为此提供任何内置内容。您还必须使用 requestboto 等库在上述代码行上编写一些自定义内容。基本上,这个想法是从远程 url 获取保存为临时文件,然后使用 attach

以下是有关如何即时获取文件的一个示例:

from django.core.mail.message import attach
import requests
response = requests.get("http://yoururl/somefile.pdf")
email.attach('My file',response.read(),mimetype="application/pdf")

关于python - 如何在 Django 中将 S3 文件附加到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58777644/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com