如何启动事件驱动的WSGI服务器而不阻塞我的代码

时间:2016-01-25 23:53:02

标签: python flask socket.io wsgi python-multithreading

python-socketio

的此片段开始
import socketio
import eventlet
from flask import Flask, render_template

sio = socketio.Server()
app = Flask(__name__)

@app.route('/')
def index():
    """Serve the client-side application."""
    return render_template('index.html')

@sio.on('connect')
def connect(sid, environ):
    print('connect ', sid)

@sio.on('my message')
def message(sid, data):
    print('message ', data)

@sio.on('disconnect')
def disconnect(sid):
    print('disconnect ', sid)

if __name__ == '__main__':
    # wrap Flask application with socketio's middleware
    app = socketio.Middleware(sio, app)

    # deploy as an eventlet WSGI server
    eventlet.wsgi.server(eventlet.listen(('', 8000)), app)     <====

最后一行代码阻止了我的代码,但我想将它作为守护进程运行并继续使用更多逻辑。这是否可能。

我已阅读this post并按照建议尝试使用threading,但我担心,我做得不对。

wst = threading.Thread(target=eventlet.wsgi.server(eventlet.listen(('', 7000)), app))
wst.daemon = True
wst.start()

任何指针?

更新

我试过这个

    # wrap Flask application with socketio's middleware
    app = socketio.Middleware(sio, app)

    # deploy as an eventlet WSGI server
    # eventlet.wsgi.server(eventlet.listen(('', 7000)), app)

    wst = threading.Thread(target=self.serve_app, args=(app))
    wst.daemon = True
    wst.start()

def serve_app(app):
    eventlet.wsgi.server(eventlet.listen(('', 7000)), app)

@4000000056a6bbe61979723c Exception in thread Thread-1:
@4000000056a6bbe619797df4 Traceback (most recent call last):
@4000000056a6bbe6197981dc   File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
@4000000056a6bbe6197985c4     self.run()
@4000000056a6bbe6197989ac   File "/usr/lib/python2.7/threading.py", line 763, in run
@4000000056a6bbe619798d94     self.__target(*self.__args, **self.__kwargs)
@4000000056a6bbe61979917c TypeError: serve_app() argument after * must be a sequence, not Middleware
@4000000056a6bbe6197a164c 

正确的方法是什么?

更新2

改变了一点代码

    wst = threading.Thread(target=self.serve_app, args=(sio))
    wst.daemon = True
    wst.start()

def serve_app(sio):     app = socketio.Middleware(sio,app)     eventlet.wsgi.server(eventlet.listen((&#39;&#39;,7000)),app)

正如建议的那样传递了一个元组(app,)但现在出现了这个错误

@4000000056a7543717fb2324   File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
@4000000056a7543717fb270c     self.run()
@4000000056a7543717fb270c   File "/usr/lib/python2.7/threading.py", line 763, in run
@4000000056a7543717fb2af4     self.__target(*self.__args, **self.__kwargs)
@4000000056a7543717fb2edc TypeError: serve_app() takes exactly 1 argument (2 given)

这看起来像我遗漏的Python语法

更新3 - 已解决

我忘记了(self,

       wst = threading.Thread(target=self.serve_app, args=(sio,app))
        wst.daemon = True
        wst.start()

def serve_app(self, _sio, _app):
    app = socketio.Middleware(_sio, _app)
    eventlet.wsgi.server(eventlet.listen(('', 7000)), app)

0 个答案:

没有答案