Всем привет, это моя первая статья на Habr, надеюсь, это будет кому-то интересно. На последнем проекте я как всегда делал какой-то REST API и вдруг меня посетила мысль что я что-то много копирую и вставляю одного и того же кода. И я решил почему бы не сделать генератор этого кода это оказалось не сложно.
Сразу оговорюсь что я использую https://github.com/tiangolo/full-stack-fastapi-postgresql и содержимое репозитория нужно положить в директорию backend/app/app что бы все заработало.
Думаю в чистом FastAPI проекте это тоже должно сработать.
По умолчанию в проектах этого типа есть два типа пользователей superuser и обыкновенный user соответсвенно CRUD будет создаваться относительно двух этих пользователей. Для генерации CRUD достаточно создать просто модель.
from sqlalchemy import Column, Integer, String from app.db.base_class import Base class Category(Base): id = Column(Integer, primary_key=True, index=True) name = Column(String, nullable=False)
Назовем этот файл models/category.py
И теперь вся магия для того что бы создать все endpoints/crud/schemas для этой модели достаточно запустить из каталога backend/app/app команду:
python3 codegen.py Category
Нужно не забыть поставить typer и jinja2 что бы скрипт заработал.
В результате мы получим вот такой файлик в директории codegen/generated
from typing import Any, List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app import crud, models, schemas from app.api import deps from app.translate import _ router = APIRouter() @router.get("/", response_model=List[schemas.Category]) def read_categories( db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100, current_user: models.User = Depends(deps.get_current_active_user), ) -> Any: """ Retrieve category. """ return crud.category.get_multi(db, skip=skip, limit=limit) @router.post("/", response_model=schemas.Category) def create_category( *, db: Session = Depends(deps.get_db), category_in: schemas.CategoryCreate, current_user: models.User = Depends(deps.get_current_active_superuser), ) -> Any: """ Create new category. """ return crud.category.create(db=db, obj_in=category_in) @router.get("/{id}", response_model=schemas.Category) def read_category( id: int, current_user: models.User = Depends(deps.get_current_active_superuser), db: Session = Depends(deps.get_db), ) -> Any: """ Get a category. """ category = crud.category.get(db=db, id=id) if not category: raise HTTPException( status_code=400, detail=_("Category doesn't exists") ) return category @router.put("/{id}", response_model=schemas.Category) def update_category( *, db: Session = Depends(deps.get_db), id: int, category_in: schemas.CategoryUpdate, current_user: models.User = Depends(deps.get_current_active_superuser), ) -> Any: """ Update a category. """ category = crud.category.get(db=db, id=id) if not category: raise HTTPException( status_code=404, detail=_("Category doesn't exists"), ) category = crud.category.update(db=db, db_obj=category, obj_in=category_in) return category @router.delete("/{id}", response_model=schemas.Category) def delete_category( *, db: Session = Depends(deps.get_db), id: int, current_user: models.User = Depends(deps.get_current_active_superuser), ) -> Any: """ Delete an category. """ category = crud.category.get(db=db, id=id) if not category: raise HTTPException(status_code=404, detail=_("Category doesn't exists")) return crud.category.remove(db=db, id=id)
И в консоли получим реквест:
Install new files? [y/N]:
Можно до того как копировать файлы просмотреть их подправить и нажать "y"
На самом деле что бы это все заработало осталось два шага чекнуть app/api/api_v1/api.py там могут быть проблемы. И добавить модель в models/__init__.py что бы сработал
alembic revision --autogenerated -m "new Model"
Забыл самое главное - это все ради новых мемберов FastAPI Ukraine.
