Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a new loop in run_app() #5572

Merged
merged 18 commits into from
Jun 21, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/5572.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Always create a new event loop in run_app() to avoid an error caused by using `asyncio.run()` beforehand.
Dreamsorcerer marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 2 additions & 1 deletion aiohttp/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,8 @@ def run_app(
reuse_port: Optional[bool] = None,
) -> None:
"""Run an app locally"""
loop = asyncio.get_event_loop()
loop = asyncio.new_event_loop()
Dreamsorcerer marked this conversation as resolved.
Show resolved Hide resolved
asyncio.set_event_loop(loop)
loop.set_debug(debug)

# Configure if and only if in debugging mode and using the default logger
Expand Down
19 changes: 19 additions & 0 deletions tests/test_web_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,22 @@ async def mock_create_server(*args, **kwargs):
assert server is runner.server
assert host is None
assert port == 8080


def test_run_after_asyncio_run() -> None:
async def nothing():
pass

async def shutdown():
raise web.GracefulExit()
Dreamsorcerer marked this conversation as resolved.
Show resolved Hide resolved

# asyncio.run() creates a new loop and closes it.
asyncio.run(nothing())

app = web.Application()
# create_task() will delay the function until app is run.
app.on_startup.append(lambda a: asyncio.create_task(shutdown()))
try:
web.run_app(app)
except RuntimeError:
pytest.fail("run_app() should work after asyncio.run().")
Dreamsorcerer marked this conversation as resolved.
Show resolved Hide resolved