Код: Выделить всё
pgsql_session.add(record)
await pgsql_session.commit()
Я использую asyncpg==0.30.0, SQLAlchemy==2.0.20, fastapi==0.109.1, uvicorn==0.23.2, SQLAlchemy== 2.0.20
Моя связь:
Код: Выделить всё
async_pgsql_engine = create_async_engine(
ASYNC_PGSQL_URI,
pool_size=PGSQL_MAX_POOL_SIZE,
max_overflow=PGSQL_MAX_POOL_OVERFLOW,
pool_recycle=PGSQL_POOL_RECYCLE,
)
AsyncSessionFactory = async_sessionmaker(
async_pgsql_engine,
autoflush=False,
expire_on_commit=False,
)
@asynccontextmanager
async def async_pgsql_session_manager() -> AsyncGenerator:
async with AsyncSessionFactory() as session:
try:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()
Код: Выделить всё
async def async_store_user_info(
user_id: int,
latitude: float | None,
longitude: float | None,
list_x: list[int],
list_y: list[int],
ab_test_group: str | None = None,
):
# Create the model instance
record = User(
user_id=user_id,
latitude=latitude,
longitude=longitude,
list_x=x if len(x) > 0 else null(),
list_y=y if len(y) > 0 else null(),
last_connection_date_utc=datetime.now(timezone.utc).replace(tzinfo=None),
ab_test_group=ab_test_group,
)
# Use the asynchronous session manager to insert the record
async with async_pgsql_session_manager() as pgsql_session:
pgsql_session.add(record)
await pgsql_session.commit()
Код: Выделить всё
@app.get("/write_data_to_postgresql/{user_id}")
async def write_data_to_postgresql(
user_id: int,
lat:float|None,
log:float|None,
x: list[int]|None,
y:list[int]|None
):
try:
task = asyncio.create_task(
async_store_user_info(
user_id=user_id,
latitude=lat,
longitude=log,
list_x=x,
list_y=y
ab_test_group=None,
)
)
await task
except Exception as exc:
logger.error(f"Error occurred while writing data to postgresql {exc}")
Подробнее здесь: https://stackoverflow.com/questions/793 ... in-product