Skip to content

Commit

Permalink
Add task_group as application attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
uSpike committed May 13, 2021
1 parent fc60420 commit 27283aa
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
7 changes: 5 additions & 2 deletions starlette/applications.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import typing

import anyio
from anyio.abc import TaskGroup

from starlette.datastructures import State, URLPath
from starlette.exceptions import ExceptionMiddleware
Expand Down Expand Up @@ -38,6 +39,8 @@ class Starlette:
standard functions, or async functions.
"""

task_group: TaskGroup

def __init__(
self,
debug: bool = False,
Expand Down Expand Up @@ -111,8 +114,8 @@ def url_path_for(self, name: str, **path_params: str) -> URLPath:

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
scope["app"] = self
task_group = scope["task_group"] = anyio.create_task_group()
async with task_group:
self.task_group = anyio.create_task_group()
async with self.task_group:
await self.middleware_stack(scope, receive, send)

# The following usages are now discouraged in favour of configuration
Expand Down
3 changes: 1 addition & 2 deletions starlette/middleware/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,12 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
async def call_next(self, request: Request) -> Response:
send_stream, recv_stream = anyio.create_memory_object_stream()
scope = request.scope
task_group = scope["task_group"]

async def coro() -> None:
async with send_stream:
await self.app(scope, request.receive, send_stream.send)

task_group.start_soon(coro)
scope["app"].task_group.start_soon(coro)

try:
message = await recv_stream.receive()
Expand Down

0 comments on commit 27283aa

Please sign in to comment.