|
| 1 | +import typing as t |
| 2 | + |
| 3 | +from fastapi import FastAPI, Request |
| 4 | +from fastapi.responses import JSONResponse |
| 5 | +from piccolo_admin.endpoints import create_admin |
| 6 | +from piccolo_api.crud.serializers import create_pydantic_model |
| 7 | +from piccolo_cursor_pagination.pagination import CursorPagination |
| 8 | +from piccolo.engine import engine_finder |
| 9 | +from starlette.routing import Route, Mount |
| 10 | +from starlette.staticfiles import StaticFiles |
| 11 | + |
| 12 | +from home.endpoints import HomeEndpoint |
| 13 | +from home.piccolo_app import APP_CONFIG |
| 14 | +from home.tables import Task |
| 15 | + |
| 16 | + |
| 17 | +app = FastAPI( |
| 18 | + routes=[ |
| 19 | + Route("/", HomeEndpoint), |
| 20 | + Mount( |
| 21 | + "/admin/", |
| 22 | + create_admin( |
| 23 | + tables=APP_CONFIG.table_classes, |
| 24 | + # Required when running under HTTPS: |
| 25 | + # allowed_hosts=['my_site.com'] |
| 26 | + ), |
| 27 | + ), |
| 28 | + Mount("/static/", StaticFiles(directory="static")), |
| 29 | + ], |
| 30 | +) |
| 31 | + |
| 32 | + |
| 33 | +TaskModelIn: t.Any = create_pydantic_model( |
| 34 | + table=Task, model_name="TaskModelIn" |
| 35 | +) |
| 36 | +TaskModelOut: t.Any = create_pydantic_model( |
| 37 | + table=Task, include_default_columns=True, model_name="TaskModelOut" |
| 38 | +) |
| 39 | + |
| 40 | + |
| 41 | +@app.get("/tasks/", response_model=t.List[TaskModelOut]) |
| 42 | +async def tasks( |
| 43 | + request: Request, |
| 44 | + __cursor: str, |
| 45 | + __previous: t.Optional[str] = None, |
| 46 | +): |
| 47 | + try: |
| 48 | + cursor = request.query_params["__cursor"] |
| 49 | + previous = request.query_params["__previous"] |
| 50 | + paginator = CursorPagination(cursor=cursor, page_size=1, order_by="id") |
| 51 | + rows_result, headers_result = paginator.get_cursor_rows(Task, request) |
| 52 | + rows = await rows_result.run() |
| 53 | + headers = headers_result |
| 54 | + response = JSONResponse( |
| 55 | + {"rows": rows[::-1]}, |
| 56 | + headers={ |
| 57 | + "next_cursor": headers["cursor"], |
| 58 | + }, |
| 59 | + ) |
| 60 | + except KeyError: |
| 61 | + cursor = request.query_params["__cursor"] |
| 62 | + paginator = CursorPagination(cursor=cursor, page_size=1, order_by="id") |
| 63 | + rows_result, headers_result = paginator.get_cursor_rows(Task, request) |
| 64 | + rows = await rows_result.run() |
| 65 | + headers = headers_result |
| 66 | + response = JSONResponse( |
| 67 | + {"rows": rows}, |
| 68 | + headers={ |
| 69 | + "next_cursor": headers["cursor"], |
| 70 | + }, |
| 71 | + ) |
| 72 | + return response |
| 73 | + |
| 74 | + |
| 75 | +@app.post("/tasks/", response_model=TaskModelOut) |
| 76 | +async def create_task(task_model: TaskModelIn): |
| 77 | + task = Task(**task_model.dict()) |
| 78 | + await task.save() |
| 79 | + return task.to_dict() |
| 80 | + |
| 81 | + |
| 82 | +@app.put("/tasks/{task_id}/", response_model=TaskModelOut) |
| 83 | +async def update_task(task_id: int, task_model: TaskModelIn): |
| 84 | + task = await Task.objects().get(Task.id == task_id) |
| 85 | + if not task: |
| 86 | + return JSONResponse({}, status_code=404) |
| 87 | + |
| 88 | + for key, value in task_model.dict().items(): |
| 89 | + setattr(task, key, value) |
| 90 | + |
| 91 | + await task.save() |
| 92 | + |
| 93 | + return task.to_dict() |
| 94 | + |
| 95 | + |
| 96 | +@app.delete("/tasks/{task_id}/") |
| 97 | +async def delete_task(task_id: int): |
| 98 | + task = await Task.objects().get(Task.id == task_id) |
| 99 | + if not task: |
| 100 | + return JSONResponse({}, status_code=404) |
| 101 | + |
| 102 | + await task.remove() |
| 103 | + |
| 104 | + return JSONResponse({}) |
| 105 | + |
| 106 | + |
| 107 | +@app.on_event("startup") |
| 108 | +async def open_database_connection_pool(): |
| 109 | + try: |
| 110 | + engine = engine_finder() |
| 111 | + await engine.start_connection_pool() |
| 112 | + except Exception: |
| 113 | + print("Unable to connect to the database") |
| 114 | + |
| 115 | + |
| 116 | +@app.on_event("shutdown") |
| 117 | +async def close_database_connection_pool(): |
| 118 | + try: |
| 119 | + engine = engine_finder() |
| 120 | + await engine.close_connection_pool() |
| 121 | + except Exception: |
| 122 | + print("Unable to connect to the database") |
0 commit comments