2010-11-26 77 views
2

我與python結合使用Twitter的Streaming API過濾器流時遇到問題。 當我在代碼下面運行代碼時發生了什麼,似乎是在執行調用中barf。我知道這是因爲我在執行調用之前和之後放置了打印語句。我使用Python 2.6.1,如果有問題,我在Mac上。Python:Twitter流式傳輸和pycurl問題

#!/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

首先,嘗試開啓冗長來幫助調試:

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)) 
1

您正在嘗試使用基本身份驗證。

基本身份驗證向HTTP 請求的標頭中發送用戶 憑據。這使它易於使用,但不安全。 OAuth是Twitter的 首選身份驗證方法 前進 - 來吧2010年8月, 我們將關閉基本身份驗證從 API。 - Authentication, Twitter

+0

是否有使用pycurl的OAuth或我必須去Python的另一條路線使用Streaming API? – calmcajun 2010-11-29 00:09:25