@@ -145,10 +145,7 @@ async def decorated(*dec_args, **dec_kwargs) -> Response:
145145 dec_kwargs ['client' ] = client
146146 try :
147147 result = func (* dec_args , ** dec_kwargs )
148- # NOTE: after building the page, there might be sub pages that have 404 -- and initial requests should send 404 status request in such cases
149- sub_pages_elements = [e for e in client .elements .values () if isinstance (e , SubPages )]
150- if any (sub_pages .has_404 for sub_pages in sub_pages_elements ):
151- raise HTTPException (404 , f'{ client .sub_pages_router .current_path } not found' )
148+ await self ._await_sub_pages_and_raise_404 (client )
152149 except Exception as e :
153150 return create_error_page (e , request )
154151 if helpers .is_coroutine_function (func ):
@@ -174,6 +171,7 @@ async def wait_for_result() -> Optional[Response]:
174171 else :
175172 result = None
176173 task .add_done_callback (check_for_late_return_value )
174+ await self ._await_sub_pages_and_raise_404 (client )
177175 if isinstance (result , Response ): # NOTE if setup returns a response, we don't need to render the page
178176 return result
179177 binding ._refresh_step () # pylint: disable=protected-access
@@ -192,3 +190,13 @@ async def wait_for_result() -> Optional[Response]:
192190 self .api_router .get (self ._path , ** self .kwargs )(decorated )
193191 Client .page_routes [func ] = self .path
194192 return func
193+
194+ @staticmethod
195+ async def _await_sub_pages_and_raise_404 (client : Client ) -> None :
196+ """Some sub pages might finish async and decide 404"""
197+ sub_pages_elements = [e for e in client .elements .values () if isinstance (e , SubPages )]
198+ if any (sp ._active_tasks for sp in sub_pages_elements ): # pylint: disable=protected-access
199+ await asyncio .sleep (0 ) # NOTE: give background tasks a brief chance to schedule nested sub pages
200+ sub_pages_elements = [e for e in client .elements .values () if isinstance (e , SubPages )]
201+ if any (sp .has_404 for sp in sub_pages_elements ):
202+ raise HTTPException (404 , f'{ client .sub_pages_router .current_path } not found' )
0 commit comments