问题
there's a demo on how to implement comet using 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()
it uses gevent's event class. if any one publish a message, anyone in the chat room will receive the message.
what if i just want someone to receive the message? should i use gevent.event.AsyncResult ? if so, how to do it?
回答1:
Use gevent.queue.Queue.
Reading from the Queue removes the message and if there are multiple readers, each message will be delivered to exactly one of them (which one is unspecified though, there's no randomness or fairness, it's just arbitrary).
来源:https://stackoverflow.com/questions/7697255/how-to-implement-comet-via-gevents-event