How to redirect from an async page function? #549
-
Hey im not even sure its issue, i might be doing something wrong.... For example: @ui.page('/logout')
async def logout(request: Request) -> None:
if await is_authenticated(request):
await redis.expire(request.session["id"], 0)
request.session['id'] = None
return RedirectResponse('/login')
else:
return RedirectResponse('/') It never redirect to anything, but when i remove async it works like intended. Any ideas how to sort this out ? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 10 replies
-
Thanks for reaching out, @espeoceka! I was confused at first, since it is working without For example, the following code is working with and without @app.get('/redirect')
async def redirect() -> None:
return RedirectResponse('/') |
Beta Was this translation helpful? Give feedback.
-
@rodja and I just noticed that @espeoceka's code example actually should work with the current implementation of |
Beta Was this translation helpful? Give feedback.
-
Hey great that this has been worked on, i found also issue related to redirecting. This looks atrocious on first glance but im trying to make dependency that simply authorize user and if no user profile is found redirects to login...... @ui.page('/user/contact_lists')
async def user_contact_lists(request: Request,client:Client,db_session=Depends(get_db),user_profile=Depends(get_user_profile)):
while True:
status = await client.connected(timeout=5)
if not client.is_waiting_for_connection:
break
await asyncio.sleep(1)
if not isinstance(user_profile,User):
ui.open(f"/login?destination={client.page.path}") This "charming" loop somehow makes redirection works.... but it cannot be used in dependency due to some pydantic error. I already guessing its not good approach at best. How this should be done ? PS. I tried to make a dependency that takes Client class but it seems to be impossible due to pydantic error ( Client class added to arguments of get_user_profile ) |
Beta Was this translation helpful? Give feedback.
Thanks for reaching out, @espeoceka!
I was confused at first, since it is working without
async
. But now I'm actually not sure, why it is working at all...As the type annotation says,
logout
is supposed to build a UI and return nothing. But instead it returns a FastAPI response. Sologout
isn't a NiceGUI page function, but a regular FastAPI endpoint. Therefore it should be decorated withapp.get
instead ofui.page
.For example, the following code is working with and without
async
: