Python: Twitter流和pycurl问题
我在使用pycurl和Twitter的流媒体API时遇到了问题。运行下面的代码时,似乎在执行perform这个调用时出错。我知道这一点是因为我在perform调用前后加了打印语句。我使用的是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>"
2 个回答
1
你正在尝试使用基本认证。
基本认证是通过HTTP请求的头部发送用户的登录信息。这种方式使用起来很简单,但安全性不高。OAuth是Twitter推荐的认证方式,从2010年8月起,我们将关闭API中的基本认证。--认证,Twitter
2
首先,试着开启详细模式,这样可以帮助你调试:
self.conn.setopt(pycurl.VERBOSE ,1)
看起来你没有设置基本的身份验证模式:
self.conn.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
根据文档,你需要把参数以POST的方式发送给API,而不是像GET那样传递:
data = dict( track='stack overflow' )
self.conn.setopt(pycurl.POSTFIELDS,urlencode(data))