2

我有两个主要模块,Tornado WebSocket 和 Tweepy Streaming,我试图让它们互相交谈。

在下面on_statusStdOutListenerTweepy 类中(标有<--),我想调用WSHandler.on_message更高层的 Tornado 类,数据从on_status.

但是,我无法这样做,因为我收到与未定义实例等相关的错误消息,代码如下。非常感谢任何帮助!

(此外,我设法同时运行两个模块的唯一非阻塞方式是使用线程,因为IOLoop.add_callback它不会StdOutListener阻止阻塞。我很想知道为什么或是否推荐这种实现。谢谢!)

import os.path
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import threading
import time
import datetime

# websocket
class FaviconHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('/static/favicon.ico')

class WebHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("websockets.html")

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self): 
        cb = tornado.ioloop.PeriodicCallback(self.spew, 1000, io_loop=main_loop)
        cb.start()
        print 'new connection'
        self.write_message("Hi, client: connection is made ...")

    def on_message(self, message):
        print 'message received: \"%s\"' % message
        self.write_message("Echo: \"" + message + "\"")
        if (message == "green"):
            self.write_message("green!")

    def on_close(self):
        print 'connection closed'

    def spew(self):
        msg = 'spew!'
        print(msg)
        self.on_message(msg)

handlers = [
    (r"/favicon.ico", FaviconHandler),
    (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
    (r'/', WebHandler),
    (r'/ws', WSHandler),
]

settings = dict(
    template_path=os.path.join(os.path.dirname(__file__), "static"),
)

application = tornado.web.Application(handlers, **settings)


# tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import simplejson as json


# new stream listener 
class StdOutListener(StreamListener, WSHandler):
    """ A listener handles tweets are the received from the stream. 
    This is a basic listener that just prints received tweets to stdout.

    """

    # tweet handling
    def on_status(self, status):
        print('@%s: %s' % (status.user.screen_name, status.text))
        WSHandler.on_message(status.text) # <--- THIS is where i want to send a msg to WSHandler.on_message

    # limit handling
    def on_limit(self, track):
        return

    # error handling
    def on_error(self, status):
        print status


def OpenStream():
    consumer_key="[redacted]"
    consumer_secret="[redacted]"
    access_token="[redacted]"
    access_token_secret="[redacted]"
    keyword = 'whatever'

    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l, gzip=True) 
    stream.filter(track=[keyword])



if __name__ == "__main__":
    threading.Thread(target=OpenStream).start()
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    main_loop = tornado.ioloop.IOLoop.instance()
#   main_loop.add_callback(OpenStream)
    main_loop.start()
4

1 回答 1

5

on_message是实例方法,而不是类方法。您需要在实例上调用它,如下所示:

handler = WSHandler()
handler.on_message('hello world')

但是,您不能只这样做,因为需要通过浏览器连接创建实例才能实际发送和接收消息。

您可能想要的是保留一个打开的连接列表(Tornado websocket 演示就是一个很好的例子):

class WSHandler(tornado.websocket.WebSocketHandler):
    connections = []

    def open(self):
        self.connections.append(self)

    ....

    def on_close(self):
        self.connections.remove(self)

然后,在 中StdOutListener.on_status,您可以执行以下操作:

for connection in WSHandler.connections:
    connection.write_message(status.text)
于 2012-09-18T21:31:29.387 回答