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

coroutine app factory #1184

Closed
wants to merge 2 commits into from
Closed
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
11 changes: 11 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,17 @@ def create_app() -> ASGIApplication:
config.load()


@pytest.mark.asyncio
async def test_coroutine_factory():
async def create_app() -> ASGIApplication:
return asgi_app

config = Config(app=create_app, factory=True, proxy_headers=False)
config.load()
await config.load_app()
assert config.loaded_app is asgi_app


def test_concrete_http_class() -> None:
config = Config(app=asgi_app, http=H11Protocol)
config.load()
Expand Down
29 changes: 29 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import contextvars
import contextlib
from logging import WARNING

import httpx
Expand Down Expand Up @@ -64,6 +66,33 @@ async def test_run_reload():
assert response.status_code == 204


@pytest.mark.asyncio
async def test_coroutine_app_factory_context():

ctx = contextvars.ContextVar[int]("ctx")
ctx.set(0)

async def test_app(scope, receive, send):
assert ctx.get() == 1
return await app(scope, receive, send)

@contextlib.contextmanager
def cm():
ctx.set(1)
yield
ctx.set(0)

async def create_app():
with cm():
return test_app

config = Config(app=create_app, loop="asyncio", factory=True, limit_max_requests=1)
async with run_server(config):
async with httpx.AsyncClient() as client:
response = await client.get("http://127.0.0.1:8000")
assert response.status_code == 204


def test_run_invalid_app_config_combination(caplog: pytest.LogCaptureFixture) -> None:
with pytest.raises(SystemExit) as exit_exception:
run(app, reload=True)
Expand Down
51 changes: 37 additions & 14 deletions uvicorn/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ def __init__(
self.factory = factory

self.loaded = False
self._loaded_app: Union[ASGIApplication, None] = None
self.configure_logging()

self.reload_dirs: List[Path] = []
Expand Down Expand Up @@ -445,13 +446,13 @@ def load(self) -> None:
self.lifespan_class = import_from_string(LIFESPAN[self.lifespan])

try:
self.loaded_app = import_from_string(self.app)
self._loaded_app = import_from_string(self.app)
except ImportFromStringError as exc:
logger.error("Error loading ASGI app. %s" % exc)
sys.exit(1)

try:
self.loaded_app = self.loaded_app()
self._loaded_app = self._loaded_app()
except TypeError as exc:
if self.factory:
logger.error("Error loading ASGI app factory: %s", exc)
Expand All @@ -462,33 +463,55 @@ def load(self) -> None:
"ASGI app factory detected. Using it, "
"but please consider setting the --factory flag explicitly."
)
if not inspect.isawaitable(self._loaded_app):
self._wrap_loaded_app()

self.loaded = True

def _wrap_loaded_app(self) -> None:
if self.interface == "auto":
if inspect.isclass(self.loaded_app):
use_asgi_3 = hasattr(self.loaded_app, "__await__")
elif inspect.isfunction(self.loaded_app):
use_asgi_3 = asyncio.iscoroutinefunction(self.loaded_app)
if inspect.isclass(self._loaded_app):
use_asgi_3 = hasattr(self._loaded_app, "__await__")
elif inspect.isfunction(self._loaded_app):
use_asgi_3 = asyncio.iscoroutinefunction(self._loaded_app)
else:
call = getattr(self.loaded_app, "__call__", None)
call = getattr(self._loaded_app, "__call__", None)
use_asgi_3 = asyncio.iscoroutinefunction(call)
self.interface = "asgi3" if use_asgi_3 else "asgi2"

if self.interface == "wsgi":
self.loaded_app = WSGIMiddleware(self.loaded_app)
self._loaded_app = WSGIMiddleware(self._loaded_app)
self.ws_protocol_class = None
elif self.interface == "asgi2":
self.loaded_app = ASGI2Middleware(self.loaded_app)
self._loaded_app = ASGI2Middleware(self._loaded_app)

if self.debug:
self.loaded_app = DebugMiddleware(self.loaded_app)
self._loaded_app = DebugMiddleware(self._loaded_app)
if logger.level <= TRACE_LOG_LEVEL:
self.loaded_app = MessageLoggerMiddleware(self.loaded_app)
self._loaded_app = MessageLoggerMiddleware(self._loaded_app)
if self.proxy_headers:
self.loaded_app = ProxyHeadersMiddleware(
self.loaded_app, trusted_hosts=self.forwarded_allow_ips
self._loaded_app = ProxyHeadersMiddleware(
self._loaded_app, trusted_hosts=self.forwarded_allow_ips
)

self.loaded = True
@property
def loaded_app(self) -> ASGIApplication:
app = self._loaded_app
if app is None:
raise AttributeError(f"'{repr(self)}' has no attribute 'loaded_app'")
if inspect.isawaitable(app):
raise RuntimeError(
"Coroutine app factories required that you call `load_app` before accessing `loaded_app`"
)
return app

async def load_app(self) -> None:
if not self.loaded:
self.load()
assert self._loaded_app is not None
if inspect.isawaitable(self._loaded_app):
self._loaded_app = await self._loaded_app
self._wrap_loaded_app()

def setup_event_loop(self) -> None:
loop_setup: Optional[Callable] = import_from_string(LOOP_SETUPS[self.loop])
Expand Down
1 change: 1 addition & 0 deletions uvicorn/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ async def serve(self, sockets: Optional[List[socket.socket]] = None) -> None:
config = self.config
if not config.loaded:
config.load()
await config.load_app()

self.lifespan = config.lifespan_class(config)

Expand Down