我需要根据查询结果生成一个csv文件,将生成的文件作为附件添加到电子邮件中并发送。正如你所看到的,我需要遍历分配的线索并将其写入文件中,因此我认为yield会起到作用。现在当我运行代码时,我收到了带有以下消息的附件电子邮件,而不是我预期的行。如果我使用return,我将从查询结果中获取一行。
<generator object data at 0x7f5e508d93c0>
def send_lead_reminder(request):
usercompany = Listing.objects.filter(submitted_by=request.user)
assigned_leads = lead.objects.filter(assigned_to__in=usercompany).distinct()
def data():
csvfile=StringIO.StringIO()
csvwriter =csv.writer(csvfile)
for leads in assigned_leads:
csvwriter.writerow([leads.business_name, leads.first_name, leads.last_name, leads.email, leads.phone_number,leads.address, leads.city, leads.state, leads.zipcode, leads.submission_date, leads.time_frame, leads.comments])
yield csvfile.getvalue()
message = EmailMessage("Hello","Your Leads","myemail@gmail.com",["myemail@gmail.com"])
message.attach('invoice.csv', data(), 'text/csv')
#message.to="myemail@gmail.com"
message.send()
return HttpResponseRedirect('/')
csv.writer()
期望一个文本模式的文件对象,所以在这里使用StringIO
是正确的 - 你需要在附加之前进行编码。我认为csvfile.getvalue().encode(...)
应该足够了 - 可能选择utf-8作为你的编码选择,但也可能是其他东西。 - Peter DeGlopper