FastAPI + uvicorn: how can I pass a reference to an object at runtime?

58 views Asked by At

I have a class (i.e. terminal) which holds state of a piece of hardware, and needs to be setup depending on user input & runtime config. Ideally this is performed in another, separate unit file responsible for the init setup. Then I have a fastAPI+uvicorn application which publish this data through an endpoint (/status), and hence needs to have access to this object. I am currently stuck trying to pass this object to the app. I searched around, sure that it would be an easy task, but wasn't able to find a solution yet. Any help is appreciated.

# filename: myapp.py

import uvicorn
from fastapi import FastAPI

fastapi = FastAPI()


# terminal() instance should be runtime-injected somehow, in order for FastAPI to use it...
# But how?

@fastapi.get("/status")
async def status():
    print(terminal.status())
    # [...]

if __name__ == '__main__':
    uvicorn.run("myapp:fastapi", host="0.0.0.0", port=10101)

I tried many solutions but the problems seems that uvicorn/FastAPI is somewhat monolithic and isolated from other parts of code/instances defined at runtime only

0

There are 0 answers