0

gevent + フラスコを使用してコメットを実装する方法に関するデモがあります。

#coding:utf-8
'''
Created on Aug 6, 2011

@author: Alan Yang
'''
import time
from gevent import monkey
monkey.patch_all()

from gevent.event import Event
from gevent.pywsgi import WSGIServer

from flask import Flask,request,render_template,jsonify

app = Flask('FlaskChat')
app.event = Event()
app.cache = []
app.cache_size = 12

@app.route('/')
def index():
    return render_template('index.html',messages=app.cache)

@app.route('/put',methods=['POST'])
def put_message():
    message = request.form.get('message','')
    app.cache.append('{0} - {1}'.format(time.strftime('%m-%d %X'),message.encode('utf-8')))
    if len(app.cache) >= app.cache_size:
        app.cache = app.cache[-1:-(app.cache_size):-1]
    app.event.set()
    app.event.clear()
    return 'OK'

@app.route('/poll',methods=['POST'])
def poll_message():
    app.event.wait()
    return jsonify(dict(data=[app.cache[-1]]))


if __name__ == '__main__':
    #app.run(debug=True)
    WSGIServer(('0.0.0.0',5000),app,log=None).serve_forever()

gevent のイベント クラスを使用します。誰かがメッセージを公開すると、チャット ルームの全員がメッセージを受信します。

誰かにメッセージを受信して​​もらいたい場合はどうすればよいですか? gevent.event.AsyncResult を使用する必要がありますか? もしそうなら、それを行う方法は?

4

1 に答える 1

0

gevent.queue.Queueを使用します。

キューから読み取るとメッセージが削除され、複数のリーダーがある場合、各メッセージはそのうちの 1 つに配信されます (ただし、どれが指定されていないかは不明ですが、ランダム性や公平性はなく、任意です)。

于 2011-10-08T14:19:22.757 に答える