Compare commits

...

9 Commits

Author SHA1 Message Date
sergey fab67f6ea9 https://www.youtube.com/watch?v=XWJWJfTWjSs&list=PLYnH8mpFQ4akzzS1D9IHkMuXacb-bD4Cl&index=9 2024-07-11 22:25:42 +03:00
sergey a32abcf472 use alembic 2024-07-11 22:13:33 +03:00
sergey afdc8e30ca use alembic 2024-07-11 21:56:42 +03:00
sergey 8a567298bc set alembic 2024-07-11 21:52:45 +03:00
sergey dc0b008e14 set alembic 2024-07-11 21:49:14 +03:00
sergey 62541a0795 set alembic 2024-07-11 21:48:42 +03:00
sergey 249ce34717 alembic 2024-07-11 21:44:03 +03:00
sergey 6cf72d26b5 добавлен конвертер + базовый класс 2024-07-11 21:26:30 +03:00
sergey 88f6524ef6 работает 2024-07-11 21:01:46 +03:00
21 changed files with 554 additions and 17 deletions

7
.gitignore vendored
View File

@ -1,6 +1,7 @@
.vscode !alembic/
.vscode/
.env .env
.venv .venv/
.log .log
.idea .idea/
*.idea *.idea

9
docker-compose.yml Normal file
View File

@ -0,0 +1,9 @@
services:
pg:
image: postgres
environment:
POSTGRES_DB: sipi
POSTGRES_USER: sys.sipidb
POSTGRES_PASSWORD: password
ports:
- "5432:5432"

122
poetry.lock generated
View File

