Use Depends to inject dependencies #3557
Unanswered
JacobMaldonado
asked this question in
Q&A
Replies: 2 comments
-
Hi @JacobMaldonado, I'm not sure. Have you tried it? Can you share an example of how this would look like? |
Beta Was this translation helpful? Give feedback.
0 replies
-
Notice this question is still marked as open, maybe this helps - you or someone else. This is how I inject authentication/authorization as dependencies in the page functions: from fastapi import HTTPException, Depends
# app.storage.user = {
# "authenticated": True,
# "tenant": "tenant name",
# "authz": ['something', 'config', 'something_else']
# }
def auth_tenant():
if app.storage.user.get("authenticated", False):
tenant = app.storage.user.get("tenant", None)
if tenant:
return tenant
raise HTTPException(status_code=307, detail="Authentication Required", headers={"Location": "/login"})
def check_authz(scope: str):
async def dependency():
authz_ok = scope in app.storage.user.get("authz", False)
if not authz_ok:
raise HTTPException(status_code=403, detail=f"Unauthorized for scope: {scope}")
return authz_ok
return dependency
@ui.page("/alarms")
async def alarms(tenant: str = Depends(auth_tenant)):
with theme.frame("alarms"):
await alarms_page.content(tenant)
@ui.page("/config")
async def config(tenant: str = Depends(auth_tenant), authz_ok: bool = Depends(check_authz("config"))):
with theme.frame("config"):
await config_page.content(tenant)
... |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Question
Hi, My question is simple, is it possible to use the Depends that FastAPI uses to inject dependencies with nicegui?,
If so is there any example of this?.
Thanks in advance
Beta Was this translation helpful? Give feedback.
All reactions