mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-08-26 16:40:40 +03:00
format
This commit is contained in:
parent
8d44b4a5eb
commit
dbe64008f8
@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
@ -7,7 +7,9 @@ from app.models.shakespeare import Paragraph
|
||||
router = APIRouter(prefix="/v1/shakespeare")
|
||||
|
||||
|
||||
@router.get("/",)
|
||||
@router.get(
|
||||
"/",
|
||||
)
|
||||
async def find_paragraph(
|
||||
character: str,
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
|
@ -38,7 +38,7 @@ class Settings(BaseSettings):
|
||||
jwt_access_toke_expire_minutes: int = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", 1)
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@lru_cache
|
||||
def get_settings():
|
||||
logger.info("Loading config settings from the environment...")
|
||||
return Settings()
|
||||
|
@ -1,10 +1,15 @@
|
||||
from typing import AsyncGenerator
|
||||
from collections.abc import AsyncGenerator
|
||||
from http.client import HTTPException
|
||||
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app import config
|
||||
from app.utils import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
global_settings = config.get_settings()
|
||||
url = global_settings.asyncpg_url
|
||||
@ -18,10 +23,28 @@ engine = create_async_engine(
|
||||
|
||||
# expire_on_commit=False will prevent attributes from being expired
|
||||
# after commit.
|
||||
async_session_factory = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
||||
AsyncSessionFactory = sessionmaker(engine, autoflush=False, expire_on_commit=False, class_=AsyncSession)
|
||||
|
||||
|
||||
# Dependency
|
||||
async def get_db() -> AsyncGenerator:
|
||||
async with async_session_factory() as session:
|
||||
async with AsyncSessionFactory() as session:
|
||||
logger.debug(f"ASYNC Pool: {engine.pool.status()}")
|
||||
yield session
|
||||
|
||||
|
||||
async def get_async_db() -> AsyncGenerator:
|
||||
try:
|
||||
session: AsyncSession = AsyncSessionFactory()
|
||||
logger.debug(f"ASYNC Pool: {engine.pool.status()}")
|
||||
yield session
|
||||
except SQLAlchemyError as sql_ex:
|
||||
await session.rollback()
|
||||
raise sql_ex
|
||||
except HTTPException as http_ex:
|
||||
await session.rollback()
|
||||
raise http_ex
|
||||
else:
|
||||
await session.commit()
|
||||
finally:
|
||||
await session.close()
|
||||
|
@ -1,8 +1,8 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.api.nonsense import router as nonsense_router
|
||||
from app.api.stuff import router as stuff_router
|
||||
from app.api.shakespeare import router as shakespeare_router
|
||||
from app.api.stuff import router as stuff_router
|
||||
from app.utils import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
@ -1,4 +1,4 @@
|
||||
# for Alembic and unit tests
|
||||
from app.models.stuff import * # noqa
|
||||
from app.models.nonsense import * # noqa
|
||||
from app.models.shakespeare import * # noqa
|
||||
from app.models.shakespeare import * # noqa
|
||||
from app.models.stuff import * # noqa
|
||||
|
@ -13,8 +13,8 @@ class BaseReadOnly:
|
||||
# Generate __tablename__ automatically
|
||||
|
||||
@declared_attr
|
||||
def __tablename__(cls) -> str:
|
||||
return cls.__name__.lower()
|
||||
def __tablename__(self) -> str:
|
||||
return self.__name__.lower()
|
||||
|
||||
|
||||
@as_declarative()
|
||||
@ -24,8 +24,8 @@ class Base:
|
||||
# Generate __tablename__ automatically
|
||||
|
||||
@declared_attr
|
||||
def __tablename__(cls) -> str:
|
||||
return cls.__name__.lower()
|
||||
def __tablename__(self) -> str:
|
||||
return self.__name__.lower()
|
||||
|
||||
async def save(self, db_session: AsyncSession):
|
||||
"""
|
||||
|
@ -10,9 +10,7 @@ from app.models.base import Base
|
||||
|
||||
class Nonsense(Base):
|
||||
__tablename__ = "nonsense"
|
||||
__table_args__ = (
|
||||
{"schema": "happy_hog"},
|
||||
)
|
||||
__table_args__ = ({"schema": "happy_hog"},)
|
||||
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)
|
||||
|
@ -10,9 +10,7 @@ from app.models.base import Base
|
||||
|
||||
class Stuff(Base):
|
||||
__tablename__ = "stuff"
|
||||
__table_args__ = (
|
||||
{"schema": "happy_hog"},
|
||||
)
|
||||
__table_args__ = ({"schema": "happy_hog"},)
|
||||
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)
|
||||
|
@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
@ -7,7 +7,7 @@ from rich.logging import RichHandler
|
||||
console = Console(color_system="256", width=200, style="blue")
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@lru_cache
|
||||
def get_logger(module_name):
|
||||
logger = logging.getLogger(module_name)
|
||||
handler = RichHandler(rich_tracebacks=True, console=console, tracebacks_show_locals=True)
|
||||
|
Loading…
x
Reference in New Issue
Block a user