Created
November 3, 2014 12:15
-
-
Save kzinglzy/f0b08cb03c2aec4cd999 to your computer and use it in GitHub Desktop.
Session with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding:utf-8 | |
from os import urandom | |
from base64 import urlsafe_b64decode, urlsafe_b64encode | |
import redis | |
import binascii | |
redis = redis.StrictRedis('localhost') | |
R_SESION = "SESSION:%s" | |
class Session: | |
EXPIRE_DAY = 365 | |
@classmethod | |
def new(cls, account, expire=EXPIRE_DAY * 24 * 3660): | |
if account: | |
key = R_SESION % account | |
s = redis.get(key) or urandom(12) | |
redis.setex(key, expire, s) | |
return _encode(account, s) | |
@classmethod | |
def rm(cls, id): | |
key = R_SESION % id | |
if key: | |
redis.delete(key) | |
@classmethod | |
def account_by_session(cls, cookie): | |
account, binary = _decode(cookie) | |
if account: | |
key = R_SESION % account | |
if binary and binary == redis.get(key): | |
return account | |
def _decode(session): | |
if not session: | |
return None, None | |
try: | |
account_value = urlsafe_b64decode(session) | |
except (binascii.Error, TypeError): | |
return None, None | |
return account_value.split('-', 1) # (account, session_value) | |
def _encode(account, session, encode=urlsafe_b64encode): | |
return urlsafe_b64encode('{}-{}'.format(account, session)) | |
if __name__ == '__main__': | |
name = "test" | |
session = Session.new(name) | |
print session | |
print Session.account_by_session(session) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
你这代码风格=。=|||