【问题标题】:CSV File Attachment Error: 'bytes' object has no attribute 'encode'CSV 文件附件错误:“字节”对象没有属性“编码”
【发布时间】:2016-01-27 04:08:22
【问题描述】:

我需要创建一个 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

追溯:get_response 中的文件“/Users/s/.virtualenvs/c/lib/python3.4/site-packages/django/core/handlers/base.py” 111. response = Wrapped_callback(request, *callback_args, **callback_kwargs) _wrapped_view 中的文件“/Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/contrib/auth/decorators.py” 21.在close_poll中返回view_func(request, *args, **kwargs)文件“/Users/stephaniesocias/git/cassie/cassie-app/polls/views.py” 101. create_send_data(poll.id) 文件“/Users/stephaniesocias/git/cassie/cassie-app/polls/tasks.py”在create_send_data 455. msg.send() 发送文件“/Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py” 286. 返回 self.get_connection(fail_silently).send_messages([self]) 文件“/Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/backends/smtp.py”在 send_messages 中 99. send = 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() 消息中的文件“/Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py” 253. msg = self._create_message(msg) 文件“/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" in _create_attachments 325. msg.attach(self._create_attachment(*attachment)) 文件“/Users/stephaniesocias/.virtualenvs/cassie/lib/python3.4/site-packages/django/core/mail/message.py”在_create_attachment 367. 附件 = self._create_mime_attachment(内容,mimetype)文件“/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" in init 175. MIMEText.init(自我,文本,子类型,无)文件“/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/email/mime/text.py”在 初始化 33. 尝试:

异常类型:AttributeError at /poll/81e21783370b46218d6e26d1366b97b8/close/ 异常值:“bytes”对象没有“encode”属性

【问题讨论】:

  • 请显示完整的回溯。看起来您没有使用您的 stringio 缓冲区,因为您仍在使用 attach_file(filename, 'text/csv')
  • @Alasdair 添加了回溯信息-您需要查看更多信息吗?
  • 完整的回溯应该说明你的代码行也引发了错误。正如我在上一条评论中所说,也要考虑一下您的代码,因为您正在写入 stringio 缓冲区但没有使用它。
  • @Alasdair 添加了更多回溯信息;嗯,我从来没有使用过 StringIO 缓冲区,所以这就是我必须出错的地方。我该如何从缓冲区中附加一些东西?

标签: python django csv email-attachments


【解决方案1】:

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

    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()

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 2019-02-02
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多