【问题标题】:Twisted server, consume from Twitter stream api and serve static content at the same timeTwisted 服务器,从 Twitter 流 api 消费并同时提供静态内容
【发布时间】:2014-04-07 10:14:19
【问题描述】:

我对扭曲的服务器和一般的服务器有点陌生。我需要在本地运行一个异步服务器,从 twitter 推文中检索数据(将数据写入本地文件),同时,我想在“local_ip:8880”处提供一些简单的内容,例如“Hello world” 问题是流 api 创建了一个 http 连接,我不知道如何同时执行这两个任务。我的代码如下所示:

"imports and connection to twitter api keys"
def pp(o):
   return json.dumps(o, indent=3)
class listener(StreamListener):

   def on_data(self,data):
      #Convert to JSON the input string
      data_json = json.loads(data)
      #print pp(data_json['user'])

      #We get the html from embedly
      tweet_id = data_json['id_str']
      tweet_user = data_json['user']['screen_name']
      tweet_url = "https://twitter.com/"+tweet_user+"/status/"+tweet_id
      html="<a class=\"embedly-card\" href=\""+tweet_url+"\">Prueba</a>\n"
      print "Datos recibidos en el listener."
      #Write the results in the file
      f = open('myfile.html','a')
      f.write(html) # python will convert \n to os.linesep
      f.close()
      return True

   def on_error(self,status):
      print status


class Root(resource.Resource,StreamListener):
   isLeaf = True
   def __init__(self):
      print "Server iniciado"
      auth = OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
      auth.set_access_token(OAUTH_TOKEN,OAUTH_TOKEN_SECRET)
      twitterStream = Stream(auth, listener())

      twitterStream.filter(track=["query"])

   def render_GET(self, request):
         print "Recibida peticion"
         return '<html><body>Hello world<body></html>'

root = Root()
site = server.Site(root)
reactor.listenTCP(8880, site)
reactor.run()

当我运行它时,我卡在控制台中,它接收流数据,但是当我访问我的“local_ip:8880”时,它无法加载“Hello world”。 有可能做到这一点吗?提前感谢您的关注,对我的英语感到抱歉。

【问题讨论】:

    标签: python api asynchronous twitter twisted


    【解决方案1】:

    如果您使用阻塞 API(例如,使用阻塞套接字执行网络 I/O 的函数),那么您将阻止 Twisted 应用程序同时执行操作。一次只能进行一项阻塞操作。

    切换到非阻塞 Twitter API - 例如,https://github.com/fiorix/twisted-twitter-stream

    【讨论】:

    • 看来我需要授权才能从新的流 api 端点“stream.twitter.com”获取数据,这就是 twisted-twitter-stream 使用的。我整个下午都在寻找另一个有效的 api,但没有人工作,所有这些都被阻塞了。有什么建议么?感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2016-08-08
    相关资源
    最近更新 更多