Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes
test.test_httpservers.BaseHTTPServerTestCase.request_handler Class Reference
Inheritance diagram for test.test_httpservers.BaseHTTPServerTestCase.request_handler:
Inheritance graph
[legend]
Collaboration diagram for test.test_httpservers.BaseHTTPServerTestCase.request_handler:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def do_TEST
def do_KEEP
def do_KEYERROR
def do_CUSTOM
def do_LATINONEHEADER
def log_message
def read
def parse_request
def handle_expect_100
def handle_one_request
def handle
def send_error
def send_response
def send_response_only
def send_header
def end_headers
def log_request
def log_error
def log_message
def version_string
def date_time_string
def log_date_time_string
def address_string
def setup
def finish

Public Attributes

 command
 request_version
 close_connection
 requestline
 headers
 raw_requestline
 connection
 rfile
 wfile
 request
 client_address
 server

Static Public Attributes

string protocol_version = 'HTTP/1.1'
string default_request_version = 'HTTP/1.1'
string sys_version = "Python/"
string server_version = "BaseHTTP/"
 error_message_format = DEFAULT_ERROR_MESSAGE
 error_content_type = DEFAULT_ERROR_CONTENT_TYPE
list weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
list monthname
 MessageClass = http.client.HTTPMessage
dictionary responses
int rbufsize = 1
int wbufsize = 0
 timeout = None
 disable_nagle_algorithm = False

Detailed Description

Definition at line 75 of file test_httpservers.py.


Member Function Documentation

Return the client address formatted for logging.

This version looks up the full hostname using gethostbyaddr(),
and tries to find a name that contains at least one dot.

Definition at line 553 of file server.py.

00553 
00554     def address_string(self):
00555         """Return the client address formatted for logging.
00556 
00557         This version looks up the full hostname using gethostbyaddr(),
00558         and tries to find a name that contains at least one dot.
00559 
00560         """
00561 
00562         host, port = self.client_address[:2]
00563         return socket.getfqdn(host)

Here is the call graph for this function:

Here is the caller graph for this function:

def http.server.BaseHTTPRequestHandler.date_time_string (   self,
  timestamp = None 
) [inherited]
Return the current date and time formatted for a message header.

Definition at line 528 of file server.py.

00528 
00529     def date_time_string(self, timestamp=None):
00530         """Return the current date and time formatted for a message header."""
00531         if timestamp is None:
00532             timestamp = time.time()
00533         year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
00534         s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
00535                 self.weekdayname[wd],
00536                 day, self.monthname[month], year,
00537                 hh, mm, ss)
00538         return s

Here is the caller graph for this function:

Definition at line 94 of file test_httpservers.py.

00094 
00095         def do_CUSTOM(self):
00096             self.send_response(999)
00097             self.send_header('Content-Type', 'text/html')
00098             self.send_header('Connection', 'close')
00099             self.end_headers()

Here is the call graph for this function:

Definition at line 85 of file test_httpservers.py.

00085 
00086         def do_KEEP(self):
00087             self.send_response(204)
00088             self.send_header('Content-Type', 'text/html')
00089             self.send_header('Connection', 'keep-alive')
00090             self.end_headers()

Here is the call graph for this function:

Definition at line 91 of file test_httpservers.py.

00091 
00092         def do_KEYERROR(self):
00093             self.send_error(999)

Here is the call graph for this function:

Definition at line 100 of file test_httpservers.py.

00100 
00101         def do_LATINONEHEADER(self):
00102             self.send_response(999)
00103             self.send_header('X-Special', 'Dängerous Mind')
00104             self.send_header('Connection', 'close')
00105             self.end_headers()
00106             body = self.headers['x-special-incoming'].encode('utf-8')
00107             self.wfile.write(body)
00108 
    def setUp(self):

Here is the call graph for this function:

Definition at line 79 of file test_httpservers.py.

00079 
00080         def do_TEST(self):
00081             self.send_response(204)
00082             self.send_header('Content-Type', 'text/html')
00083             self.send_header('Connection', 'close')
00084             self.end_headers()

Here is the call graph for this function:

Send the blank line ending the MIME headers.

Definition at line 471 of file server.py.

00471 
00472     def end_headers(self):
00473         """Send the blank line ending the MIME headers."""
00474         if self.request_version != 'HTTP/0.9':
00475             self._headers_buffer.append(b"\r\n")
00476             self.wfile.write(b"".join(self._headers_buffer))
00477             self._headers_buffer = []

