如何在不使用任何包的情况下从django url加密和解密pk 基本上我有一个类似的网址
example.com/update/1
其中 pk=1
我想像 pk 1 = 345345435cgsfd2asdfaas 一样加密 pk
请您参考如下方法:
我认为没有内置方法,但使用 TimestampSigner ,您可以执行以下操作:
使用 TimestampSigner,您可以加密您的 PK,然后在您需要原始字符串时解密。
>>> from datetime import timedelta
>>> from django.core.signing import TimestampSigner
>>> signer = TimestampSigner()
>>> value = signer.sign(str(pk)) # encrypt the PK.
>>> value
'1:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
>>> value = value.replace(pk,"") # doing this because, it append the original primary key + encrypted string.
>>> value # use this PK to show in the URL.
'1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
>>> repack = "{}:{}".format(pk,value) # When you want back the original PK, add the PK + encrypted string.
>>>repack
'1:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
>>> signer.unsign(repack) # decrypt the PK.
'1'
希望对您有所帮助。
