0

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

Henry
  • 1
  • 3
  • One way is to store terminal status in a file/database and retrieve it in the `status` function. – shaik moeed Jul 10 '23 at 14:42
  • Does [this](https://stackoverflow.com/a/71537393/17865804) answer your question? Related answers can also be found [here](https://stackoverflow.com/a/71298949/17865804), as well as [here](https://stackoverflow.com/a/71465282/17865804) and [here](https://stackoverflow.com/a/76322910/17865804) – Chris Jul 10 '23 at 14:54
  • @Chris thanks for your reply, it was helpful to provide a direction to a working short-term solution. Nevertheless, I am still unable to separate creation of terminal() and uvicorn.run() into separate files. I believe `uvicorn.run("myfile:fastapi", ...)` does not care about what is defined in **myfile** outside the scope of app context, i.e.the terminal instance, passed as per your hint: `fastapi.state.terminal = terminal` is not "seen" if it is not in the _same file_ as `uvicorn.run()` – Henry Jul 12 '23 at 14:30

0 Answers0