Cookies
This section explains how to extract and validate cookies using Rapidy.
You can validate the data using any type supported by pydantic.
Description
A cookie is a small set of user data stored on their device without modifications or processing.
The web client sends this data to the web server as part of an HTTP request each time it accesses the corresponding website.
Extracting a Single Cookie
Cookie allows retrieving a specific cookie by its name.
from rapidy.http import get, Cookie
@get('/')
async def handler(
user_id: str = Cookie(alias='UserID'),
) -> ...:
from rapidy.http import get, Cookie
@get('/')
async def handler(
user_id: str = Cookie(alias='UserID'),
user_session: str = Cookie(alias='UserSession'),
) -> ...:
Extracting All Cookies
Cookies allows retrieving all cookies at once.
Extracting into a Predefined Schema
pydantic.BaseModel
from pydantic import BaseModel, Field
from rapidy.http import get, Cookies
class CookieData(BaseModel):
user_id: str = Field(alias='UserID')
user_session: str = Field(alias='User-Session')
@get('/')
async def handler(
cookie_data: CookieData = Cookies(),
) -> ...:
dataclasses.dataclass
dataclasses.dataclass is supported as a model type, but it is not possible to set an alias using standard dataclasses tools.
from dataclasses import dataclass
from rapidy.http import get, Cookies
@dataclass
class CookieData:
UserID: str # camelCase syntax if cookie name is 'UserID'
user_session: str # cannot extract if cookie name is 'User-Session'
@get('/')
async def handler(
cookie_data: CookieData = Cookies(),
) -> ...:
# {"errors": [{"type": "missing", "loc": ["cookie", "user_session"], "msg": "Field required"}]}
Extracting into a Dictionary
from rapidy.http import get, Cookies
@get('/')
async def handler(
cookie_data: dict[str, str] = Cookies(),
) -> ...:
# {'UserID': ..., 'User-Session': ...}
Extracting Without Validation
Disabling validation is not recommended.
If validation is disabled, the parameter will return a basic aiohttp structure:
Cookie→strCookies→Mapping[str, str]
Ways to Disable Validation
Explicit Disabling
from rapidy.http import get, Cookie, Cookies
@get('/')
async def handler_1(
user_id: int = Cookie(alias='UserID', validate=False)
) -> ...:
# ...
@get('/')
async def handler_2(
cookie_data: int = Cookies(validate=False)
) -> ...:
# # {'UserID': ..., 'User-Session': ...}
Using Any
from typing import Any
@get('/')
async def handler_1(
user_id: Any = Cookie(alias='UserID', validate=False)
) -> ...:
# ...
@get('/')
async def handler_2(
cookie_data: Any = Cookies(validate=False)
) -> ...:
# # {'UserID': ..., 'User-Session': ...}
No Type Annotation
If no type is specified, it defaults to Any.
@get('/')
async def handler_1(
user_id=Cookie(alias='UserID')
) -> ...:
# ...
@get('/')
async def handler_2(
cookie_data=Cookies()
) -> ...:
# # {'UserID': ..., 'User-Session': ...}
Default Values
The default value for Cookie will be used if no cookie with the specified name is found in the request.
The default value for Cookies will be used if no cookies are found in the request.
Using default
@get('/')
async def handler(
some_cookie: str = Cookie(alias='Some-Cookie', default='SomeValue'),
) -> ...:
from typing import Annotated
@get('/')
async def handler(
some_cookie: Annotated[str, Cookie(alias='Some-Cookie', default='SomeValue')],
) -> ...:
from typing import Annotated
@get('/')
async def handler(
some_cookie: Annotated[str, Cookie(alias='Some-Cookie')] = 'SomeValue',
) -> ...:
Using default_factory
@get('/')
async def handler(
some_cookie: str = Cookie(alias='Some-Cookie', default_factory=lambda: 'SomeValue'),
) -> ...:
from typing import Annotated
@get('/')
async def handler(
some_cookie: Annotated[str, Cookie(alias='Some-Cookie', default_factory=lambda:'SomeValue')],
) -> ...:
You cannot use default and default_factory simultaneously.
Attempting to specify both will raise a pydantic exception:
Warnings and Considerations
Using Cookie and Cookies together
It is not possible to use Cookie and Cookies in the same handler.
@get('/')
async def handler(
user_id: str = Cookie(alias='UserID'),
cookie_data: CookieData = Cookies(),
) -> ...:
When the application starts, an AnotherDataExtractionTypeAlreadyExistsError exception will be raised.
------------------------------
Attribute with this data extraction type cannot be added to the handler - another data extraction type is already in use.
Handler path: `main.py`
Handler name: `handler`
Attribute name: `cookie_data`
------------------------------
The alias Attribute in Cookies
The alias attribute does not work in the Cookies() parameter.
@get('/')
async def handler(
cookie_data: CookieData = Cookies(alias='SomeName'), # <-- alias not working
) -> ...:
How Raw Data Is Extracted
Rapidy uses the cookies method of the Request object and then passes the retrieved data to a pydantic model for validation.
How data extraction works in Rapidy
Rapidy uses built-in aiohttp mechanisms for data extraction.
More details about the aiohttp.Request object and methods for extracting data from it can be found
here.