Skip to content

Commit

Permalink
Ensure auto request connectons are released
Browse files Browse the repository at this point in the history
The after request functions are not called if the connection is
aborted (thereby resulting in a CancelledError), thereby resulting in
a leaked connection. The teardown request function is always called,
hence the switch.

It is easier, and sufficient, to test for aiosqlite only.
  • Loading branch information
pgjones committed Oct 18, 2023
1 parent 068d265 commit 94a68e1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/quart_db/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from urllib.parse import urlsplit

import click
from quart import g, Quart, Response
from quart import g, Quart
from quart.cli import pass_script_info, ScriptInfo

from ._migration import setup_schema
Expand Down Expand Up @@ -116,7 +116,7 @@ def init_app(self, app: Quart) -> None:

if app.config.get("QUART_DB_AUTO_REQUEST_CONNECTION", self._auto_request_connection):
app.before_request(self.before_request)
app.after_request(self.after_request)
app.teardown_request(self.teardown_request)

app.cli.add_command(_migrate_command)
app.cli.add_command(_schema_command)
Expand All @@ -137,11 +137,10 @@ async def after_serving(self) -> None:
async def before_request(self) -> None:
g.connection = await self.acquire()

async def after_request(self, response: Response) -> Response:
async def teardown_request(self, _exception: Optional[BaseException]) -> None:
if getattr(g, "connection", None) is not None:
await self.release(g.connection)
g.connection = None
return response

async def migrate(self) -> None:
migrations_folder = None
Expand Down
25 changes: 25 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from asyncio import CancelledError
from typing import NoReturn, Type

import pytest
from quart import g, Quart, ResponseReturnValue

from quart_db import QuartDB
Expand All @@ -16,3 +20,24 @@ async def index() -> ResponseReturnValue:
response = await test_client.get("/")
data = await response.get_data(as_text=True)
assert data == "test"


@pytest.mark.parametrize(
"exception",
[CancelledError, ValueError],
)
async def test_g_connection_release(url: str, exception: Type[Exception]) -> None:
if not url.startswith("sqlite"):
pytest.skip("aiosqlite - simpler backend to test")

app = Quart(__name__)
db = QuartDB(app, auto_request_connection=True, url=url)

@app.get("/")
async def index() -> NoReturn:
raise exception()

async with app.test_app():
test_client = app.test_client()
await test_client.get("/")
assert db._backend._connections == set() # type: ignore

0 comments on commit 94a68e1

Please sign in to comment.