22
33import anyio
44
5+ from starlette .background import BackgroundTask
56from starlette .requests import Request
6- from starlette .responses import Response , StreamingResponse
7+ from starlette .responses import ContentStream , Response , StreamingResponse
78from starlette .types import ASGIApp , Message , Receive , Scope , Send
89
910RequestResponseEndpoint = typing .Callable [[Request ], typing .Awaitable [Response ]]
@@ -75,6 +76,9 @@ async def coro() -> None:
7576
7677 try :
7778 message = await recv_stream .receive ()
79+ info = message .get ("info" , None )
80+ if message ["type" ] == "http.response.debug" and info is not None :
81+ message = await recv_stream .receive ()
7882 except anyio .EndOfStream :
7983 if app_exc is not None :
8084 raise app_exc
@@ -93,8 +97,8 @@ async def body_stream() -> typing.AsyncGenerator[bytes, None]:
9397 if app_exc is not None :
9498 raise app_exc
9599
96- response = StreamingResponse (
97- status_code = message ["status" ], content = body_stream ()
100+ response = _StreamingResponse (
101+ status_code = message ["status" ], content = body_stream (), info = info
98102 )
99103 response .raw_headers = message ["headers" ]
100104 return response
@@ -109,3 +113,22 @@ async def dispatch(
109113 self , request : Request , call_next : RequestResponseEndpoint
110114 ) -> Response :
111115 raise NotImplementedError () # pragma: no cover
116+
117+
118+ class _StreamingResponse (StreamingResponse ):
119+ def __init__ (
120+ self ,
121+ content : ContentStream ,
122+ status_code : int = 200 ,
123+ headers : typing .Optional [typing .Mapping [str , str ]] = None ,
124+ media_type : typing .Optional [str ] = None ,
125+ background : typing .Optional [BackgroundTask ] = None ,
126+ info : typing .Optional [typing .Mapping [str , typing .Any ]] = None ,
127+ ) -> None :
128+ self ._info = info
129+ super ().__init__ (content , status_code , headers , media_type , background )
130+
131+ async def stream_response (self , send : Send ) -> None :
132+ if self ._info :
133+ await send ({"type" : "http.response.debug" , "info" : self ._info })
134+ return await super ().stream_response (send )
0 commit comments