Here is the caller graph for this function:

def socketserver.StreamRequestHandler.finish (   self) [inherited]

Reimplemented from socketserver.BaseRequestHandler.

Reimplemented in test.test_wsgiref.MockHandler.

Definition at line 691 of file socketserver.py.

00691 
00692     def finish(self):
00693         if not self.wfile.closed:
00694             self.wfile.flush()
00695         self.wfile.close()
00696         self.rfile.close()
00697 

Here is the caller graph for this function:

def http.server.BaseHTTPRequestHandler.handle (   self) [inherited]
Handle multiple requests if necessary.

Reimplemented from socketserver.BaseRequestHandler.

Reimplemented in test.test_xmlrpc.BaseKeepaliveServerTestCase.RequestHandler, and wsgiref.simple_server.WSGIRequestHandler.

Definition at line 395 of file server.py.

00395 
00396     def handle(self):
00397         """Handle multiple requests if necessary."""
00398         self.close_connection = 1
00399 
00400         self.handle_one_request()
00401         while not self.close_connection:
00402             self.handle_one_request()

Here is the call graph for this function:

Here is the caller graph for this function:

Decide what to do with an "Expect: 100-continue" header.

If the client is expecting a 100 Continue response, we must
respond with either a 100 Continue or a final response before
waiting for the request body. The default is to always respond
with a 100 Continue. You can behave differently (for example,
reject unauthorized requests) by overriding this method.

This method should either return True (possibly after sending
a 100 Continue response) or send an error response and return
False.

Definition at line 343 of file server.py.

00343 
00344     def handle_expect_100(self):
00345         """Decide what to do with an "Expect: 100-continue" header.
00346 
00347         If the client is expecting a 100 Continue response, we must
00348         respond with either a 100 Continue or a final response before
00349         waiting for the request body. The default is to always respond
00350         with a 100 Continue. You can behave differently (for example,
00351         reject unauthorized requests) by overriding this method.
00352 
00353         This method should either return True (possibly after sending
00354         a 100 Continue response) or send an error response and return
00355         False.
00356 
00357         """
00358         self.send_response_only(100)
00359         return True

Here is the call graph for this function:

Handle a single HTTP request.

You normally don't need to override this method; see the class
__doc__ string for information on how to handle specific HTTP
commands such as GET and POST.

Reimplemented in test.test_xmlrpc.BaseKeepaliveServerTestCase.RequestHandler.

Definition at line 360 of file server.py.

00360 
00361     def handle_one_request(self):
00362         """Handle a single HTTP request.
00363 
00364         You normally don't need to override this method; see the class
00365         __doc__ string for information on how to handle specific HTTP
00366         commands such as GET and POST.
00367 
00368         """
00369         try:
00370             self.raw_requestline = self.rfile.readline(65537)
00371             if len(self.raw_requestline) > 65536:
00372                 self.requestline = ''
00373                 self.request_version = ''
00374                 self.command = ''
00375                 self.send_error(414)
00376                 return
00377             if not self.raw_requestline:
00378                 self.close_connection = 1
00379                 return
00380             if not self.parse_request():
00381                 # An error code has been sent, just exit
00382                 return
00383             mname = 'do_' + self.command
00384             if not hasattr(self, mname):
00385                 self.send_error(501, "Unsupported method (%r)" % self.command)
00386                 return
00387             method = getattr(self, mname)
00388             method()
00389             self.wfile.flush() #actually send the response if not already done.
00390         except socket.timeout as e:
00391             #a read or a write timed out.  Discard this connection
00392             self.log_error("Request timed out: %r", e)
00393             self.close_connection = 1
00394             return

Here is the caller graph for this function:

Return the current time formatted for logging.

Definition at line 539 of file server.py.

00539 
00540     def log_date_time_string(self):
00541         """Return the current time formatted for logging."""
00542         now = time.time()
00543         year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
00544         s = "%02d/%3s/%04d %02d:%02d:%02d" % (
00545                 day, self.monthname[month], year, hh, mm, ss)
00546         return s

Here is the caller graph for this function:

def http.server.BaseHTTPRequestHandler.log_error (   self,
  format,
  args 
) [inherited]
Log an error.

This is called when a request cannot be fulfilled.  By
default it passes the message on to log_message().

Arguments are the same as for log_message().

XXX This should go to the separate error log.

Definition at line 488 of file server.py.

00488 
00489     def log_error(self, format, *args):
00490         """Log an error.
00491 
00492         This is called when a request cannot be fulfilled.  By
00493         default it passes the message on to log_message().
00494 
00495         Arguments are the same as for log_message().
00496 
00497         XXX This should go to the separate error log.
00498 
00499         """
00500 
00501         self.log_message(format, *args)

Here is the call graph for this function:

Here is the caller graph for this function:

def test.test_httpservers.NoLogRequestHandler.log_message (   self,
  args 
) [inherited]

Definition at line 26 of file test_httpservers.py.

00026 
00027     def log_message(self, *args):
00028         # don't write log messages to stderr
00029         pass

def http.server.BaseHTTPRequestHandler.log_message (   self,
  format,
  args 
) [inherited]
Log an arbitrary message.

This is used by all other logging functions.  Override
it if you have specific logging wishes.

The first argument, FORMAT, is a format string for the
message to be logged.  If the format string contains
any % escapes requiring parameters, they should be
specified as subsequent arguments (it's just like
printf!).

The client host and current date/time are prefixed to
every message.

Reimplemented in test.test_urllib2_localnet.FakeProxyHandler, and mp_webserver.RequestHandler.

Definition at line 502 of file server.py.

00502 
00503     def log_message(self, format, *args):
00504         """Log an arbitrary message.
00505 
00506         This is used by all other logging functions.  Override
00507         it if you have specific logging wishes.
00508 
00509         The first argument, FORMAT, is a format string for the
00510         message to be logged.  If the format string contains
00511         any % escapes requiring parameters, they should be
00512         specified as subsequent arguments (it's just like
00513         printf!).
00514 
00515         The client host and current date/time are prefixed to
00516         every message.
00517 
00518         """
00519 
00520         sys.stderr.write("%s - - [%s] %s\n" %
00521                          (self.address_string(),
00522                           self.log_date_time_string(),
00523                           format%args))

Here is the call graph for this function:

Here is the caller graph for this function:

def http.server.BaseHTTPRequestHandler.log_request (   self,
  code = '-',
  size = '-' 
) [inherited]
Log an accepted request.

This is called by send_response().

Reimplemented in xmlrpc.server.SimpleXMLRPCRequestHandler.

Definition at line 478 of file server.py.

00478 
00479     def log_request(self, code='-', size='-'):
00480         """Log an accepted request.
00481 
00482         This is called by send_response().
00483 
00484         """
00485 
00486         self.log_message('"%s" %s %s',
00487                          self.requestline, str(code), str(size))

Here is the call graph for this function:

Here is the caller graph for this function:

Parse a request (internal).

The request should be stored in self.raw_requestline; the results
are in self.command, self.path, self.request_version and
self.headers.

Return True for success, False for failure; on failure, an
error is sent back.

Definition at line 259 of file server.py.

00259 
00260     def parse_request(self):
00261         """Parse a request (internal).
00262 
00263         The request should be stored in self.raw_requestline; the results
00264         are in self.command, self.path, self.request_version and
00265         self.headers.
00266 
00267         Return True for success, False for failure; on failure, an
00268         error is sent back.
00269 
00270         """
00271         self.command = None  # set in case of error on the first line
00272         self.request_version = version = self.default_request_version
00273         self.close_connection = 1
00274         requestline = str(self.raw_requestline, 'iso-8859-1')
00275         if requestline[-2:] == '\r\n':
00276             requestline = requestline[:-2]
00277         elif requestline[-1:] == '\n':
00278             requestline = requestline[:-1]
00279         self.requestline = requestline
00280         words = requestline.split()
00281         if len(words) == 3:
00282             [command, path, version] = words
00283             if version[:5] != 'HTTP/':
00284                 self.send_error(400, "Bad request version (%r)" % version)
00285                 return False
00286             try:
00287                 base_version_number = version.split('/', 1)[1]
00288                 version_number = base_version_number.split(".")
00289                 # RFC 2145 section 3.1 says there can be only one "." and
00290                 #   - major and minor numbers MUST be treated as
00291                 #      separate integers;
00292                 #   - HTTP/2.4 is a lower version than HTTP/2.13, which in
00293                 #      turn is lower than HTTP/12.3;
00294                 #   - Leading zeros MUST be ignored by recipients.
00295                 if len(version_number) != 2:
00296                     raise ValueError
00297                 version_number = int(version_number[0]), int(version_number[1])
00298             except (ValueError, IndexError):
00299                 self.send_error(400, "Bad request version (%r)" % version)
00300                 return False
00301             if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
00302                 self.close_connection = 0
00303             if version_number >= (2, 0):
00304                 self.send_error(505,
00305                           "Invalid HTTP Version (%s)" % base_version_number)
00306                 return False
00307         elif len(words) == 2:
00308             [command, path] = words
00309             self.close_connection = 1
00310             if command != 'GET':
00311                 self.send_error(400,
00312                                 "Bad HTTP/0.9 request type (%r)" % command)
00313                 return False
00314         elif not words:
00315             return False
00316         else:
00317             self.send_error(400, "Bad request syntax (%r)" % requestline)
00318             return False
00319         self.command, self.path, self.request_version = command, path, version
00320 
00321         # Examine the headers and look for a Connection directive.
00322         try:
00323             self.headers = http.client.parse_headers(self.rfile,
00324                                                      _class=self.MessageClass)
00325         except http.client.LineTooLong:
00326             self.send_error(400, "Line too long")
00327             return False
00328 
00329         conntype = self.headers.get('Connection', "")
00330         if conntype.lower() == 'close':
00331             self.close_connection = 1
00332         elif (conntype.lower() == 'keep-alive' and
00333               self.protocol_version >= "HTTP/1.1"):
00334             self.close_connection = 0
00335         # Examine the headers and look for an Expect directive
00336         expect = self.headers.get('Expect', "")
00337         if (expect.lower() == "100-continue" and
00338                 self.protocol_version >= "HTTP/1.1" and
00339                 self.request_version >= "HTTP/1.1"):
00340             if not self.handle_expect_100():
00341                 return False
00342         return True

def test.test_httpservers.NoLogRequestHandler.read (   self,
  n = None 
) [inherited]

Definition at line 30 of file test_httpservers.py.

00030 
00031     def read(self, n=None):
00032         return ''
00033 

Here is the caller graph for this function:

def http.server.BaseHTTPRequestHandler.send_error (   self,
  code,
  message = None 
) [inherited]
Send and log an error reply.

Arguments are the error code, and a detailed message.
The detailed message defaults to the short entry matching the
response code.

This sends an error response (so it must be called before any
output has been generated), logs the error, and finally sends
a piece of HTML explaining the error to the user.

Definition at line 403 of file server.py.

00403 
00404     def send_error(self, code, message=None):
00405         """Send and log an error reply.
00406 
00407         Arguments are the error code, and a detailed message.
00408         The detailed message defaults to the short entry matching the
00409         response code.
00410 
00411         This sends an error response (so it must be called before any
00412         output has been generated), logs the error, and finally sends
00413         a piece of HTML explaining the error to the user.
00414 
00415         """
00416 
00417         try:
00418             shortmsg, longmsg = self.responses[code]
00419         except KeyError:
00420             shortmsg, longmsg = '???', '???'
00421         if message is None:
00422             message = shortmsg
00423         explain = longmsg
00424         self.log_error("code %d, message %s", code, message)
00425         # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
00426         content = (self.error_message_format %
00427                    {'code': code, 'message': _quote_html(message), 'explain': explain})
00428         self.send_response(code, message)
00429         self.send_header("Content-Type", self.error_content_type)
00430         self.send_header('Connection', 'close')
00431         self.end_headers()
00432         if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
00433             self.wfile.write(content.encode('UTF-8', 'replace'))

Here is the call graph for this function:

Here is the caller graph for this function:

def http.server.BaseHTTPRequestHandler.send_header (   self,
  keyword,
  value 
) [inherited]
Send a MIME header.

Definition at line 457 of file server.py.

00457 
00458     def send_header(self, keyword, value):
00459         """Send a MIME header."""
00460         if self.request_version != 'HTTP/0.9':
00461             if not hasattr(self, '_headers_buffer'):
00462                 self._headers_buffer = []
00463             self._headers_buffer.append(
00464                 ("%s: %s\r\n" % (keyword, value)).encode('latin1', 'strict'))
00465 
00466         if keyword.lower() == 'connection':
00467             if value.lower() == 'close':
00468                 self.close_connection = 1
00469             elif value.lower() == 'keep-alive':
00470                 self.close_connection = 0

Here is the caller graph for this function:

def http.server.BaseHTTPRequestHandler.send_response (   self,
  code,
  message = None 
) [inherited]
Send the response header and log the response code.

Also send two standard headers with the server software
version and the current date.

