python itsdangerous[留下记录,以便回忆]

python的 itsdangerous 作用:Sometimes you just want to send some data to untrusted environments. But how to do this safely? The trick involves signing. Given a key only you know, you can cryptographically sign your data and hand it over to someone else. When you get the data back you can easily ensure that nobody tampered with it.简单一点讲就是用指定的密钥对“数据”加密,然后可以根据密钥进行解密。

pip install itsdangerous #安装

pip install -U itsdangerous #升级,在python3中用pip3 install itsdangerous

Example Use Cases

  • You can serialize and sign a user ID in a URL and email it to them to unsubscribe from a newsletter. This way you don’t need to generate one-time tokens and store them in the database. Same thing with any kind of activation link for accounts and similar things.
  • Signed objects can be stored in cookies or other untrusted sources which means you don’t need to have sessions stored on the server, which reduces the number of necessary database queries.
  • Signed information can safely do a roundtrip between server and client in general which makes them useful for passing server-side state to a client and then back.

实际中运用:

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired
serial = Serializer(secret_key='your secret key',salt='thisis salt',expires_in=60)#60秒过期
ss = serial.dumps({'username':u'中文','user_id':1})
token = ss.decode()
print(token)
#将生成的字符进行解密
try:
res = serial.loads('eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2MTA0MTk1NiwiZXhwIjoxNTYxMDQyMDE2fQ.eyJ1c2VybmFtZSI6IuadqOS4h-i2hSIsInVzZXJfaWQiOjF9.1wbKHogOjY29sqdNX7l21kn8EWvNBF9LyHWjS6WDEl1smiOKq4i8a5ebHgNkCHTT1toOx9IiGUeKJLcutnkXYg')
print(res)
error = ""
except SignatureExpired:
error = u"你的钥匙过期了"

转载于:https://www.cnblogs.com/cqmay5th/articles/11062002.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值