创建CSV的最佳方法,压缩它并用Emai附加

2024-05-14 14:18:16 发布

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

我有一个问题,我正在寻找执行以下任务的最佳方法。在

  • 在内存中创建csv文件
  • 压缩它(Gizip或Zip)
  • 随邮件附上

我很难找到确切的解决办法,我正在寻找。在

这是我的密码。在

代码

prospects = Customer.objects.filter(state_id=2)
csvfile = StringIO.StringIO()
writer = UnicodeWriter(csvfile, encoding='utf-8')
writer.writerow(["Name", "Email"])
for prospect in prospects:
    writer.writerow(
        [prospect.name, prospect.email]
    )
csvobj = csvfile.getvalue() # not sure about it. 

代码第2部分

^{pr2}$

代码第3部分

  msg = EmailMultiAlternatives(
            subject="Innovation",
            body="text_context",
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=["bac@gmail.com"]
        )
  msg.attach("z.gzip",g, 'application/zip')
  msg.send(True)

错误

TypeError: 'GzipFile' object does not support indexing

Tags: 文件csvcsvfile方法内存代码emailnot
1条回答
网友
1楼 · 发布于 2024-05-14 14:18:16

这是我该怎么做的。

import StringIO
import tablib

headers = ["name", "Email"]
values = Customer.objects.filter(state_id=2).values_list(‘name’, ‘email’)
data = tablib.Dataset(*values, headers=headers)

csvfile = StringIO.StringIO()
csvfile.write(data.csv)

gzipped = gzip.GzipFile(mode='wb', fileobj=csvfile.getvalue())
gzipped.close()

# msg stuff...
msg.attach("z.gzip", gzipped, 'application/zip')

对我来说很好,如果你这么做你还会出错吗?

相关问题 更多 >

    热门问题