【问题标题】:In Python, what does getresponse() return?在 Python 中,getresponse() 返回什么?
【发布时间】:2009-11-17 22:20:45
【问题描述】:
 import httplib
    conn = httplib.HTTPConnection(head)
    conn.request("HEAD",tail)
    res = conn.getresponse()

我可以得到 res.status ,也就是http状态码。

我还能获得哪些其他元素? 为什么当我打印 res 时,它不会打印字典?我只想查看该字典中的键...

【问题讨论】:

    标签: python linux http unix


    【解决方案1】:

    您始终可以使用dir 来检查对象;这会告诉你它有哪些属性。

    >>> import httplib
    >>> conn = httplib.HTTPConnection("www.google.nl")
    >>> conn.request("HEAD", "/index.html")
    >>> res = conn.getresponse()
    >>> dir(res)
    ['__doc__', '__init__', '__module__', '_check_close', '_method', '_read_chunked', '_read_status', '_safe_read', 'begin', 'chunk_left', 'chunked', 'close', 'debuglevel', 'fp', 'getheader', 'getheaders', 'isclosed', 'length', 'msg', 'read', 'reason', 'status', 'strict', 'version', 'will_close']
    

    同样,您可以调用help,如果它具有__doc__ 属性,它将显示对象的文档。如您所见,res 就是这种情况,所以试试:

    >>> help(res)
    

    除此之外,文档指出getresponse 返回一个HTTPResponse 对象。因此,正如您在此处(以及在help(res) 中)所读到的,在HTTPResponse 对象上定义了以下属性和方法:

    • HTTPResponse.read([amt]): 读取并返回响应正文,或直到下一个 amt 字节。

    • HTTPResponse.getheader(name[, default]): 获取头部名称的内容,如果没有匹配头部则默认。

    • HTTPResponse.getheaders(): 返回 (header, value) 元组的列表。 (2.4 版中的新功能。)

    • HTTPResponse.msg: 包含响应标头的 mimetools.Message 实例。

    • HTTPResponse.version: 服务器使用的 HTTP 协议版本。 HTTP/1.0 为 10,HTTP/1.1 为 11。

    • HTTPResponse.status: 服务器返回的状态码。

    • HTTPResponse.reason: 服务器返回的原因短语。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      相关资源
      最近更新 更多