Python/Django:无法通过电子邮件发送TempFile,“object没有属性”splitlines“”

2024-04-26 05:42:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个函数,将查询集转换为CSV文件,然后通过电子邮件发送给用户。因为不需要在系统上存储文件,所以我决定使用Tempfile对象。 然而,尽管我成功地写了这些对象,我无法阅读它们-这阻止了我通过电子邮件将它们作为附件

columns = instances[0].get_columns
# create tempfile, in TEXT (t) mode so as not to trip up the
# csv module, which cant handle binary data.
file = tempfile.NamedTemporaryFile(mode='wt')

try:
    writer = csv.writer(file)
    writer.writerow([field[0] for field in columns])

    for instance in instances:
        row = [getattr(instance, str(field[0])) for field in columns]


    # email the file
    body = 'The exported file has been included as a attachment.'
    email = EmailMessage(
    subject='CSV Export',
    from_email='******',
    to=['*****'],
    body=body,
    )
    email.attach('export.csv', file, 'text/csv')
    email.send()

这将触发以下错误: '_io.TextIOWrapper'对象没有属性'splitlines'

经过一番谷歌搜索,我似乎不得不.read()文件 但是,新代码(email.attach('export.csv', file.read(), 'text/csv')unportedOperation:notreadable`错误。在

其他帖子建议,除了.read()之外,我需要使用file.seek(0, os.SEEK_END)来“倒带”文件,但是not readable error一直在触发。在

如果我删除file.read()而保留{} 这将导致返回'_io.TextIOWrapper' object has no attribute 'splitlines'错误。在

有人知道我做错了什么吗?在


Tags: columns文件csv对象instancesinfieldfor