Перейти к содержанию

Cookies

Warning

The current page still doesn't have a translation for this language.

But you can help translating it: Contributing.

Setting up cookies is also something that usually happens within the scope of almost any application.

Let's assume you need to setup a cookie in your application. There are a few ways.

In your API you need a cookie to be passed onto the call to make you run some extra security validations, like CSRF.

from pydantic import BaseModel, EmailStr

from esmerald import Cookie, Esmerald, Gateway, JSONResponse, post


class User(BaseModel):
    name: str
    email: EmailStr


@post(path="/create")
async def create_user(
    data: User,
    cookie: str = Cookie(value="csrftoken"),
) -> JSONResponse:
    """
    Run validations with the token header
    """
    ...


app = Esmerald(routes=Gateway(handler=create_user))

The cookie is nothing more nothing less than pydantic FieldInfo with some extra things specific for the cookie that extends the Param.

from esmerald import Param

# or

from esmerald.params import Param

The same result can be achieved by using directly the Param field.

from pydantic import BaseModel, EmailStr

from esmerald import Esmerald, Gateway, JSONResponse, Param, post


class User(BaseModel):
    name: str
    email: EmailStr


@post(path="/create")
async def create_user(
    data: User,
    cookie: str = Param(cookie="csrftoken"),
) -> JSONResponse:
    """
    Run validations with the token header
    """
    ...


app = Esmerald(routes=Gateway(handler=create_user))

Since the Param is the base for the Esmerald parameters, you can use it directly with a key difference.

the Cookie expects a value field whereas the Param expects a cookie value.

If a cookie is defined and not sent properly when the call is made it will raise a 400 BadRequest.

Response cookies

This is something else entirely and it is used when you want to send a cookie with the response. Very easy to use as well.

The response_headers is a simple python list.

from pydantic import BaseModel, EmailStr

from esmerald import Esmerald, Gateway, Response, post
from esmerald.datastructures import Cookie


class User(BaseModel):
    name: str
    email: EmailStr


@post(
    path="/create",
    response_cookies=[
        Cookie(
            key="csrf",
            value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
            max_age=3000,
            httponly=True,
        )
    ],
)
async def create_user(data: User) -> Response:
    """
    Run validations with the token header
    """
    ...


app = Esmerald(routes=Gateway(handler=create_user))

When you check the response from the api call, you should now also have a csrf cookie being sent as well with the value CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz.

This is how simple and effective you can manage response cookies.

Caution

Although Cookie from response cookies looks very similar to Cookie from the params they are in fact very different.

This cookie is a datastructure that contains unique fields to create a cookie to be sent back in the response.

To import it:

from esmerald.datastructures import Cookie

# or

from esmerald.datastructures import Cookie as ResponseCookie

The cookie used with the example as param is not a datastructure but a FieldInfo so it cannot be used to set and create a new cookie like the one from response cookies.

To import it:

from esmerald import Cookie

# or

from esmerald.params import Cookie