From 06fa4e272739690777dc68406fe6964110ff890b Mon Sep 17 00:00:00 2001 From: grillazz Date: Sun, 13 Jun 2021 12:28:22 +0200 Subject: [PATCH] nonsense part added --- the_app/api/nonsense.py | 40 ++++++++++++++++++++++++++++++ the_app/database.py | 3 ++- the_app/main.py | 10 ++++++-- the_app/models/__init__.py | 2 ++ the_app/models/base.py | 16 ++++++++++++ the_app/models/nonsense.py | 38 ++++++++++++++++++++++++++++ the_app/models/stuff.py | 6 +++++ the_app/schemas/nnonsense.py | 48 ++++++++++++++++++++++++++++++++++++ 8 files changed, 160 insertions(+), 3 deletions(-) create mode 100644 the_app/api/nonsense.py create mode 100644 the_app/models/nonsense.py create mode 100644 the_app/schemas/nnonsense.py diff --git a/the_app/api/nonsense.py b/the_app/api/nonsense.py new file mode 100644 index 0000000..8f6ca2b --- /dev/null +++ b/the_app/api/nonsense.py @@ -0,0 +1,40 @@ +from fastapi import APIRouter, Depends, status +from sqlalchemy.ext.asyncio import AsyncSession + +from the_app.database import get_db +from the_app.models.nonsense import Nonsense +from the_app.schemas.nnonsense import NonsenseResponse, NonsenseSchema + +router = APIRouter() + + +@router.post("/", status_code=status.HTTP_201_CREATED, response_model=NonsenseResponse) +async def create_nonsense(payload: NonsenseSchema, db_session: AsyncSession = Depends(get_db)): + nonsense = Nonsense(**payload.dict()) + await nonsense.save(db_session) + return nonsense + + +@router.get("/", response_model=NonsenseResponse) +async def find_nonsense( + name: str, + db_session: AsyncSession = Depends(get_db), +): + return await Nonsense.find(db_session, name) + + +@router.delete("/") +async def delete_nonsense(name: str, db_session: AsyncSession = Depends(get_db)): + nonsense = await Nonsense.find(db_session, name) + return await nonsense.delete(nonsense, db_session) + + +@router.patch("/", response_model=NonsenseResponse) +async def update_nonsense( + payload: NonsenseSchema, + name: str, + db_session: AsyncSession = Depends(get_db), +): + nonsense = await Nonsense.find(db_session, name) + await nonsense.update(db_session, **payload.dict()) + return nonsense diff --git a/the_app/database.py b/the_app/database.py index 635209c..a8e032b 100644 --- a/the_app/database.py +++ b/the_app/database.py @@ -2,7 +2,7 @@ from typing import AsyncGenerator from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine -from sqlalchemy.orm import sessionmaker +from sqlalchemy.orm import declarative_base, sessionmaker from the_app import config @@ -11,6 +11,7 @@ url = global_settings.asyncpg_url engine = create_async_engine( url, + future=True, echo=True, ) diff --git a/the_app/main.py b/the_app/main.py index 2c19f78..06ac205 100644 --- a/the_app/main.py +++ b/the_app/main.py @@ -2,6 +2,7 @@ import logging from fastapi import FastAPI +from the_app.api.nonsense import router as nonsense_router from the_app.api.stuff import router as stuff_router from the_app.database import engine from the_app.models.base import Base @@ -11,13 +12,18 @@ log = logging.getLogger(__name__) app = FastAPI(title="Stuff And Nonsense", version="0.1") app.include_router(stuff_router, prefix="/v1") +app.include_router(nonsense_router, prefix="/v1") + + +async def start_db(): + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) @app.on_event("startup") async def startup_event(): log.info("Starting up...") - async with engine.begin() as conn: - await conn.run_sync(Base.metadata.create_all) + await start_db() @app.on_event("shutdown") diff --git a/the_app/models/__init__.py b/the_app/models/__init__.py index e69de29..9b56a8a 100644 --- a/the_app/models/__init__.py +++ b/the_app/models/__init__.py @@ -0,0 +1,2 @@ +from the_app.models.nonsense import Nonsense +from the_app.models.stuff import Stuff diff --git a/the_app/models/base.py b/the_app/models/base.py index 83bd875..21d913f 100644 --- a/the_app/models/base.py +++ b/the_app/models/base.py @@ -16,6 +16,11 @@ class Base: return cls.__name__.lower() async def save(self, db_session: AsyncSession): + """ + + :param db_session: + :return: + """ try: db_session.add(self) return await db_session.commit() @@ -23,6 +28,11 @@ class Base: raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)) async def delete(self, db_session: AsyncSession): + """ + + :param db_session: + :return: + """ try: await db_session.delete(self) await db_session.commit() @@ -31,6 +41,12 @@ class Base: raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)) async def update(self, db_session: AsyncSession, **kwargs): + """ + + :param db_session: + :param kwargs: + :return: + """ for k, v in kwargs.items(): setattr(self, k, v) await self.save(db_session) diff --git a/the_app/models/nonsense.py b/the_app/models/nonsense.py new file mode 100644 index 0000000..52178e6 --- /dev/null +++ b/the_app/models/nonsense.py @@ -0,0 +1,38 @@ +import uuid + +from fastapi import HTTPException, status +from sqlalchemy import Column, String, select +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.ext.asyncio import AsyncSession + +from the_app.models.base import Base + + +class Nonsense(Base): + __tablename__ = "nonsense" + id = Column(UUID(as_uuid=True), unique=True, default=uuid.uuid4, autoincrement=True) + name = Column(String, nullable=False, primary_key=True, unique=True) + description = Column(String, nullable=False) + + def __init__(self, name: str, description: str): + self.name = name + self.description = description + + @classmethod + async def find(cls, db_session: AsyncSession, name: str): + """ + + :param db_session: + :param name: + :return: + """ + stmt = select(cls).where(cls.name == name) + result = await db_session.execute(stmt) + instance = result.scalars().first() + if instance is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail={"Record not found": f"There is no record for requested name value : {name}"}, + ) + else: + return instance diff --git a/the_app/models/stuff.py b/the_app/models/stuff.py index cfe2a95..2eafb3c 100644 --- a/the_app/models/stuff.py +++ b/the_app/models/stuff.py @@ -20,6 +20,12 @@ class Stuff(Base): @classmethod async def find(cls, db_session: AsyncSession, name: str): + """ + + :param db_session: + :param name: + :return: + """ stmt = select(cls).where(cls.name == name) result = await db_session.execute(stmt) instance = result.scalars().first() diff --git a/the_app/schemas/nnonsense.py b/the_app/schemas/nnonsense.py new file mode 100644 index 0000000..8c691c9 --- /dev/null +++ b/the_app/schemas/nnonsense.py @@ -0,0 +1,48 @@ +from uuid import UUID + +from pydantic import BaseModel, Field + + +class NonsenseSchema(BaseModel): + name: str = Field( + title="", + description="", + ) + description: str = Field( + title="", + description="", + ) + + class Config: + orm_mode = True + schema_extra = { + "example": { + "name": "Name for Some Nonsense", + "description": "Some Nonsense Description", + } + } + + +class NonsenseResponse(BaseModel): + id: UUID = Field( + title="Id", + description="", + ) + name: str = Field( + title="", + description="", + ) + description: str = Field( + title="", + description="", + ) + + class Config: + orm_mode = True + schema_extra = { + "example": { + "config_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "name": "Name for Some Nonsense", + "description": "Some Nonsense Description", + } + }