【问题标题】:Django/gevent socket.IO with redis pubsub. Where do I put things?带有 redis pubsub 的 Django/gevent socket.IO。我把东西放在哪里?
【发布时间】:2011-10-06 17:49:58
【问题描述】:

我有一个独立的 python 脚本,它简单地从 Twitter 的流 API 中捕获数据,然后在收到每条消息时,使用它发布到频道“tweets”的 redis pubsub。这是那个脚本:

def main():
    username = "username"
    password = "password"
    track_list = ["apple", "microsoft", "google"]

    with tweetstream.FilterStream(username, password, track=track_list) as stream:
        for tweet in stream:
            text = tweet["text"]
            user = tweet["user"]["screen_name"]
            message = {"text": text, "user": user}
            db.publish("tweets", message)

if __name__ == '__main__':
    try:
        print "Started..."
        main()
    except KeyboardInterrupt:
        print '\nGoodbye!'

我的服务器端 socket.io 实现是使用 django-socketio(基于 gevent-socketio)https://github.com/stephenmcd/django-socketio 完成的,它只提供了一些辅助装饰器以及一个 broadcast_channel 方法。因为它是在 django 中完成的,所以我只是简单地将这段代码放在 views.py 中,以便它们被导入。我的views.py代码:

def index(request):
    return render_to_response("twitter_app/index.html", {
    }, context_instance=RequestContext(request))

def _listen(socket):
    db = redis.Redis(host="localhost", port=6379, db=0)
    client = db.pubsub()
    client.subscribe("tweets")
    tweets = client.listen()

    while True:
        tweet = tweets.next()
        tweet_data = ast.literal_eval(tweet["data"])
        message = {"text": tweet_data["text"], "user": tweet_data["user"], "type": "tweet"}
        socket.broadcast_channel(message)

@on_subscribe(channel="livestream")
def subscribe(request, socket, context, channel):
    g = Greenlet.spawn(_listen, socket)

客户端 socket.io JavaScript 只是简单地连接并订阅频道“livestream”,并将任何接收到的消息捕获到该频道:

var socket = new io.Socket();
socket.connect();
socket.on('connect', function() {
    socket.subscribe("livestream");
});
socket.on('message', function(data) {
    console.log(data);
});

这段代码的明显问题是,每次新用户或浏览器窗口打开页面时,都会产生一个新的 _listen 方法,并且为每个用户订阅和广播推文,导致在客户。我的问题是,将 _listen 方法放在哪里合适,以便它只创建一次,而不管客户端的数量如何?另外,请记住,broadcast_channel 方法是套接字实例的方法。

【问题讨论】:

    标签: python django socket.io publish-subscribe gevent


    【解决方案1】:

    问题是我应该使用 socket.send 时使用的是 socket.broadcast_channel。

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多