我有两个主要模块,Tornado WebSocket 和 Tweepy Streaming,我试图让它们互相交谈。
在下面on_status
的StdOutListener
Tweepy 类中(标有<--
),我想调用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()