8000 Mark http_exception as async to prevent thread creation. by danlapid · Pull Request #2922 · encode/starlette · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Mark http_exception as async to prevent thread creation. #2922

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

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion starlette/middleware/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:

await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)

def http_exception(self, request: Request, exc: Exception) -> Response:
async def http_exception(self, request: Request, exc: Exception) -> Response:
assert isinstance(exc, HTTPException)
if exc.status_code in {204, 304}:
return Response(status_code=exc.status_code, headers=exc.headers)
Expand Down
21 changes: 21 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import typing
from collections.abc import Generator

import pytest
from pytest import MonkeyPatch

from starlette.exceptions import HTTPException, WebSocketException
from starlette.middleware.exceptions import ExceptionMiddleware
Expand Down Expand Up @@ -184,3 +186,22 @@ def test_request_in_app_and_handler_is_the_same_object(client: TestClient) -> No
response = client.post("/consume_body_in_endpoint_and_handler", content=b"Hello!")
assert response.status_code == 422
assert response.json() == {"body": "Hello!"}


def test_http_exception_does_not_use_threadpool(client: TestClient, monkeypatch: MonkeyPatch) -> None:
"""
Verify that handling HTTPException does not invoke run_in_threadpool,
confirming the handler correctly runs in the main async context.
"""
from starlette import _exception_handler

# Replace run_in_threadpool with a function that raises an error
def mock_run_in_threadpool(*args: typing.Any, **kwargs: typing.Any) -> None:
pytest.fail("run_in_threadpool should not be called for HTTP exceptions") # pragma: no cover

# Apply the monkeypatch only during this test
monkeypatch.setattr(_exception_handler, "run_in_threadpool", mock_run_in_threadpool)

# This should succeed because http_exception is async and won't use run_in_threadpool
response = client.get("/not_acceptable")
assert response.status_code == 406
0