gpt4 book ai didi

python - 如何将后台线程添加到 flask ?

转载 作者:IT老高 更新时间:2023-10-28 21:36:28 24 4
gpt4 key购买 nike

我正忙着写一个小型游戏服务器来尝试 flask 。游戏通过 REST 向用户公开一个 API。用户执行操作和查询数据很容易,但是我想在 app.run() 循环之外为 "game world" 服务以更新游戏实体,等等。鉴于 Flask 实现得如此干净,我想看看是否有 Flask 方法可以做到这一点。

最佳答案

您的附加线程必须从 WSGI 服务器调用的同一个应用程序启动。

下面的示例创建了一个后台线程,该线程每 5 秒执行一次并操作也可用于 Flask 路由函数的数据结构。

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
app = Flask(__name__)

def interrupt():
global yourThread
yourThread.cancel()

def doStuff():
global commonDataStruct
global yourThread
with dataLock:
pass
# Do your stuff with commonDataStruct Here

# Set the next thread to happen
yourThread = threading.Timer(POOL_TIME, doStuff, ())
yourThread.start()

def doStuffStart():
# Do initialisation stuff here
global yourThread
# Create your thread
yourThread = threading.Timer(POOL_TIME, doStuff, ())
yourThread.start()

# Initiate
doStuffStart()
# When you kill Flask (SIGTERM), clear the trigger for the next thread
atexit.register(interrupt)
return app

app = create_app()

从 Gunicorn 调用它,如下所示:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

关于python - 如何将后台线程添加到 flask ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14384739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com