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

Hen*_*ryM 3 python django amazon-s3 boto3

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

email.attach_file(standard.download.url)
Run Code Online (Sandbox Code Playgroud)

该模型定义如下:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

当我尝试运行代码时

没有这样的文件或目录:'https:/bucket-name.s3.amazonaws.com/media/standard_downloads/filename.ext

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

bha*_*arc 5

这是attach_file来自 Django的源代码。它清楚地说明 - 从文件系统附加文件。它不适用于远程网址。当你给它一个 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)
Run Code Online (Sandbox Code Playgroud)

Django 没有为此提供任何内置的东西。您还必须使用request或 之类的库在上述代码行上编写一些自定义内容boto。基本上这个想法是从远程 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")
Run Code Online (Sandbox Code Playgroud)

  • 将 `response.read()` 更改为 `response.content` 并且它有效。谢谢 (2认同)