5

現在、Twitter APIストリーム(http://stream.twitter.com/1/statuses/sample.json)をカーリングしているので、常にデータを受信して​​います。ストリームからX個のオブジェクトを取得したら、ストリームのcURLを停止したいと思います(この例では、任意の数として10を指定します)。

以下のコードで、接続を閉じようとした方法を確認できます。curling.perform()の下のコードは、データの連続ストリームであるため、実行されません。そこで、body_callbackでストリームを閉じようとしましたが、perform()が現在実行されているため、close()を呼び出すことができません。

どんな助けでもいただければ幸いです。

コード:

# Imports
import pycurl # Used for doing cURL request
import base64 # Used to encode username and API Key
import json # Used to break down the json objects

# Settings to access stream and API
userName = 'twitter_username' # My username
password = 'twitter_password' # My API Key
apiURL = 'http://stream.twitter.com/1/statuses/sample.json' # the twitter api
tweets = [] # An array of Tweets

# Methods to do with the tweets array
def how_many_tweets():
    print 'Collected: ',len(tweets)
    return len(tweets)

class Tweet:
    def __init__(self):
        self.raw = ''
        self.id = ''
        self.content = ''

    def decode_json(self):
        return True

    def set_id(self):
        return True

    def set_content(self):
        return True

    def set_raw(self, data):
        self.raw = data

# Class to print out the stream as it comes from the API
class Stream:
    def __init__(self):
        self.tweetBeingRead =''

    def body_callback(self, buf):
        # This gets whole Tweets, and adds them to an array called tweets
        if(buf.startswith('{"in_reply_to_status_id_str"')): # This is the start of a tweet
            # Added Tweet to Global Array Tweets
            print 'Added:' # Priniting output to console
            print self.tweetBeingRead # Printing output to console
            theTweetBeingProcessed = Tweet() # Create a new Tweet Object
            theTweetBeingProcessed.set_raw(self.tweetBeingRead) # Set its raw value to tweetBeingRead
            tweets.append(theTweetBeingProcessed) # Add it to the global array of tweets
            # Start processing a new tweet
            self.tweet = buf # Start a new tweet from scratch
        else:
            self.tweetBeingRead = self.tweetBeingRead+buf
        if(how_many_tweets()>10):
            try:
                curling.close() # This is where the problem lays. I want to close the stream
            except Exception as CurlError:
                print ' Tried closing stream: ',CurlError

# Used to initiate the cURLing of the Data Sift streams
datastream = Stream()
curling = pycurl.Curl()
curling.setopt(curling.URL, apiURL)
curling.setopt(curling.HTTPHEADER, ['Authorization: '+base64.b64encode(userName+":"+password)])
curling.setopt(curling.WRITEFUNCTION, datastream.body_callback)
curling.perform() # This is cURLing starts
print 'I cant reach here.'
curling.close() # This never gets called. :(
4

1 に答える 1

4

渡された数と同じ量ではない数値を返すことにより、書き込みコールバックを中止できます。(デフォルトでは、「None」を返すことは、渡されたのと同じ番号を返すことと同じように扱われます)

中止すると、転送全体が完了したと見なされ、perform()呼び出しが適切に返されます。

転送が中止されたため、その転送はエラーを返します。

于 2011-05-18T10:09:06.087 に答える