0

有一个关于如何使用 gevent + flask 实现彗星的演示。

#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

从队列中读取会删除消息,如果有多个阅读器,则每条消息将被传递给其中一个(虽然未指定哪个,没有随机性或公平性,它只是任意的)。

于 2011-10-08T14:19:22.757 回答