|
| 1 | +""" |
| 2 | +Define endpoints routes in python class-based fashion |
| 3 | +example: |
| 4 | +
|
| 5 | +@Controller("/dogs", tag="Dogs", description="Dogs Resources") |
| 6 | +class MyController(ControllerBase): |
| 7 | + @get('/') |
| 8 | + def index(self): |
| 9 | + return {'detail': "Welcome Dog's Resources"} |
| 10 | +""" |
| 11 | + |
| 12 | +import typing_extensions as types |
| 13 | +from ellar.common import ( |
| 14 | + Body, |
| 15 | + Controller, |
| 16 | + ControllerBase, |
| 17 | + Query, |
| 18 | + Version, |
| 19 | + get, |
| 20 | + post, |
| 21 | + render, |
| 22 | +) |
| 23 | +from ellar.openapi import ApiTags |
| 24 | + |
| 25 | +from .schemas import CarListFilter, CreateCarSerializer |
| 26 | +from .services import CarRepository |
| 27 | + |
| 28 | + |
| 29 | +@Controller("/car") |
| 30 | +@ApiTags( |
| 31 | + description="Example of Car Resource with <strong>Controller</strong>", |
| 32 | + name="CarController", |
| 33 | +) |
| 34 | +class CarController(ControllerBase): |
| 35 | + def __init__(self, repo: CarRepository): |
| 36 | + self.repo = repo |
| 37 | + |
| 38 | + @get("/list-html") |
| 39 | + @render() |
| 40 | + async def list(self): |
| 41 | + return self.repo.get_all() |
| 42 | + |
| 43 | + @post() |
| 44 | + async def create(self, payload: types.Annotated[CreateCarSerializer, Body()]): |
| 45 | + result = self.repo.create_car(payload) |
| 46 | + result.update(message="This action adds a new car") |
| 47 | + return result |
| 48 | + |
| 49 | + @get("/{car_id:str}") |
| 50 | + async def get_one(self, car_id: str): |
| 51 | + return f"This action returns a #{car_id} car" |
| 52 | + |
| 53 | + @get() |
| 54 | + async def get_all(self, query: CarListFilter = Query()): |
| 55 | + res = { |
| 56 | + "cars": self.repo.get_all(), |
| 57 | + "message": f"This action returns all cars at limit={query.limit}, offset={query.offset}", |
| 58 | + } |
| 59 | + return res |
| 60 | + |
| 61 | + @post("/", name="v2_create") |
| 62 | + @Version("v2") |
| 63 | + async def create_v2(self, payload: Body[CreateCarSerializer]): |
| 64 | + result = self.repo.create_car(payload) |
| 65 | + result.update(message="This action adds a new car - version 2") |
| 66 | + return result |
0 commit comments