Django如何生成邮件激活的自动激活密钥link

Django how to generate an automatic activation key for email activation link

我想知道如何生成自动激活密钥以连接到我的电子邮件激活中 link 那就是发送的 link : http://localhost:8001/sign_up/60/subsribe/14/confirmEmail 但为了更安全,我想发送类似的内容:http://localhost:8001/sign_up/60/subsribe/14/confirmEmail/{{ activation_key }}

mail = EmailMultiAlternatives("Confirmation d\'email pour finaliser votre inscripttion","pour finaliser votre inscription, veuillez consulter le lien ci-dessus ",from_email, to=[email])

mail.attach_alternative('http://localhost:8001/sign_up/' + str(id_account) + '/subscribe/' + str(id_sub) + '/confirmEmail',"text/html")

mail.send()

您可以使用 Signer class 来实现这一点。即

from django.core.signing import Signer
signer = Signer()
signed_value = signer.sign(profile.user.email)#gives 'email@email.com:signed_things', extract signed_things'
key = ''.join(signed_value.split(':')[1:])
#send out key as part of url

然后您可以将密钥与用户个人资料一起存储。当请求 link 时,您可以执行以下操作:

profile = get_object_or_404(UserProfile, key=key)
signer = Signer()
if signer.unsign('{0}:{1}'.format(profile.user.email, key)) == profile.user.email:
    profile.verified = True