init
This commit is contained in:
0
api/__init__.py
Normal file
0
api/__init__.py
Normal file
BIN
api/__pycache__/__init__.cpython-310.pyc
Normal file
BIN
api/__pycache__/__init__.cpython-310.pyc
Normal file
Binary file not shown.
BIN
api/__pycache__/database.cpython-310.pyc
Normal file
BIN
api/__pycache__/database.cpython-310.pyc
Normal file
Binary file not shown.
BIN
api/__pycache__/models.cpython-310.pyc
Normal file
BIN
api/__pycache__/models.cpython-310.pyc
Normal file
Binary file not shown.
14
api/app.py
Normal file
14
api/app.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
from api.di import Container
|
||||
from api.router.user import router
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.container = Container()
|
||||
app.include_router(router)
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
34
api/di.py
Normal file
34
api/di.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import os
|
||||
|
||||
from dependency_injector import containers, providers
|
||||
from repository.user import UserRepository
|
||||
from service.user import UserService
|
||||
from uow.database import Database
|
||||
|
||||
|
||||
class Container(containers.DeclarativeContainer):
|
||||
wiring_config = containers.WiringConfiguration(modules=["router.user"])
|
||||
|
||||
config = providers.Configuration(yaml_files=[f"{os.getenv('CONFIG_PATH')}"])
|
||||
|
||||
db = providers.Singleton(
|
||||
Database,
|
||||
db_url="postgresql+asyncpg://{}:{}@{}:{}/{}".format(
|
||||
config.db.user,
|
||||
config.db.password,
|
||||
config.db.host,
|
||||
# config.db.port,
|
||||
"5432",
|
||||
config.db.database,
|
||||
),
|
||||
)
|
||||
|
||||
user_repository = providers.Factory(
|
||||
UserRepository,
|
||||
session_factory=db.provided.session,
|
||||
)
|
||||
|
||||
user_service = providers.Factory(
|
||||
UserService,
|
||||
user_repository=user_repository,
|
||||
)
|
1
api/migrations/README
Normal file
1
api/migrations/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
BIN
api/migrations/__pycache__/env.cpython-310.pyc
Normal file
BIN
api/migrations/__pycache__/env.cpython-310.pyc
Normal file
Binary file not shown.
77
api/migrations/env.py
Normal file
77
api/migrations/env.py
Normal file
@@ -0,0 +1,77 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
import api.model.user # type: ignore
|
||||
from api.uow.database import Base
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
26
api/migrations/script.py.mako
Normal file
26
api/migrations/script.py.mako
Normal file
@@ -0,0 +1,26 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
Binary file not shown.
38
api/migrations/versions/ec1380cb4f18_initial.py
Normal file
38
api/migrations/versions/ec1380cb4f18_initial.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""initial
|
||||
|
||||
Revision ID: ec1380cb4f18
|
||||
Revises:
|
||||
Create Date: 2024-03-04 03:11:36.206211
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "ec1380cb4f18"
|
||||
down_revision: str | None = None
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"users",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("email", sa.String(), nullable=True),
|
||||
sa.Column("hashed_password", sa.String(), nullable=True),
|
||||
sa.Column("is_active", sa.Boolean(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("email"),
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("users")
|
||||
# ### end Alembic commands ###
|
0
api/model/__init__.py
Normal file
0
api/model/__init__.py
Normal file
20
api/model/user.py
Normal file
20
api/model/user.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from sqlalchemy import Boolean, Column, Integer, String
|
||||
|
||||
from .database import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
email = Column(String, unique=True)
|
||||
hashed_password = Column(String)
|
||||
is_active = Column(Boolean, default=True)
|
||||
|
||||
def __repr__(self):
|
||||
return (
|
||||
f"<User(id={self.id}, "
|
||||
f'email="{self.email}", '
|
||||
f'hashed_password="{self.hashed_password}", '
|
||||
f"is_active={self.is_active})>"
|
||||
)
|
0
api/repository/__init__.py
Normal file
0
api/repository/__init__.py
Normal file
48
api/repository/user.py
Normal file
48
api/repository/user.py
Normal file
@@ -0,0 +1,48 @@
|
||||
from contextlib import AbstractContextManager
|
||||
from typing import Callable
|
||||
|
||||
from model.user import User
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
class UserRepository:
|
||||
def __init__(self, session_factory: Callable[..., AbstractContextManager[Session]]) -> None:
|
||||
self.session_factory = session_factory
|
||||
|
||||
def get_all(self):
|
||||
with self.session_factory() as session:
|
||||
return session.query(User).all()
|
||||
|
||||
def get_by_id(self, user_id: int) -> User:
|
||||
with self.session_factory() as session:
|
||||
user = session.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise UserNotFoundError(user_id)
|
||||
return user
|
||||
|
||||
def add(self, email: str, password: str, is_active: bool = True) -> User:
|
||||
with self.session_factory() as session:
|
||||
user = User(email=email, hashed_password=password, is_active=is_active)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
return user
|
||||
|
||||
def delete_by_id(self, user_id: int) -> None:
|
||||
with self.session_factory() as session:
|
||||
entity: User = session.query(User).filter(User.id == user_id).first()
|
||||
if not entity:
|
||||
raise UserNotFoundError(user_id)
|
||||
session.delete(entity)
|
||||
session.commit()
|
||||
|
||||
|
||||
class NotFoundError(Exception):
|
||||
entity_name: str
|
||||
|
||||
def __init__(self, entity_id):
|
||||
super().__init__(f"{self.entity_name} not found, id: {entity_id}")
|
||||
|
||||
|
||||
class UserNotFoundError(NotFoundError):
|
||||
entity_name: str = "User"
|
0
api/router/__init__.py
Normal file
0
api/router/__init__.py
Normal file
55
api/router/user.py
Normal file
55
api/router/user.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from dependency_injector.wiring import Provide, inject
|
||||
from fastapi import APIRouter, Depends, Response, status
|
||||
|
||||
from ..di import Container
|
||||
from ..repository.user import NotFoundError
|
||||
from ..service.user import UserService
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
@inject
|
||||
def get_list(
|
||||
user_service: UserService = Depends(Provide[Container.user_service]),
|
||||
):
|
||||
return user_service.get_users()
|
||||
|
||||
|
||||
@router.get("/users/{user_id}")
|
||||
@inject
|
||||
def get_by_id(
|
||||
user_id: int,
|
||||
user_service: UserService = Depends(Provide[Container.user_service]),
|
||||
):
|
||||
try:
|
||||
return user_service.get_user_by_id(user_id)
|
||||
except NotFoundError:
|
||||
return Response(status_code=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
|
||||
@router.post("/users", status_code=status.HTTP_201_CREATED)
|
||||
@inject
|
||||
def add(
|
||||
user_service: UserService = Depends(Provide[Container.user_service]),
|
||||
):
|
||||
return user_service.create_user()
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
@inject
|
||||
def remove(
|
||||
user_id: int,
|
||||
user_service: UserService = Depends(Provide[Container.user_service]),
|
||||
):
|
||||
try:
|
||||
user_service.delete_user_by_id(user_id) # type: ignore
|
||||
except NotFoundError:
|
||||
return Response(status_code=status.HTTP_404_NOT_FOUND)
|
||||
else:
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def get_status():
|
||||
return {"status": "OK"}
|
0
api/service/__init__.py
Normal file
0
api/service/__init__.py
Normal file
22
api/service/user.py
Normal file
22
api/service/user.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from model.user import User
|
||||
from repository.user import UserRepository
|
||||
|
||||
|
||||
class UserService:
|
||||
def __init__(self, user_repository: UserRepository) -> None:
|
||||
self._repository: UserRepository = user_repository
|
||||
|
||||
def get_users(self):
|
||||
return self._repository.get_all()
|
||||
|
||||
def get_user_by_id(self, user_id: int) -> User:
|
||||
return self._repository.get_by_id(user_id)
|
||||
|
||||
async def create_user(self) -> User:
|
||||
uid = uuid4()
|
||||
return await self._repository.add(email=f"{uid}@email.com", password="pwd")
|
||||
|
||||
async def delete_user_by_id(self, user_id: int) -> None:
|
||||
return await self._repository.delete_by_id(user_id)
|
0
api/uow/__init__.py
Normal file
0
api/uow/__init__.py
Normal file
29
api/uow/database.py
Normal file
29
api/uow/database.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self, db_url: str) -> None:
|
||||
self._engine = create_async_engine(db_url, echo=True)
|
||||
self._async_session = async_sessionmaker(
|
||||
self._engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
async def __aenter__(self):
|
||||
async with self._async_session() as session:
|
||||
self.session = session
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
await self.session.rollback()
|
||||
await self.session.close()
|
||||
|
||||
async def commit(self):
|
||||
await self.session.commit()
|
||||
|
||||
async def rollback(self):
|
||||
await self.session.rollback()
|
Reference in New Issue
Block a user