mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-11-30 13:20:40 +03:00
init codebase
This commit is contained in:
0
the_app/__init__.py
Normal file
0
the_app/__init__.py
Normal file
0
the_app/api/__init__.py
Normal file
0
the_app/api/__init__.py
Normal file
39
the_app/api/stuff.py
Normal file
39
the_app/api/stuff.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from the_app.database import get_db
|
||||
from the_app.models.stuff import Stuff
|
||||
from the_app.schemas.stuff import StuffResponse, StuffSchema
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/", response_model=StuffResponse)
|
||||
async def create_stuff(stuff: StuffSchema, db_session: AsyncSession = Depends(get_db)):
|
||||
stuff_id = await Stuff.create(db_session, stuff)
|
||||
return {**stuff.dict(), "id": stuff_id}
|
||||
|
||||
|
||||
@router.delete("/")
|
||||
async def delete_stuff(stuff_id: UUID, db_session: AsyncSession = Depends(get_db)):
|
||||
return await Stuff.delete(db_session, stuff_id)
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def find_stuff(
|
||||
name: str,
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await Stuff.find(db_session, name)
|
||||
|
||||
|
||||
@router.patch("/")
|
||||
async def update_config(
|
||||
stuff: StuffSchema,
|
||||
name: str,
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
instance_of_the_stuff = await Stuff.find(db_session, name)
|
||||
return instance_of_the_stuff.update(db_session, stuff)
|
||||
41
the_app/config.py
Normal file
41
the_app/config.py
Normal file
@@ -0,0 +1,41 @@
|
||||
import logging
|
||||
import os
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic import BaseSettings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""
|
||||
|
||||
BaseSettings, from Pydantic, validates the data so that when we create an instance of Settings,
|
||||
environment and testing will have types of str and bool, respectively.
|
||||
|
||||
Parameters:
|
||||
pg_user (str):
|
||||
pg_pass (str):
|
||||
pg_database: (str):
|
||||
pg_test_database: (str):
|
||||
asyncpg_url: AnyUrl:
|
||||
asyncpg_test_url: AnyUrl:
|
||||
|
||||
Returns:
|
||||
instance of Settings
|
||||
|
||||
"""
|
||||
|
||||
pg_user: str = os.getenv("POSTGRES_USER", "")
|
||||
pg_pass: str = os.getenv("POSTGRES_PASS", "")
|
||||
pg_host: str = os.getenv("POSTGRES_HOST", "")
|
||||
pg_database: str = os.getenv("POSTGRES_DB", "")
|
||||
pg_test_database: str = os.getenv("POSTGRES_TEST_DB", "")
|
||||
asyncpg_url: str = f"postgresql+asyncpg://{pg_user}:{pg_pass}@{pg_host}:5432/{pg_database}"
|
||||
asyncpg_test_url: str = f"postgresql+asyncpg://{pg_user}:{pg_pass}@{pg_host}:5432/{pg_test_database}"
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_settings():
|
||||
log.info("Loading config settings from the environment...")
|
||||
return Settings()
|
||||
30
the_app/database.py
Normal file
30
the_app/database.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from the_app import config
|
||||
|
||||
global_settings = config.get_settings()
|
||||
url = global_settings.asyncpg_url
|
||||
|
||||
engine = create_async_engine(
|
||||
url,
|
||||
echo=True,
|
||||
)
|
||||
|
||||
# expire_on_commit=False will prevent attributes from being expired
|
||||
# after commit.
|
||||
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
||||
|
||||
|
||||
# Dependency
|
||||
async def get_db():
|
||||
session = async_session()
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except SQLAlchemyError as ex:
|
||||
await session.rollback()
|
||||
raise ex
|
||||
finally:
|
||||
await session.close()
|
||||
25
the_app/main.py
Normal file
25
the_app/main.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from the_app.api.stuff import router as stuff_router
|
||||
from the_app.database import engine
|
||||
from the_app.models.base import Base
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI(title="Stuff And Nonsense", version="0.1")
|
||||
|
||||
app.include_router(stuff_router, prefix="/v1")
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown_event():
|
||||
log.info("Shutting down...")
|
||||
0
the_app/models/__init__.py
Normal file
0
the_app/models/__init__.py
Normal file
23
the_app/models/base.py
Normal file
23
the_app/models/base.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.ext.declarative import as_declarative, declared_attr
|
||||
|
||||
|
||||
@as_declarative()
|
||||
class Base:
|
||||
id: Any
|
||||
__name__: str
|
||||
# Generate __tablename__ automatically
|
||||
@declared_attr
|
||||
def __tablename__(cls) -> str:
|
||||
return cls.__name__.lower()
|
||||
|
||||
async def save(self, db_session: AsyncSession):
|
||||
try:
|
||||
db_session.add(self)
|
||||
return await db_session.commit()
|
||||
except SQLAlchemyError as ex:
|
||||
print(f"Have to rollback, save failed: {ex}")
|
||||
raise
|
||||
46
the_app/models/stuff.py
Normal file
46
the_app/models/stuff.py
Normal file
@@ -0,0 +1,46 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Column, String, delete, select
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from the_app.models.base import Base
|
||||
from the_app.schemas.stuff import StuffSchema
|
||||
|
||||
|
||||
class Stuff(Base):
|
||||
__tablename__ = "stuff"
|
||||
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, unique=True)
|
||||
|
||||
def __init__(self, name: str, description: str):
|
||||
self.name = name
|
||||
self.description = description
|
||||
|
||||
@classmethod
|
||||
async def create(cls, db_session: AsyncSession, schema: StuffSchema):
|
||||
stuff = Stuff(
|
||||
name=schema.name,
|
||||
description=schema.description,
|
||||
)
|
||||
await stuff.save(db_session)
|
||||
return stuff.id
|
||||
|
||||
async def update(self, db_session: AsyncSession, schema: StuffSchema):
|
||||
self.name = schema.name
|
||||
self.description = schema.description
|
||||
return await self.save(db_session)
|
||||
|
||||
@classmethod
|
||||
async def find(cls, db_session: AsyncSession, name: str):
|
||||
stmt = select(cls).where(cls.name == name)
|
||||
result = await db_session.execute(stmt)
|
||||
return result.scalars().first()
|
||||
|
||||
@classmethod
|
||||
async def delete(cls, db_session: AsyncSession, stuff_id: UUID):
|
||||
stmt = delete(cls).where(cls.id == stuff_id)
|
||||
await db_session.execute(stmt)
|
||||
await db_session.commit()
|
||||
return True
|
||||
0
the_app/schemas/__init__.py
Normal file
0
the_app/schemas/__init__.py
Normal file
47
the_app/schemas/stuff.py
Normal file
47
the_app/schemas/stuff.py
Normal file
@@ -0,0 +1,47 @@
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class StuffSchema(BaseModel):
|
||||
name: str = Field(
|
||||
title="",
|
||||
description="",
|
||||
)
|
||||
description: str = Field(
|
||||
title="",
|
||||
description="",
|
||||
)
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
schema_extra = {
|
||||
"example": {
|
||||
"name": "Name for Some Stuff",
|
||||
"description": "Some Stuff Description",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class StuffResponse(BaseModel):
|
||||
id: UUID = Field(
|
||||
title="Id",
|
||||
description="",
|
||||
)
|
||||
name: str = Field(
|
||||
title="",
|
||||
description="",
|
||||
)
|
||||
description: str = Field(
|
||||
title="",
|
||||
description="",
|
||||
)
|
||||
|
||||
class Config:
|
||||
schema_extra = {
|
||||
"example": {
|
||||
"config_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
|
||||
"name": "Name for Some Stuff",
|
||||
"description": "Some Stuff Description",
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user