Skip to content

Instantly share code, notes, and snippets.

@kzinglzy
Created November 3, 2014 12:15
Show Gist options
  • Save kzinglzy/f0b08cb03c2aec4cd999 to your computer and use it in GitHub Desktop.
Save kzinglzy/f0b08cb03c2aec4cd999 to your computer and use it in GitHub Desktop.
Session with Python
#!/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)
@kxxoling
Copy link

kxxoling commented Nov 3, 2014

你这代码风格=。=|||

@kzinglzy
Copy link
Author

kzinglzy commented Nov 4, 2014

欢迎围观https://github.com/Kzinglzy/hiblog 查找更多的42web风格代码: D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment