如何将背景线程添加到烧瓶中?

时间:2013-01-17 17:29:40

标签: python rest flask

我正在忙着写一个小游戏服务器试用烧瓶。游戏通过REST向用户公开API。用户可以轻松执行操作和查询数据,但是我想在app.run()循环之外为“游戏世界”提供服务以更新游戏实体等。鉴于Flask实施得非常干净,我想要看看是否有Flask方法可以做到这一点。

3 个答案:

答案 0 :(得分:68)

您的其他线程必须从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()          

使用类似的东西从Gunicorn调用它:

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

答案 1 :(得分:3)

除了使用纯线程或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()

答案 2 :(得分:1)

首先,您应该使用任何 WebSocket 或轮询机制将发生的更改通知前端部分。我使用 Flask-SocketIO 包装器,并且对我的小应用程序的异步消息感到非常满意。

嵌套,你可以在一个单独的线程中完成你需要的所有逻辑,并通过 SocketIO 对象通知前端(Flask 保持与每个前端客户端的持续开放连接)。

举个例子,我刚刚在后端文件修改时实现了页面重新加载:

<!doctype html>
<script>
    sio = io()

    sio.on('reload',(info)=>{
        console.log(['sio','reload',info])
        document.location.reload()
    })
</script>
class App(Web, Module):

    def __init__(self, V):
        ## flask module instance
        self.flask = flask
        ## wrapped application instance
        self.app = flask.Flask(self.value)
        self.app.config['SECRET_KEY'] = config.SECRET_KEY
        ## `flask-socketio`
        self.sio = SocketIO(self.app)
        self.watchfiles()

    ## inotify reload files after change via `sio(reload)``
    def watchfiles(self):
        from watchdog.observers import Observer
        from watchdog.events import FileSystemEventHandler
        class Handler(FileSystemEventHandler):
            def __init__(self,sio):
                super().__init__()
                self.sio = sio
            def on_modified(self, event):
                print([self.on_modified,self,event])
                self.sio.emit('reload',[event.src_path,event.event_type,event.is_directory])
        self.observer = Observer()
        self.observer.schedule(Handler(self.sio),path='static',recursive=True)
        self.observer.schedule(Handler(self.sio),path='templates',recursive=True)
        self.observer.start()