django写入csv并发送邮件
import csv
import io
from django.core.mail import EmailMessage
from datetime import datetime
from django.conf import settings
def post(self, request):
failed_list = [{"渠道":"taobao","收货人姓名":"skycc","联系手机":17621948046,"产品品类":1,"运动次数":0},...]
message, csvfile = self.other()
header = ["渠道","收货人姓名","联系手机","产品品类","运动次数"]
if failed_list:
self.deal_data(failed_list, header,
"莫比名单", message, csvfile)
def other(self):
csvfile = io.StringIO()
msg_from = settings.EMAIL_FROM_USER
msg_to = settings.COURSE_RECIEVER
message = EmailMessage('data_info{}'.format(datetime.now().date()), from_email=msg_from, to=msg_to)
message.encoding = "utf_8_sig"
return message, csvfile
def send_email(self,message, csvfile):
message.send()
csvfile.close()
def deal_data(self, row, header, res, message, csvfile):
dictWriter = csv.DictWriter(csvfile, fieldnames=header)
dictWriter.writeheader()
for i in row:
dictWriter.writerow(i)
message.attach('{}.csv'.format(res), csvfile.getvalue(), 'text/csv')
csvfile.seek(0)
csvfile.truncate(0)
self.send_email(message, csvfile)