python中密码的保存和token的生成验证itsdangerous模块

密码的保存:

1
2
import hashlib
hashlib.sha1(config.SECRET_KEY+password).hexdigest()

token的生成和保存:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired

class QXToken(object):
"""
生成/验证 用户token
"""
def __init__(self, name):
self.name = name

def generate_auth_token(self, expiration=3600):
s = Serializer(config.SECRET_KEY, expires_in=expiration)
return s.dumps({'name': self.name})

def verify_auth_token(self, token):
s = Serializer(config.SECRET_KEY)
try:
data = s.loads(token)
print 'data:', data
except SignatureExpired:
return 0 # valid token, but expired
except BadSignature:
return -1 # invalid token
return data['name'] == self.name

#生成token
qxtoken = QXToken('name')
token = qxtoken.generate_auth_token()

#验证token
q = QXToken('name')
res = q.verify_auth_token()