|
from YourProjectName import settings |
|
import datetime |
|
|
|
_unit = dict( |
|
s=1, |
|
m=60, |
|
h=3600, |
|
d=86400, |
|
) |
|
|
|
try: |
|
if isinstance(settings.COOKIE_EXPIRE, (str, unicode)): |
|
if settings.COOKIE_EXPIRE[-1].lower() in 'smhd': |
|
num = int(settings.COOKIE_EXPIRE[:-1]) |
|
_expire = num * _unit[settings.COOKIE_EXPIRE[-1].lower()] |
|
else: |
|
_expire = int(settings.COOKIE_EXPIRE) |
|
elif isinstance(settings.COOKIE_EXPIRE, (int, long)): |
|
_expire = int(settings.COOKIE_EXPIRE) |
|
else: |
|
_expire = int(str(settings.COOKIE_EXPIRE)) |
|
except: |
|
_expire = 86400 * 7 # 7 days |
|
|
|
class CookieIO(object): |
|
def __init__(self, handler): |
|
''' |
|
@param handler: CookieHandler |
|
''' |
|
self._handler = handler |
|
self._expire = _expire |
|
|
|
|
|
def get(self, key, default=None): |
|
return self._handler.cookie.get(key=key, default=default) |
|
|
|
def set(self, key, value, expire=_expire, domain=None, secure_only=None, httponly=False): |
|
if secure_only is None: |
|
secure_only = self._handler.request.is_secure() |
|
self._handler.set_cookie(key=key, value=value, expire=expire, domain=domain, secure_only=secure_only, httponly=httponly) |
|
|
|
def remove(self, key, domain=None, secure_only=None, httponly=False): |
|
if secure_only is None: |
|
secure_only = self._handler.request.is_secure() |
|
self.set(key=key, value='XXX', expire=-233333333, domain=domain, secure_only=secure_only, httponly=httponly) |
|
|
|
def __delitem__(self, key): |
|
self.remove(key) |
|
|
|
def __getitem__(self, key): |
|
return self._handler.cookie.__getitem__(key) |
|
|
|
def __setitem__(self, key, value): |
|
if not isinstance(key, (str, unicode)): |
|
raise KeyError('key should be a string or unicode') |
|
if not isinstance(value, (str, unicode)): |
|
if hasattr(value, '__str__'): |
|
value = value.__str__() |
|
elif hasattr(value, '__unicode__'): |
|
value = value.__unicode__() |
|
else: |
|
raise ValueError('value can not be converted to string or unicode.') |
|
|
|
self.set(key=key, value=value) |
|
|
|
class CookieHandler(object): |
|
def __init__(self): |
|
self.changed_cookie = {} |
|
|
|
def _make_time(self, life): |
|
return datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=life), '%a, %d %b %Y %H:%M:%S GMT') |
|
|
|
def set_cookie(self, key, value, expire, domain, secure_only, httponly): |
|
self.changed_cookie[key] = (value, expire, domain, secure_only, httponly) |
|
|
|
def process_request(self, request): |
|
self.cookie = request.COOKIES |
|
self.request = request |
|
request.Cookies = CookieIO(self) |
|
|
|
def process_response(self, request, response): |
|
for cookie in self.changed_cookie.iteritems(): |
|
key, values = cookie |
|
response.set_cookie(key=key, value=values[0], expires=self._make_time(values[1]), domain=values[2], secure=values[3], httponly=values[4]) |
|
return response |
|
|