fastapi全局变量

在应用程序启动时使用FastAPI启动事件定义变量data

from fastapi import FastAPI
import uvicorn

app = FastAPI()
data = {}

@app.on_event('startup')
def init_data():
    print("init call")
    path='/an/example/path'
    data[1] = "123"
    data[2] = "abc"
    return data

@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)

 

posted on 2022-07-28 18:43  帅胡  阅读(2349)  评论(1编辑  收藏  举报

导航