sanic.cookies.request.CookieRequestParameters#

A container for accessing single and multiple cookie values.

Inherits from: RequestParameters, dict

class CookieRequestParameters(self)

Because the HTTP standard allows for multiple cookies with the same name, a standard dictionary cannot be used to access cookie values. This class provides a way to access cookie values in a way that is similar to a dictionary, but also allows for accessing multiple values for a single cookie name when necessary.

Parameters
cookies
Dict[str, List[str]]

A dictionary containing the cookie names as keys and a list of values for each cookie.

Examples
raw = 'name1=value1; name2="value2"; name3=value3'
cookies = parse_cookie(raw)
# cookies will be {'name1': ['value1'], 'name2': ['value2'], 'name3': ['value3']}

request_cookies = CookieRequestParameters(cookies)
request_cookies['name1']  # 'value1'
request_cookies.get('name1')  # 'value1'
request_cookies.getlist('name1')  # ['value1']

get#

Return the first value, either the default or actual

def get(self, name: <class 'str'>, default: typing.Optional[typing.Any] = None): -> typing.Optional[typing.Any]

Parameters
name
str

The name of the parameter

default
Optional[Any]

The default value. Defaults to None.

Return
Optional[Any]

The first value of the list

getlist#

Return the entire list

def getlist(self, name: <class 'str'>, default: typing.Optional[typing.Any] = None): -> typing.Optional[typing.Any]

Parameters
name
str

The name of the parameter

default
Optional[Any]

The default value. Defaults to None.

Return
Optional[Any]

The entire list

sanic.cookies.request.parse_cookie#

Parses a raw cookie string into a dictionary.

def parse_cookie(raw: <class 'str'>): -> typing.Dict[str, typing.List[str]]

The function takes a raw cookie string (usually from HTTP headers) and returns a dictionary where each key is a cookie name and the value is a list of values for that cookie. The function handles quoted values and skips invalid cookie names.

Parameters
raw
str

The raw cookie string to be parsed.

Return
Dict[str, List[str]]

A dictionary containing the cookie names as keys and a list of values for each cookie.

Examples
raw = 'name1=value1; name2="value2"; name3=value3'
cookies = parse_cookie(raw)
# cookies will be {'name1': ['value1'], 'name2': ['value2'], 'name3': ['value3']}

A representation of a HTTP cookie, providing an interface to manipulate cookie attributes intended for a response.

Inherits from: dict

class Cookie(key: str, value: str, path: str = "/", domain: Optional[str] = None, secure: bool = True, max_age: Optional[int] = None, expires: Optional[datetime] = None, httponly: bool = False, samesite: Optional[SameSite] = Lax, partitioned: bool = False, comment: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False)

This class is a simplified representation of a cookie, similar to the Morsel SimpleCookie in Python's standard library. It allows the manipulation of various cookie attributes including path, domain, security settings, and others.

Several "smart defaults" are provided to make it easier to create cookies that are secure by default. These include:

  • Setting the secure flag to True by default
  • Setting the samesite flag to Lax by default
Parameters
key
str

The key (name) of the cookie.

value
str

The value of the cookie.

path
str

The path for the cookie. Defaults to "/".

domain
Optional[str]

The domain for the cookie. Defaults to None.

secure
bool

Whether the cookie is secure. Defaults to True.

max_age
Optional[int]

The maximum age of the cookie in seconds. Defaults to None.

expires
Optional[datetime]

The expiration date of the cookie. Defaults to None.

httponly
bool

HttpOnly flag for the cookie. Defaults to False.

samesite
Optional[SameSite]

The SameSite attribute for the cookie. Defaults to "Lax".

partitioned
bool

Whether the cookie is partitioned. Defaults to False.

comment
Optional[str]

A comment for the cookie. Defaults to None.

host_prefix
bool

Whether to use the host prefix. Defaults to False.

secure_prefix
bool

Whether to use the secure prefix. Defaults to False.

A comment for the cookie. Defaults to None.

@property
def comment(self): -> Optional[str]

The domain of the cookie. Defaults to None.

@property
def domain(self): -> Optional[str]

Encode the cookie content in a specific type of encoding instructed by the developer.

def encode(self, encoding: str): -> bytes

Leverages the str.encode method provided by Python.

This method can be used to encode and embed utf-8 content into the cookies.

Warning

Direct encoding of a Cookie object has been deprecated and will be removed in v24.3.

Parameters
encoding
str

The encoding type to be used.

Return
bytes

The encoded cookie content.

The expiration date of the cookie. Defaults to None.

@property
def expires(self): -> Optional[datetime]

Whether the cookie is HTTP only. Defaults to False.

@property
def httponly(self): -> bool

Create a cookie key with the appropriate prefix.

@classmethod
def make_key(key: str, host_prefix: bool = False, secure_prefix: bool = False): -> str

