在使用django 2.0的python 3.6上,对字节文字的解码不能按预期工作。
是的,当我打印它时,我得到了正确的结果,但即使你正确打印它,b'值仍然存在。
这就是im编码
uid': urlsafe_base64_encode(force_bytes(user.pk)),
这就是即时解码:
uid = force_text(urlsafe_base64_decode(uidb64))
这就是django 2.0所说的:
urlsafe_base64_encode(s)[source]
在base64中对字节串进行编码,以便在URL中使用,剥去任何尾随等号。
urlsafe_base64_decode(s)[source]
解码base64编码的字符串,添加可能已被剥离的任何尾随等号。
这是我的account_activation_email_test.html文件
{% autoescape off %}
Hi {{ user.username }},
Please click on the link below to confirm your registration:
http://{{ domain }}{% url 'accounts:activate' uidb64=uid token=token %}
{% endautoescape %}
这是我的主机响应:
Content-Type:text / plain;字符集= “UTF-8”
MIME版本:1.0
内容传输编码:7位
主题:激活您的MySite帐户
来自:webmaster @ localhost
致:testuser@yahoo.com
日期:星期五,2018年4月20日06:26:46 -0000
消息ID:< 152420560682.16725.4597194169307598579@Dash-U>
嗨testuser,
请点击以下链接确认您的注册:
http://127.0.0.1:8000/activate/b'MjU'/4vi-fasdtRf2db2989413ba/
,您可以看到uid = b'MjU'
预期uid = MjU
在控制台中测试:
$ python
Python 3.6.4 (default, Apr 7 2018, 00:45:33)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
>>> from django.utils.encoding import force_bytes, force_text
>>> var1=urlsafe_base64_encode(force_bytes(3))
>>> print(var1)
b'Mw'
>>> print(var1.decode())
Mw
>>>
经过调查,它似乎与python 3有关。
我的解决方法非常简单:
'uid': user.pk,
我在激活功能上以uidb64的形式收到它:
user = User.objects.get(pk=uidb64)
瞧:
Content-Transfer-Encoding: 7bit
Subject: Activate Your MySite Account
From: webmaster@localhost
To: testuser@yahoo.com
Date: Fri, 20 Apr 2018 20:44:46 -0000
Message-ID: <152425708646.11228.13738465662759110946@Dash-U>
Hi testuser,
Please click on the link below to confirm your registration:
http://127.0.0.1:8000/activate/45/4vi-3895fbb6b74016ad1882/
现在它运作正常。 :)