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)