【问题标题】:How can I get the response body from pycurl multi curl requests如何从 pycurl 多卷曲请求中获取响应正文
【发布时间】:2013-03-21 09:16:45
【问题描述】:

在执行 curl 多请求时,除了空响应外,我什么也得不到。没有抛出异常,但是响应值没有内容(在下面的sn-p中注释)

这是我的代码的简化版本:

from StringIO import StringIO

import pycurl


class CurlStream(object):
    curl_count = 0
    curl_storage = []

    def __init__(self):
        self.curl_multi = pycurl.CurlMulti()

    def add_request(self, request, post_fields=None):
        self.curl_count += 1
        curl = self._create_curl(request, post_fields)
        self.curl_multi.add_handle(curl)

    def perform(self):
        while self.curl_count:
            while True:
                response, self.curl_count = self.curl_multi.perform()
                if response != pycurl.E_CALL_MULTI_PERFORM:
                    break
            self.curl_multi.select(1.0)

    def read_all(self):
        for response in self.curl_storage:
            print response.getvalue() # this does nothing --prints blank lines

    def close(self):
        self.curl_multi.close()

    def _create_curl(self, request, post_fields):
        curl = pycurl.Curl()
        output = StringIO()
        self.curl_storage.append(output)
        curl.setopt(curl.URL, request)
        curl.setopt(curl.WRITEFUNCTION, output.write)
        curl.setopt(curl.TIMEOUT, 20)
        return curl


def main():
    curl_stream = CurlStream()
    curl_stream.add_request('http://www.google.com')
    curl_stream.add_request('http://www.example.com')
    curl_stream.perform()
    curl_stream.read_all()
    curl_stream.close()

if __name__ == '__main__':
    main()

我用相同的选项发出了单个请求,但没有使用 curl multi,它可以工作。

【问题讨论】:

    标签: python python-2.7 pycurl stringio


    【解决方案1】:

    好的,所以当我将_create_curl 方法更改为此(添加write_out 进行调试)时,我发现它有效:

    def _create_curl(self, request, post_fields):
        curl = pycurl.Curl()
        curl.setopt(curl.URL, request)
        curl.setopt(curl.WRITEFUNCTION, self.write_out)
        curl.setopt(curl.TIMEOUT, 20)
    
        # Below is the important bit, I am now adding each curl object to a list
        self.curl_storage.append(curl)
        return curl
    
    def write_out(self, data):
            print data
            return len(data)
    

    问题是在将 curl 对象添加到 multicurl 对象时,我没有保留对单个 curl 对象的任何引用,因此它被自动关闭了。

    根据pycurl docs 的 curl close() 方法:

    对应于 libcurl 中的 curl_easy_cleanup。这种方法是 当 Curl 对象不再有任何对象时,由 pycurl 自动调用 引用它,但也可以显式调用。

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 2015-10-27
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 2011-04-23
      • 2014-10-09
      • 1970-01-01
      相关资源
      最近更新 更多