tools.py 823 B

12345678910111213141516171819202122232425262728
  1. from django.conf import settings
  2. import datetime
  3. import json
  4. def set_cookie(response, key, value, days_expire = 7):
  5. if days_expire is None:
  6. max_age = 365 * 24 * 60 * 60 # one year
  7. else:
  8. max_age = days_expire * 24 * 60 * 60
  9. expires = datetime.datetime.strftime(
  10. datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
  11. '%a, %d-%b-%Y %H:%M:%S GMT'
  12. )
  13. response.set_cookie(
  14. key,
  15. json.dumps(value),
  16. max_age=max_age,
  17. expires=expires,
  18. domain=settings.SESSION_COOKIE_DOMAIN,
  19. secure=settings.SESSION_COOKIE_SECURE or None
  20. )
  21. def get_cookie(request, key, default):
  22. strval = request.COOKIES.get(key)
  23. if strval:
  24. return json.loads(strval)
  25. return default