如何通过gevent的事件实现彗星 [英] how to implement comet via gevent's event

查看:71
本文介绍了如何通过gevent的事件实现彗星的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于如何实现彗星的 demo 使用gevent + flask。

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()

它使用gevent的事件类。如果有人发布消息,则聊天室中的任何人都会收到消息。

it uses gevent's event class. if any one publish a message, anyone in the chat room will receive the message.

如果我只想某人接收消息,该怎么办?我应该使用gevent.event.AsyncResult吗?如果是,怎么办?

what if i just want someone to receive the message? should i use gevent.event.AsyncResult ? if so, how to do it?

推荐答案

使用 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).

这篇关于如何通过gevent的事件实现彗星的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