【问题标题】:How to cancel a curl request from a WRITEFUNCTION?如何取消来自 WRITEFUNCTION 的 curl 请求?
【发布时间】:2011-07-03 22:31:48
【问题描述】:

我在 python 中有一个 curl 请求,它将大量数据输出到 writefunction (CURLOPT_WRITEFUNCTION)。如果满足某个条件,我希望能够取消来自 writefunction 的 curl 请求。我尝试过使用 ch.close(),但错误提示它在执行请求时无法关闭请求。还有其他方法可以让它停止写功能吗?这是我的代码:

    self.ch = pycurl.Curl()

    self.ch.setopt(pycurl.URL, file_url)
    self.ch.setopt(pycurl.CONNECTTIMEOUT, 60)
    self.ch.setopt(pycurl.WRITEFUNCTION, self.WriteWrapper)
    self.ch.setopt(pycurl.HEADERFUNCTION, self.ParseHeaders)
    self.ch.setopt(pycurl.FOLLOWLOCATION, True)
    self.ch.setopt(pycurl.COOKIE, cookies[file_host])
    self.ch.setopt(pycurl.HTTPHEADER, self.headers_received)

    self.ch.perform()
    self.ch.close()


def do_POST(self):
    return self.do_GET()

def WriteWrapper(self, data):
    if self.do_curl_request:
        try:
            return self.wfile.write(data)
        except:
            self.ch.close() # This doesn't work :(

【问题讨论】:

  • 只是在这里猜测(基于on this),但也许return None

标签: python curl pycurl


【解决方案1】:

如果从你的 write 函数返回的数字不等于它认为它正在写入的数字,pycurl 会引发错误,因此在你的 write 函数中返回 -1 或引发异常将导致它引发 pycurl.error。请注意,返回 'None' 被解释为 'all bytes written'.

>>> class Writer:
...   def __init__(self):
...     self.count = 0
...   def write(self, data):
...     print "Write called", len(data)
...     return -1
...
>>> curl = pycurl.Curl()
>>> writer = Writer()
>>> curl.setopt(pycurl.WRITEFUNCTION, writer.write)
>>> curl.setopt(pycurl.URL, "file:///some_big_file.txt")
>>> curl.perform()
Write called 16383
pycurl.error: invalid return value for write callback -1 16383
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
pycurl.error: (23, 'Failed writing body (0 != 16383)')

【讨论】:

    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多