Mar*_*nus 73 python rest flask
我正在忙着写一个小游戏服务器试用烧瓶.游戏通过REST向用户公开API.用户可以轻松执行操作和查询数据,但是我想在app.run()循环之外为"游戏世界"提供服务以更新游戏实体等.鉴于Flask实施得非常干净,我想要看看Flask是否有办法做到这一点.
小智 67
您的其他线程必须从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:
# 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()
Run Code Online (Sandbox Code Playgroud)
从Gunicorn中调用它是这样的:
gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app
Run Code Online (Sandbox Code Playgroud)
And*_*röm 10
除了使用纯线程或 Celery 队列(注意不再需要flask-celery),你还可以看看flask-apscheduler:
https://github.com/viniciuschiele/flask-apscheduler
从https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py复制的一个简单示例:
from flask import Flask
from flask_apscheduler import APScheduler
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'jobs:job1',
'args': (1, 2),
'trigger': 'interval',
'seconds': 10
}
]
SCHEDULER_API_ENABLED = True
def job1(a, b):
print(str(a) + ' ' + str(b))
if __name__ == '__main__':
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
# it is also possible to enable the API directly
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
app.run()
Run Code Online (Sandbox Code Playgroud)