MCPcopy Create free account
hub / github.com/sqlalchemy/sqlalchemy / run_sync

Method run_sync

lib/sqlalchemy/ext/asyncio/session.py:335–397  ·  view source on GitHub ↗

Invoke the given synchronous (i.e. not async) callable, passing a synchronous-style :class:`_orm.Session` as the first argument. This method allows traditional synchronous SQLAlchemy functions to run within the context of an asyncio application. E.g.::

(
        self,
        fn: Callable[Concatenate[Session, _P], _T],
        *arg: _P.args,
        **kw: _P.kwargs,
    )

Source from the content-addressed store, hash-verified

333 )
334
335 async def run_sync(
336 self,
337 fn: Callable[Concatenate[Session, _P], _T],
338 *arg: _P.args,
339 **kw: _P.kwargs,
340 ) -> _T:
341 '''Invoke the given synchronous (i.e. not async) callable,
342 passing a synchronous-style :class:`_orm.Session` as the first
343 argument.
344
345 This method allows traditional synchronous SQLAlchemy functions to
346 run within the context of an asyncio application.
347
348 E.g.::
349
350 def some_business_method(session: Session, param: str) -> str:
351 """A synchronous function that does not require awaiting
352
353 :param session: a SQLAlchemy Session, used synchronously
354
355 :return: an optional return value is supported
356
357 """
358 session.add(MyObject(param=param))
359 session.flush()
360 return "success"
361
362
363 async def do_something_async(async_engine: AsyncEngine) -> None:
364 """an async function that uses awaiting"""
365
366 with AsyncSession(async_engine) as async_session:
367 # run some_business_method() with a sync-style
368 # Session, proxied into an awaitable
369 return_code = await async_session.run_sync(
370 some_business_method, param="param1"
371 )
372 print(return_code)
373
374 This method maintains the asyncio event loop all the way through
375 to the database connection by running the given callable in a
376 specially instrumented greenlet.
377
378 .. tip::
379
380 The provided callable is invoked inline within the asyncio event
381 loop, and will block on traditional IO calls. IO within this
382 callable should only call into SQLAlchemy's asyncio database
383 APIs which will be properly adapted to the greenlet context.
384
385 .. seealso::
386
387 :class:`.AsyncAttrs` - a mixin for ORM mapped classes that provides
388 a similar feature more succinctly on a per-attribute basis
389
390 :meth:`.AsyncConnection.run_sync`
391
392 :ref:`session_run_sync`

Callers 15

asyncioFunction · 0.45
async_mainFunction · 0.45
test_sequence_executeMethod · 0.45
goMethod · 0.45
test_run_asyncMethod · 0.45
test_cursor_closeMethod · 0.45
async_setupMethod · 0.45
async_mainFunction · 0.45
async_mainFunction · 0.45
async_mainFunction · 0.45

Calls 1

greenlet_spawnFunction · 0.50

Tested by 7

test_sequence_executeMethod · 0.36
goMethod · 0.36
test_run_asyncMethod · 0.36
test_cursor_closeMethod · 0.36
async_setupMethod · 0.36