Skip to content

Commit

Permalink
fix: correctly handle asyncio.run when loop exists
Browse files Browse the repository at this point in the history
  • Loading branch information
alekseik1 authored and jairhenrique committed Dec 30, 2024
1 parent 8197865 commit 3fb62e0
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion vcr/stubs/httpx_stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,22 @@ def _inner_send(*args, **kwargs):
return _inner_send


def _run_async_function(sync_func, *args, **kwargs):
"""
Safely run an asynchronous function from a synchronous context.
Handles both cases:
- An event loop is already running.
- No event loop exists yet.
"""
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(sync_func(*args, **kwargs))
else:
# If inside a running loop, create a task and wait for it
return asyncio.ensure_future(sync_func(*args, **kwargs))


def _sync_vcr_send(cassette, real_send, *args, **kwargs):
vcr_request, response = _shared_vcr_send(cassette, real_send, *args, **kwargs)
if response:
Expand All @@ -174,7 +190,7 @@ def _sync_vcr_send(cassette, real_send, *args, **kwargs):
return response

real_response = real_send(*args, **kwargs)
asyncio.run(_record_responses(cassette, vcr_request, real_response, aread=False))
_run_async_function(_record_responses, cassette, vcr_request, real_response, aread=False)
return real_response


Expand Down

0 comments on commit 3fb62e0

Please sign in to comment.