python - 如何取消来自 WRITEFUNCTION 的 curl 请求?

标签 python curl pycurl

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

    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 :(

最佳答案

如果从您的写入函数返回的数字不等于它认为正在写入的数字,pycurl 会引发错误,因此返回 -1 或在您的写入函数内引发异常将导致它引发 pycurl.error。请注意,返回“无”被解释为 '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)')

关于python - 如何取消来自 WRITEFUNCTION 的 curl 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111353/

相关文章:

python - Pushbullet pycurl 在消息中带有换行符

python - 如何使用 python 在 xlsxwriter 上进行编码

Python:使用 numpy 保存/加载大数组

curl - 将 paypal curl get access token 请求转换为 guzzle

curl 跟随位置错误

php - curl PHP 文件上传

ssl - 验证对等点与发送 https post 分开

python - pycurl:如何重置 cookie session

python - 如何在 Keras 中使用类权重进行图像分割

python - 以编程方式修改 Django 设置