Skip to main content

Database lib Async

Обертка над SqlAlchemy для успешного асинхронного взаимодействия с базой данных

Параметры

Наименование Обязательность Тип Пример
props да AbstractEngineProps EngineProps.initialize("postgresql+asyncpg://test:test@localhost:5432/test", "example_project")

Методы класса

Наименование Что делает Принимаемые параметры Возвращаемый объект
get_dep_session Возвращает сессию для работы с БД. Используется в Dependency - AsyncSession
get_session Возвращает сессию для работы с БД - AsyncGenerator[AsyncSession, None]
init_echo_compiled_query Инициализирует логгирование скомпилированных запросов к БД. Лучше, чем использовать echo в engin'e log: Optional[Logger] -

Атрибуты класса

Наименование Возвращаемый объект
async_session_maker AsyncGenerator[AsyncSession, None]
engine AsyncEngine

Example

import logging
import asyncio

from fastapi import FastAPI, Depends
from sqlalchemy import Integer, String, MetaData
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, mapped_column, declarative_base

from async_sqlalchemy_bridge import AsyncDataBase, EngineProps, CrudRepository

Base = declarative_base(metadata=MetaData(schema="public"))

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - [%(levelname)s] - %(name)s - (%(filename)s).%(funcName)s(%(lineno)d) - %(message)s",
    datefmt='%H:%M:%S',
)

logger = logging.getLogger(__name__)


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment="Идентификатор записи")
    first_name: Mapped[str] = mapped_column(String(30), comment="Имя", nullable=False)
    last_name: Mapped[str] = mapped_column(String(50), comment="Фамилия", nullable=False)


class Repo(CrudRepository):
    _table = User


def init_db() -> AsyncDataBase:
    props = EngineProps.initialize("postgresql+asyncpg://test:test@localhost:5432/test", "example_project")
    db = AsyncDataBase(props)
    db.init_echo_compiled_query(logger)
    return db


async def create_tables(db: AsyncDataBase) -> None:
    async with db.engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all, checkfirst=True)


async def main():
    db: AsyncDataBase = init_db()
    await create_tables(db)
    async with db.get_session() as session:
        repo = Repo(session)
        user = User(
            first_name="Ivan",
            last_name="Ivanov"
        )
        await repo.create(user)
        await session.commit()


def some_fastapi():
    app = FastAPI()
    db: AsyncDataBase = init_db()

    @app.put("/add")
    async def root(first_name: str, last_name: str, session: AsyncSession = Depends(db.get_dep_session)) -> int:
        repo = Repo(session)
        user = User(
            first_name=first_name,
            last_name=last_name
        )
        await repo.create(user)
        await session.commit()
        return user.id


if __name__ == "__main__":
    asyncio.run(main())

Metadata

Release files for async-sqlalchemy-bridge 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for async-sqlalchemy-bridge 1.0.0
File Size Uploaded
async_sqlalchemy_bridge-1.0.0.tar.gz 7.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for async-sqlalchemy-bridge 1.0.0
File Interpreter ABI Platform
async_sqlalchemy_bridge-1.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 15.3 kB

Release files / async_sqlalchemy_bridge-1.0.0.tar.gz

Download URL async_sqlalchemy_bridge-1.0.0.tar.gz
Size 7.6 kB
Tags Source
SHA-256 checksum
How to use checksums
fb12dfaa9e8aba871a041175f39ac6b7070fa3ae69fe028b6e117b9268db3533
BLAKE2b-256 checksum
How to use checksums
dbb437001b3e949c80ef650ef6bea1bfc191a1f0d2c2a0aecba7d0d3b0f015b6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.9.19

Release files / async_sqlalchemy_bridge-1.0.0-py3-none-any.whl

Download URL async_sqlalchemy_bridge-1.0.0-py3-none-any.whl
Size 7.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
452ae7469a6c6098517cc40bcce1c1b9501e64eea98e1b0cb8603fadeb24cfd4
BLAKE2b-256 checksum
How to use checksums
50e52871137d1e820c7ee5593851397e2fb2ecfdb24ef72a4a93e0c0c984e5af
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.9.19

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page