如何在使用Twitter流的流示例上停止、终止、停止或关闭PycURL请求

2024-10-01 09:16:53 发布

您现在位置:Python中文网/ 问答频道 /正文

Im目前正在卷曲twitter API流(http://stream.twitter.com/1/statuses/sample.json),所以我一直在接收数据。我希望在从流中检索到X个数量的对象后停止卷曲流(在本例中,我将10作为任意数)。在

您可以在下面的代码中看到我是如何尝试关闭连接的。下面的代码冰壶表演()从不执行,因为它是连续的数据流。因此,我尝试在body_回调中关闭流,但是由于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. :(

Tags: thetoselfapijsonclosestreamraw
1条回答
网友
1楼 · 发布于 2024-10-01 09:16:53

您可以通过返回一个与传入的值不同的数字来中止写回调。(默认情况下,返回“None”与返回传递给它的数字相同)

当您中止它时,整个传输将被视为已完成,perform()调用将正确返回。在

当传输被中止时,该传输将返回一个错误。在

相关问题 更多 >