Skip to content

EsmeraldInterceptor class

This is the reference for the main object EsmeraldInterceptor that contains all the parameters, attributes and functions.

esmerald.EsmeraldInterceptor

Bases: ABC, InterceptorProtocol

EsmeraldInterceptor base class. The object that must be subclassed when implementing interceptors in esmerald.

This is also an abstract class and the intercept must be implemented when subclassing.

Example

from esmerald import Esmerald, Gateway, JSONResponse, get

from loguru import logger
from lilya.types import Receive, Scope, Send


class LoggingInterceptor(EsmeraldInterceptor):
    async def intercept(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
        # Log a message here
        logger.info("This is my interceptor being called before reaching the handler.")


@get("/home")
async def home() -> JSONResponse:
    return JSONResponse({"message": "Welcome home"})

Esmerald(routes=[Gateway(handler=home, interceptors=[LoggingInterceptor])])

intercept async

intercept(scope, receive, send)

The method that needs to be implemented for any interceptor. Containing all the logic for the inceptor itself.

Example

from loguru import logger
from lilya.types import Receive, Scope, Send


class LoggingInterceptor(EsmeraldInterceptor):
    async def intercept(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
        # Log a message here
        logger.info("This is my interceptor being called before reaching the handler.")
PARAMETER DESCRIPTION
scope

TYPE: Scope

receive

TYPE: Receive

send

TYPE: Send

Source code in esmerald/interceptors/interceptor.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
async def intercept(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
    """
    The method that needs to be implemented for any interceptor.
    Containing all the logic for the inceptor itself.

    **Example**

    ```python
    from loguru import logger
    from lilya.types import Receive, Scope, Send


    class LoggingInterceptor(EsmeraldInterceptor):
        async def intercept(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
            # Log a message here
            logger.info("This is my interceptor being called before reaching the handler.")
    ```
    """
    raise NotImplementedError("intercept must be implemented")