jonra1993 / fastapi-alembic-sqlmodel-async

This is a project template which uses FastAPI, Pydantic 2.0, Alembic and async SQLModel as ORM. It shows a complete async CRUD using authentication and role base access control.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

base route always returns "Hello World 2"

bazylhorsey opened this issue · comments

Looking at the code, it seems what was anticipated would it would be a sequence for every request looking like: 2, 4, 8, 16, 32, etc.
This seems to always return the same response which would indicate the global is not actually iterating as expected.
Great code by the way, I was completely unaware of async lifetimes and managing contexts.

Hello, @bazylhorsey I was thinking the same at the beginning but that middleware is in charge of resetting to default values. The context variables online exist in the context of a handler which causes this context to be useful for read-only global variables for now you can check this here http://glenfant.github.io/flask-g-object-for-fastapi.html which is the base of the fastapi-global.

If you remove the middleware in that sample the global is shared between different requests which is not secure.
image

The context variables are stored within an instance of the Globals class. Although you can modify the value of a context variable within a handler, each handler runs in a separate context, so the changes made in one handler will not be reflected in another handler.

This can provide you more ingo about g object https://stackoverflow.com/questions/30514749/what-is-the-g-object-in-this-flask-code

image

For a read/write global store something like this can be used

from fastapi import FastAPI
import threading

app = FastAPI()
state_lock = threading.Lock()

@app.get("/get-state")
async def get_state():
    # Access the state in a thread-safe manner
    with state_lock:
        state = app.state.my_state
    return {"state": state}

@app.post("/update-state")
async def update_state(new_value: str):
    # Modify the state in a thread-safe manner
    with state_lock:
        app.state.my_state = new_value
    return {"message": "State updated successfully"}