Launch background task only after successful login #5263
-
|
Hello, I need some guidance please on how to resolve this little problem, I'm sure it's simple but can't see the obvious solution. I have configured protected pages so that the content is shown only if a user is logged in: I setup the Only AFTER a successful login, I want to start the background task @rx.page(
route="/clusters",
title="Clusters",
on_load=BaseState.check_login,
)
@template
def clusters():
return rx.flex(
rx.text(
"Clusters",
class_name="p-2 text-8xl font-semibold",
),
rx.hstack(new_cluster_dialog(), direction="row-reverse", class_name="p-4"),
rx.flex(clusters_table(), class_name="flex-1 flex-col overflow-y-scroll p-2"),
class_name="flex-1 flex-col overflow-hidden",
on_mount=State.fetch_all_clusters,
)This is the bg task @rx.event(background=True)
async def fetch_all_clusters(self):
if self.is_already_running:
return
async with self:
self.is_already_running = True
while True:
if self.router.page.path != "/clusters":
print("clusters.py: Stopping background task.")
async with self:
self.is_already_running = False
break
async with self:
self.clusters = db.get_all_clusters()
await asyncio.sleep(5)I am a bit confused by this behavior. Even if How can I make sure that the login is checked first before any other operation takes place, such as mounting the website or firing off bg tasks please? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
|
Add a state variable like To avoid a blank page, return something else than your page if user is not logged in: In your page |
Beta Was this translation helpful? Give feedback.
-
|
Thanks Lars, that works well, I added the Curious though, how do you start the bg task from my |
Beta Was this translation helpful? Give feedback.
-
|
your
|
Beta Was this translation helpful? Give feedback.
Add a state variable like
AuthState.is_logged_in: bool = False. Set toTrueonly once the user is logged in. Reset state on logout.To avoid a blank page, return something else than your page if user is not logged in:
In your page
on_loadfunction you can check the auth state as well and redirect to a login page if the user isn't authenticated yet. Otherwise start the background task, etc.