【问题标题】:Python: Twitter Streaming and pycurl problemsPython:Twitter 流和 pycurl 问题
【发布时间】:2010-11-26 22:50:38
【问题描述】:

我在将 pycurl 与 Twitter 的 Streaming API 过滤器流结合使用时遇到问题。 当我运行下面的代码时发生了什么,它似乎在执行调用时出错了。我知道这一点是因为我在执行调用之前和之后放置了打印语句。我正在使用 Python 2.6.1,如果这很重要,我在 Mac 上。

#!/usr/bin/python
print "Content-type: text/html"
print
import pycurl, json, urllib

STREAM_URL = "http://stream.twitter.com/1/statuses/filter.json?follow=1&count=100"
USER = "user"
PASS = "password"
print "<html><head></head><body>"


class Client:
    def __init__(self):
        self.buffer = ""
        self.conn = pycurl.Curl()
        self.conn.setopt(pycurl.POST,1)
        self.conn.setopt(pycurl.USERPWD, "%s:%s" % (USER,PASS))
        self.conn.setopt(pycurl.URL, STREAM_URL)
        self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)

        try:
            self.conn.perform()
            self.conn.close()
        except BaseException:
            traceback.print_exc()

    def on_receive(self,data):
        self.buffer += data
        if data.endswith("\r\n") and self.buffer.strip():
            content = json.loads(self.buffer)
            self.buffer = ""
            print content
            if "text" in content:
                print u"{0[user][name]}: {0[text]}".format(content)

client = Client()

print "</body></html>"

【问题讨论】:

    标签: python twitter pycurl


    【解决方案1】:

    首先,尝试打开详细程度以帮助调试:

        self.conn.setopt(pycurl.VERBOSE ,1)
    

    您似乎没有设置基本身份验证模式:

        self.conn.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
    

    另外根据文档,您需要向 API 提供参数的 POST,而不是作为 GET 参数传入:

        data = dict( track='stack overflow' )
        self.conn.setopt(pycurl.POSTFIELDS,urlencode(data))
    

    【讨论】:

      【解决方案2】:

      您正在尝试使用基本身份验证。

      基本身份验证发送用户 HTTP 标头中的凭据 要求。这使它易于使用, 但不安全。 OAuth 是 Twitter 首选的身份验证方法 向前迈进 - 来 2010 年 8 月, 我们将关闭基本身份验证 API。 --Authentication, Twitter

      【讨论】:

      • 是否可以将 OAuth 与 pycurl 一起使用,或者我是否必须通过 Python 走另一条路线才能使用 Streaming API?
      • 或者像code.google.com/p/python-twitter这样的东西?无需重新发明轮子。
      • 轮子改造对于教育目的是可以的,只要它不会在生产代码中结束。例如,很高兴知道我们可以从头开始编写一个链表类……
      • 我同意车轮改造。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多