This commit is contained in:
dderbentsov
2023-07-13 01:25:29 +03:00
commit bc339cefb9
25 changed files with 494 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*.cpython
__pycache__

1
Dockerfile Normal file
View File

@@ -0,0 +1 @@
FROM python:3.11.3

89
alembic.ini Normal file
View File

@@ -0,0 +1,89 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migration
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; this defaults
# to migration/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat migration/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = postgresql://barbie:redStar4,1@localhost:5432/personal_info_db
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

1
migration/README Normal file
View File

@@ -0,0 +1 @@
Generic single-database configuration.

78
migration/env.py Normal file
View File

@@ -0,0 +1,78 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from personal_info.db.models 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.
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():
"""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():
"""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()

24
migration/script.py.mako Normal file
View File

@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

5
notes.txt Normal file
View File

@@ -0,0 +1,5 @@
export PYTHONPATH='/home/dd/astra/personal_information/src'
docker run -itd -e POSTGRES_USER=barbie -e POSTGRES_PASSWORD=redStar4,1 -p 5432:5432 -v /home/dd/astra/postgresql_db:/var/lib/postgresql/data --name personal_info_db postgres
docker exec -it personal_info_db bash
psql -U barbie -d barbie
CREATE DATABASE personal_info_db;

67
requirements.txt Normal file
View File

@@ -0,0 +1,67 @@
# This file may be used to create an environment using:
# $ conda create --name <env> --file <this file>
# platform: linux-64
_libgcc_mutex=0.1=conda_forge
_openmp_mutex=4.5=2_gnu
alembic=1.10.4=pyhd8ed1ab_0
anyio=3.6.2=pyhd8ed1ab_0
bzip2=1.0.8=h7f98852_4
ca-certificates=2022.12.7=ha878542_0
certifi=2022.12.7=pyhd8ed1ab_0
click=8.1.3=py311h38be061_1
colorama=0.4.6=pyhd8ed1ab_0
exceptiongroup=1.1.1=pyhd8ed1ab_0
fastapi=0.95.1=pyhd8ed1ab_0
greenlet=2.0.2=py311hcafe171_0
h11=0.14.0=pyhd8ed1ab_0
h2=4.1.0=pyhd8ed1ab_0
hpack=4.0.0=pyh9f0ad1d_0
httpcore=0.17.0=pyhd8ed1ab_0
httpx=0.24.0=pyhd8ed1ab_1
hyperframe=6.0.1=pyhd8ed1ab_0
idna=3.4=pyhd8ed1ab_0
importlib-metadata=6.6.0=pyha770c72_0
importlib_resources=5.12.0=pyhd8ed1ab_0
iniconfig=2.0.0=pyhd8ed1ab_0
keyutils=1.6.1=h166bdaf_0
krb5=1.20.1=h81ceb04_0
ld_impl_linux-64=2.40=h41732ed_0
libedit=3.1.20191231=he28a2e2_2
libexpat=2.5.0=hcb278e6_1
libffi=3.4.2=h7f98852_5
libgcc-ng=12.2.0=h65d4601_19
libgomp=12.2.0=h65d4601_19
libnsl=2.0.0=h7f98852_0
libpq=15.2=hb675445_0
libsqlite=3.40.0=h753d276_1
libstdcxx-ng=12.2.0=h46fd767_19
libuuid=2.38.1=h0b41bf4_0
libzlib=1.2.13=h166bdaf_4
mako=1.2.4=pyhd8ed1ab_0
markupsafe=2.1.2=py311h2582759_0
ncurses=6.3=h27087fc_1
openssl=3.1.0=hd590300_3
packaging=23.1=pyhd8ed1ab_0
pip=23.1.2=pyhd8ed1ab_0
pluggy=1.0.0=py311h38be061_4
psycopg2=2.9.3=py311h968e94b_2
psycopg2-binary=2.9.3=pyhd8ed1ab_2
pydantic=1.10.7=py311h2582759_0
pytest=7.3.1=pyhd8ed1ab_0
python=3.11.3=h2755cc3_0_cpython
python-dotenv=1.0.0=pyhd8ed1ab_0
python_abi=3.11=3_cp311
readline=8.2=h8228510_1
setuptools=67.7.2=pyhd8ed1ab_0
sniffio=1.3.0=pyhd8ed1ab_0
sqlalchemy=2.0.11=py311h459d7ec_0
starlette=0.26.1=pyhd8ed1ab_0
tk=8.6.12=h27826a3_0
tomli=2.0.1=pyhd8ed1ab_0
typing-extensions=4.5.0=hd8ed1ab_0
typing_extensions=4.5.0=pyha770c72_0
tzdata=2023c=h71feb2d_0
uvicorn=0.22.0=py311h38be061_0
wheel=0.40.0=pyhd8ed1ab_0
xz=5.2.6=h166bdaf_0
zipp=3.15.0=pyhd8ed1ab_0

13
setup.py Normal file
View File

@@ -0,0 +1,13 @@
from setuptools import find_packages, setup
install_requires = ['fastapi', 'uvicorn']
setup(
name='personal_info',
install_requires=install_requires,
use_scm_version=True,
setup_requires=['setuptools_scm'],
packages=find_packages(where='src'),
package_dir={'':'src'},
include_package_data=True,
)

View File

19
src/personal_info/app.py Normal file
View File

@@ -0,0 +1,19 @@
from fastapi import FastAPI
def create_app() -> FastAPI:
app = FastAPI (
title='personal_info',
description='Personal Information Service',
version='1.0'
)
@app.get('/health')
async def health() -> str:
return 'ok'
from personal_info.routers import persons
app.include(persons.router)
return app

