mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
Проверка 09.02.2025
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
# ext/asyncio/__init__.py
|
||||
# Copyright (C) 2020-2024 the SQLAlchemy authors and contributors
|
||||
# Copyright (C) 2020-2025 the SQLAlchemy authors and contributors
|
||||
# <see AUTHORS file>
|
||||
#
|
||||
# This module is part of SQLAlchemy and is released under
|
||||
|
@@ -1,5 +1,5 @@
|
||||
# ext/asyncio/base.py
|
||||
# Copyright (C) 2020-2024 the SQLAlchemy authors and contributors
|
||||
# Copyright (C) 2020-2025 the SQLAlchemy authors and contributors
|
||||
# <see AUTHORS file>
|
||||
#
|
||||
# This module is part of SQLAlchemy and is released under
|
||||
@@ -224,7 +224,9 @@ def asyncstartablecontext(
|
||||
``@contextlib.asynccontextmanager`` supports, and the usage pattern
|
||||
is different as well.
|
||||
|
||||
Typical usage::
|
||||
Typical usage:
|
||||
|
||||
.. sourcecode:: text
|
||||
|
||||
@asyncstartablecontext
|
||||
async def some_async_generator(<arguments>):
|
||||
|
@@ -1,5 +1,5 @@
|
||||
# ext/asyncio/engine.py
|
||||
# Copyright (C) 2020-2024 the SQLAlchemy authors and contributors
|
||||
# Copyright (C) 2020-2025 the SQLAlchemy authors and contributors
|
||||
# <see AUTHORS file>
|
||||
#
|
||||
# This module is part of SQLAlchemy and is released under
|
||||
@@ -41,6 +41,8 @@ from ...engine.base import NestedTransaction
|
||||
from ...engine.base import Transaction
|
||||
from ...exc import ArgumentError
|
||||
from ...util.concurrency import greenlet_spawn
|
||||
from ...util.typing import Concatenate
|
||||
from ...util.typing import ParamSpec
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ...engine.cursor import CursorResult
|
||||
@@ -61,6 +63,7 @@ if TYPE_CHECKING:
|
||||
from ...sql.base import Executable
|
||||
from ...sql.selectable import TypedReturnsRows
|
||||
|
||||
_P = ParamSpec("_P")
|
||||
_T = TypeVar("_T", bound=Any)
|
||||
|
||||
|
||||
@@ -195,6 +198,7 @@ class AsyncConnection(
|
||||
method of :class:`_asyncio.AsyncEngine`::
|
||||
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
|
||||
|
||||
async with engine.connect() as conn:
|
||||
@@ -414,6 +418,7 @@ class AsyncConnection(
|
||||
yield_per: int = ...,
|
||||
insertmanyvalues_page_size: int = ...,
|
||||
schema_translate_map: Optional[SchemaTranslateMapType] = ...,
|
||||
preserve_rowcount: bool = False,
|
||||
**opt: Any,
|
||||
) -> AsyncConnection: ...
|
||||
|
||||
@@ -540,7 +545,7 @@ class AsyncConnection(
|
||||
|
||||
E.g.::
|
||||
|
||||
result = await conn.stream(stmt):
|
||||
result = await conn.stream(stmt)
|
||||
async for row in result:
|
||||
print(f"{row}")
|
||||
|
||||
@@ -812,9 +817,12 @@ class AsyncConnection(
|
||||
yield result.scalars()
|
||||
|
||||
async def run_sync(
|
||||
self, fn: Callable[..., _T], *arg: Any, **kw: Any
|
||||
self,
|
||||
fn: Callable[Concatenate[Connection, _P], _T],
|
||||
*arg: _P.args,
|
||||
**kw: _P.kwargs,
|
||||
) -> _T:
|
||||
"""Invoke the given synchronous (i.e. not async) callable,
|
||||
'''Invoke the given synchronous (i.e. not async) callable,
|
||||
passing a synchronous-style :class:`_engine.Connection` as the first
|
||||
argument.
|
||||
|
||||
@@ -824,26 +832,26 @@ class AsyncConnection(
|
||||
E.g.::
|
||||
|
||||
def do_something_with_core(conn: Connection, arg1: int, arg2: str) -> str:
|
||||
'''A synchronous function that does not require awaiting
|
||||
"""A synchronous function that does not require awaiting
|
||||
|
||||
:param conn: a Core SQLAlchemy Connection, used synchronously
|
||||
|
||||
:return: an optional return value is supported
|
||||
|
||||
'''
|
||||
conn.execute(
|
||||
some_table.insert().values(int_col=arg1, str_col=arg2)
|
||||
)
|
||||
"""
|
||||
conn.execute(some_table.insert().values(int_col=arg1, str_col=arg2))
|
||||
return "success"
|
||||
|
||||
|
||||
async def do_something_async(async_engine: AsyncEngine) -> None:
|
||||
'''an async function that uses awaiting'''
|
||||
"""an async function that uses awaiting"""
|
||||
|
||||
async with async_engine.begin() as async_conn:
|
||||
# run do_something_with_core() with a sync-style
|
||||
# Connection, proxied into an awaitable
|
||||
return_code = await async_conn.run_sync(do_something_with_core, 5, "strval")
|
||||
return_code = await async_conn.run_sync(
|
||||
do_something_with_core, 5, "strval"
|
||||
)
|
||||
print(return_code)
|
||||
|
||||
This method maintains the asyncio event loop all the way through
|
||||
@@ -874,9 +882,11 @@ class AsyncConnection(
|
||||
|
||||
:ref:`session_run_sync`
|
||||
|
||||
""" # noqa: E501
|
||||
''' # noqa: E501
|
||||
|
||||
return await greenlet_spawn(fn, self._proxied, *arg, **kw)
|
||||
return await greenlet_spawn(
|
||||
fn, self._proxied, *arg, _require_await=False, **kw
|
||||
)
|
||||
|
||||
def __await__(self) -> Generator[Any, None, AsyncConnection]:
|
||||
return self.start().__await__()
|
||||
@@ -921,7 +931,7 @@ class AsyncConnection(
|
||||
return self._proxied.invalidated
|
||||
|
||||
@property
|
||||
def dialect(self) -> Any:
|
||||
def dialect(self) -> Dialect:
|
||||
r"""Proxy for the :attr:`_engine.Connection.dialect` attribute
|
||||
on behalf of the :class:`_asyncio.AsyncConnection` class.
|
||||
|
||||
@@ -930,7 +940,7 @@ class AsyncConnection(
|
||||
return self._proxied.dialect
|
||||
|
||||
@dialect.setter
|
||||
def dialect(self, attr: Any) -> None:
|
||||
def dialect(self, attr: Dialect) -> None:
|
||||
self._proxied.dialect = attr
|
||||
|
||||
@property
|
||||
@@ -991,6 +1001,7 @@ class AsyncEngine(ProxyComparable[Engine], AsyncConnectable):
|
||||
:func:`_asyncio.create_async_engine` function::
|
||||
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname")
|
||||
|
||||
.. versionadded:: 1.4
|
||||
@@ -1047,7 +1058,6 @@ class AsyncEngine(ProxyComparable[Engine], AsyncConnectable):
|
||||
)
|
||||
await conn.execute(text("my_special_procedure(5)"))
|
||||
|
||||
|
||||
"""
|
||||
conn = self.connect()
|
||||
|
||||
|
@@ -1,5 +1,5 @@
|
||||
# ext/asyncio/exc.py
|
||||
# Copyright (C) 2020-2024 the SQLAlchemy authors and contributors
|
||||
# Copyright (C) 2020-2025 the SQLAlchemy authors and contributors
|
||||
# <see AUTHORS file>
|
||||
#
|
||||
# This module is part of SQLAlchemy and is released under
|
||||
|
@@ -1,5 +1,5 @@
|
||||
# ext/asyncio/result.py
|
||||
# Copyright (C) 2020-2024 the SQLAlchemy authors and contributors
|
||||
# Copyright (C) 2020-2025 the SQLAlchemy authors and contributors
|
||||
# <see AUTHORS file>
|
||||
#
|
||||
# This module is part of SQLAlchemy and is released under
|
||||
@@ -333,11 +333,11 @@ class AsyncResult(_WithKeys, AsyncCommon[Row[_TP]]):
|
||||
"""Return exactly one scalar result or raise an exception.
|
||||
|
||||
This is equivalent to calling :meth:`_asyncio.AsyncResult.scalars` and
|
||||
then :meth:`_asyncio.AsyncResult.one`.
|
||||
then :meth:`_asyncio.AsyncScalarResult.one`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:meth:`_asyncio.AsyncResult.one`
|
||||
:meth:`_asyncio.AsyncScalarResult.one`
|
||||
|
||||
:meth:`_asyncio.AsyncResult.scalars`
|
||||
|
||||
@@ -356,11 +356,11 @@ class AsyncResult(_WithKeys, AsyncCommon[Row[_TP]]):
|
||||
"""Return exactly one scalar result or ``None``.
|
||||
|
||||
This is equivalent to calling :meth:`_asyncio.AsyncResult.scalars` and
|
||||
then :meth:`_asyncio.AsyncResult.one_or_none`.
|
||||
then :meth:`_asyncio.AsyncScalarResult.one_or_none`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:meth:`_asyncio.AsyncResult.one_or_none`
|
||||
:meth:`_asyncio.AsyncScalarResult.one_or_none`
|
||||
|
||||
:meth:`_asyncio.AsyncResult.scalars`
|
||||
|
||||
@@ -869,11 +869,11 @@ class AsyncTupleResult(AsyncCommon[_R], util.TypingOnly):
|
||||
"""Return exactly one scalar result or raise an exception.
|
||||
|
||||
This is equivalent to calling :meth:`_engine.Result.scalars`
|
||||
and then :meth:`_engine.Result.one`.
|
||||
and then :meth:`_engine.AsyncScalarResult.one`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:meth:`_engine.Result.one`
|
||||
:meth:`_engine.AsyncScalarResult.one`
|
||||
|
||||
:meth:`_engine.Result.scalars`
|
||||
|
||||
@@ -892,11 +892,11 @@ class AsyncTupleResult(AsyncCommon[_R], util.TypingOnly):
|
||||
"""Return exactly one or no scalar result.
|
||||
|
||||
This is equivalent to calling :meth:`_engine.Result.scalars`
|
||||
and then :meth:`_engine.Result.one_or_none`.
|
||||
and then :meth:`_engine.AsyncScalarResult.one_or_none`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:meth:`_engine.Result.one_or_none`
|
||||
:meth:`_engine.AsyncScalarResult.one_or_none`
|
||||
|
||||
:meth:`_engine.Result.scalars`
|
||||
|
||||
|
@@ -1,5 +1,5 @@
|
||||
# ext/asyncio/scoping.py
|
||||
# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
|
||||
# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
|
||||
# <see AUTHORS file>
|
||||
#
|
||||
# This module is part of SQLAlchemy and is released under
|
||||
@@ -364,7 +364,7 @@ class async_scoped_session(Generic[_AS]):
|
||||
object is entered::
|
||||
|
||||
async with async_session.begin():
|
||||
# .. ORM transaction is begun
|
||||
... # ORM transaction is begun
|
||||
|
||||
Note that database IO will not normally occur when the session-level
|
||||
transaction is begun, as database transactions begin on an
|
||||
@@ -808,28 +808,28 @@ class async_scoped_session(Generic[_AS]):
|
||||
|
||||
# construct async engines w/ async drivers
|
||||
engines = {
|
||||
'leader':create_async_engine("sqlite+aiosqlite:///leader.db"),
|
||||
'other':create_async_engine("sqlite+aiosqlite:///other.db"),
|
||||
'follower1':create_async_engine("sqlite+aiosqlite:///follower1.db"),
|
||||
'follower2':create_async_engine("sqlite+aiosqlite:///follower2.db"),
|
||||
"leader": create_async_engine("sqlite+aiosqlite:///leader.db"),
|
||||
"other": create_async_engine("sqlite+aiosqlite:///other.db"),
|
||||
"follower1": create_async_engine("sqlite+aiosqlite:///follower1.db"),
|
||||
"follower2": create_async_engine("sqlite+aiosqlite:///follower2.db"),
|
||||
}
|
||||
|
||||
|
||||
class RoutingSession(Session):
|
||||
def get_bind(self, mapper=None, clause=None, **kw):
|
||||
# within get_bind(), return sync engines
|
||||
if mapper and issubclass(mapper.class_, MyOtherClass):
|
||||
return engines['other'].sync_engine
|
||||
return engines["other"].sync_engine
|
||||
elif self._flushing or isinstance(clause, (Update, Delete)):
|
||||
return engines['leader'].sync_engine
|
||||
return engines["leader"].sync_engine
|
||||
else:
|
||||
return engines[
|
||||
random.choice(['follower1','follower2'])
|
||||
random.choice(["follower1", "follower2"])
|
||||
].sync_engine
|
||||
|
||||
|
||||
# apply to AsyncSession using sync_session_class
|
||||
AsyncSessionMaker = async_sessionmaker(
|
||||
sync_session_class=RoutingSession
|
||||
)
|
||||
AsyncSessionMaker = async_sessionmaker(sync_session_class=RoutingSession)
|
||||
|
||||
The :meth:`_orm.Session.get_bind` method is called in a non-asyncio,
|
||||
implicitly non-blocking context in the same manner as ORM event hooks
|
||||
@@ -864,7 +864,7 @@ class async_scoped_session(Generic[_AS]):
|
||||
|
||||
This method retrieves the history for each instrumented
|
||||
attribute on the instance and performs a comparison of the current
|
||||
value to its previously committed value, if any.
|
||||
value to its previously flushed or committed value, if any.
|
||||
|
||||
It is in effect a more expensive and accurate
|
||||
version of checking for the given instance in the
|
||||
|
@@ -1,5 +1,5 @@
|
||||
# ext/asyncio/session.py
|
||||
# Copyright (C) 2020-2024 the SQLAlchemy authors and contributors
|
||||
# Copyright (C) 2020-2025 the SQLAlchemy authors and contributors
|
||||
# <see AUTHORS file>
|
||||
#
|
||||
# This module is part of SQLAlchemy and is released under
|
||||
@@ -38,6 +38,9 @@ from ...orm import Session
|
||||
from ...orm import SessionTransaction
|
||||
from ...orm import state as _instance_state
|
||||
from ...util.concurrency import greenlet_spawn
|
||||
from ...util.typing import Concatenate
|
||||
from ...util.typing import ParamSpec
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .engine import AsyncConnection
|
||||
@@ -71,6 +74,7 @@ if TYPE_CHECKING:
|
||||
|
||||
_AsyncSessionBind = Union["AsyncEngine", "AsyncConnection"]
|
||||
|
||||
_P = ParamSpec("_P")
|
||||
_T = TypeVar("_T", bound=Any)
|
||||
|
||||
|
||||
@@ -332,9 +336,12 @@ class AsyncSession(ReversibleProxy[Session]):
|
||||
)
|
||||
|
||||
async def run_sync(
|
||||
self, fn: Callable[..., _T], *arg: Any, **kw: Any
|
||||
self,
|
||||
fn: Callable[Concatenate[Session, _P], _T],
|
||||
*arg: _P.args,
|
||||
**kw: _P.kwargs,
|
||||
) -> _T:
|
||||
"""Invoke the given synchronous (i.e. not async) callable,
|
||||
'''Invoke the given synchronous (i.e. not async) callable,
|
||||
passing a synchronous-style :class:`_orm.Session` as the first
|
||||
argument.
|
||||
|
||||
@@ -344,25 +351,27 @@ class AsyncSession(ReversibleProxy[Session]):
|
||||
E.g.::
|
||||
|
||||
def some_business_method(session: Session, param: str) -> str:
|
||||
'''A synchronous function that does not require awaiting
|
||||
"""A synchronous function that does not require awaiting
|
||||
|
||||
:param session: a SQLAlchemy Session, used synchronously
|
||||
|
||||
:return: an optional return value is supported
|
||||
|
||||
'''
|
||||
"""
|
||||
session.add(MyObject(param=param))
|
||||
session.flush()
|
||||
return "success"
|
||||
|
||||
|
||||
async def do_something_async(async_engine: AsyncEngine) -> None:
|
||||
'''an async function that uses awaiting'''
|
||||
"""an async function that uses awaiting"""
|
||||
|
||||
with AsyncSession(async_engine) as async_session:
|
||||
# run some_business_method() with a sync-style
|
||||
# Session, proxied into an awaitable
|
||||
return_code = await async_session.run_sync(some_business_method, param="param1")
|
||||
return_code = await async_session.run_sync(
|
||||
some_business_method, param="param1"
|
||||
)
|
||||
print(return_code)
|
||||
|
||||
This method maintains the asyncio event loop all the way through
|
||||
@@ -384,9 +393,11 @@ class AsyncSession(ReversibleProxy[Session]):
|
||||
:meth:`.AsyncConnection.run_sync`
|
||||
|
||||
:ref:`session_run_sync`
|
||||
""" # noqa: E501
|
||||
''' # noqa: E501
|
||||
|
||||
return await greenlet_spawn(fn, self.sync_session, *arg, **kw)
|
||||
return await greenlet_spawn(
|
||||
fn, self.sync_session, *arg, _require_await=False, **kw
|
||||
)
|
||||
|
||||
@overload
|
||||
async def execute(
|
||||
@@ -868,28 +879,28 @@ class AsyncSession(ReversibleProxy[Session]):
|
||||
|
||||
# construct async engines w/ async drivers
|
||||
engines = {
|
||||
'leader':create_async_engine("sqlite+aiosqlite:///leader.db"),
|
||||
'other':create_async_engine("sqlite+aiosqlite:///other.db"),
|
||||
'follower1':create_async_engine("sqlite+aiosqlite:///follower1.db"),
|
||||
'follower2':create_async_engine("sqlite+aiosqlite:///follower2.db"),
|
||||
"leader": create_async_engine("sqlite+aiosqlite:///leader.db"),
|
||||
"other": create_async_engine("sqlite+aiosqlite:///other.db"),
|
||||
"follower1": create_async_engine("sqlite+aiosqlite:///follower1.db"),
|
||||
"follower2": create_async_engine("sqlite+aiosqlite:///follower2.db"),
|
||||
}
|
||||
|
||||
|
||||
class RoutingSession(Session):
|
||||
def get_bind(self, mapper=None, clause=None, **kw):
|
||||
# within get_bind(), return sync engines
|
||||
if mapper and issubclass(mapper.class_, MyOtherClass):
|
||||
return engines['other'].sync_engine
|
||||
return engines["other"].sync_engine
|
||||
elif self._flushing or isinstance(clause, (Update, Delete)):
|
||||
return engines['leader'].sync_engine
|
||||
return engines["leader"].sync_engine
|
||||
else:
|
||||
return engines[
|
||||
random.choice(['follower1','follower2'])
|
||||
random.choice(["follower1", "follower2"])
|
||||
].sync_engine
|
||||
|
||||
|
||||
# apply to AsyncSession using sync_session_class
|
||||
AsyncSessionMaker = async_sessionmaker(
|
||||
sync_session_class=RoutingSession
|
||||
)
|
||||
AsyncSessionMaker = async_sessionmaker(sync_session_class=RoutingSession)
|
||||
|
||||
The :meth:`_orm.Session.get_bind` method is called in a non-asyncio,
|
||||
implicitly non-blocking context in the same manner as ORM event hooks
|
||||
@@ -945,7 +956,7 @@ class AsyncSession(ReversibleProxy[Session]):
|
||||
object is entered::
|
||||
|
||||
async with async_session.begin():
|
||||
# .. ORM transaction is begun
|
||||
... # ORM transaction is begun
|
||||
|
||||
Note that database IO will not normally occur when the session-level
|
||||
transaction is begun, as database transactions begin on an
|
||||
@@ -1298,7 +1309,7 @@ class AsyncSession(ReversibleProxy[Session]):
|
||||
|
||||
This method retrieves the history for each instrumented
|
||||
attribute on the instance and performs a comparison of the current
|
||||
value to its previously committed value, if any.
|
||||
value to its previously flushed or committed value, if any.
|
||||
|
||||
It is in effect a more expensive and accurate
|
||||
version of checking for the given instance in the
|
||||
@@ -1622,16 +1633,22 @@ class async_sessionmaker(Generic[_AS]):
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
async def run_some_sql(async_session: async_sessionmaker[AsyncSession]) -> None:
|
||||
|
||||
async def run_some_sql(
|
||||
async_session: async_sessionmaker[AsyncSession],
|
||||
) -> None:
|
||||
async with async_session() as session:
|
||||
session.add(SomeObject(data="object"))
|
||||
session.add(SomeOtherObject(name="other object"))
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# an AsyncEngine, which the AsyncSession will use for connection
|
||||
# resources
|
||||
engine = create_async_engine('postgresql+asyncpg://scott:tiger@localhost/')
|
||||
engine = create_async_engine(
|
||||
"postgresql+asyncpg://scott:tiger@localhost/"
|
||||
)
|
||||
|
||||
# create a reusable factory for new AsyncSession instances
|
||||
async_session = async_sessionmaker(engine)
|
||||
@@ -1730,7 +1747,6 @@ class async_sessionmaker(Generic[_AS]):
|
||||
|
||||
# commits transaction, closes session
|
||||
|
||||
|
||||
"""
|
||||
|
||||
session = self()
|
||||
@@ -1763,7 +1779,7 @@ class async_sessionmaker(Generic[_AS]):
|
||||
|
||||
AsyncSession = async_sessionmaker(some_engine)
|
||||
|
||||
AsyncSession.configure(bind=create_async_engine('sqlite+aiosqlite://'))
|
||||
AsyncSession.configure(bind=create_async_engine("sqlite+aiosqlite://"))
|
||||
""" # noqa E501
|
||||
|
||||
self.kw.update(new_kw)
|
||||
@@ -1854,7 +1870,7 @@ class AsyncSessionTransaction(
|
||||
) -> AsyncSessionTransaction:
|
||||
self.sync_transaction = self._assign_proxied(
|
||||
await greenlet_spawn(
|
||||
self.session.sync_session.begin_nested # type: ignore
|
||||
self.session.sync_session.begin_nested
|
||||
if self.nested
|
||||
else self.session.sync_session.begin
|
||||
)
|
||||
|
Reference in New Issue
Block a user