@ -18,6 +18,25 @@ PyMySQL = ">=1.0"
rsa = ["PyMySQL[rsa] (>=1.0)"] rsa = ["PyMySQL[rsa] (>=1.0)"]
sa = ["sqlalchemy (>=1.3,<1.4)"] sa = ["sqlalchemy (>=1.3,<1.4)"]
[[package]]
name = "alembic"
version = "1.13.2"
description = "A database migration tool for SQLAlchemy."
optional = false
python-versions = ">=3.8"
files = [
{file = "alembic-1.13.2-py3-none-any.whl", hash = "sha256:6b8733129a6224a9a711e17c99b08462dbf7cc9670ba8f2e2ae9af860ceb1953"},
{file = "alembic-1.13.2.tar.gz", hash = "sha256:1ff0ae32975f4fd96028c39ed9bb3c867fe3af956bd7bb37343b54c9fe7445ef"},
]
[package.dependencies]
Mako = "*"
SQLAlchemy = ">=1.3.0"
typing-extensions = ">=4"
[package.extras]
tz = ["backports.zoneinfo"]
[[package]] [[package]]
name = "annotated-types" name = "annotated-types"
version = "0.7.0" version = "0.7.0"
@ -103,6 +122,50 @@ files = [
docs = ["Sphinx (>=5.3.0,<5.4.0)", "sphinx-rtd-theme (>=1.2.2)", "sphinxcontrib-asyncio (>=0.3.0,<0.4.0)"] docs = ["Sphinx (>=5.3.0,<5.4.0)", "sphinx-rtd-theme (>=1.2.2)", "sphinxcontrib-asyncio (>=0.3.0,<0.4.0)"]
test = ["flake8 (>=6.1,<7.0)", "uvloop (>=0.15.3)"] test = ["flake8 (>=6.1,<7.0)", "uvloop (>=0.15.3)"]
[[package]]
name = "black"
version = "24.4.2"
description = "The uncompromising code formatter."
optional = false
python-versions = ">=3.8"
files = [
{file = "black-24.4.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:dd1b5a14e417189db4c7b64a6540f31730713d173f0b63e55fabd52d61d8fdce"},
{file = "black-24.4.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e537d281831ad0e71007dcdcbe50a71470b978c453fa41ce77186bbe0ed6021"},
{file = "black-24.4.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eaea3008c281f1038edb473c1aa8ed8143a5535ff18f978a318f10302b254063"},
{file = "black-24.4.2-cp310-cp310-win_amd64.whl", hash = "sha256:7768a0dbf16a39aa5e9a3ded568bb545c8c2727396d063bbaf847df05b08cd96"},
{file = "black-24.4.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:257d724c2c9b1660f353b36c802ccece186a30accc7742c176d29c146df6e474"},
{file = "black-24.4.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:bdde6f877a18f24844e381d45e9947a49e97933573ac9d4345399be37621e26c"},
{file = "black-24.4.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e151054aa00bad1f4e1f04919542885f89f5f7d086b8a59e5000e6c616896ffb"},
{file = "black-24.4.2-cp311-cp311-win_amd64.whl", hash = "sha256:7e122b1c4fb252fd85df3ca93578732b4749d9be076593076ef4d07a0233c3e1"},
{file = "black-24.4.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:accf49e151c8ed2c0cdc528691838afd217c50412534e876a19270fea1e28e2d"},
{file = "black-24.4.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:88c57dc656038f1ab9f92b3eb5335ee9b021412feaa46330d5eba4e51fe49b04"},
{file = "black-24.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:be8bef99eb46d5021bf053114442914baeb3649a89dc5f3a555c88737e5e98fc"},
{file = "black-24.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:415e686e87dbbe6f4cd5ef0fbf764af7b89f9057b97c908742b6008cc554b9c0"},
{file = "black-24.4.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:bf10f7310db693bb62692609b397e8d67257c55f949abde4c67f9cc574492cc7"},
{file = "black-24.4.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:98e123f1d5cfd42f886624d84464f7756f60ff6eab89ae845210631714f6db94"},
{file = "black-24.4.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:48a85f2cb5e6799a9ef05347b476cce6c182d6c71ee36925a6c194d074336ef8"},
{file = "black-24.4.2-cp38-cp38-win_amd64.whl", hash = "sha256:b1530ae42e9d6d5b670a34db49a94115a64596bc77710b1d05e9801e62ca0a7c"},
{file = "black-24.4.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:37aae07b029fa0174d39daf02748b379399b909652a806e5708199bd93899da1"},
{file = "black-24.4.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:da33a1a5e49c4122ccdfd56cd021ff1ebc4a1ec4e2d01594fef9b6f267a9e741"},
{file = "black-24.4.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ef703f83fc32e131e9bcc0a5094cfe85599e7109f896fe8bc96cc402f3eb4b6e"},
{file = "black-24.4.2-cp39-cp39-win_amd64.whl", hash = "sha256:b9176b9832e84308818a99a561e90aa479e73c523b3f77afd07913380ae2eab7"},
{file = "black-24.4.2-py3-none-any.whl", hash = "sha256:d36ed1124bb81b32f8614555b34cc4259c3fbc7eec17870e8ff8ded335b58d8c"},
{file = "black-24.4.2.tar.gz", hash = "sha256:c872b53057f000085da66a19c55d68f6f8ddcac2642392ad3a355878406fbd4d"},
]
[package.dependencies]
click = ">=8.0.0"
mypy-extensions = ">=0.4.3"
packaging = ">=22.0"
pathspec = ">=0.9.0"
platformdirs = ">=2"
[package.extras]
colorama = ["colorama (>=0.4.3)"]
d = ["aiohttp (>=3.7.4)", "aiohttp (>=3.7.4,!=3.9.0)"]
jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"]
uvloop = ["uvloop (>=0.15.2)"]
[[package]] [[package]]
name = "certifi" name = "certifi"
version = "2024.7.4" version = "2024.7.4"
@ -432,6 +495,25 @@ MarkupSafe = ">=2.0"
[package.extras] [package.extras]
i18n = ["Babel (>=2.7)"] i18n = ["Babel (>=2.7)"]
[[package]]
name = "mako"
version = "1.3.5"
description = "A super-fast templating language that borrows the best ideas from the existing templating languages."
optional = false
python-versions = ">=3.8"
files = [
{file = "Mako-1.3.5-py3-none-any.whl", hash = "sha256:260f1dbc3a519453a9c856dedfe4beb4e50bd5a26d96386cb6c80856556bb91a"},
{file = "Mako-1.3.5.tar.gz", hash = "sha256:48dbc20568c1d276a2698b36d968fa76161bf127194907ea6fc594fa81f943bc"},
]
[package.dependencies]
MarkupSafe = ">=0.9.2"
[package.extras]
babel = ["Babel"]
lingua = ["lingua"]
testing = ["pytest"]
[[package]] [[package]]
name = "markdown-it-py" name = "markdown-it-py"
version = "3.0.0" version = "3.0.0"
@ -536,6 +618,17 @@ files = [
{file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"}, {file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"},
] ]
[[package]]
name = "mypy-extensions"
version = "1.0.0"
description = "Type system extensions for programs checked with the mypy type checker."
optional = false
python-versions = ">=3.5"
files = [
{file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"},
{file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"},
]
[[package]] [[package]]
name = "orjson" name = "orjson"
version = "3.10.6" version = "3.10.6"
@ -607,6 +700,33 @@ files = [
{file = "packaging-24.1.tar.gz", hash = "sha256:026ed72c8ed3fcce5bf8950572258698927fd1dbda10a5e981cdf0ac37f4f002"}, {file = "packaging-24.1.tar.gz", hash = "sha256:026ed72c8ed3fcce5bf8950572258698927fd1dbda10a5e981cdf0ac37f4f002"},
] ]
[[package]]
name = "pathspec"
version = "0.12.1"
description = "Utility library for gitignore style pattern matching of file paths."
optional = false
python-versions = ">=3.8"
files = [
{file = "pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08"},
{file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"},
]
[[package]]
name = "platformdirs"
version = "4.2.2"
description = "A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`."
optional = false
python-versions = ">=3.8"
files = [
{file = "platformdirs-4.2.2-py3-none-any.whl", hash = "sha256:2d7a1657e36a80ea911db832a8a6ece5ee53d8de21edd5cc5879af6530b1bfee"},
{file = "platformdirs-4.2.2.tar.gz", hash = "sha256:38b7b51f512eed9e84a22788b4bce1de17c0adb134d6becb09836e37d8654cd3"},
]
[package.extras]
docs = ["furo (>=2023.9.10)", "proselint (>=0.13)", "sphinx (>=7.2.6)", "sphinx-autodoc-typehints (>=1.25.2)"]
test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=7.4.3)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)"]
type = ["mypy (>=1.8)"]
[[package]] [[package]]
name = "pluggy" name = "pluggy"
version = "1.5.0" version = "1.5.0"
@ -1401,4 +1521,4 @@ files = [
[metadata] [metadata]
lock-version = "2.0" lock-version = "2.0"
python-versions = "^3.12" python-versions = "^3.12"
content-hash = "3bede1020d1a7fb055f4332cb83dd555c5edb67f8c6afb67ad02a6e839655ec6" content-hash = "b805d7217d4a5f810fa35f95f5c0525af761ce3cd4b71676ae11a309feb547f4"

View File

@ -15,9 +15,11 @@ pydantic-settings = "^2.3.4"
sqlalchemy = {extras = ["asyncio"], version = "^2.0.31"} sqlalchemy = {extras = ["asyncio"], version = "^2.0.31"}
aiomysql = "^0.2.0" aiomysql = "^0.2.0"
asyncpg = "^0.29.0" asyncpg = "^0.29.0"
alembic = "^1.13.2"
[tool.poetry.group.dev.dependencies] [tool.poetry.group.dev.dependencies]
pytest = "^8.2.2" pytest = "^8.2.2"
black = "^24.4.2"
[build-system] [build-system]
requires = ["poetry-core"] requires = ["poetry-core"]

2
sipi-app/.env-template Normal file
View File

@ -0,0 +1,2 @@
SIPI_CONFIG__DB__URL=postgresql+asyncpg://username:password@localhost:5432/dbname
SIPI_CONFIG__DB__ECHO=0

114
sipi-app/alembic.ini Normal file
View File

@ -0,0 +1,114 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# Use forward slashes (/) also on windows to provide an os agnostic path
script_location = alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(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.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# 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 alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = driver://user:pass@localhost/dbname
[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
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix 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
sipi-app/alembic/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration with an async dbapi.

92
sipi-app/alembic/env.py Normal file
View File

@ -0,0 +1,92 @@
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
from core.config import settings
from core.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.
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.
config.set_main_option('sqlalchemy.url', str(settings.db.url))
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 do_run_migrations(connection: Connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View 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"}

View File

@ -0,0 +1,34 @@
"""create users table
Revision ID: 799cc8915cb1
Revises:
Create Date: 2024-07-11 22:08:25.362239
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "799cc8915cb1"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("username", sa.String(), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_users")),
sa.UniqueConstraint("username", name=op.f("uq_users_username")),
)
def downgrade() -> None:
op.drop_table("users")

View File

@ -0,0 +1,37 @@
"""update users table
Revision ID: 443e39c236a6
Revises: 799cc8915cb1
Create Date: 2024-07-11 22:11:47.011912
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "443e39c236a6"
down_revision: Union[str, None] = "799cc8915cb1"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("users", sa.Column("foo", sa.Integer(), nullable=False))
op.add_column("users", sa.Column("bar", sa.Integer(), nullable=False))
op.create_unique_constraint(
op.f("uq_users_foo_bar"), "users", ["foo", "bar"]
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(op.f("uq_users_foo_bar"), "users", type_="unique")
op.drop_column("users", "bar")
op.drop_column("users", "foo")
# ### end Alembic commands ###

View File

@ -0,0 +1,13 @@
from fastapi import APIRouter
from core.config import settings
from .users import router as users_router
router = APIRouter(
prefix=settings.api.v1.users,
)
router.include_router(users_router,
prefix=settings.api.v1.users,
)

View File

@ -0,0 +1,6 @@
from fastapi import APIRouter
router = APIRouter(
tags=['Users'],
)

View File

@ -14,8 +14,14 @@ class RunConfig(BaseModel):
reload: bool = True reload: bool = True
class ApiV1Prefix(BaseModel):
prefix: str = '/v1'
users: str = '/users'
class ApiPrefix(BaseModel): class ApiPrefix(BaseModel):
prefix: str = '/api' prefix: str = '/api'
v1: ApiV1Prefix = ApiV1Prefix()
class DatabaseConfig(BaseModel): class DatabaseConfig(BaseModel):
@ -26,19 +32,19 @@ class DatabaseConfig(BaseModel):
max_overflow: int = 10 max_overflow: int = 10
naming_convention: dict[str, str] = { naming_convention: dict[str, str] = {
"ix": "ix_%(column_0_label)s", 'ix': 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_N_name)s", 'uq': 'uq_%(table_name)s_%(column_0_N_name)s',
"ck": "ck_%(table_name)s_%(constraint_name)s", 'ck': 'ck_%(table_name)s_%(constraint_name)s',
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", 'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s',
"pk": "pk_%(table_name)s", 'pk': 'pk_%(table_name)s',
} }
class Settings(BaseSettings): class Settings(BaseSettings):
model_config = SettingsConfigDict( model_config = SettingsConfigDict(
env_file=(".env.template", ".env"), env_file=('.env-template', '.env'),
case_sensitive=False, case_sensitive=False,
env_nested_delimiter="__", env_nested_delimiter='__',
env_prefix="APP_CONFIG__", env_prefix='SIPI_CONFIG__',
) )
run: RunConfig = RunConfig() run: RunConfig = RunConfig()
api: ApiPrefix = ApiPrefix() api: ApiPrefix = ApiPrefix()
@ -46,3 +52,4 @@ class Settings(BaseSettings):
settings = Settings() settings = Settings()

View File

@ -1,5 +1,9 @@
__all__ = ( __all__ = (
'db_helper' 'db_helper',
'Base',
'User',
) )
from .db_helper import db_helper from .db_helper import db_helper
from .base import Base
from .user import User

View File

@ -0,0 +1,19 @@
from sqlalchemy import MetaData
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, declared_attr
from core.config import settings
from utils import camel_case_to_snake_case
class Base(DeclarativeBase):
__abstract__ = True
metadata = MetaData(
naming_convention=settings.db.naming_convention,
)
@declared_attr.directive
def __tablename__(cls) -> str:
return f'{camel_case_to_snake_case(cls.__name__)}s'
id: Mapped[int] = mapped_column(primary_key=True)

View File

@ -1,4 +1,8 @@
from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, async_sessionmaker, AsyncSession from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncEngine
from sqlalchemy.ext.asyncio import async_sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession
from typing import AsyncGenerator from typing import AsyncGenerator
from core.config import settings from core.config import settings

View File

@ -0,0 +1,14 @@
from sqlalchemy import UniqueConstraint
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from .base import Base
class User(Base):
username: Mapped[str] = mapped_column(unique=True)
foo: Mapped[int]
bar: Mapped[int]
__table_args__ = (
UniqueConstraint('foo', 'bar'),
)

View File

@ -10,15 +10,13 @@ from fastapi import FastAPI
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
#startap
yield yield
#shutdown
print('dispose engine')
await db_helper.dispose() await db_helper.dispose()
main_app = FastAPI( main_app = FastAPI(
lifespan=lifespan, lifespan=lifespan,
) )
main_app.include_router(api_router, main_app.include_router(api_router,
prefix=settings.api.prefix) prefix=settings.api.prefix)

View File

@ -0,0 +1,5 @@
__all__ = (
'camel_case_to_snake_case',
)
from .case_converter import camel_case_to_snake_case

View File

@ -0,0 +1,29 @@
"""
Taken from
https://github.com/mahenzon/ri-sdk-python-wrapper/blob/master/ri_sdk_codegen/utils/case_converter.py
"""
def camel_case_to_snake_case(input_str: str) -> str:
"""
>>> camel_case_to_snake_case("SomeSDK")
'some_sdk'
>>> camel_case_to_snake_case("RServoDrive")
'r_servo_drive'
>>> camel_case_to_snake_case("SDKDemo")
'sdk_demo'
"""
chars = []
for c_idx, char in enumerate(input_str):
if c_idx and char.isupper():
nxt_idx = c_idx + 1
# idea of the flag is to separate abbreviations
# as new words, show them in lower case
flag = nxt_idx >= len(input_str) or input_str[nxt_idx].isupper()
prev_char = input_str[c_idx - 1]
if prev_char.isupper() and flag:
pass
else:
chars.append("_")
chars.append(char.lower())
return "".join(chars)