mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-08-26 16:40:40 +03:00
nonsense part added
This commit is contained in:
parent
3719cd1ca0
commit
06fa4e2727
40
the_app/api/nonsense.py
Normal file
40
the_app/api/nonsense.py
Normal file
@ -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
|
@ -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,
|
||||
)
|
||||
|
||||
|
@ -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")
|
||||
|
@ -0,0 +1,2 @@
|
||||
from the_app.models.nonsense import Nonsense
|
||||
from the_app.models.stuff import Stuff
|
@ -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)
|
||||
|
38
the_app/models/nonsense.py
Normal file
38
the_app/models/nonsense.py
Normal file
@ -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
|
@ -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()
|
||||
|
48
the_app/schemas/nnonsense.py
Normal file
48
the_app/schemas/nnonsense.py
Normal file
@ -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",
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user