I want to define a dict variable once, generated from a text file, and use it to answer to API requests.
This variable should be always available till the end of server run.
In an example below:
from fastapi import FastAPI
import uvicorn
app = FastAPI()
def init_data(path):
print("init call")
data = {}
data[1] = "123"
data[2] = "abc"
return data
data = init_data('path')
@app.get('/')
def example_method():
# data is defined
return {'Data': data[1]}
if __name__ == '__main__':
uvicorn.run(f'example_trouble:app', host='localhost', port=8000)
I will get:
init call
init call
INFO: Started server process [9356]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://localhost:8000 (Press CTRL+C to quit)
and request to localhost:8000 wouldn't raise any errors
How should I define a variable once, that would be accessed as a global variable to any request? Is there a common way to define it once and use it?
requirements if necessary:
fastapi==0.68.1
pydantic==1.8.2
starlette==0.14.2
typing-extensions==3.10.0.2