相关疑难解决方法(0)

跨多个工作人员共享 python 对象

我们已经使用 FastAPI 创建了一个服务。当我们的服务启动时,它会创建一些 Python 对象,然后端点使用这些对象来存储或检索数据。

生产中的 FastAPI 从多个工人开始。我们的问题是每个工人创建自己的对象而不是共享一个

下面的脚本显示了我们正在做的(简化的)示例,尽管在我们的例子中 Meta() 的使用要复杂得多。

from fastapi import FastAPI, status

class Meta:
   def __init__(self):
      self.count = 0  

app = FastAPI()

meta = Meta()

# increases the count variable in the meta object by 1
@app.get("/increment")
async def increment():
    meta.count += 1
    return status.HTTP_200_OK

# returns a json containing the current count from the meta object
@app.get("/report")
async def report():
    return {'count':meta.count}

# resets the count in the meta object to 0
@app.get("/reset") …
Run Code Online (Sandbox Code Playgroud)

python asynchronous python-asyncio fastapi

9
推荐指数
4
解决办法
3151
查看次数

标签 统计

asynchronous ×1

fastapi ×1

python ×1

python-asyncio ×1