I'm trying to create helper function for my projects, but some legacy projects are in sync environment.
my helper function looks like:
def func_for_async_and_sync(session, data):
statement = select(Obj).where(Obj.id == data['id'])
# and more code
if isinstance(session, AsyncSession):
obj = await session.execute(statement)
else:
obj = session.execute(statement)
# edit obj and return
return obj
Of course it not work. How can I call AsyncSession.execute in normal function?
The main difference between How to call a async function from a synchronized code Python is I need return value from async function.
If I rewrite my function to:
loop = asyncio.get_running_loop()
obj = asyncio.run_coroutine_threadsafe(
session.get(model_class, primary_key_value), loop
).result(timeout=5)
I will always get TimeoutError. Future.result() will not return correctly, and this is my minimal test code:
import asyncio
async def main():
"""main is async and started as normal with asyncio.run"""
print("BEGIN main")
loop = asyncio.get_running_loop()
timeout = 3
# Create a coroutine
coro = asyncio.sleep(1, result=3)
# Submit the coroutine to a given loop
future = asyncio.run_coroutine_threadsafe(coro, loop)
# Wait for the result with an optional timeout argument
assert future.result(timeout) == 3
if __name__ == "__main__":
asyncio.run(main())
async_to_syncandsync_to_asyncfunctions).RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly