Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Private Member Functions | Private Attributes
http.client.HTTPResponse Class Reference
Inheritance diagram for http.client.HTTPResponse:
Inheritance graph
[legend]
Collaboration diagram for http.client.HTTPResponse:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def begin
def close
def closed
def flush
def readable
def isclosed
def read
def fileno
def getheader
def getheaders
def __iter__
def info
def geturl
def getcode
def __new__
def register
def __instancecheck__
def __subclasscheck__

Public Attributes

 fp
 debuglevel
 headers
 msg
 version
 status
 reason
 chunked
 chunk_left
 length
 will_close
 code

Private Member Functions

def _read_status
def _check_close
def _read_chunked
def _safe_read

Private Attributes

 _method

Detailed Description

Definition at line 264 of file client.py.


Constructor & Destructor Documentation

def http.client.HTTPResponse.__init__ (   self,
  sock,
  debuglevel = 0,
  strict = _strict_sentinel,
  method = None,
  url = None 
)

Definition at line 273 of file client.py.

00273 
00274     def __init__(self, sock, debuglevel=0, strict=_strict_sentinel, method=None, url=None):
00275         # If the response includes a content-length header, we need to
00276         # make sure that the client doesn't read more than the
00277         # specified number of bytes.  If it does, it will block until
00278         # the server times out and closes the connection.  This will
00279         # happen if a self.fp.read() is done (without a size) whether
00280         # self.fp is buffered or not.  So, no self.fp.read() by
00281         # clients unless they know what they are doing.
00282         self.fp = sock.makefile("rb")
00283         self.debuglevel = debuglevel
00284         if strict is not _strict_sentinel:
00285             warnings.warn("the 'strict' argument isn't supported anymore; "
00286                 "http.client now always assumes HTTP/1.x compliant servers.",
00287                 DeprecationWarning, 2)
00288         self._method = method
00289 
00290         # The HTTPResponse object is returned via urllib.  The clients
00291         # of http and urllib expect different attributes for the
00292         # headers.  headers is used here and supports urllib.  msg is
00293         # provided as a backwards compatibility layer for http
00294         # clients.
00295 
00296         self.headers = self.msg = None
00297 
00298         # from the Status-Line of the response
00299         self.version = _UNKNOWN # HTTP-Version
00300         self.status = _UNKNOWN  # Status-Code
00301         self.reason = _UNKNOWN  # Reason-Phrase
00302 
00303         self.chunked = _UNKNOWN         # is "chunked" being used?
00304         self.chunk_left = _UNKNOWN      # bytes left to read in current chunk
00305         self.length = _UNKNOWN          # number of bytes left in response
00306         self.will_close = _UNKNOWN      # conn will close at end of response

Here is the caller graph for this function:


Member Function Documentation

def abc.ABCMeta.__instancecheck__ (   cls,
  instance 
) [inherited]
Override for isinstance(instance, cls).

Definition at line 158 of file abc.py.

00158 
00159     def __instancecheck__(cls, instance):
00160         """Override for isinstance(instance, cls)."""
00161         # Inline the cache checking
00162         subclass = instance.__class__
00163         if subclass in cls._abc_cache:
00164             return True
00165         subtype = type(instance)
00166         if subtype is subclass:
00167             if (cls._abc_negative_cache_version ==
00168                 ABCMeta._abc_invalidation_counter and
00169                 subclass in cls._abc_negative_cache):
00170                 return False
00171             # Fall back to the subclass check.
00172             return cls.__subclasscheck__(subclass)
00173         return any(cls.__subclasscheck__(c) for c in {subclass, subtype})

Here is the call graph for this function:

Definition at line 617 of file client.py.

00617 
00618     def __iter__(self):
00619         return self

def abc.ABCMeta.__new__ (   mcls,
  name,
  bases,
  namespace 
) [inherited]

Definition at line 116 of file abc.py.

00116 
00117     def __new__(mcls, name, bases, namespace):
00118         cls = super().__new__(mcls, name, bases, namespace)
00119         # Compute set of abstract method names
00120         abstracts = {name
00121                      for name, value in namespace.items()
00122                      if getattr(value, "__isabstractmethod__", False)}
00123         for base in bases:
00124             for name in getattr(base, "__abstractmethods__", set()):
00125                 value = getattr(cls, name, None)
00126                 if getattr(value, "__isabstractmethod__", False):
00127                     abstracts.add(name)
00128         cls.__abstractmethods__ = frozenset(abstracts)
00129         # Set up inheritance registry
00130         cls._abc_registry = WeakSet()
00131         cls._abc_cache = WeakSet()
00132         cls._abc_negative_cache = WeakSet()
00133         cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
00134         return cls

Here is the call graph for this function:

def abc.ABCMeta.__subclasscheck__ (   cls,
  subclass 
) [inherited]
Override for issubclass(subclass, cls).

Definition at line 174 of file abc.py.

00174 
00175     def __subclasscheck__(cls, subclass):
00176         """Override for issubclass(subclass, cls)."""
00177         # Check cache
00178         if subclass in cls._abc_cache:
00179             return True
00180         # Check negative cache; may have to invalidate
00181         if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
00182             # Invalidate the negative cache
00183             cls._abc_negative_cache = WeakSet()
00184             cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
00185         elif subclass in cls._abc_negative_cache:
00186             return False
00187         # Check the subclass hook
00188         ok = cls.__subclasshook__(subclass)
00189         if ok is not NotImplemented:
00190             assert isinstance(ok, bool)
00191             if ok:
00192                 cls._abc_cache.add(subclass)
00193             else:
00194                 cls._abc_negative_cache.add(subclass)
00195             return ok
00196         # Check if it's a direct subclass
00197         if cls in getattr(subclass, '__mro__', ()):
00198             cls._abc_cache.add(subclass)
00199             return True
00200         # Check if it's a subclass of a registered class (recursive)
00201         for rcls in cls._abc_registry:
00202             if issubclass(subclass, rcls):
00203                 cls._abc_cache.add(subclass)
00204                 return True
00205         # Check if it's a subclass of a subclass (recursive)
00206         for scls in cls.__subclasses__():
00207             if issubclass(subclass, scls):
00208                 cls._abc_cache.add(subclass)
00209                 return True
00210         # No dice; update negative cache
00211         cls._abc_negative_cache.add(subclass)
00212         return False

Here is the call graph for this function:

def http.client.HTTPResponse._check_close (   self) [private]

Definition at line 419 of file client.py.

00419 
00420     def _check_close(self):
00421         conn = self.headers.get("connection")
00422         if self.version == 11:
00423             # An HTTP/1.1 proxy is assumed to stay open unless
00424             # explicitly closed.
00425             conn = self.headers.get("connection")
00426             if conn and "close" in conn.lower():
00427                 return True
00428             return False
00429 
00430         # Some HTTP/1.0 implementations have support for persistent
00431         # connections, using rules different than HTTP/1.1.
00432 
00433         # For older HTTP, Keep-Alive indicates persistent connection.
00434         if self.headers.get("keep-alive"):
00435             return False
00436 
00437         # At least Akamai returns a "Connection: Keep-Alive" header,
00438         # which was supposed to be sent by the client.
00439         if conn and "keep-alive" in conn.lower():
00440             return False
00441 
00442         # Proxy-Connection is a netscape hack.
00443         pconn = self.headers.get("proxy-connection")
00444         if pconn and "keep-alive" in pconn.lower():
00445             return False
00446 
00447         # otherwise, assume it will close
00448         return True

def http.client.HTTPResponse._read_chunked (   self,
  amt 
) [private]

Definition at line 516 of file client.py.

00516 
00517     def _read_chunked(self, amt):
00518         assert self.chunked != _UNKNOWN
00519         chunk_left = self.chunk_left
00520         value = []
00521         while True:
00522             if chunk_left is None:
00523                 line = self.fp.readline(_MAXLINE + 1)
00524                 if len(line) > _MAXLINE:
00525                     raise LineTooLong("chunk size")
00526                 i = line.find(b";")
00527                 if i >= 0:
00528                     line = line[:i] # strip chunk-extensions
00529                 try:
00530                     chunk_left = int(line, 16)
00531                 except ValueError:
00532                     # close the connection as protocol synchronisation is
00533                     # probably lost
00534                     self.close()
00535                     raise IncompleteRead(b''.join(value))
00536                 if chunk_left == 0:
00537                     break
00538             if amt is None:
00539                 value.append(self._safe_read(chunk_left))
00540             elif amt < chunk_left:
00541                 value.append(self._safe_read(amt))
00542                 self.chunk_left = chunk_left - amt
00543                 return b''.join(value)
00544             elif amt == chunk_left:
00545                 value.append(self._safe_read(amt))
00546                 self._safe_read(2)  # toss the CRLF at the end of the chunk
00547                 self.chunk_left = None
00548                 return b''.join(value)
00549             else:
00550                 value.append(self._safe_read(chunk_left))
00551                 amt -= chunk_left
00552 
00553             # we read the whole chunk, get another
00554             self._safe_read(2)      # toss the CRLF at the end of the chunk
00555             chunk_left = None
00556 
00557         # read and discard trailer up to the CRLF terminator
00558         ### note: we shouldn't have any trailers!
00559         while True:
00560             line = self.fp.readline(_MAXLINE + 1)
00561             if len(line) > _MAXLINE:
00562                 raise LineTooLong("trailer line")
00563             if not line:
00564                 # a vanishingly small number of sites EOF without
00565                 # sending the trailer
00566                 break
00567             if line == b"\r\n":
00568                 break
00569 
00570         # we read everything; close the "file"
00571         self.close()
00572 
00573         return b''.join(value)

Here is the call graph for this function:

Here is the caller graph for this function:

def http.client.HTTPResponse._read_status (   self) [private]

Definition at line 307 of file client.py.

00307 
00308     def _read_status(self):
00309         line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
00310         if len(line) > _MAXLINE:
00311             raise LineTooLong("status line")
00312         if self.debuglevel > 0:
00313             print("reply:", repr(line))
00314         if not line:
00315             # Presumably, the server closed the connection before
00316             # sending a valid response.
00317             raise BadStatusLine(line)
00318         try:
00319             version, status, reason = line.split(None, 2)
00320         except ValueError:
00321             try:
00322                 version, status = line.split(None, 1)
00323                 reason = ""
00324             except ValueError:
00325                 # empty version will cause next test to fail.
00326                 version = ""
00327         if not version.startswith("HTTP/"):
00328             self.close()
00329             raise BadStatusLine(line)
00330 
00331         # The status code is a three-digit number
00332         try:
00333             status = int(status)
00334             if status < 100 or status > 999:
00335                 raise BadStatusLine(line)
00336         except ValueError:
00337             raise BadStatusLine(line)
00338         return version, status, reason

Here is the call graph for this function:

Here is the caller graph for this function:

def http.client.HTTPResponse._safe_read (   self,
  amt 
) [private]
Read the number of bytes requested, compensating for partial reads.

Normally, we have a blocking socket, but a read() can be interrupted
by a signal (resulting in a partial read).

Note that we cannot distinguish between EOF and an interrupt when zero
bytes have been read. IncompleteRead() will be raised in this
situation.

This function should be used when <amt> bytes "should" be present for
reading. If the bytes are truly not available (due to EOF), then the
IncompleteRead exception can be used to detect the problem.

Definition at line 574 of file client.py.

00574 
00575     def _safe_read(self, amt):
00576         """Read the number of bytes requested, compensating for partial reads.
00577 
00578         Normally, we have a blocking socket, but a read() can be interrupted
00579         by a signal (resulting in a partial read).
00580 
00581         Note that we cannot distinguish between EOF and an interrupt when zero
00582         bytes have been read. IncompleteRead() will be raised in this
00583         situation.
00584 
00585         This function should be used when <amt> bytes "should" be present for
00586         reading. If the bytes are truly not available (due to EOF), then the
00587         IncompleteRead exception can be used to detect the problem.
00588         """
00589         s = []
00590         while amt > 0:
00591             chunk = self.fp.read(min(amt, MAXAMOUNT))
00592             if not chunk:
00593                 raise IncompleteRead(b''.join(s), amt)
00594             s.append(chunk)
00595             amt -= len(chunk)
00596         return b"".join(s)

Here is the caller graph for this function:

Definition at line 339 of file client.py.

00339 
00340     def begin(self):
00341         if self.headers is not None:
00342             # we've already started reading the response
00343             return
00344 
00345         # read until we get a non-100 response
00346         while True:
00347             version, status, reason = self._read_status()
00348             if status != CONTINUE:
00349                 break
00350             # skip the header from the 100 response
00351             while True:
00352                 skip = self.fp.readline(_MAXLINE + 1)
00353                 if len(skip) > _MAXLINE:
00354                     raise LineTooLong("header line")
00355                 skip = skip.strip()
00356                 if not skip:
00357                     break
00358                 if self.debuglevel > 0:
00359                     print("header:", skip)
00360 
00361         self.code = self.status = status
00362         self.reason = reason.strip()
00363         if version in ("HTTP/1.0", "HTTP/0.9"):
00364             # Some servers might still return "0.9", treat it as 1.0 anyway
00365             self.version = 10
00366         elif version.startswith("HTTP/1."):
00367             self.version = 11   # use HTTP/1.1 code for HTTP/1.x where x>=1
00368         else:
00369             raise UnknownProtocol(version)
00370 
00371         self.headers = self.msg = parse_headers(self.fp)
00372 
00373         if self.debuglevel > 0:
00374             for hdr in self.headers:
00375                 print("header:", hdr, end=" ")
00376 
00377         # are we using the chunked-style of transfer encoding?
00378         tr_enc = self.headers.get("transfer-encoding")
00379         if tr_enc and tr_enc.lower() == "chunked":
00380             self.chunked = True
00381             self.chunk_left = None
00382         else:
00383             self.chunked = False
00384 
00385         # will the connection close at the end of the response?
00386         self.will_close = self._check_close()
00387 
00388         # do we have a Content-Length?
00389         # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
00390         self.length = None
00391         length = self.headers.get("content-length")
00392 
00393          # are we using the chunked-style of transfer encoding?
00394         tr_enc = self.headers.get("transfer-encoding")
00395         if length and not self.chunked:
00396             try:
00397                 self.length = int(length)
00398             except ValueError:
00399                 self.length = None
00400             else:
00401                 if self.length < 0:  # ignore nonsensical negative lengths
00402                     self.length = None
00403         else:
00404             self.length = None
00405 
00406         # does the body have a fixed length? (of zero)
00407         if (status == NO_CONTENT or status == NOT_MODIFIED or
00408             100 <= status < 200 or      # 1xx codes
00409             self._method == "HEAD"):
00410             self.length = 0
00411 
00412         # if the connection remains open, and we aren't using chunked, and
00413         # a content-length was not provided, then assume that the connection
00414         # WILL close.
00415         if (not self.will_close and
00416             not self.chunked and
00417             self.length is None):
00418             self.will_close = True

Here is the call graph for this function:

Definition at line 449 of file client.py.

00449 
00450     def close(self):
00451         if self.fp:
00452             self.fp.close()
00453             self.fp = None

Definition at line 460 of file client.py.

00460 
00461     def closed(self):
00462         return self.isclosed()

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 597 of file client.py.

00597 
00598     def fileno(self):
00599         return self.fp.fileno()

Here is the caller graph for this function:

Definition at line 463 of file client.py.

00463 
00464     def flush(self):
00465         self.fp.flush()

Here is the caller graph for this function:

Definition at line 628 of file client.py.

00628 
00629     def getcode(self):
00630         return self.status

def http.client.HTTPResponse.getheader (   self,
  name,
  default = None 
)

Definition at line 600 of file client.py.

00600 
00601     def getheader(self, name, default=None):
00602         if self.headers is None:
00603             raise ResponseNotReady()
00604         headers = self.headers.get_all(name) or default
00605         if isinstance(headers, str) or not hasattr(headers, '__iter__'):
00606             return headers
00607         else:
00608             return ', '.join(headers)

Return list of (header, value) tuples.

Definition at line 609 of file client.py.

00609 
00610     def getheaders(self):
00611         """Return list of (header, value) tuples."""
00612         if self.headers is None:
00613             raise ResponseNotReady()
00614         return list(self.headers.items())

Definition at line 625 of file client.py.

00625 
00626     def geturl(self):
00627         return self.url

Definition at line 622 of file client.py.

00622 
00623     def info(self):
00624         return self.headers

Here is the caller graph for this function:

Definition at line 471 of file client.py.

00471 
00472     def isclosed(self):
00473         # NOTE: it is possible that we will not ever call self.close(). This
00474         #       case occurs when will_close is TRUE, length is None, and we
00475         #       read up to the last byte, but NOT past it.
00476         #
00477         # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
00478         #          called, meaning self.isclosed() is meaningful.
00479         return self.fp is None

Here is the caller graph for this function:

def http.client.HTTPResponse.read (   self,
  amt = None 
)

Definition at line 480 of file client.py.

00480 
00481     def read(self, amt=None):
00482         if self.fp is None:
00483             return b""
00484 
00485         if self._method == "HEAD":
00486             self.close()
00487             return b""
00488 
00489         if self.chunked:
00490             return self._read_chunked(amt)
00491 
00492         if amt is None:
00493             # unbounded read
00494             if self.length is None:
00495                 s = self.fp.read()
00496             else:
00497                 s = self._safe_read(self.length)
00498                 self.length = 0
00499             self.close()        # we read everything
00500             return s
00501 
00502         if self.length is not None:
00503             if amt > self.length:
00504                 # clip the read to the "end of response"
00505                 amt = self.length
00506 
00507         # we do not use _safe_read() here because this may be a .will_close
00508         # connection, and the user is reading more bytes than will be provided
00509         # (for example, reading in 1k chunks)
00510         s = self.fp.read(amt)
00511         if self.length is not None:
00512             self.length -= len(s)
00513             if not self.length:
00514                 self.close()
00515         return s

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 466 of file client.py.

00466 
00467     def readable(self):
00468         return True

def abc.ABCMeta.register (   cls,
  subclass 
) [inherited]
Register a virtual subclass of an ABC.

Definition at line 135 of file abc.py.

00135 
00136     def register(cls, subclass):
00137         """Register a virtual subclass of an ABC."""
00138         if not isinstance(subclass, type):
00139             raise TypeError("Can only register classes")
00140         if issubclass(subclass, cls):
00141             return  # Already a subclass
00142         # Subtle: test for cycles *after* testing for "already a subclass";
00143         # this means we allow X.register(X) and interpret it as a no-op.
00144         if issubclass(cls, subclass):
00145             # This would create a cycle, which is bad for the algorithm below
00146             raise RuntimeError("Refusing to create an inheritance cycle")
00147         cls._abc_registry.add(subclass)
00148         ABCMeta._abc_invalidation_counter += 1  # Invalidate negative cache

Here is the caller graph for this function:


Member Data Documentation

Definition at line 287 of file client.py.

Definition at line 303 of file client.py.

Definition at line 302 of file client.py.

Definition at line 360 of file client.py.

Definition at line 282 of file client.py.

Definition at line 281 of file client.py.

Definition at line 295 of file client.py.

Definition at line 304 of file client.py.

Definition at line 295 of file client.py.

Definition at line 300 of file client.py.

Definition at line 299 of file client.py.

Definition at line 298 of file client.py.

Definition at line 305 of file client.py.


The documentation for this class was generated from the following file: