如何限制写入函数的curl调用次数?

时间:2011-01-17 04:46:21

标签: python curl pycurl

我试图限制调用此WRITEFUNCTION的次数。我有什么方法可以做到吗?

定义写函数:

conn.setopt(pycurl.WRITEFUNCTION, on_receive)

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

这是一个应该有效的脏简单版本。构建PycURL以测试并找到更好的方法。

import pycurl, json

STREAM_URL = "http://chirpstream.twitter.com/2b/user.json"

USER = "segphault"
PASS = "XXXXXXXXX"

class LimitError(Exception): pass

counter = 0
limit = 10
def on_receive(data):
    global counter
    if counter < 10:
        print data
        counter += 1
    else:
        raise LimitError    
conn = pycurl.Curl()
conn.setopt(pycurl.USERPWD, "%s:%s" % (USER, PASS))
conn.setopt(pycurl.URL, STREAM_URL)
conn.setopt(pycurl.WRITEFUNCTION, on_receive)

try:
    conn.perform()
    print "Exited Normally"
except LimitError:
    print "Reached limit, exiting"
except pycurl.error:
    if counter == limit:
        print "pycurl expected error, nothing to worry about"
    else:
        raise
finally:
    conn.close()

print "All done"