【问题标题】:Issue encoding an email for my app为我的应用程序编码电子邮件
【发布时间】:2015-08-14 16:31:48
【问题描述】:

我正在配置一个仅使用电子邮件操作订阅的应用程序,除了我的表单的一部分应该对收到的所有电子邮件进行编码之外,所有操作都运行良好。

这是我用邮箱注册时出现的错误:

**Unicode-objects must be encoded before hashing**

Traceback: File "/home/draicore/SUNFLOWER/AMBIENTE1/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132. response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "/home/draicore/SUNFLOWER/AMBIENTE1/lib/python3.4/site-packages/django/views/generic/base.py" in view
  71. return self.dispatch(request, *args, **kwargs) 
File "/home/draicore/SUNFLOWER/AMBIENTE1/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
  89. return handler(request, *args, **kwargs) 
File "/home/draicore/SUNFLOWER/AMBIENTE1/lib/python3.4/site-packages/django/views/generic/edit.py" in post
  214. if form.is_valid(): 
File "/home/draicore/SUNFLOWER/AMBIENTE1/lib/python3.4/site-packages/django/forms/forms.py" in is_valid
  184. return self.is_bound and not self.errors 
File "/home/draicore/SUNFLOWER/AMBIENTE1/lib/python3.4/site-packages/django/forms/forms.py" in errors
  176. self.full_clean() 
File "/home/draicore/SUNFLOWER/AMBIENTE1/lib/python3.4/site-packages/django/forms/forms.py" in full_clean
  393. self._clean_form() 
File "/home/draicore/SUNFLOWER/AMBIENTE1/lib/python3.4/site-packages/django/forms/forms.py" in _clean_form
  417. cleaned_data = self.clean() 
File "/home/draicore/SUNFLOWER/GIRASOL/apps/newsletter/forms.py" in clean
  47. self.cleaned_data['activation_key'] = generate_activation_key(data['email']) 
File "/home/draicore/SUNFLOWER/GIRASOL/apps/newsletter/forms.py" in generate_activation_key
  16. salt = hashlib.md5(str(random.random())).hexdigest()[:10]

Exception Type: TypeError at /request/ 
Exception Value: Unicode-objects must be encoded before hashing

我有这个代码负责在我的 forms.py 上编码电子邮件:

def generate_activation_key(email):
    if isinstance(email, str):
        email = email.encode('utf-8')
    salt = hashlib.md5(str(random.random()).encode('utf-8')).hexdigest()[:10]
    return hashlib.md5(salt+email).hexdigest()


class EmailSubscriberForm(forms.ModelForm):
    email = forms.EmailField(max_length=256, label=_('Email'), required=True)
    captcha = CaptchaField(label=_('Security code'))
    activation_key = forms.CharField(widget=forms.HiddenInput(), required=False)
    activation_request_sent_at = forms.DateField(widget=forms.HiddenInput(), required=False)

    class Meta:
        model = EmailSubscriber
        fields = (
            'email',
            'activation_key',
            'activation_request_sent_at',
        )

    def clean_email(self):
        email = self.cleaned_data['email'].strip()
        try:
            self.instance = EmailSubscriber.objects.get(email__iexact=email)
            if self.instance is not None:
                return email.lower()
        except EmailSubscriber.DoesNotExist:
            return email.lower()
        raise forms.ValidationError(_('This email is already subscribed.'))

    def clean(self):
        data = self.cleaned_data
        if 'email' in data:
            self.cleaned_data['activation_key'] = generate_activation_key(data['email'])
            self.cleaned_data['activation_request_sent_at'] = timezone.now()
        return self.cleaned_data

我相信这个问题是由 python 版本不兼容引起的(我有 Python 3.4.1),我试图在这里寻找其他问题的解决方案,我找到了关于设置新格式的答案.encode('utf-8')。我不知道我应该改变什么。

如果我忽略了什么,请提前向我道歉。欢迎投稿,感谢评价!

祝你有美好的一天!

【问题讨论】:

    标签: python django forms python-2.7 email


    【解决方案1】:

    您还应该对您的 random 盐字符串进行编码:

    str(random.random()).encode('utf-8')
    

    但是,您将收到一个新错误...因为emailbytessaltstring。我将由您决定如何规范化这些,以便可以将它们相加。

    【讨论】:

    • 感谢您的评价!我曾试图这样写,但我得到了这个错误Can't convert 'bytes' object to str implicitly,正如你所说的
    • 这就是我在回答的第二部分中所说的。您需要将email 转换为字符串,或将salt 转换为字节。
    猜你喜欢
    • 2010-12-20
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多