Cookies can have one ow two prefixes. The first is __Host- which requires that the cookie be set with path="/", domain=None, and secure=True. The second is __Secure- which requires that secure=True.

They cannot be combined.

Parameters
key
str

The key (name) of the cookie.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Return
str

The key with the appropriate prefix.

Raises
ServerError

If both host_prefix and secure_prefix are set.

The maximum age of the cookie in seconds. Defaults to None.

@property
def max_age(self): -> Optional[int]

Whether the cookie is partitioned. Defaults to False.

@property
def partitioned(self): -> bool

The path of the cookie. Defaults to "/".

@property
def path(self): -> str

The SameSite attribute for the cookie. Defaults to "Lax".

@property
def samesite(self): -> Optional[SameSite]

Whether the cookie is secure. Defaults to True.

@property
def secure(self): -> bool

sanic.cookies.response.CookieJar#

A container to manipulate cookies.

Inherits from: dict

class CookieJar(headers: Header)

CookieJar dynamically writes headers as cookies are added and removed It gets around the limitation of one header per name by using the MultiHeader class to provide a unique key that encodes to Set-Cookie.

Parameters
headers
Header

The headers object to write cookies to.

add_cookie#

Add a cookie to the CookieJar.

def add_cookie(self, key: str, value: str, path: str = "/", domain: Optional[str] = None, secure: bool = True, max_age: Optional[int] = None, expires: Optional[datetime] = None, httponly: bool = False, samesite: Optional[SameSite] = Lax, partitioned: bool = False, comment: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> Cookie

Parameters
key
str

Key of the cookie.

value
str

Value of the cookie.

path
str

Path of the cookie. Defaults to "/".

domain
Optional[str]

Domain of the cookie. Defaults to None.

secure
bool

Whether to set it as a secure cookie. Defaults to True.

max_age
Optional[int]

Max age of the cookie in seconds; if set to 0 a browser should delete it. Defaults to None.

expires
Optional[datetime]

When the cookie expires; if set to None browsers should set it as a session cookie. Defaults to None.

httponly
bool

Whether to set it as HTTP only. Defaults to False.

samesite
Optional[SameSite]

How to set the samesite property, should be strict, lax, or none (case insensitive). Defaults to "Lax".

partitioned
bool

Whether to set it as partitioned. Defaults to False.

comment
Optional[str]

A cookie comment. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Return
Cookie

The instance of the created cookie.

Raises
ServerError

If host_prefix is set without secure=True.

ServerError

If host_prefix is set without path="/" and domain=None.

ServerError

If host_prefix is set with domain.

ServerError

If secure_prefix is set without secure=True.

ServerError

If partitioned is set without host_prefix=True.

Examples

Basic usage

cookie = add_cookie('name', 'value')

Adding a cookie with a custom path and domain

cookie = add_cookie('name', 'value', path='/custom', domain='example.com')

Adding a secure, HTTP-only cookie with a comment

cookie = add_cookie('name', 'value', secure=True, httponly=True, comment='My Cookie')

Adding a cookie with a max age of 60 seconds

cookie = add_cookie('name', 'value', max_age=60)

cookie_headers#

Deprecated in v24.3

@property
def cookie_headers(self): -> Dict[str, str]

cookies#

A list of cookies in the CookieJar.

@property
def cookies(self): -> List[Cookie]

Return
List[Cookie]

A list of cookies in the CookieJar.

delete_cookie#

Delete a cookie

def delete_cookie(self, key: str, path: str = "/", domain: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> None

This will effectively set it as Max-Age: 0, which a browser should interpret it to mean: "delete the cookie".

Since it is a browser/client implementation, your results may vary depending upon which client is being used.

Parameters
key
str

The key to be deleted

path
Optional[str], optional

Path of the cookie, defaults to None

domain
Optional[str], optional

Domain of the cookie, defaults to None

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True, defaults to False

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True, defaults to False

get#

Deprecated in v24.3

def get(self, args, kwargs)

get_cookie#

Fetch a cookie from the CookieJar.

def get_cookie(self, key: str, path: str = "/", domain: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> Optional[Cookie]

Parameters
key
str

The key of the cookie to fetch.

path
str

The path of the cookie. Defaults to "/".

domain
Optional[str]

The domain of the cookie. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Return
Optional[Cookie]

The cookie if it exists, otherwise None.

has_cookie#

Check if a cookie exists in the CookieJar.

def has_cookie(self, key: str, path: str = "/", domain: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> bool

Parameters
key
str

The key of the cookie to check.

path
str

The path of the cookie. Defaults to "/".

domain
Optional[str]

The domain of the cookie. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Return
bool

Whether the cookie exists.

header_key#

Deprecated in v24.3

@property
def header_key(self)

items#

Deprecated in v24.3

def items(self)

keys#

Deprecated in v24.3

def keys(self)

pop#

Deprecated in v24.3

def pop(self, key, args, kwargs)

values#

Deprecated in v24.3

def values(self)