【问题标题】:FastApi: How to define a global variable onceFastApi:如何定义一个全局变量一次
【发布时间】:2021-09-07 07:18:03
【问题描述】:

我想定义一个 dict 变量一次,从文本文件生成,并用它来回答 API 请求。

这个变量应该一直可用到服务器运行结束。

在下面的示例中:

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)

我会得到:

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)

并且对 localhost:8000 的请求不会引发任何错误

我应该如何定义一个变量,它将作为全局变量访问任何请求?有没有一种通用的方式来定义一次并使用它?

必要时的要求:

fastapi==0.68.1
pydantic==1.8.2
starlette==0.14.2
typing-extensions==3.10.0.2

【问题讨论】:

  • 你的方法有什么问题?
  • 从一个大文件创建一个字典两次可能是一个真正的问题
  • @Alex 你知道为什么你的方法被执行了两次吗?
  • 我想这是由于服务器的异步特性

标签: python fastapi asgi


【解决方案1】:

一种方法是在应用启动时使用FastAPI startup event 定义变量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)

运行应用时,您会看到该函数只执行一次:

INFO:     Started server process [37992]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
init call

【讨论】:

  • 它几乎可以工作。我将“data = {}”更改为“全局数据”并在 init_data() 中定义了全局变量。在本例中,数据变量在 init_data 方法调用后再次重新定义为 Empty dict
猜你喜欢
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多