View File

@@ -0,0 +1,15 @@
from functools import lru_cache
from typing import Optional
from pydantic import BaseSettings, PostgresDsn
class Settings(BaseSettings):
database_url: Optional[PostgresDsn]
@lru_cache
def get_settings() -> Settings:
settings = Settings() # type: ignore
print('333333333333333333333333333333333333333333')
print(settings)
#CONTINUE
return settings

View File

View File

@@ -0,0 +1,17 @@
import uuid
from typing import Any
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.sql.schema import ForeignKey
Base: Any = declarative_base()
class Person(Base):
__tablename__ = 'people'
id = sa.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
first_name = sa.Column(sa.Text, nullable=False)
last_name = sa.Column(sa.Text, nullable=False)

View File

@@ -0,0 +1 @@
from .person import *

View File

@@ -0,0 +1,16 @@
from datetime import datetime
from typing import List
from pydantic import BaseModel, Field
from pydantic.types import UUID4
class Person(BaseModel):
id: UUID4
first_name: str
last_name: str
class PersonCreate(Person):
pass
class PersonDetail(Person):
pass

View File

@@ -0,0 +1,23 @@
from functools import lru_cache
from typing import Generator
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from personal_info.config import get_settings
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
@lru_cache
def create_session() -> scoped_session:
Session = scoped_session(
sessionmaker(autocommit=False, autoflush=False, bind=engine)
)
return Session
def get_session() -> Generator[scoped_session, None, None]:
Session = create_session()
try:
yield Session
finally:
Session.remove()

View File

@@ -0,0 +1,3 @@
from personal_info.app import create_app
app = create_app()

View File

View File

@@ -0,0 +1,27 @@
from fastapi import Depends
from fastapi.routing import APIRouter
from pydantic.types import UUID4
from personal_info.db import models
from personal_info.db.schemas import Person, PersonDetail
from personal_info.services import PersonService, get_persons_service
router = APIrouter(prefix='/people')
@router.get('/', response_model=List[Person])
async def list_persons(
persons_service: PersonService = Depends(get_persons_service),
) -> List[models.Person]:
return persons_service.list()
@router.get('/{person_id}', response_model=PersonDetail)
async def get_person(
person_id: UUID4, persons_service: PersonService = Depends(get_persons_service)
) -> Optional[models.Person]:
return persons_service.get(person_id)
@router.post('/', status_code=201, response_model=PersonDetail)
async def create_person(
person: PersonCreate, persons_service: PersonService = Depends(get_persons_service)
) -> models.Person:
return persons_service.create(person)

View File

@@ -0,0 +1,11 @@
from fastapi import Depends
from sqlalchemy.orm import Session
from personal_info.db.session import get_session
from .people import PersonService
def get_persons_service(db_session: Session = Depends(get_session)) -> PersonService:
return PersonService(db_session)
__all__ = ('get_persons_service')

View File

@@ -0,0 +1,52 @@
from typing import Any, Generic, List, Optional, Type, TypeVar
import sqlalchemy
from pydantic import BaseModel
from sqlalchemy.orm import Session
from starlette.exceptions import HTTPException
from personal_info.db.models import Base
ModelType = TypeVar('ModelType', bound=Base)
CreateSchemaType = TypeVar('CreateSchemaType', bound=BaseModel)
UpdateSchemaType = TypeVar('UpdateSchemaType', bound=BaseModel)
class BaseService(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
def __init__(self, model: Type[ModelType], db_session: Session):
self.model = model
self.db_session = db_session
def get(self, id: Any) -> Optional[ModelType]:
obj: Optional[ModelType] = self.db_session.get(self.model, id)
if obj is None:
raise HTTPException(status_code=404, detail='NotFound')
return obj
def list(self) -> List[ModelType]:
objs: List[ModelType] = self.db_session.query(self.model).all()
return objs
def create(self, obj: CreateSchemaType) -> ModelType:
db_obj: ModelType = self.model(**obj.dict())
self.db_session.add(db_obj)
try:
self.db_session.commit()
except sqlalchemy.exc.IntegrityError as e:
self.db_session.rollback()
if 'duplicate key' in str(e):
raise HTTPException(status_code=409, detail='Conflict Error')
else:
raise e
return db_obj
def update(self, id: Any, obj: UpdateSchemaType) -> Optional[ModelType]:
db_obj = self.get(id)
for column, value in obj.dict(exclude_unset=True).items():
setattr(db_obj, column, value)
self.db_session.commit()
return db_obj
def delete(self, id: Any) -> None:
db_obj = self.db_session.get(self.model, id)
self.db_session.delete(db_obj)
self.db_session.commit()

View File

@@ -0,0 +1,19 @@
from typing import Any
from sqlalchemy.orm import Session
from personal_info.db.models import Person
from personal_info.db.schemas import PersonCreate
from personal_info.services.base import BaseService
class PersonService(BaseService[Person, PersonCreate, Any]):
def __init__(self, db_session: Session):
super(PersonService, self).__init__(Person, db_session)
def create(self, obj: PersonCreate) -> Person:
person: Person = Person()
self.db_session.add(person)
self.db_session.flush()
self.db_session.commit()
return person

8
tests/conftest.py Normal file
View File

@@ -0,0 +1,8 @@
from fastapi.testclient import TestClient
import pytest
from personal_info.app import create_app
@pytest.fixture()
def app_client():
app = create_app()
yield TestClient(app)

3
tests/test_app.py Normal file
View File

@@ -0,0 +1,3 @@
def test_health(app_client):
rv = app_client.get('/health')
assert rv.status_code == 200