Cookies¶
Reading a cookie¶
The easiest way to read a single cookie is to query the request.cookies
attribute. This is a MultiDict
mapping cookie names to single
instances of Cookie
:
from fresco import context, Response, FrescoApp
from fresco.exceptions import Forbidden
def view():
secret = context.request.cookies.get('secret')
if secret == 'marmot':
return Response(['pass, friend'])
else:
return Response.forbidden()
Setting cookies¶
Call response.add_cookie
to add a cookie to the response.
Note that by default fresco adds SameSite=Lax
to all cookies.
def view():
response = Response(["content"])
return response.add_cookie(
'partnumber',
'Rocket_Launcher_0001',
path='/acme',
max_age=3600,
domain='example.com',
samesite='None',
secure=True
)
Clearing cookies¶
Delete a cookie by calling delete_cookie()
:
return response.delete_cookie('partnumber')
API reference: fresco.cookie¶
- class fresco.cookie.Cookie(name, value, max_age=None, expires=None, path='/', secure=False, domain=None, comment=None, httponly=False, samesite='Lax', version=1)[source]¶
Represents an HTTP cookie.
See rfc2109, HTTP State Management Mechanism
Example:
>>> from fresco.cookie import Cookie >>> c = Cookie('session_id', 'abc123') >>> c.path = '/cgi-bin' >>> c.domain = '.example.org' >>> c.path '/cgi-bin' >>> str(c) 'session_id=abc123;Domain=.example.org;Path=/cgi-bin;SameSite=Lax'
- property expires¶
Return the cookie
expires
value as an instance ofdatetime
.
- fresco.cookie.expire_cookie(cookie_or_name: Any, *args, **kwargs)[source]¶
Synopsis:
>>> from fresco import Response >>> from fresco.cookie import expire_cookie >>> def view(): ... return Response(set_cookie=expire_cookie('X', path='/')) ... >>> from fresco import FrescoApp >>> with FrescoApp().requestcontext() as c: ... print(view().get_header('Set-Cookie')) ... X=;Expires=Tue, 01 Jan 1980 00:00:00 GMT;Max-Age=0;Path=/;SameSite=Lax
- fresco.cookie.format_date(utctimetuple)[source]¶
Format a date for inclusion in a Set-Cookie header, eg ‘Sun, 06 Nov 1994 08:49:37 GMT’.
According to RFC6265, this must be an “rfc1123-date, defined in RFC2616, Section 3.3.1”
RFC2616 says in turn:
HTTP applications have historically allowed three different formats for the representation of date/time stamps:
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 Sun Nov 6 08:49:37 1994 ; ANSI C’s asctime() format
The first format is preferred as an Internet standard[…]
- fresco.cookie.parse_cookie_header(cookie_string, unquote=<function unquote>)[source]¶
Return a list of cookie (name, value) pairs read from the request headers.
- Parameters:
cookie_string – The cookie, eg
CUSTOMER=FRED
unquote – A function to decode values. By default values are assumed to be url quoted. If
None
the raw value will be returned