|
"""Cookie utility methods |
|
|
|
This module implements a minimal API to consistently and reliably manage |
|
browser cookies. This has two advantages over using the WebOb API: |
|
|
|
1. Using a minimal API allows for more simpler calls specifying the intention |
|
instead of implementation details. For example you must specify a cookie |
|
must be long-lasting isntead of proving an exact expiration time. |
|
2. The implementation works for views that directly return a response object, |
|
removing the need to add (multiple) response callbacks. |
|
""" |
|
import datetime |
|
|
|
|
|
PERSISTENT_COOKIE_TTL = datetime.timedelta(days=365 * 10) |
|
|
|
|
|
def _update_cookies(request, response): |
|
for change in request._cookie_changes: |
|
if change[0] == 'set': |
|
(name, value, type, parent_domain) = change[1:] |
|
domain = request.parent_domain if parent_domain else None |
|
max_age = PERSISTENT_COOKIE_TTL if type == 'persistent' else None |
|
response.set_cookie(name, value, max_age=max_age, domain=domain) |
|
elif change[0] == 'delete': |
|
(name, parent_domain) = change[1:] |
|
domain = request.parent_domain if parent_domain else None |
|
response.delete_cookie(name, domain=domain) |
|
|
|
|
|
def _prepare_request(request): |
|
if not hasattr(request, '_cookie_changes'): |
|
request._cookie_changes = [] |
|
request.add_response_callback(_update_cookies) |
|
|
|
|
|
def set_cookie(request, name, value, type='session', parent_domain=True): |
|
"""Set/update a HTTP cookie. |
|
|
|
:param request: Pyramid request object |
|
:param str name: cookie name |
|
:param str value: cookie value |
|
:param type: the desired cookie type. Must be one of ``session`` to set |
|
a session cookie or ``persistent`` for long-lasting cookies. |
|
:param bool parent_domain: If set to True set the cookie for the parent |
|
domain of the current site. |
|
""" |
|
_prepare_request(request) |
|
request._cookie_changes.append(('set', name, value, type, parent_domain)) |
|
request.cookies[name] = value |
|
|
|
|
|
def delete_cookie(request, name, parent_domain=True): |
|
"""Delete a HTTP cookie. |
|
|
|
:param request: Pyramid request object |
|
:param str name: cookie name |
|
:param bool parent_domain: If set to True set the cookie for the parent |
|
domain of the current site. |
|
""" |
|
_prepare_request(request) |
|
request._cookie_changes.append(('delete', name, parent_domain)) |
|
|
|
|
|
__all__ = ['delete_cookie', 'set_cookie'] |