Replies: 1 comment
-
Hi @shato20, It's currently not mentioned in the documentation, but the storage module requires the following two middlewares to be set: fastapi_app.add_middleware(storage.RequestTrackingMiddleware)
fastapi_app.add_middleware(SessionMiddleware, secret_key='SECRET') Here is an executable example: import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from starlette.datastructures import Headers
from starlette.middleware.sessions import SessionMiddleware
from nicegui import Client, app, storage, ui
fastapi_app = FastAPI()
fastapi_app.add_middleware(storage.RequestTrackingMiddleware)
fastapi_app.add_middleware(SessionMiddleware, secret_key='SECRET')
@app.middleware("http")
async def auth_middleware(request: Request, call_next):
if not app.storage.user.get('authenticated', False):
if request.url.path in Client.page_routes.values() and request.url.path != '/login':
app.storage.user['referrer_path'] = request.url.path
return RedirectResponse('/login')
request._headers = Headers(scope=request.scope)
request.headers.__dict__['_list'].append((b'authorization', f"Bearer {app.storage.user.get('token')}".encode()))
print(f'auth_middleware auth: {request.headers.get("Authorization")}')
return await call_next(request)
@ui.page('/login')
def show():
ui.label('Hello, FastAPI!')
ui.run_with(fastapi_app, storage_secret='private')
if __name__ == "__main__":
uvicorn.run("main:fastapi_app", host="localhost", log_level="info") |
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
Can someone please tell me what i'm doing wrong with this example? i go the basic integration with FastAPI running, now i am trying to add a middleware, but getting the folling error: RuntimeError: app.storage.user can only be used within a UI context
thanks
frontend.py:
main.py:
Beta Was this translation helpful? Give feedback.
All reactions