"""HTTP/1.1 client library
HTTPConnection go through a number of "states", which defines when a client
may legally make another request or fetch the response for a particular
request. This diagram details these state transitions:
| ( putheader() )* endheaders()
| response = getresponse()
Unread-response [Response-headers-read]
| response.read() | putrequest()
Idle Req-started-unread-response
response.read() | | ( putheader() )* endheaders()
Request-started Req-sent-unread-response
This diagram presents the following rules:
-- a second request may not be started until {response-headers-read}
-- a response [object] cannot be retrieved until {request-sent}
-- there is no differentiation between an unread response body and a
partially read response body
Note: this enforcement is applied by the HTTPConnection class. The
HTTPResponse class does not enforce this state machine, which
implies sophisticated clients may accelerate the request/response
pipeline. Caution should be taken, though: accelerating the states
beyond the above pattern may imply knowledge of the server's
connection-close behavior for certain requests. For example, it
is impossible to tell whether the server will close the connection
UNTIL the response headers have been read; this means that further
requests cannot be placed into the pipeline until it is known that
the server will NOT be closing the connection.
Logical State __state __response
------------- ------- ----------
Request-started _CS_REQ_STARTED None
Request-sent _CS_REQ_SENT None
Unread-response _CS_IDLE <response_class>
Req-started-unread-response _CS_REQ_STARTED <response_class>
Req-sent-unread-response _CS_REQ_SENT <response_class>
from urlparse
import urlsplit
from cStringIO
import StringIO
from StringIO
import StringIO
__all__
= ["HTTP", "HTTPResponse", "HTTPConnection", "HTTPSConnection",
"HTTPException", "NotConnected", "UnknownProtocol",
"UnknownTransferEncoding", "UnimplementedFileMode",
"IncompleteRead", "InvalidURL", "ImproperConnectionState",
"CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
"BadStatusLine", "error"]
_CS_REQ_STARTED
= 'Request-started'
_CS_REQ_SENT
= 'Request-sent'
SWITCHING_PROTOCOLS
= 101
NON_AUTHORITATIVE_INFORMATION
= 203
PROXY_AUTHENTICATION_REQUIRED
= 407
PRECONDITION_FAILED
= 412
REQUEST_ENTITY_TOO_LARGE
= 413
REQUEST_URI_TOO_LONG
= 414
UNSUPPORTED_MEDIA_TYPE
= 415
REQUESTED_RANGE_NOT_SATISFIABLE
= 416
UNPROCESSABLE_ENTITY
= 422
INTERNAL_SERVER_ERROR
= 500
SERVICE_UNAVAILABLE
= 503
HTTP_VERSION_NOT_SUPPORTED
= 505
INSUFFICIENT_STORAGE
= 507
class HTTPMessage(mimetools
.Message
):
def addheader(self
, key
, value
):
"""Add header for field key handling repeats."""
prev
= self
.dict.get(key
)
combined
= ", ".join((prev
, value
))
self
.dict[key
] = combined
def addcontinue(self
, key
, more
):
"""Add more field data from a continuation line."""
self
.dict[key
] = prev
+ "\n " + more
Read header lines up to the entirely blank line that terminates them.
The (normally blank) line that ends the headers is skipped, but not
included in the returned list. If a non-header line ends the headers,
(which is an error), an attempt is made to backspace over it; it is
never included in the returned list.
The variable self.status is set to the empty string if all went well,
otherwise it is an error message. The variable self.headers is a
completely uninterpreted list of lines contained in the header (so
printing them will reproduce the header exactly as it appears in the
If multiple header fields with the same name occur, they are combined
according to the rules in RFC 2616 sec 4.2:
Appending each subsequent field-value to the first, each separated
by a comma. The order in which header fields with the same field-name
are received is significant to the interpretation of the combined
# XXX The implementation overrides the readheaders() method of
# rfc822.Message. The base class design isn't amenable to
# customized behavior here so the method here is a copy of the
# base class code with a few small changes.
self
.headers
= hlist
= []
startofline
= unread
= tell
= None
if hasattr(self
.fp
, 'unread'):
startofline
= tell
= None
line
= self
.fp
.readline()
self
.status
= 'EOF in headers'
# Skip unix From name time lines
if firstline
and line
.startswith('From '):
self
.unixfrom
= self
.unixfrom
+ line
if headerseen
and line
[0] in ' \t':
# XXX Not sure if continuation lines are handled properly
# for http and/or for repeating headers
# It's a continuation line.
self
.addcontinue(headerseen
, line
.strip())
elif self
.iscomment(line
):
# It's a comment. Ignore it.
# Note! No pushback here! The delimiter line gets eaten.
headerseen
= self
.isheader(line
)
# It's a legal header line, save it.
self
.addheader(headerseen
, line
[len(headerseen
)+1:].strip())
# It's not a header line; throw it back and stop here.
self
.status
= 'No headers'
self
.status
= 'Non-header line where header expected'
self
.fp
.seek(startofline
)
self
.status
= self
.status
+ '; bad seek'
# strict: If true, raise BadStatusLine if the status line can't be
# parsed as a valid HTTP/1.0 or 1.1 status line. By default it is
# false because it prevents clients from talking to HTTP/0.9
# servers. Note that a response with a sufficiently corrupted
# status line will look like an HTTP/0.9 response.
# See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
def __init__(self
, sock
, debuglevel
=0, strict
=0, method
=None):
self
.fp
= sock
.makefile('rb', 0)
self
.debuglevel
= debuglevel
# from the Status-Line of the response
self
.version
= _UNKNOWN
# HTTP-Version
self
.status
= _UNKNOWN
# Status-Code
self
.reason
= _UNKNOWN
# Reason-Phrase
self
.chunked
= _UNKNOWN
# is "chunked" being used?
self
.chunk_left
= _UNKNOWN
# bytes left to read in current chunk
self
.length
= _UNKNOWN
# number of bytes left in response
self
.will_close
= _UNKNOWN
# conn will close at end of response
# Initialize with Simple-Response defaults
line
= self
.fp
.readline()
print "reply:", repr(line
)
# Presumably, the server closed the connection before
# sending a valid response.
raise BadStatusLine(line
)
[version
, status
, reason
] = line
.split(None, 2)
[version
, status
] = line
.split(None, 1)
# empty version will cause next test to fail and status
# will be treated as 0.9 response.
if not version
.startswith('HTTP/'):
raise BadStatusLine(line
)
# assume it's a Simple-Response from an 0.9 server
self
.fp
= LineAndFileWrapper(line
, self
.fp
)
return "HTTP/0.9", 200, ""
# The status code is a three-digit number
if status
< 100 or status
> 999:
raise BadStatusLine(line
)
raise BadStatusLine(line
)
return version
, status
, reason
# we've already started reading the response
# read until we get a non-100 response
version
, status
, reason
= self
._read
_status
()
# skip the header from the 100 response
skip
= self
.fp
.readline().strip()
self
.reason
= reason
.strip()
if version
== 'HTTP/1.0':
elif version
.startswith('HTTP/1.'):
self
.version
= 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
elif version
== 'HTTP/0.9':
raise UnknownProtocol(version
)
self
.msg
= HTTPMessage(StringIO())
self
.msg
= HTTPMessage(self
.fp
, 0)
for hdr
in self
.msg
.headers
:
# don't let the msg keep an fp
# are we using the chunked-style of transfer encoding?
tr_enc
= self
.msg
.getheader('transfer-encoding')
if tr_enc
and tr_enc
.lower() == "chunked":
# will the connection close at the end of the response?
self
.will_close
= self
._check
_close
()
# do we have a Content-Length?
# NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
length
= self
.msg
.getheader('content-length')
if length
and not self
.chunked
:
self
.length
= int(length
)
# does the body have a fixed length? (of zero)
if (status
== NO_CONTENT
or status
== NOT_MODIFIED
or
100 <= status
< 200 or # 1xx codes
# if the connection remains open, and we aren't using chunked, and
# a content-length was not provided, then assume that the connection
if not self
.will_close
and \
conn
= self
.msg
.getheader('connection')
# An HTTP/1.1 proxy is assumed to stay open unless
conn
= self
.msg
.getheader('connection')
if conn
and "close" in conn
.lower():
# Some HTTP/1.0 implementations have support for persistent
# connections, using rules different than HTTP/1.1.
# For older HTTP, Keep-Alive indiciates persistent connection.
if self
.msg
.getheader('keep-alive'):
# At least Akamai returns a "Connection: Keep-Alive" header,
# which was supposed to be sent by the client.
if conn
and "keep-alive" in conn
.lower():
# Proxy-Connection is a netscape hack.
pconn
= self
.msg
.getheader('proxy-connection')
if pconn
and "keep-alive" in pconn
.lower():
# otherwise, assume it will close
# NOTE: it is possible that we will not ever call self.close(). This
# case occurs when will_close is TRUE, length is None, and we
# read up to the last byte, but NOT past it.
# IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
# called, meaning self.isclosed() is meaningful.
# XXX It would be nice to have readline and __iter__ for this, too.
def read(self
, amt
=None):
return self
._read
_chunked
(amt
)
s
= self
._safe
_read
(self
.length
)
self
.close() # we read everything
if self
.length
is not None:
# clip the read to the "end of response"
# we do not use _safe_read() here because this may be a .will_close
# connection, and the user is reading more bytes than will be provided
# (for example, reading in 1k chunks)
if self
.length
is not None:
def _read_chunked(self
, amt
):
assert self
.chunked
!= _UNKNOWN
chunk_left
= self
.chunk_left
# XXX This accumulates chunks by repeated string concatenation,
# which is not efficient as the number or size of chunks gets big.
line
= self
.fp
.readline()
line
= line
[:i
] # strip chunk-extensions
chunk_left
= int(line
, 16)
value
+= self
._safe
_read
(chunk_left
)
value
+= self
._safe
_read
(amt
)
self
.chunk_left
= chunk_left
- amt
value
+= self
._safe
_read
(amt
)
self
._safe
_read
(2) # toss the CRLF at the end of the chunk
value
+= self
._safe
_read
(chunk_left
)
# we read the whole chunk, get another
self
._safe
_read
(2) # toss the CRLF at the end of the chunk
# read and discard trailer up to the CRLF terminator
### note: we shouldn't have any trailers!
line
= self
.fp
.readline()
# we read everything; close the "file"
def _safe_read(self
, amt
):
"""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
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.
chunk
= self
.fp
.read(amt
)
def getheader(self
, name
, default
=None):
return self
.msg
.getheader(name
, default
)
"""Return list of (header, value) tuples."""
_http_vsn_str
= 'HTTP/1.1'
response_class
= HTTPResponse
def __init__(self
, host
, port
=None, strict
=None):
self
._set
_hostport
(host
, port
)
def _set_hostport(self
, host
, port
):
j
= host
.rfind(']') # ipv6 addresses have [...]
raise InvalidURL("nonnumeric port: '%s'" % host
[i
+1:])
if host
and host
[0] == '[' and host
[-1] == ']':
def set_debuglevel(self
, level
):
"""Connect to the host and port specified in __init__."""
msg
= "getaddrinfo returns an empty list"
for res
in socket
.getaddrinfo(self
.host
, self
.port
, 0,
af
, socktype
, proto
, canonname
, sa
= res
self
.sock
= socket
.socket(af
, socktype
, proto
)
print "connect: (%s, %s)" % (self
.host
, self
.port
)
except socket
.error
, msg
:
print 'connect fail:', (self
.host
, self
.port
)
"""Close the connection to the HTTP server."""
self
.sock
.close() # close it manually... there may be other refs
"""Send `str' to the server."""
# send the data to the server. if we get a broken pipe, then close
# the socket. we want to reconnect when somebody tries to send again.
# NOTE: we DO propagate the error, though, because we cannot simply
# ignore the error... the caller will know if they can retry.
if v
[0] == 32: # Broken pipe
"""Add a line of output to the current request buffer.
Assumes that the line does *not* end with \\r\\n.
"""Send the currently buffered request and clear the buffer.
Appends an extra \\r\\n to the buffer.
self
._buffer
.extend(("", ""))
msg
= "\r\n".join(self
._buffer
)
def putrequest(self
, method
, url
, skip_host
=0, skip_accept_encoding
=0):
"""Send a request to the server.
`method' specifies an HTTP request method, e.g. 'GET'.
`url' specifies the object being requested, e.g. '/index.html'.
`skip_host' if True does not add automatically a 'Host:' header
`skip_accept_encoding' if True does not add automatically an
'Accept-Encoding:' header
# if a prior response has been completed, then forget about it.
if self
.__response
and self
.__response
.isclosed():
# in certain cases, we cannot issue another request on this connection.
# 1) we are in the process of sending a request. (_CS_REQ_STARTED)
# 2) a response to a previous request has signalled that it is going
# to close the connection upon completion.
# 3) the headers for the previous response have not been read, thus
# we cannot determine whether point (2) is true. (_CS_REQ_SENT)
# if there is no prior response, then we can request at will.
# if point (2) is true, then we will have passed the socket to the
# response (effectively meaning, "there is no prior response"), and
# will open a new one when a new request is made.
# Note: if a prior response exists, then we *can* start a new request.
# We are not allowed to begin fetching the response to this new
# request, however, until that prior response is complete.
if self
.__state
== _CS_IDLE
:
self
.__state
= _CS_REQ_STARTED
raise CannotSendRequest()
# Save the method we use, we need it later in the response phase
str = '%s %s %s' % (method
, url
, self
._http
_vsn
_str
)
# Issue some standard headers for better HTTP/1.1 compliance
# this header is issued *only* for HTTP/1.1
# connections. more specifically, this means it is
# only issued when the client uses the new
# HTTPConnection() class. backwards-compat clients
# will be using HTTP/1.0 and those clients may be
# issuing this header themselves. we should NOT issue
# it twice; some web servers (such as Apache) barf
# when they see two Host: headers
# If we need a non-standard port,include it in the
# header. If the request is going through a proxy,
# but the host of the actual URL, not the host of the
if url
.startswith('http'):
nil
, netloc
, nil
, nil
, nil
= urlsplit(url
)
self
.putheader('Host', netloc
.encode("idna"))
elif self
.port
== HTTP_PORT
:
self
.putheader('Host', self
.host
.encode("idna"))
self
.putheader('Host', "%s:%s" % (self
.host
.encode("idna"), self
.port
))
# note: we are assuming that clients will not attempt to set these
# headers since *this* library must deal with the
# consequences. this also means that when the supporting
# libraries are updated to recognize other forms, then this
# code should be changed (removed or updated).
# we only want a Content-Encoding of "identity" since we don't
# support encodings such as x-gzip or x-deflate.
if not skip_accept_encoding
:
self
.putheader('Accept-Encoding', 'identity')
# we can accept "chunked" Transfer-Encodings, but no others
# NOTE: no TE header implies *only* "chunked"
#self.putheader('TE', 'chunked')
# if TE is supplied in the header, then it must appear in a
#self.putheader('Connection', 'TE')
# For HTTP/1.0, the server will assume "not chunked"
def putheader(self
, header
, value
):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
if self
.__state
!= _CS_REQ_STARTED
:
str = '%s: %s' % (header
, value
)
"""Indicate that the last header line has been sent to the server."""
if self
.__state
== _CS_REQ_STARTED
:
self
.__state
= _CS_REQ_SENT
def request(self
, method
, url
, body
=None, headers
={}):
"""Send a complete request to the server."""
self
._send
_request
(method
, url
, body
, headers
)
# trap 'Broken pipe' if we're allowed to automatically reconnect
if v
[0] != 32 or not self
.auto_open
:
self
._send
_request
(method
, url
, body
, headers
)
def _send_request(self
, method
, url
, body
, headers
):
# honour explicitly requested Host: and Accept-Encoding headers
header_names
= dict.fromkeys([k
.lower() for k
in headers
])
if 'host' in header_names
:
if 'accept-encoding' in header_names
:
skips
['skip_accept_encoding'] = 1
self
.putrequest(method
, url
, **skips
)
if body
and ('content-length' not in header_names
):
self
.putheader('Content-Length', str(len(body
)))
for hdr
, value
in headers
.iteritems():
self
.putheader(hdr
, value
)
"Get the response from the server."
# if a prior response has been completed, then forget about it.
if self
.__response
and self
.__response
.isclosed():
# if a prior response exists, then it must be completed (otherwise, we
# cannot read this response's header to determine the connection-close
# note: if a prior response existed, but was connection-close, then the
# socket and response were made independent of this HTTPConnection
# object since a new request requires that we open a whole new
# this means the prior response had one of two states:
# 1) will_close: this connection was reset and the prior socket and
# response operate independently
# 2) persistent: the response was retained and we await its
# isclosed() status to become true.
if self
.__state
!= _CS_REQ_SENT
or self
.__response
:
response
= self
.response_class(self
.sock
, self
.debuglevel
,
response
= self
.response_class(self
.sock
, strict
=self
.strict
,
assert response
.will_close
!= _UNKNOWN
# this effectively passes the connection to the response
# remember this, so we can tell when it is complete
self
.__response
= response
# The next several classes are used to define FakeSocket,a socket-like
# interface to an SSL connection.
# The primary complexity comes from faking a makefile() method. The
# standard socket makefile() implementation calls dup() on the socket
# file descriptor. As a consequence, clients can call close() on the
# parent socket and its makefile children in any order. The underlying
# socket isn't closed until they are all closed.
# The implementation uses reference counting to keep the socket open
# until the last client calls close(). SharedSocket keeps track of
# the reference counting and SharedSocketClient provides an constructor
# and close() method that call incref() and decref() correctly.
def __init__(self
, sock
):
class SharedSocketClient
:
def __init__(self
, shared
):
class SSLFile(SharedSocketClient
):
"""File-like object wrapping an SSL socket."""
def __init__(self
, sock
, ssl
, bufsize
=None):
SharedSocketClient
.__init
__(self
, sock
)
self
._bufsize
= bufsize
or self
.__class
__.BUFSIZE
# put in a loop so that we retry on transient errors
buf
= self
._ssl
.read(self
._bufsize
)
except socket
.sslerror
, err
:
if (err
[0] == socket
.SSL_ERROR_WANT_READ
or err
[0] == socket
.SSL_ERROR_WANT_WRITE
):
if (err
[0] == socket
.SSL_ERROR_ZERO_RETURN
or err
[0] == socket
.SSL_ERROR_EOF
):
except socket
.error
, err
:
if err
[0] == errno
.EINTR
:
if err
[0] == errno
.EBADF
:
def read(self
, size
=None):
while size
is None or avail
< size
:
# loop exited because there is no more data
# XXX could do enough bookkeeping not to do a 2nd search
def readlines(self
, sizehint
=0):
if sizehint
and total
>= sizehint
:
return self
._sock
.fileno()
class FakeSocket(SharedSocketClient
):
def __getattr__(self
, name
):
raise error(9, 'Bad file descriptor')
def __init__(self
, sock
, ssl
):
sock
= SharedSocket(sock
)
SharedSocketClient
.__init
__(self
, sock
)
SharedSocketClient
.close(self
)
self
._sock
= self
.__class
__._closedsocket
()
def makefile(self
, mode
, bufsize
=None):
if mode
!= 'r' and mode
!= 'rb':
raise UnimplementedFileMode()
return SSLFile(self
._shared
, self
._ssl
, bufsize
)
def send(self
, stuff
, flags
= 0):
return self
._ssl
.write(stuff
)
def recv(self
, len = 1024, flags
= 0):
return self
._ssl
.read(len)
def __getattr__(self
, attr
):
return getattr(self
._sock
, attr
)
class HTTPSConnection(HTTPConnection
):
"This class allows communication via SSL."
default_port
= HTTPS_PORT
def __init__(self
, host
, port
=None, key_file
=None, cert_file
=None,
HTTPConnection
.__init
__(self
, host
, port
, strict
)
self
.cert_file
= cert_file
"Connect to a host on a given (SSL) port."
sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
sock
.connect((self
.host
, self
.port
))
ssl
= socket
.ssl(sock
, self
.key_file
, self
.cert_file
)
self
.sock
= FakeSocket(sock
, ssl
)
"Compatibility class with httplib.py from 1.5."
_http_vsn_str
= 'HTTP/1.0'
_connection_class
= HTTPConnection
def __init__(self
, host
='', port
=None, strict
=None):
"Provide a default host, since the superclass requires one."
# some joker passed 0 explicitly, meaning default port
# Note that we may pass an empty string as the host; this will throw
# an error when we attempt to connect. Presumably, the client code
# will call connect before then, with a proper host.
self
._setup
(self
._connection
_class
(host
, port
, strict
))
# set up delegation to flesh out interface
self
.putrequest
= conn
.putrequest
self
.endheaders
= conn
.endheaders
self
.set_debuglevel
= conn
.set_debuglevel
conn
._http
_vsn
= self
._http
_vsn
conn
._http
_vsn
_str
= self
._http
_vsn
_str
def connect(self
, host
=None, port
=None):
"Accept arguments to set the host/port, since the superclass doesn't."
self
._conn
._set
_hostport
(host
, port
)
"Provide a getfile, since the superclass' does not use this concept."
def putheader(self
, header
, *values
):
"The superclass allows only one value argument."
self
._conn
.putheader(header
, '\r\n\t'.join(values
))
"""Compat definition since superclass does not define it.
Returns a tuple consisting of:
- server status code (e.g. '200' if all goes well)
- server "reason" corresponding to status code
- any RFC822 headers in the response from the server
response
= self
._conn
.getresponse()
### hmm. if getresponse() ever closes the socket on a bad request,
### then we are going to have problems with self.sock
### should we keep this behavior? do people use it?
# keep the socket open (as a file), and return it
self
.file = self
._conn
.sock
.makefile('rb', 0)
# close our socket -- we want to restart after any protocol error
self
.headers
= response
.msg
return response
.status
, response
.reason
, response
.msg
# note that self.file == response.fp, which gets closed by the
# superclass. just clear the object ref here.
### hmm. messy. if status==-1, then self.file is owned by us.
### well... we aren't explicitly closing, but losing this ref will
if hasattr(socket
, 'ssl'):
"""Compatibility with 1.5 httplib interface
Python 1.5.2 did not have an HTTPS class, but it defined an
interface for sending http requests that is also useful for
_connection_class
= HTTPSConnection
def __init__(self
, host
='', port
=None, key_file
=None, cert_file
=None,
# provide a default host, pass the X509 cert info
# urf. compensate for bad input.
self
._setup
(self
._connection
_class
(host
, port
, key_file
,
# we never actually use these for anything, but we keep them
# here for compatibility with post-1.5.2 CVS.
self
.cert_file
= cert_file
class HTTPException(Exception):
# Subclasses that define an __init__ must call Exception.__init__
# or define self.args. Otherwise, str() will fail.
class NotConnected(HTTPException
):
class InvalidURL(HTTPException
):
class UnknownProtocol(HTTPException
):
def __init__(self
, version
):
class UnknownTransferEncoding(HTTPException
):
class UnimplementedFileMode(HTTPException
):
class IncompleteRead(HTTPException
):
def __init__(self
, partial
):
class ImproperConnectionState(HTTPException
):
class CannotSendRequest(ImproperConnectionState
):
class CannotSendHeader(ImproperConnectionState
):
class ResponseNotReady(ImproperConnectionState
):
class BadStatusLine(HTTPException
):
def __init__(self
, line
):
# for backwards compatibility
class LineAndFileWrapper
:
"""A limited file-like object for HTTP/0.9 responses."""
# The status-line parsing code calls readline(), which normally
# get the HTTP status line. For a 0.9 response, however, this is
# actually the first line of the body! Clients need to get a
# readable file object that contains that line.
def __init__(self
, line
, file):
self
._line
_left
= len(line
)
def __getattr__(self
, attr
):
return getattr(self
._file
, attr
)
# called when the last byte is read from the line. After the
# call, all read methods are delegated to the underlying file
self
.read
= self
._file
.read
self
.readline
= self
._file
.readline
self
.readlines
= self
._file
.readlines
def read(self
, amt
=None):
return self
._file
.read(amt
)
if amt
is None or amt
> self
._line
_left
:
s
= self
._line
[self
._line
_offset
:]
return s
+ self
._file
.read()
return s
+ self
._file
.read(amt
- len(s
))
assert amt
<= self
._line
_left
return self
._file
.readline()
s
= self
._line
[self
._line
_offset
:]
def readlines(self
, size
=None):
return self
._file
.readlines(size
)
L
= [self
._line
[self
._line
_offset
:]]
return L
+ self
._file
.readlines()
return L
+ self
._file
.readlines(size
)
A hodge podge of tests collected here, because they have too many
external dependencies for the regular test suite.
opts
, args
= getopt
.getopt(sys
.argv
[1:], 'd')
if o
== '-d': dl
= dl
+ 1
if args
[0:]: host
= args
[0]
if args
[1:]: selector
= args
[1]
h
.putrequest('GET', selector
)
status
, reason
, headers
= h
.getreply()
print "read", len(h
.getfile().read())
for header
in headers
.headers
: print header
.strip()
# minimal test that code to extract host from url works
_http_vsn_str
= 'HTTP/1.1'
h
= HTTP11('www.python.org')
h
.putrequest('GET', 'http://www.python.org/~jeremy/')
if hasattr(socket
, 'ssl'):
for host
, selector
in (('sourceforge.net', '/projects/python'),
print "https://%s%s" % (host
, selector
)
hs
.putrequest('GET', selector
)
status
, reason
, headers
= hs
.getreply()
print "read", len(hs
.getfile().read())
for header
in headers
.headers
: print header
.strip()
if __name__
== '__main__':