Problem with app.storage / ui.run_with #4037
-
QuestionCan 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: from fastapi import FastAPI, Request
from nicegui import app, ui, Client
import nicegui
import asyncio
from starlette.datastructures import Headers
def init(fastapi_app: FastAPI) -> None:
unrestricted_page_routes = {'/login'}
@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 not in unrestricted_page_routes:
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') main.py: import frontend
from fastapi import FastAPI
import uvicorn
app=FastAPI()
frontend.init(app)
if __name__ =="__main__" :
uvicorn.run("main:app", host="localhost", log_level="info") |
Beta Was this translation helpful? Give feedback.
Answered by
falkoschindler
Nov 27, 2024
Replies: 1 comment 3 replies
-
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.
3 replies
Answer selected by
shato20
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @shato20,
It's currently not mentioned in the documentation, but the storage module requires the following two middlewares to be set:
Here is an executable example: