【问题标题】:python-requests hook similar to pycurl.WRITEFUNCTION?python-requests 钩子类似于 pycurl.WRITEFUNCTION?
【发布时间】:2013-11-07 20:00:30
【问题描述】:

我一直在为我的项目 https://pypi.python.org/pypi/tidehunter 使用 PycURL,它利用 pycurl.WRITEFUNCTION 挂钩以可控的方式使用传入的 HTTP 流。用例可以在项目页面上找到,或者像这样的技术:

def _on_data_receive(self, data):
    self.buffer += data

    if data.endswith('\r\n'):  # or any valid chunk delimiter
        # Do something about self.buffer
        print self.buffer

    if True:  # some valid condition to disconnect
        return -1  # the way to stop the stream, would raise pycurl.error

我正在考虑退出 PycURL,因为我用来终止按需流的解决方案相当老套(也很高兴使用 PycURL 为该用例获得更好的解决方案)。 requests 也是一个使用起来更愉快的库。

那么requests 中有什么我可以用来实现相同目的的东西吗?或者也许它也是我需要探索的传入流处理程序。

提前致谢。

【问题讨论】:

标签: python python-requests pycurl


【解决方案1】:

编辑 2016-03-22:为自私道歉。

当前答案

下面的 sn-p 是我申请使用 python-requests 完全替换 pycurl 的内容。简而言之,只需提供 stream=True 参数即可。

import requests

def tide_on(url):
    r = requests.get(url, stream=True, **kwargs)

    for line in r.iter_lines():
        # wish to stop after consuming just one line
        print(line)
        break

    r.close()

上一个“答案”

在发言时requests 的当前版本确实很容易实现我的要求。非常感谢requests背后的团队!

自 1.0 版以来,我在 tidehunter 中将 PycURL 完全替换为 requests,效果很好!

再次感谢以上所有的 cmets :)

【讨论】:

  • 请在答案中写下你是如何解决的,这样其他人也可以受益。这实际上不是您问题的答案。
  • @Hjulle 感谢您的建议。我最终用一个更像答案的答案来编辑这个。希望它比我之前的自私评论能帮助更多的人。
猜你喜欢
  • 2013-03-13
  • 2014-08-04
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多