lint code + format

This commit is contained in:
Jakub Miazek
2023-01-17 21:00:45 +01:00
parent efadedaab0
commit f0ae471c39
13 changed files with 239 additions and 149 deletions

View File

@@ -9,7 +9,9 @@ router = APIRouter(prefix="/v1/nonsense")
@router.post("/", status_code=status.HTTP_201_CREATED, response_model=NonsenseResponse)
async def create_nonsense(payload: NonsenseSchema, db_session: AsyncSession = Depends(get_db)):
async def create_nonsense(
payload: NonsenseSchema, db_session: AsyncSession = Depends(get_db)
):
nonsense = Nonsense(**payload.dict())
await nonsense.save(db_session)
return nonsense

View File

@@ -13,21 +13,31 @@ logger = get_logger(__name__)
@router.post("/add_many", status_code=status.HTTP_201_CREATED)
async def create_multi_stuff(payload: list[StuffSchema], db_session: AsyncSession = Depends(get_db)):
async def create_multi_stuff(
payload: list[StuffSchema], db_session: AsyncSession = Depends(get_db)
):
try:
stuff_instances = [Stuff(name=stuf.name, description=stuf.description) for stuf in payload]
stuff_instances = [
Stuff(name=stuf.name, description=stuf.description) for stuf in payload
]
db_session.add_all(stuff_instances)
await db_session.commit()
except SQLAlchemyError as ex:
# logger.exception(ex)
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)) from ex
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)
) from ex
else:
logger.info(f"{len(stuff_instances)} instances of Stuff inserted into database.")
logger.info(
f"{len(stuff_instances)} instances of Stuff inserted into database."
)
return True
@router.post("", status_code=status.HTTP_201_CREATED, response_model=StuffResponse)
async def create_stuff(payload: StuffSchema, db_session: AsyncSession = Depends(get_db)):
async def create_stuff(
payload: StuffSchema, db_session: AsyncSession = Depends(get_db)
):
stuff = Stuff(name=payload.name, description=payload.description)
await stuff.save(db_session)
return stuff

View File

@@ -31,7 +31,9 @@ class Settings(BaseSettings):
pg_pass: str = os.getenv("POSTGRES_PASSWORD", "")
pg_host: str = os.getenv("SQL_HOST", "")
pg_database: str = os.getenv("SQL_DB", "")
asyncpg_url: str = f"postgresql+asyncpg://{pg_user}:{pg_pass}@{pg_host}:5432/{pg_database}"
asyncpg_url: str = (
f"postgresql+asyncpg://{pg_user}:{pg_pass}@{pg_host}:5432/{pg_database}"
)
jwt_secret_key: str = os.getenv("SECRET_KEY", "")
jwt_algorithm: str = os.getenv("ALGORITHM", "")

View File

@@ -1,8 +1,6 @@
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
@@ -23,7 +21,9 @@ engine = create_async_engine(
# expire_on_commit=False will prevent attributes from being expired
# after commit.
AsyncSessionFactory = sessionmaker(engine, autoflush=False, expire_on_commit=False, class_=AsyncSession)
AsyncSessionFactory = sessionmaker(
engine, autoflush=False, expire_on_commit=False, class_=AsyncSession
)
# Dependency
@@ -31,4 +31,3 @@ async def get_db() -> AsyncGenerator:
async with AsyncSessionFactory() as session:
logger.debug(f"ASYNC Pool: {engine.pool.status()}")
yield session

View File

@@ -37,7 +37,9 @@ class Base:
db_session.add(self)
return await db_session.commit()
except SQLAlchemyError as ex:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)) from ex
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)
) from ex
async def delete(self, db_session: AsyncSession):
"""
@@ -50,7 +52,9 @@ class Base:
await db_session.commit()
return True
except SQLAlchemyError as ex:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)) from ex
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)
) from ex
async def update(self, db_session: AsyncSession, **kwargs):
"""

View File

@@ -29,7 +29,9 @@ class Nonsense(Base):
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}"},
detail={
"Record not found": f"There is no record for requested name value : {name}"
},
)
else:
return instance

View File

@@ -20,7 +20,10 @@ metadata = Base.metadata
class Character(Base):
__tablename__ = "character"
__table_args__ = (PrimaryKeyConstraint("id", name="character_pkey"), {"schema": "shakespeare"})
__table_args__ = (
PrimaryKeyConstraint("id", name="character_pkey"),
{"schema": "shakespeare"},
)
id = Column(String(32))
name = Column(String(64), nullable=False)
@@ -28,13 +31,18 @@ class Character(Base):
abbrev = Column(String(32))
description = Column(String(2056))
work = relationship("Work", secondary="shakespeare.character_work", back_populates="character")
work = relationship(
"Work", secondary="shakespeare.character_work", back_populates="character"
)
paragraph = relationship("Paragraph", back_populates="character")
class Wordform(Base):
__tablename__ = "wordform"
__table_args__ = (PrimaryKeyConstraint("id", name="wordform_pkey"), {"schema": "shakespeare"})
__table_args__ = (
PrimaryKeyConstraint("id", name="wordform_pkey"),
{"schema": "shakespeare"},
)
id = Column(Integer)
plain_text = Column(String(64), nullable=False)
@@ -45,7 +53,10 @@ class Wordform(Base):
class Work(Base):
__tablename__ = "work"
__table_args__ = (PrimaryKeyConstraint("id", name="work_pkey"), {"schema": "shakespeare"})
__table_args__ = (
PrimaryKeyConstraint("id", name="work_pkey"),
{"schema": "shakespeare"},
)
id = Column(String(32))
title = Column(String(32), nullable=False)
@@ -57,7 +68,9 @@ class Work(Base):
total_paragraphs = Column(Integer, nullable=False)
notes = Column(Text)
character = relationship("Character", secondary="shakespeare.character_work", back_populates="work")
character = relationship(
"Character", secondary="shakespeare.character_work", back_populates="work"
)
chapter = relationship("Chapter", back_populates="work")
paragraph = relationship("Paragraph", back_populates="work")
@@ -65,10 +78,15 @@ class Work(Base):
class Chapter(Base):
__tablename__ = "chapter"
__table_args__ = (
ForeignKeyConstraint(["work_id"], ["shakespeare.work.id"], name="chapter_work_id_fkey"),
ForeignKeyConstraint(
["work_id"], ["shakespeare.work.id"], name="chapter_work_id_fkey"
),
PrimaryKeyConstraint("id", name="chapter_pkey"),
UniqueConstraint(
"work_id", "section_number", "chapter_number", name="chapter_work_id_section_number_chapter_number_key"
"work_id",
"section_number",
"chapter_number",
name="chapter_work_id_section_number_chapter_number_key",
),
{"schema": "shakespeare"},
)
@@ -88,8 +106,14 @@ t_character_work = Table(
metadata,
Column("character_id", ForeignKey("shakespeare.character.id"), nullable=False),
Column("work_id", ForeignKey("shakespeare.work.id"), nullable=False),
ForeignKeyConstraint(["character_id"], ["shakespeare.character.id"], name="character_work_character_id_fkey"),
ForeignKeyConstraint(["work_id"], ["shakespeare.work.id"], name="character_work_work_id_fkey"),
ForeignKeyConstraint(
["character_id"],
["shakespeare.character.id"],
name="character_work_character_id_fkey",
),
ForeignKeyConstraint(
["work_id"], ["shakespeare.work.id"], name="character_work_work_id_fkey"
),
PrimaryKeyConstraint("character_id", "work_id", name="character_work_pkey"),
schema="shakespeare",
)
@@ -98,13 +122,23 @@ t_character_work = Table(
class Paragraph(Base):
__tablename__ = "paragraph"
__table_args__ = (
ForeignKeyConstraint(["character_id"], ["shakespeare.character.id"], name="paragraph_character_id_fkey"),
ForeignKeyConstraint(
["character_id"],
["shakespeare.character.id"],
name="paragraph_character_id_fkey",
),
ForeignKeyConstraint(
["work_id", "section_number", "chapter_number"],
["shakespeare.chapter.work_id", "shakespeare.chapter.section_number", "shakespeare.chapter.chapter_number"],
[
"shakespeare.chapter.work_id",
"shakespeare.chapter.section_number",
"shakespeare.chapter.chapter_number",
],
name="paragraph_chapter_fkey",
),
ForeignKeyConstraint(["work_id"], ["shakespeare.work.id"], name="paragraph_work_id_fkey"),
ForeignKeyConstraint(
["work_id"], ["shakespeare.work.id"], name="paragraph_work_id_fkey"
),
PrimaryKeyConstraint("id", name="paragraph_pkey"),
{"schema": "shakespeare"},
)
@@ -128,7 +162,13 @@ class Paragraph(Base):
@classmethod
async def find(cls, db_session: AsyncSession, character: str):
stmt = select(cls).join(Character).join(Chapter).join(Work).where(Character.name == character)
stmt = (
select(cls)
.join(Character)
.join(Chapter)
.join(Work)
.where(Character.name == character)
)
result = await db_session.execute(stmt)
instance = result.scalars().all()
return instance

View File

@@ -10,8 +10,12 @@ console = Console(color_system="256", width=200, style="blue")
@lru_cache
def get_logger(module_name):
logger = logging.getLogger(module_name)
handler = RichHandler(rich_tracebacks=True, console=console, tracebacks_show_locals=True)
handler.setFormatter(logging.Formatter("[ %(threadName)s:%(funcName)s:%(lineno)d ] - %(message)s"))
handler = RichHandler(
rich_tracebacks=True, console=console, tracebacks_show_locals=True
)
handler.setFormatter(
logging.Formatter("[ %(threadName)s:%(funcName)s:%(lineno)d ] - %(message)s")
)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger