CSV文件附件错误:'字节'对象没有属性' encode'

时间:2015-10-27 16:19:31

标签: python django csv email-attachments

我需要创建一个CSV文件并将其作为电子邮件附件发送。我想在内存中创建文件,以便它实际上不占用我的文件系统中的空间。当我尝试发送电子邮件时,我似乎已经开始工作了,除非我收到错误:'bytes' object has no attribute 'encode'任何想法出了什么问题?

    from django.core.mail import EmailMultiAlternatives
    import csv, io

    csvfile = io.StringIO()
    fieldnames = ['user_id', 'user_name', 'user_forecast', 'is_correct', 'correct_answer',
        'forecast_to_event_seconds']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for f in forecasts:
        writer.writerow({'user_id': f.profile.id, 'user_name': f.profile.name,
            'user_forecast': f.answer_text, 'is_correct': f.is_correct, 'correct_answer': correct_answer, 
            'forecast_to_event_seconds': (event_end-f.created_on).total_seconds()})

    # Send email with CSV attachment
    subject='Data'
    to=["hello@me.com",]
    from_email=from_email
    context={'group': group.replace('-', ' '), 'question': poll.question, 'site': Site.objects.get_current(),
        'STATIC_URL': settings.STATIC_URL}
    template='polls/notifications/castie_data.txt'
    message = render_to_string('polls/notifications/castie_data.txt', context)

    msg = EmailMultiAlternatives(subject, message, to=to, from_email=from_email)
    msg.attach_alternative(render_to_string('polls/notifications/castie_data.html', context), 'text/html')

    file_name = "%s-%s.csv" % (group, poll.question.replace(' ', '-'))
    msg.attach_file(file_name, 'text/csv')
    msg.content_subtype = "html"
    msg.send()

完整追溯:

环境:

请求方法:POST请求网址:http://localhost:8000/poll/81e21783370b46218d6e26d1366b97b8/close/

Django版本:1.7.7 Python版本:3.4.3

Traceback:File" /Users/s/.virtualenvs/c/lib/python3.4/site-packages/django/core/handlers/base.py"在get_response中   111.response = wrapped_callback(request,* callback_args,** callback_kwargs)File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/contrib/auth/decorators.py&# 34;在_wrapped_view中   21. return view_func(request,* args,** kwargs)File" /Users/stephaniesocias/git/cassie/cassie-app/polls/views.py"在close_poll   101. create_send_data(poll.id)File" /Users/stephaniesocias/git/cassie/cassie-app/polls/tasks.py"在create_send_data中   455. msg.send()File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py"发送   286. return self.get_connection(fail_silently).send_messages([self])File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/backends/smtp的.py"在send_messages中   99. sent = self._send(message)File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/backends/smtp.py"在_send   113. message = email_message.message()File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py"在消息中   253. msg = self._create_message(msg)File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py"在_create_message中   409. return self._create_attachments(self._create_alternatives(msg))File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py" ;在_create_attachments中   325. msg.attach(self._create_attachment(* attachment))File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py" ;在_create_attachment中   367. attachment = self._create_mime_attachment(content,mimetype)File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py"在_create_mime_attachment中   338. attachment = SafeMIMEText(content,subtype,encoding)File" /Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py"在 init   175. MIMEText。 init (自我,文本,子类型,无)文件" /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/email/mime/text的.py"在 init   33.尝试:

异常类型:AttributeError at / poll / 81e21783370b46218d6e26d1366b97b8 / close / Exception Value:' bytes'对象没有属性'编码'

1 个答案:

答案 0 :(得分:-2)

不是最优雅的解决方案,但它有效:

    import csv, io
    csvfile = io.StringIO()
    fieldnames = ['user_id', 'user_name', 'user_forecast', 'is_correct', 'correct_answer',
        'forecast_to_event_seconds', 'answer_types']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for f in forecasts:
        writer.writerow({'user_id': f.profile.id, 'user_name': f.profile.name,
            'user_forecast': f.answer_text, 'is_correct': f.is_correct, 'correct_answer': correct_answer, 
            'forecast_to_event_seconds': (event_end-f.created_on).total_seconds(), 'answer_types': poll.answer_type})

    # Send email with CSV attachment
    subject='Data'
    to=["hello@me.com",]
    from_email=from_email
    context={'group': group.replace('-', ' '), 'question': poll.question, 'site': Site.objects.get_current(),
        'STATIC_URL': settings.STATIC_URL}
    template='polls/notifications/castie_data.txt'
    message = render_to_string('polls/notifications/castie_data.txt', context)

    msg = EmailMultiAlternatives(subject, message, to=to, from_email=from_email)
    msg.attach_alternative(render_to_string('polls/notifications/castie_data.html', context), 'text/html')

    file_name = "%s-%s.csv" % (group, poll.question.replace(' ', '-'))
    csv_file = csvfile.getvalue()
    msg.attach(file_name, csv_file,'text/csv')
    msg.content_subtype = "html"
    msg.send()