Definition at line 434 of file server.py.

00434 
00435     def send_response(self, code, message=None):
00436         """Send the response header and log the response code.
00437 
00438         Also send two standard headers with the server software
00439         version and the current date.
00440 
00441         """
00442         self.log_request(code)
00443         self.send_response_only(code, message)
00444         self.send_header('Server', self.version_string())
00445         self.send_header('Date', self.date_time_string())

Here is the call graph for this function:

Here is the caller graph for this function:

def http.server.BaseHTTPRequestHandler.send_response_only (   self,
  code,
  message = None 
) [inherited]
Send the response header only.

Definition at line 446 of file server.py.

00446 
00447     def send_response_only(self, code, message=None):
00448         """Send the response header only."""
00449         if message is None:
00450             if code in self.responses:
00451                 message = self.responses[code][0]
00452             else:
00453                 message = ''
00454         if self.request_version != 'HTTP/0.9':
00455             self.wfile.write(("%s %d %s\r\n" %
00456                               (self.protocol_version, code, message)).encode('latin1', 'strict'))

Here is the caller graph for this function:

def socketserver.StreamRequestHandler.setup (   self) [inherited]

Reimplemented from socketserver.BaseRequestHandler.

Reimplemented in test.test_wsgiref.MockHandler.

Definition at line 681 of file socketserver.py.

00681 
00682     def setup(self):
00683         self.connection = self.request
00684         if self.timeout is not None:
00685             self.connection.settimeout(self.timeout)
00686         if self.disable_nagle_algorithm:
00687             self.connection.setsockopt(socket.IPPROTO_TCP,
00688                                        socket.TCP_NODELAY, True)
00689         self.rfile = self.connection.makefile('rb', self.rbufsize)
00690         self.wfile = self.connection.makefile('wb', self.wbufsize)

Here is the caller graph for this function:

Return the server software version string.

Definition at line 524 of file server.py.

00524 
00525     def version_string(self):
00526         """Return the server software version string."""
00527         return self.server_version + ' ' + self.sys_version

Here is the caller graph for this function:


Member Data Documentation

Definition at line 634 of file socketserver.py.

Definition at line 272 of file server.py.

Definition at line 270 of file server.py.

Reimplemented in test.test_wsgiref.MockHandler.

Definition at line 682 of file socketserver.py.

Reimplemented from http.server.BaseHTTPRequestHandler.

Definition at line 77 of file test_httpservers.py.

Reimplemented in xmlrpc.server.SimpleXMLRPCRequestHandler.

Definition at line 679 of file socketserver.py.

http.server.BaseHTTPRequestHandler.error_content_type = DEFAULT_ERROR_CONTENT_TYPE [static, inherited]

Definition at line 251 of file server.py.

http.server.BaseHTTPRequestHandler.error_message_format = DEFAULT_ERROR_MESSAGE [static, inherited]

Definition at line 250 of file server.py.

Definition at line 322 of file server.py.

Definition at line 571 of file server.py.

Initial value:
[None,
                 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

Definition at line 549 of file server.py.

Reimplemented from http.server.BaseHTTPRequestHandler.

Definition at line 76 of file test_httpservers.py.

Reimplemented in wsgiref.simple_server.WSGIRequestHandler.

Definition at line 369 of file server.py.

Reimplemented in http.server.CGIHTTPRequestHandler.

Definition at line 671 of file socketserver.py.

Definition at line 633 of file socketserver.py.

Definition at line 271 of file server.py.

Definition at line 278 of file server.py.

Definition at line 576 of file server.py.

Definition at line 688 of file socketserver.py.

Definition at line 635 of file socketserver.py.

string http.server.BaseHTTPRequestHandler.server_version = "BaseHTTP/" [static, inherited]
string http.server.BaseHTTPRequestHandler.sys_version = "Python/" [static, inherited]

Definition at line 243 of file server.py.

socketserver.StreamRequestHandler.timeout = None [static, inherited]

Reimplemented in test.test_imaplib.SimpleIMAPHandler.

Definition at line 675 of file socketserver.py.

Reimplemented in xmlrpc.server.SimpleXMLRPCRequestHandler.

Definition at line 672 of file socketserver.py.

list http.server.BaseHTTPRequestHandler.weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] [static, inherited]

Definition at line 547 of file server.py.

Reimplemented in test.test_wsgiref.MockHandler.

Definition at line 689 of file socketserver.py.


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