admin revised this gist . Go to revision
1 file changed, 117 insertions
base_rest.py(file created)
| @@ -0,0 +1,117 @@ | |||
| 1 | + | from typing import List | |
| 2 | + | from fastapi import APIRouter, HTTPException | |
| 3 | + | import peewee as pw | |
| 4 | + | from peewee import DoesNotExist | |
| 5 | + | from pydantic import BaseModel | |
| 6 | + | ||
| 7 | + | ||
| 8 | + | class BaseRest: | |
| 9 | + | def __init__(self, model: pw.Model, pydantic_model: BaseModel, methods: List[str]=None): | |
| 10 | + | self.model = model | |
| 11 | + | self.pydantic_model = pydantic_model | |
| 12 | + | self.model_class_name = model._meta.name | |
| 13 | + | self.router = APIRouter() | |
| 14 | + | self.openapi_extra = { | |
| 15 | + | "requestBody": { | |
| 16 | + | "content": { | |
| 17 | + | "application/json": { | |
| 18 | + | "schema": self.pydantic_model.model_json_schema() | |
| 19 | + | } | |
| 20 | + | }, | |
| 21 | + | "required": True, | |
| 22 | + | }, | |
| 23 | + | } | |
| 24 | + | if methods is None: | |
| 25 | + | methods = ["list", "create", "get", "update", "delete"] | |
| 26 | + | ||
| 27 | + | if "list" in methods: | |
| 28 | + | self.router.add_api_route( | |
| 29 | + | path=f"{self.model_class_name}", | |
| 30 | + | endpoint=self.list, | |
| 31 | + | response_model=List[self.pydantic_model], | |
| 32 | + | methods=["GET"] | |
| 33 | + | ) | |
| 34 | + | if "create" in methods: | |
| 35 | + | self.router.add_api_route( | |
| 36 | + | path=f"{self.model_class_name}", | |
| 37 | + | endpoint=self.create, | |
| 38 | + | openapi_extra=self.openapi_extra, | |
| 39 | + | methods=["POST"] | |
| 40 | + | ) | |
| 41 | + | if "get" in methods: | |
| 42 | + | self.router.add_api_route( | |
| 43 | + | path=f"{self.model_class_name}/{{{self.model_class_name}_id}}", | |
| 44 | + | endpoint=self.get, | |
| 45 | + | response_model=self.pydantic_model, | |
| 46 | + | methods=["GET"] | |
| 47 | + | ) | |
| 48 | + | if "update" in methods: | |
| 49 | + | self.router.add_api_route( | |
| 50 | + | path=f"{self.model_class_name}/{{{self.model_class_name}_id}}", | |
| 51 | + | endpoint=self.update, | |
| 52 | + | openapi_extra=self.openapi_extra, | |
| 53 | + | methods=["PUT"] | |
| 54 | + | ) | |
| 55 | + | if "delete" in methods: | |
| 56 | + | self.router.add_api_route( | |
| 57 | + | path=f"{self.model_class_name}/{{{self.model_class_name}_id}}", | |
| 58 | + | endpoint=self.delete, | |
| 59 | + | methods=["DELETE"] | |
| 60 | + | ) | |
| 61 | + | ||
| 62 | + | # Метод для получения списка объектов | |
| 63 | + | async def list(self): | |
| 64 | + | try: | |
| 65 | + | return list(self.model.select()) | |
| 66 | + | except Exception as e: | |
| 67 | + | raise HTTPException(status_code=500, detail=str(e)) | |
| 68 | + | ||
| 69 | + | # Метод для создания нового объекта | |
| 70 | + | async def create(self, data: BaseModel): | |
| 71 | + | try: | |
| 72 | + | # Преобразуем Pydantic модель в словарь | |
| 73 | + | data_dict = data.dict() | |
| 74 | + | # Создаем новый объект | |
| 75 | + | instance = self.model.create(**data_dict) | |
| 76 | + | return instance | |
| 77 | + | except Exception as e: | |
| 78 | + | raise HTTPException(status_code=400, detail=str(e)) | |
| 79 | + | ||
| 80 | + | # Метод для получения объекта по ID | |
| 81 | + | async def get(self, id: int): | |
| 82 | + | try: | |
| 83 | + | instance = self.model.get_by_id(id) | |
| 84 | + | return instance | |
| 85 | + | except DoesNotExist: | |
| 86 | + | raise HTTPException(status_code=404, detail="Объект не найден") | |
| 87 | + | except Exception as e: | |
| 88 | + | raise HTTPException(status_code=500, detail=str(e)) | |
| 89 | + | ||
| 90 | + | # Метод для обновления объекта | |
| 91 | + | async def update(self, id: int, data: BaseModel): | |
| 92 | + | try: | |
| 93 | + | # Получаем объект | |
| 94 | + | instance = self.model.get_by_id(id) | |
| 95 | + | # Обновляем поля | |
| 96 | + | for field, value in data.model_dump().items(): | |
| 97 | + | setattr(instance, field, value) | |
| 98 | + | instance.save() | |
| 99 | + | return instance | |
| 100 | + | except DoesNotExist: | |
| 101 | + | raise HTTPException(status_code=404, detail="Объект не найден") | |
| 102 | + | except Exception as e: | |
| 103 | + | raise HTTPException(status_code=400, detail=str(e)) | |
| 104 | + | ||
| 105 | + | # Метод для удаления объекта | |
| 106 | + | async def delete(self, id: int): | |
| 107 | + | try: | |
| 108 | + | # Получаем объект | |
| 109 | + | instance = self.model.get_by_id(id) | |
| 110 | + | # Удаляем его | |
| 111 | + | instance.delete_instance() | |
| 112 | + | return {"message": "Объект успешно удален"} | |
| 113 | + | except DoesNotExist: | |
| 114 | + | raise HTTPException(status_code=404, detail="Объект не найден") | |
| 115 | + | except Exception as e: | |
| 116 | + | raise HTTPException(status_code=500, detail=str(e)) | |
| 117 | + | ||
Newer
Older