【问题标题】:pycurl and lot of callback functionspycurl 和很多回调函数
【发布时间】:2010-03-04 12:35:20
【问题描述】:

我有很大的 URL 列表,我必须并行下载并检查每个响应返回的标题之一。

我可以使用CurlMulti 进行并行化。 我可以使用/dev/null 作为fb,因为我对正文不感兴趣,只对标题感兴趣。

但是如何检查每个标题?

要接收标头,我必须设置 HEADERFUNCTION 回调。我明白了。

但在这个回调函数中,我只得到带有标题的缓冲区。如何区分一个请求和另一个请求?

我不喜欢创建与 URL 一样多的回调函数的想法。我应该创建一些类和该类的尽可能多的实例吗?也不是很聪明。

【问题讨论】:

    标签: python libcurl pycurl


    【解决方案1】:

    我会使用 Python 内置的 httplib 和线程模块。我认为不需要第 3 方模块。

    【讨论】:

    • 嗯,同样的原因你会使用 python 而不是 C/ASM - 让事情变得更容易/更好。
    • 如果考虑到查找和学习如何使用第 3 方模块所花费的类型,对于这样一个小问题并没有多少节省。
    • 这不是争论。您还必须学习内置模块,因此花费的时间是相同的。在某些情况下(例如这种情况),您会得到质量较低的代码。
    【解决方案2】:

    我知道您在询问 pycurl,但我发现它太难使用且不符合 Python 标准。 API 很奇怪。

    这是一个twisted 示例:

    from twisted.web.client import Agent
    from twisted.internet import reactor, defer
    
    def get_headers(response, url):
        '''Extract a dict of headers from the response'''
        return url, dict(response.headers.getAllRawHeaders())
    
    def got_everything(all_headers):
        '''print results and end program'''
        print dict(all_headers)
        reactor.stop()
    
    agent = Agent(reactor)
    urls = (line.strip() for line in open('urls.txt'))
    reqs = [agent.request('HEAD', url).addCallback(get_headers, url) for url in urls if url]
    defer.gatherResults(reqs).addCallback(got_everything)
    reactor.run()
    

    此示例异步启动所有请求,并收集所有结果。这是具有 3 个 url 的文件的输出:

    {'http://debian.org': {'Content-Type': ['text/html; charset=iso-8859-1'],
                           'Date': ['Thu, 04 Mar 2010 13:27:25 GMT'],
                           'Location': ['http://www.debian.org/'],
                           'Server': ['Apache'],
                           'Vary': ['Accept-Encoding']},
     'http://google.com': {'Cache-Control': ['public, max-age=2592000'],
                           'Content-Type': ['text/html; charset=UTF-8'],
                           'Date': ['Thu, 04 Mar 2010 13:27:25 GMT'],
                           'Expires': ['Sat, 03 Apr 2010 13:27:25 GMT'],
                           'Location': ['http://www.google.com/'],
                           'Server': ['gws'],
                           'X-Xss-Protection': ['0']},
     'http://stackoverflow.com': {'Cache-Control': ['private'],
                                  'Content-Type': ['text/html; charset=utf-8'],
                                  'Date': ['Thu, 04 Mar 2010 13:27:24 GMT'],
                                  'Expires': ['Thu, 04 Mar 2010 13:27:25 GMT'],
                                  'Server': ['Microsoft-IIS/7.5']}}
    

    【讨论】:

      【解决方案3】:

      解决方案是使用一点函数式编程将一些附加信息“粘贴”到我们的回调函数中。

      functools.partial

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-12
        • 2013-05-26
        • 2017-11-02
        • 1970-01-01
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多