Back to index

python3.2  3.2.2
Classes | Functions | Variables
wsgiref.validate Namespace Reference

Classes

class  WSGIWarning
class  InputWrapper
class  ErrorWrapper
class  WriteWrapper
class  PartialIteratorWrapper
class  IteratorWrapper

Functions

def assert_
def check_string_type
def validator
def check_environ
def check_input
def check_errors
def check_status
def check_headers
def check_content_type
def check_exc_info
def check_iterator

Variables

list __all__ = ['validator']
tuple header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
tuple bad_header_value_re = re.compile(r'[\000-\037]')

Class Documentation

class wsgiref::validate::WSGIWarning
Raised in response to WSGI-spec-related warnings

Definition at line 121 of file validate.py.


Function Documentation

def wsgiref.validate.assert_ (   cond,
  args 
)

Definition at line 126 of file validate.py.

00126 
00127 def assert_(cond, *args):
00128     if not cond:
00129         raise AssertionError(*args)

Here is the caller graph for this function:

def wsgiref.validate.check_content_type (   status,
  headers 
)

Definition at line 416 of file validate.py.

00416 
00417 def check_content_type(status, headers):
00418     status = check_string_type(status, "Status")
00419     code = int(status.split(None, 1)[0])
00420     # @@: need one more person to verify this interpretation of RFC 2616
00421     #     http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
00422     NO_MESSAGE_BODY = (204, 304)
00423     for name, value in headers:
00424         name = check_string_type(name, "Header name")
00425         if name.lower() == 'content-type':
00426             if code not in NO_MESSAGE_BODY:
00427                 return
00428             assert_(0, ("Content-Type header found in a %s response, "
00429                         "which must not return content.") % code)
00430     if code not in NO_MESSAGE_BODY:
00431         assert_(0, "No Content-Type header found in headers (%s)" % headers)

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.validate.check_environ (   environ)

Definition at line 298 of file validate.py.

00298 
00299 def check_environ(environ):
00300     assert_(type(environ) is dict,
00301         "Environment is not of the right type: %r (environment: %r)"
00302         % (type(environ), environ))
00303 
00304     for key in ['REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT',
00305                 'wsgi.version', 'wsgi.input', 'wsgi.errors',
00306                 'wsgi.multithread', 'wsgi.multiprocess',
00307                 'wsgi.run_once']:
00308         assert_(key in environ,
00309             "Environment missing required key: %r" % (key,))
00310 
00311     for key in ['HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH']:
00312         assert_(key not in environ,
00313             "Environment should not have the key: %s "
00314             "(use %s instead)" % (key, key[5:]))
00315 
00316     if 'QUERY_STRING' not in environ:
00317         warnings.warn(
00318             'QUERY_STRING is not in the WSGI environment; the cgi '
00319             'module will use sys.argv when this variable is missing, '
00320             'so application errors are more likely',
00321             WSGIWarning)
00322 
00323     for key in environ.keys():
00324         if '.' in key:
00325             # Extension, we don't care about its type
00326             continue
00327         assert_(type(environ[key]) is str,
00328             "Environmental variable %s is not a string: %r (value: %r)"
00329             % (key, type(environ[key]), environ[key]))
00330 
00331     assert_(type(environ['wsgi.version']) is tuple,
00332         "wsgi.version should be a tuple (%r)" % (environ['wsgi.version'],))
00333     assert_(environ['wsgi.url_scheme'] in ('http', 'https'),
00334         "wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
00335 
00336     check_input(environ['wsgi.input'])
00337     check_errors(environ['wsgi.errors'])
00338 
00339     # @@: these need filling out:
00340     if environ['REQUEST_METHOD'] not in (
00341         'GET', 'HEAD', 'POST', 'OPTIONS','PUT','DELETE','TRACE'):
00342         warnings.warn(
00343             "Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
00344             WSGIWarning)
00345 
00346     assert_(not environ.get('SCRIPT_NAME')
00347             or environ['SCRIPT_NAME'].startswith('/'),
00348         "SCRIPT_NAME doesn't start with /: %r" % environ['SCRIPT_NAME'])
00349     assert_(not environ.get('PATH_INFO')
00350             or environ['PATH_INFO'].startswith('/'),
00351         "PATH_INFO doesn't start with /: %r" % environ['PATH_INFO'])
00352     if environ.get('CONTENT_LENGTH'):
00353         assert_(int(environ['CONTENT_LENGTH']) >= 0,
00354             "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
00355 
00356     if not environ.get('SCRIPT_NAME'):
00357         assert_('PATH_INFO' in environ,
00358             "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
00359             "should at least be '/' if SCRIPT_NAME is empty)")
00360     assert_(environ.get('SCRIPT_NAME') != '/',
00361         "SCRIPT_NAME cannot be '/'; it should instead be '', and "
00362         "PATH_INFO should be '/'")

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.validate.check_errors (   wsgi_errors)

Definition at line 369 of file validate.py.

00369 
00370 def check_errors(wsgi_errors):
00371     for attr in ['flush', 'write', 'writelines']:
00372         assert_(hasattr(wsgi_errors, attr),
00373             "wsgi.errors (%r) doesn't have the attribute %s"
00374             % (wsgi_errors, attr))

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.validate.check_exc_info (   exc_info)

Definition at line 432 of file validate.py.

00432 
00433 def check_exc_info(exc_info):
00434     assert_(exc_info is None or type(exc_info) is tuple,
00435         "exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
00436     # More exc_info checks?

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.validate.check_headers (   headers)

Definition at line 389 of file validate.py.

00389 
00390 def check_headers(headers):
00391     assert_(type(headers) is list,
00392         "Headers (%r) must be of type list: %r"
00393         % (headers, type(headers)))
00394     header_names = {}
00395     for item in headers:
00396         assert_(type(item) is tuple,
00397             "Individual headers (%r) must be of type tuple: %r"
00398             % (item, type(item)))
00399         assert_(len(item) == 2)
00400         name, value = item
00401         name = check_string_type(name, "Header name")
00402         value = check_string_type(value, "Header value")
00403         assert_(name.lower() != 'status',
00404             "The Status header cannot be used; it conflicts with CGI "
00405             "script, and HTTP status is not given through headers "
00406             "(value: %r)." % value)
00407         header_names[name.lower()] = None
00408         assert_('\n' not in name and ':' not in name,
00409             "Header names may not contain ':' or '\\n': %r" % name)
00410         assert_(header_re.search(name), "Bad header name: %r" % name)
00411         assert_(not name.endswith('-') and not name.endswith('_'),
00412             "Names may not end in '-' or '_': %r" % name)
00413         if bad_header_value_re.search(value):
00414             assert_(0, "Bad header value: %r (bad char: %r)"
00415             % (value, bad_header_value_re.search(value).group(0)))

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.validate.check_input (   wsgi_input)

Definition at line 363 of file validate.py.

00363 
00364 def check_input(wsgi_input):
00365     for attr in ['read', 'readline', 'readlines', '__iter__']:
00366         assert_(hasattr(wsgi_input, attr),
00367             "wsgi.input (%r) doesn't have the attribute %s"
00368             % (wsgi_input, attr))

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.validate.check_iterator (   iterator)

Definition at line 437 of file validate.py.

00437 
00438 def check_iterator(iterator):
00439     # Technically a bytestring is legal, which is why it's a really bad
00440     # idea, because it may cause the response to be returned
00441     # character-by-character
00442     assert_(not isinstance(iterator, (str, bytes)),
00443         "You should not return a string as your application iterator, "
00444         "instead return a single-item list containing a bytestring.")

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 375 of file validate.py.

00375 
00376 def check_status(status):
00377     status = check_string_type(status, "Status")
00378     # Implicitly check that we can turn it into an integer:
00379     status_code = status.split(None, 1)[0]
00380     assert_(len(status_code) == 3,
00381         "Status codes must be three characters: %r" % status_code)
00382     status_int = int(status_code)
00383     assert_(status_int >= 100, "Status code is invalid: %r" % status_int)
00384     if len(status) < 4 or status[3] != ' ':
00385         warnings.warn(
00386             "The status string (%r) should be a three-digit integer "
00387             "followed by a single space and a status explanation"
00388             % status, WSGIWarning)

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.validate.check_string_type (   value,
  title 
)

Definition at line 130 of file validate.py.

00130 
00131 def check_string_type(value, title):
00132     if type (value) is str:
00133         return value
00134     raise AssertionError(
00135         "{0} must be of type str (got {1})".format(title, repr(value)))

Here is the caller graph for this function:

def wsgiref.validate.validator (   application)
When applied between a WSGI server and a WSGI application, this
middleware will check for WSGI compliancy on a number of levels.
This middleware does not modify the request or response in any
way, but will throw an AssertionError if anything seems off
(except for a failure to close the application iterator, which
will be printed to stderr -- there's no way to throw an exception
at that point).

Definition at line 136 of file validate.py.

00136 
00137 def validator(application):
00138 
00139     """
00140     When applied between a WSGI server and a WSGI application, this
00141     middleware will check for WSGI compliancy on a number of levels.
00142     This middleware does not modify the request or response in any
00143     way, but will throw an AssertionError if anything seems off
00144     (except for a failure to close the application iterator, which
00145     will be printed to stderr -- there's no way to throw an exception
00146     at that point).
00147     """
00148 
00149     def lint_app(*args, **kw):
00150         assert_(len(args) == 2, "Two arguments required")
00151         assert_(not kw, "No keyword arguments allowed")
00152         environ, start_response = args
00153 
00154         check_environ(environ)
00155 
00156         # We use this to check if the application returns without
00157         # calling start_response:
00158         start_response_started = []
00159 
00160         def start_response_wrapper(*args, **kw):
00161             assert_(len(args) == 2 or len(args) == 3, (
00162                 "Invalid number of arguments: %s" % (args,)))
00163             assert_(not kw, "No keyword arguments allowed")
00164             status = args[0]
00165             headers = args[1]
00166             if len(args) == 3:
00167                 exc_info = args[2]
00168             else:
00169                 exc_info = None
00170 
00171             check_status(status)
00172             check_headers(headers)
00173             check_content_type(status, headers)
00174             check_exc_info(exc_info)
00175 
00176             start_response_started.append(None)
00177             return WriteWrapper(start_response(*args))
00178 
00179         environ['wsgi.input'] = InputWrapper(environ['wsgi.input'])
00180         environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors'])
00181 
00182         iterator = application(environ, start_response_wrapper)
00183         assert_(iterator is not None and iterator != False,
00184             "The application must return an iterator, if only an empty list")
00185 
00186         check_iterator(iterator)
00187 
00188         return IteratorWrapper(iterator, start_response_started)
00189 
00190     return lint_app

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Definition at line 111 of file validate.py.

Definition at line 119 of file validate.py.

tuple wsgiref.validate.header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')

Definition at line 118 of file validate.py.