|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import logging |
| 4 | +from contextlib import ExitStack |
4 | 5 | from itertools import chain |
5 | 6 | from typing import Any |
6 | 7 |
|
7 | | -from mangum._compat import asyncio_run |
8 | 8 | from mangum.exceptions import ConfigurationError |
9 | 9 | from mangum.handlers import ALB, APIGateway, HTTPGateway, LambdaAtEdge |
10 | 10 | from mangum.protocols import HTTPCycle, LifespanCycle |
@@ -59,20 +59,17 @@ def infer(self, event: LambdaEvent, context: LambdaContext) -> LambdaHandler: |
59 | 59 | ) |
60 | 60 |
|
61 | 61 | def __call__(self, event: LambdaEvent, context: LambdaContext) -> dict[str, Any]: |
62 | | - async def handle_request() -> dict[str, Any]: |
63 | | - handler = self.infer(event, context) |
64 | | - scope = handler.scope |
65 | | - |
| 62 | + handler = self.infer(event, context) |
| 63 | + scope = handler.scope |
| 64 | + with ExitStack() as stack: |
66 | 65 | if self.lifespan in ("auto", "on"): |
67 | 66 | lifespan_cycle = LifespanCycle(self.app, self.lifespan) |
68 | | - async with lifespan_cycle: |
69 | | - scope.update({"state": lifespan_cycle.lifespan_state.copy()}) |
70 | | - http_cycle = HTTPCycle(scope, handler.body) |
71 | | - http_response = await http_cycle(self.app) |
72 | | - return handler(http_response) |
73 | | - else: |
74 | | - http_cycle = HTTPCycle(scope, handler.body) |
75 | | - http_response = await http_cycle(self.app) |
76 | | - return handler(http_response) |
| 67 | + stack.enter_context(lifespan_cycle) |
| 68 | + scope.update({"state": lifespan_cycle.lifespan_state.copy()}) |
| 69 | + |
| 70 | + http_cycle = HTTPCycle(scope, handler.body) |
| 71 | + http_response = http_cycle(self.app) |
| 72 | + |
| 73 | + return handler(http_response) |
77 | 74 |
|
78 | | - return asyncio_run(handle_request()) |
| 75 | + assert False, "unreachable" # pragma: no cover |
0 commit comments