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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file async_sqlalchemy_bridge-1.0.0.tar.gz
.
File metadata
- Download URL: async_sqlalchemy_bridge-1.0.0.tar.gz
- Upload date:
- Size: 7.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.9.19
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | fb12dfaa9e8aba871a041175f39ac6b7070fa3ae69fe028b6e117b9268db3533 |
|
MD5 | fa20f7e330b8f4dcb45dbc5b7fdd0965 |
|
BLAKE2b-256 | dbb437001b3e949c80ef650ef6bea1bfc191a1f0d2c2a0aecba7d0d3b0f015b6 |
File details
Details for the file async_sqlalchemy_bridge-1.0.0-py3-none-any.whl
.
File metadata
- Download URL: async_sqlalchemy_bridge-1.0.0-py3-none-any.whl
- Upload date:
- Size: 7.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.9.19
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 452ae7469a6c6098517cc40bcce1c1b9501e64eea98e1b0cb8603fadeb24cfd4 |
|
MD5 | 18d7b2a99d0136c99f34801d34d65acc |
|
BLAKE2b-256 | 50e52871137d1e820c7ee5593851397e2fb2ecfdb24ef72a4a93e0c0c984e5af |