MCPcopy
hub / github.com/sqlalchemy/sqlalchemy / run_sync

Method run_sync

lib/sqlalchemy/ext/asyncio/session.py:341–403  ·  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

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

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