我试图向客户端返回一个 twitter 元数据流,客户端以由 tweepy 的“轨道”过滤的形式输入该元数据。
我遇到的问题是没有任何东西返回给浏览器,即使服务器接收到它并处理了请求。到目前为止,这是我的代码:
主.py:
import flask
from flask.views import MethodView
from tweetStreamsRT import StreamerRt
app = flask.Flask(__name__)
app.secret_key = "asecret"
class View(MethodView):
def get(self):
return flask.render_template('index.html')
def post(self):
results = StreamerRt().filter(track = (flask.request.form['event']))
flask.flash(results)
return self.get()
app.add_url_rule('/', view_func = View.as_view('index'), methods=['GET', 'POST'])
app.debug = True
app.run()
连接到 Twitter Streaming API 的类:
import sys
import tweepy
import json
import time
#from textwrap import TextWrapper
import pymongo
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_TOKEN_SECRET = ''
auth = tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
connection = pymongo.Connection()
db = connection.twitterStream
class Listener(tweepy.StreamListener):
def on_status(self, status):
message = {}
if status.author.lang == 'en':
try:
message = {
'Author': status.author.screen_name,
'Author_id': status.id,
'Time_normal': str(status.created_at),
'geo_enabled': status.author.geo_enabled,
'Geo': status.geo,
'Place' : status.place,
'Coordinates': status.coordinates}
db.tweetStream.insert(message)
except Exception, e:
print >> sys.stderr, 'Encountered Exception:', e
pass
def on_error(self, status_code):
waitPeriod = 60
if status_code == 420:
print >> sys.stderr, 'Encountered a %i Error, will retry in %i minutes' % \
(status_code, waitPeriod/60)
time.sleep(waitPeriod)
waitPeriod *= 2
return waitPeriod
else:
print >> sys.stderr, 'Encountered error with status code:', status_code
return True
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True
def StreamerRt():
return tweepy.streaming.Stream(auth, Listener(), timeout=60)
我的 html 文件继承自基础并形成 html 文件:
{% extends "base.html" %}
{% import "forms.html" as forms %}
{% block page_header %}
<div class="page-header">
<h1>Welcome</h1>
</div>
{% endblock %}
{% block content %}
<h2>Enter the Event you would like to follow</h2>
<form action="/" method="post">
<input type="text" name="event" />
<input type="submit" value="Submit Query" />
</form>
{% with messages = get_flashed_messages() %}
{% if messages %}
Results:
<pre>
{% for message in messages %}
{{ message }}
{% endfor %}
</pre>
{% endif %}
{% endwith %}
{% endblock %}
似乎我无法将任何流数据返回给客户端。
您如何将某些元数据从 Twitter Streaming API 返回到浏览器,同时将其写入数据库。
谢谢
此外,StreamerRt 函数不会按轨道作为来自客户端的输入进行过滤,但似乎会返回整个公共时间线。