【问题标题】:Get header values of reply using pycurl使用 pycurl 获取回复的标头值
【发布时间】:2013-03-16 11:38:36
【问题描述】:

我想知道一些在使用 PyCurl 发出请求时捕获和访问回复的标头信息的方法:

c = pycurl.Curl() 
c.setopt(c.URL,'MY_URL')
c.setopt(c.COOKIEFILE,'cookies')
c.setopt(c.COOKIE,'cookies')
c.setopt(c.POST,1)
c.setopt(c.POSTFIELDS,'MY AUTH VALUES')
c.setopt(c.VERBOSE, True)
b = StringIO.StringIO()
c.setopt(c.WRITEFUNCTION, b.write)
c.perform()

回复将以格式正确的 JSON 格式写入缓冲区 b。

我希望恢复回复中“Location”标头的值。

尝试使用 curl 时,可以在详细输出中看到此值:

[... Curl output ...]
> GET XXXXXXXXX
[... Request ...]
[... Curl output ...]
< HTTP/1.1 302 Found
[... Other headers ...]
< Location: YYYYYYYYYYYYYYY
[... Rest of reply ...]

如何从 python 中恢复 Location 标头的值?

【问题讨论】:

    标签: python pycurl verbose


    【解决方案1】:
    import pycurl
    import cStringIO
    
    buf = cStringIO.StringIO()
    URL = 'http://stackoverflow.com/questions/15641080/get-header-values-of-reply-using-pycurl'
    c = pycurl.Curl()
    c.setopt(c.URL, URL)
    c.setopt(c.NOBODY, 1)
    c.setopt(c.HEADERFUNCTION, buf.write)
    c.perform()
    
    header = buf.getvalue()
    print header
    

    【讨论】:

      【解决方案2】:

      如果你必须使用 PyCurl

      那么就可以通过回调函数来获取头部信息:

      # code...
      
      # Callback function invoked when header data is ready
      def header(buf):
          # Print header data to stderr
          import sys
          sys.stderr.write(buf)
          # Returning None implies that all bytes were written
      
      # more code...
      
      c.setopt(pycurl.HEADERFUNCTION, header)
      
      # yet more code...
      

      the docs了解更多信息。

      你也可以使用 requests 代替 pycurl

      虽然这可能是不可能的,并且不能直接回答您的问题,但我建议您使用 requests library 而不是 pyCurl:

      import requests
      
      payload = {"key":"value"}
      cookies = {"key":"value"}
      
      r = requests.post('https://my.example.com', data=payload, cookies=cookies)
      
      location = r.headers["Location"]
      content  = r.text
      
      print(content)
      

      它会让你的生活更轻松。通过reading the docs了解更多信息

      【讨论】:

      • 我也不知道为什么它被否决了。我可能会建议使用friendly_curl 而不是/以及requests,因为这是一个小得多的变化,但是……除此之外,我看不到任何可以改进的地方,更不用说反对了。我绝对+1。 (对于接受的答案也是如此,无论是谁投了反对票。)
      • 感谢requests 的提示!处理起来容易得多。
      【解决方案3】:

      本质上,很多自定义函数和注册回调函数。让我们分段浏览 curl 的详细输出。首先,如果您提供自己的CURLOPT_OPENSOCKETFUNCTION,则大多数情况下都可以填写有关连接的信息。

      接下来,请求标头可以是您提前知道的内容,并且可以根据需要打印出来。对于进度条,有CURLOPT_PROGRESSFUNCTION,它允许您注册回调以“大约每秒一次”更新进度。

      您还可以注册一个响应标头写入函数 (CURLOPT_HEADERFUNCTION),然后您可以使用它来捕获和/或显示响应标头。

      或者,您可以使用CURLOPT_DEBUGFUNCTION 注册回调,以获取您发送的标头信息、获得响应等信息。

      【讨论】:

      • 非常感谢..:) 我能够使用 CURLOPT_DEBUGFUNCTION 解决。
      • 等一下,当 pycurl 专门为 headers 提供回调时,你为什么要使用CURLOPT_DEBUGFUNCTION
      • 嘿,我主要使用 curl 的 C 绑定 :-) 在 python 中,我也使用requests
      猜你喜欢
      • 2011-09-27
      • 2010-10-03
      • 2011-03-03
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      相关资源
      最近更新 更多