我有一个问题,我正在寻找执行以下任务的最佳方法。
- 创建内存中的 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 部分
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
请您参考如下方法:
这是我的做法。
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')
对我来说效果很好,如果你尝试这样做,你还会收到错误消息吗?
