Use FastAPI's Depends
to inject dependencies
#3557
-
QuestionHi, My question is simple, is it possible to use the Depends that FastAPI uses to inject dependencies with nicegui?, |
Beta Was this translation helpful? Give feedback.
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.
-
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", [])
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.
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: