创建CSV文件、压缩并附加到邮件的最佳方法
我有个问题,我正在寻找一个最佳的方法来完成以下任务。
- 创建一个内存中的CSV文件
- 对它进行压缩(可以是Gzip或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
g = gzip.GzipFile(fileobj=csvobj)
g.close()
代码部分 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
1 个回答
2
这是我会这样做的。
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')
对我来说没问题,如果你试试这个,还是会出错吗?