Custom decorators
Inspired by Nestjs, Nestipy allows us to create custom parameter decorators (alias param type annotated) and perform decorator composition.
Param type annotated
Nestipy offers pre-defined, reusable parameter type annotations as an alternative to using parameter decorators from
Nestjs in Python.
Req()
is used to inject aRequest
object via method parameters, such asreq: Annotated[Request, Req()]
.Res()
is used to inject aResponse
object via method parameters, such asres: Annotated[Response, Res()]
.Param()
is used to inject request path parameters via method parameters, such asparams: Annotated[dict, Param()]
.Query()
is used to inject request query parameters via method parameters, such asqueries: Annotated[dict, Query()]
.Session()
is used to inject request sessions via method parameters, such assessions: Annotated[dict, Session()]
.Header()
is used to inject request headers via method parameters, such asheaders: Annotated[dict, Header()]
.Cookie()
is used to inject request cookies via method parameters, such ascookies: Annotated[dict, Cookie()]
.Body()
is used to inject the request body via method parameters, such asbody: Annotated[dict, Body()]
.Arg()
is used to inject GraphQL request arguments via method parameters, such asdata: Annotated[TestInput, Arg()]
.SocketData()
is used to inject WebSocket data via method parameters, such asdata: Annotated[TestInput, SocketData()]
.WebSocketClient()
is used to inject WebSocket client information via method parameters, such asclient: Annotated[TestInput, WebSocketClient()]
.
Custom param type annotated.
We can now create our own param type annotated.
from typing import Optional, Type
from nestipy.ioc import create_type_annotated, RequestContextContainer
def user_callback(_name: str, _token: Optional[str], _type_ref: Type, _request_context: RequestContextContainer):
return "User"
User = create_type_annotated(user_callback, "user")
We can now use User
as param annotated in method parameter.
from typing import Annotated, Any
from nestipy.common import Controller, Get
@Controller()
class AppController:
@Get()
def get(self, user: Annotated[Any, User()]):
pass
Decorator composition
Nestipy includes a helper method for combining multiple decorators. For instance, if you want to merge all OpenApi-related decorators into one, you can achieve this with the following approach:
from nestipy.common import apply_decorators, Controller
from nestipy.openapi import ApiNotFoundResponse, ApiCreatedResponse, ApiOkResponse
def ApiDecorators():
return apply_decorators(
ApiNotFoundResponse(),
ApiCreatedResponse(),
ApiOkResponse()
)
@ApiDecorators()
@Controller()
class AppController:
...
Support us
Nestipy is a project released under the MIT license, meaning it's open source and freely available for use and modification. Its development thrives with the generous contributions of these fantastic individuals.