Skip to main content

The async library for easy connect to postgres database

Project description

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())

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

async_sqlalchemy_bridge-1.0.0.tar.gz (7.6 kB view details)

Uploaded Source

Built Distribution

async_sqlalchemy_bridge-1.0.0-py3-none-any.whl (7.6 kB view details)

Uploaded Python 3

File details

Details for the file async_sqlalchemy_bridge-1.0.0.tar.gz.

File metadata

File hashes

Hashes for async_sqlalchemy_bridge-1.0.0.tar.gz
Algorithm Hash digest
SHA256 fb12dfaa9e8aba871a041175f39ac6b7070fa3ae69fe028b6e117b9268db3533
MD5 fa20f7e330b8f4dcb45dbc5b7fdd0965
BLAKE2b-256 dbb437001b3e949c80ef650ef6bea1bfc191a1f0d2c2a0aecba7d0d3b0f015b6

See more details on using hashes here.

File details

Details for the file async_sqlalchemy_bridge-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for async_sqlalchemy_bridge-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 452ae7469a6c6098517cc40bcce1c1b9501e64eea98e1b0cb8603fadeb24cfd4
MD5 18d7b2a99d0136c99f34801d34d65acc
BLAKE2b-256 50e52871137d1e820c7ee5593851397e2fb2ecfdb24ef72a4a93e0c0c984e5af

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page