簡體   English   中英

如何通過gevent的事件實現彗星

[英]how to implement comet via gevent's event

有一個演示如何使用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嗎? 如果可以,該怎么辦?

使用gevent.queue.Queue

從隊列中讀取將刪除該消息,並且如果有多個閱讀器,則每條消息將被准確地傳遞給其中的一個(盡管未指定,但沒有隨機性或公平性,只是任意的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM