Back to index

moin  1.9.0~rc2
Classes | Functions | Variables
MoinMoin.support.werkzeug.utils Namespace Reference

Classes

class  FileStorage
class  SharedDataMiddleware
class  DispatcherMiddleware
class  ClosingIterator
class  FileWrapper
class  LimitedStream
class  Href
class  cached_property
class  environ_property
class  header_property
class  HTMLBuilder
class  ArgumentValidationError

Functions

def make_line_iter
def parse_form_data
def get_content_type
def format_string
def url_decode
def url_encode
def url_quote
def url_quote_plus
def url_unquote
def url_unquote_plus
def url_fix
def secure_filename
def escape
def unescape
def get_host
def get_current_url
def pop_path_info
def peek_path_info
def cookie_date
def parse_cookie
def dump_cookie
def http_date
def redirect
def append_slash_redirect
def responder
def wrap_file
def import_string
def find_modules
def validate_arguments
def bind_arguments
def create_environ
def run_wsgi_app

Variables

tuple _format_re = re.compile(r'\$(?:(%s)|\{(%s)\})' % (('[a-zA-Z_][a-zA-Z0-9_]*',) * 2))
tuple _entity_re = re.compile(r'&([^;]+);')
tuple _filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]')
tuple _windows_device_files
tuple html = HTMLBuilder('html')
tuple xhtml = HTMLBuilder('xhtml')

Function Documentation

def MoinMoin.support.werkzeug.utils.append_slash_redirect (   environ,
  code = 301 
)
Redirect to the same URL but with a slash appended.  The behavior
of this function is undefined if the path ends with a slash already.

:param environ: the WSGI environment for the request that triggers
                the redirect.
:param code: the status code for the redirect.

Definition at line 1460 of file utils.py.

01460 
01461 def append_slash_redirect(environ, code=301):
01462     """Redirect to the same URL but with a slash appended.  The behavior
01463     of this function is undefined if the path ends with a slash already.
01464 
01465     :param environ: the WSGI environment for the request that triggers
01466                     the redirect.
01467     :param code: the status code for the redirect.
01468     """
01469     new_path = environ['PATH_INFO'].strip('/') + '/'
01470     query_string = environ['QUERY_STRING']
01471     if query_string:
01472         new_path += '?' + query_string
01473     return redirect(new_path, code)
01474 

Here is the call graph for this function:

def MoinMoin.support.werkzeug.utils.bind_arguments (   func,
  args,
  kwargs 
)
Bind the arguments provided into a dict.  When passed a function,
a tuple of arguments and a dict of keyword arguments `bind_arguments`
returns a dict of names as the function would see it.  This can be useful
to implement a cache decorator that uses the function arguments to build
the cache key based on the values of the arguments.

:param func: the function the arguments should be bound for.
:param args: tuple of positional arguments.
:param kwargs: a dict of keyword arguments.
:return: a :class:`dict` of bound keyword arguments.

Definition at line 1618 of file utils.py.

01618 
01619 def bind_arguments(func, args, kwargs):
01620     """Bind the arguments provided into a dict.  When passed a function,
01621     a tuple of arguments and a dict of keyword arguments `bind_arguments`
01622     returns a dict of names as the function would see it.  This can be useful
01623     to implement a cache decorator that uses the function arguments to build
01624     the cache key based on the values of the arguments.
01625 
01626     :param func: the function the arguments should be bound for.
01627     :param args: tuple of positional arguments.
01628     :param kwargs: a dict of keyword arguments.
01629     :return: a :class:`dict` of bound keyword arguments.
01630     """
01631     args, kwargs, missing, extra, extra_positional, \
01632         arg_spec, vararg_var, kwarg_var = _parse_signature(func)(args, kwargs)
01633     values = {}
01634     for (name, has_default, default), value in zip(arg_spec, args):
01635         values[name] = value
01636     if vararg_var is not None:
01637         values[vararg_var] = tuple(extra_positional)
01638     elif extra_positional:
01639         raise TypeError('too many positional arguments')
01640     if kwarg_var is not None:
01641         multikw = set(extra) & set([x[0] for x in arg_spec])
01642         if multikw:
01643             raise TypeError('got multiple values for keyword argument ' +
01644                             repr(iter(multikw).next()))
01645         values[kwarg_var] = extra
01646     elif extra:
01647         raise TypeError('got unexpected keyword argument ' +
01648                         repr(iter(extra).next()))
01649     return values
01650 

Here is the call graph for this function:

Formats the time to ensure compatibility with Netscape's cookie
standard.

Accepts a floating point number expressed in seconds since the epoc in, a
datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
function can be used to parse such a date.

Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.

:param expires: If provided that date is used, otherwise the current.

Definition at line 1321 of file utils.py.

01321 
01322 def cookie_date(expires=None):
01323     """Formats the time to ensure compatibility with Netscape's cookie
01324     standard.
01325 
01326     Accepts a floating point number expressed in seconds since the epoc in, a
01327     datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
01328     function can be used to parse such a date.
01329 
01330     Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.
01331 
01332     :param expires: If provided that date is used, otherwise the current.
01333     """
01334     return _dump_date(expires, '-')
01335 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.create_environ (   args,
  kwargs 
)
backward compatibility.

Definition at line 1678 of file utils.py.

01678 
01679 def create_environ(*args, **kwargs):
01680     """backward compatibility."""
01681     from werkzeug.test import create_environ
01682     return create_environ(*args, **kwargs)

def MoinMoin.support.werkzeug.utils.dump_cookie (   key,
  value = '',
  max_age = None,
  expires = None,
  path = '/',
  domain = None,
  secure = None,
  httponly = False,
  charset = 'utf-8',
  sync_expires = True 
)
Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
The parameters are the same as in the cookie Morsel object in the
Python standard library but it accepts unicode data, too.

:param max_age: should be a number of seconds, or `None` (default) if
                the cookie should last only as long as the client's
                browser session.  Additionally `timedelta` objects
                are accepted, too.
:param expires: should be a `datetime` object or unix timestamp.
:param path: limits the cookie to a given path, per default it will
             span the whole domain.
:param domain: Use this if you want to set a cross-domain cookie. For
               example, ``domain=".example.com"`` will set a cookie
               that is readable by the domain ``www.example.com``,
               ``foo.example.com`` etc. Otherwise, a cookie will only
               be readable by the domain that set it.
:param secure: The cookie will only be available via HTTPS
:param httponly: disallow JavaScript to access the cookie.  This is an
                 extension to the cookie standard and probably not
                 supported by all browsers.
:param charset: the encoding for unicode values.
:param sync_expires: automatically set expires if max_age is defined
                     but expires not.

Definition at line 1376 of file utils.py.

01376 
01377                 sync_expires=True):
01378     """Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
01379     The parameters are the same as in the cookie Morsel object in the
01380     Python standard library but it accepts unicode data, too.
01381 
01382     :param max_age: should be a number of seconds, or `None` (default) if
01383                     the cookie should last only as long as the client's
01384                     browser session.  Additionally `timedelta` objects
01385                     are accepted, too.
01386     :param expires: should be a `datetime` object or unix timestamp.
01387     :param path: limits the cookie to a given path, per default it will
01388                  span the whole domain.
01389     :param domain: Use this if you want to set a cross-domain cookie. For
01390                    example, ``domain=".example.com"`` will set a cookie
01391                    that is readable by the domain ``www.example.com``,
01392                    ``foo.example.com`` etc. Otherwise, a cookie will only
01393                    be readable by the domain that set it.
01394     :param secure: The cookie will only be available via HTTPS
01395     :param httponly: disallow JavaScript to access the cookie.  This is an
01396                      extension to the cookie standard and probably not
01397                      supported by all browsers.
01398     :param charset: the encoding for unicode values.
01399     :param sync_expires: automatically set expires if max_age is defined
01400                          but expires not.
01401     """
01402     try:
01403         key = str(key)
01404     except UnicodeError:
01405         raise TypeError('invalid key %r' % key)
01406     if isinstance(value, unicode):
01407         value = value.encode(charset)
01408     morsel = _ExtendedMorsel(key, value)
01409     if isinstance(max_age, timedelta):
01410         max_age = (max_age.days * 60 * 60 * 24) + max_age.seconds
01411     if expires is not None:
01412         if not isinstance(expires, basestring):
01413             expires = cookie_date(expires)
01414         morsel['expires'] = expires
01415     elif max_age is not None and sync_expires:
01416         morsel['expires'] = cookie_date(time() + max_age)
01417     for k, v in (('path', path), ('domain', domain), ('secure', secure),
01418                  ('max-age', max_age), ('httponly', httponly)):
01419         if v is not None and v is not False:
01420             morsel[k] = str(v)
01421     return morsel.output(header='').lstrip()
01422 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.escape (   s,
  quote = False 
)
Replace special characters "&", "<" and ">" to HTML-safe sequences.  If
the optional flag `quote` is `True`, the quotation mark character (") is
also translated.

There is a special handling for `None` which escapes to an empty string.

:param s: the string to escape.
:param quote: set to true to also escape double quotes.

Definition at line 1161 of file utils.py.

01161 
01162 def escape(s, quote=False):
01163     """Replace special characters "&", "<" and ">" to HTML-safe sequences.  If
01164     the optional flag `quote` is `True`, the quotation mark character (") is
01165     also translated.
01166 
01167     There is a special handling for `None` which escapes to an empty string.
01168 
01169     :param s: the string to escape.
01170     :param quote: set to true to also escape double quotes.
01171     """
01172     if s is None:
01173         return ''
01174     elif hasattr(s, '__html__'):
01175         return s.__html__()
01176     elif not isinstance(s, basestring):
01177         s = unicode(s)
01178     s = s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
01179     if quote:
01180         s = s.replace('"', "&quot;")
01181     return s
01182 

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.find_modules (   import_path,
  include_packages = False,
  recursive = False 
)
Find all the modules below a package.  This can be useful to
automatically import all views / controllers so that their metaclasses /
function decorators have a chance to register themselves on the
application.

Packages are not returned unless `include_packages` is `True`.  This can
also recursively list modules but in that case it will import all the
packages to get the correct load path of that module.

:param import_name: the dotted name for the package to find child modules.
:param include_packages: set to `True` if packages should be returned, too.
:param recursive: set to `True` if recursion should happen.
:return: generator

Definition at line 1533 of file utils.py.

01533 
01534 def find_modules(import_path, include_packages=False, recursive=False):
01535     """Find all the modules below a package.  This can be useful to
01536     automatically import all views / controllers so that their metaclasses /
01537     function decorators have a chance to register themselves on the
01538     application.
01539 
01540     Packages are not returned unless `include_packages` is `True`.  This can
01541     also recursively list modules but in that case it will import all the
01542     packages to get the correct load path of that module.
01543 
01544     :param import_name: the dotted name for the package to find child modules.
01545     :param include_packages: set to `True` if packages should be returned, too.
01546     :param recursive: set to `True` if recursion should happen.
01547     :return: generator
01548     """
01549     module = import_string(import_path)
01550     path = getattr(module, '__path__', None)
01551     if path is None:
01552         raise ValueError('%r is not a package' % import_path)
01553     basename = module.__name__ + '.'
01554     for modname, ispkg in _iter_modules(path):
01555         modname = basename + modname
01556         if ispkg:
01557             if include_packages:
01558                 yield modname
01559             if recursive:
01560                 for item in find_modules(modname, include_packages, True):
01561                     yield item
01562         else:
01563             yield modname
01564 

Here is the call graph for this function:

def MoinMoin.support.werkzeug.utils.format_string (   string,
  context 
)
String-template format a string:

>>> format_string('$foo and ${foo}s', dict(foo=42))
'42 and 42s'

This does not do any attribute lookup etc.  For more advanced string
formattings have a look at the `werkzeug.template` module.

:param string: the format string.
:param context: a dict with the variables to insert.

Definition at line 923 of file utils.py.

00923 
00924 def format_string(string, context):
00925     """String-template format a string:
00926 
00927     >>> format_string('$foo and ${foo}s', dict(foo=42))
00928     '42 and 42s'
00929 
00930     This does not do any attribute lookup etc.  For more advanced string
00931     formattings have a look at the `werkzeug.template` module.
00932 
00933     :param string: the format string.
00934     :param context: a dict with the variables to insert.
00935     """
00936     def lookup_arg(match):
00937         x = context[match.group(1) or match.group(2)]
00938         if not isinstance(x, basestring):
00939             x = type(string)(x)
00940         return x
00941     return _format_re.sub(lookup_arg, string)
00942 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.get_content_type (   mimetype,
  charset 
)
Return the full content type string with charset for a mimetype.

If the mimetype represents text the charset will be appended as charset
parameter, otherwise the mimetype is returned unchanged.

:param mimetype: the mimetype to be used as content type.
:param charset: the charset to be appended in case it was a text mimetype.
:return: the content type.

Definition at line 905 of file utils.py.

00905 
00906 def get_content_type(mimetype, charset):
00907     """Return the full content type string with charset for a mimetype.
00908 
00909     If the mimetype represents text the charset will be appended as charset
00910     parameter, otherwise the mimetype is returned unchanged.
00911 
00912     :param mimetype: the mimetype to be used as content type.
00913     :param charset: the charset to be appended in case it was a text mimetype.
00914     :return: the content type.
00915     """
00916     if mimetype.startswith('text/') or \
00917        mimetype == 'application/xml' or \
00918        (mimetype.startswith('application/') and
00919         mimetype.endswith('+xml')):
00920         mimetype += '; charset=' + charset
00921     return mimetype
00922 

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.get_current_url (   environ,
  root_only = False,
  strip_querystring = False,
  host_only = False 
)
A handy helper function that recreates the full URL for the current
request or parts of it.  Here an example:

>>> env = create_environ("/?param=foo", "http://localhost/script")
>>> get_current_url(env)
'http://localhost/script/?param=foo'
>>> get_current_url(env, root_only=True)
'http://localhost/script/'
>>> get_current_url(env, host_only=True)
'http://localhost/'
>>> get_current_url(env, strip_querystring=True)
'http://localhost/script/'

:param environ: the WSGI environment to get the current URL from.
:param root_only: set `True` if you only want the root URL.
:param strip_querystring: set to `True` if you don't want the querystring.
:param host_only: set to `True` if the host URL should be returned.

Definition at line 1222 of file utils.py.

01222 
01223                     host_only=False):
01224     """A handy helper function that recreates the full URL for the current
01225     request or parts of it.  Here an example:
01226 
01227     >>> env = create_environ("/?param=foo", "http://localhost/script")
01228     >>> get_current_url(env)
01229     'http://localhost/script/?param=foo'
01230     >>> get_current_url(env, root_only=True)
01231     'http://localhost/script/'
01232     >>> get_current_url(env, host_only=True)
01233     'http://localhost/'
01234     >>> get_current_url(env, strip_querystring=True)
01235     'http://localhost/script/'
01236 
01237     :param environ: the WSGI environment to get the current URL from.
01238     :param root_only: set `True` if you only want the root URL.
01239     :param strip_querystring: set to `True` if you don't want the querystring.
01240     :param host_only: set to `True` if the host URL should be returned.
01241     """
01242     tmp = [environ['wsgi.url_scheme'], '://', get_host(environ)]
01243     cat = tmp.append
01244     if host_only:
01245         return ''.join(tmp) + '/'
01246     cat(urllib.quote(environ.get('SCRIPT_NAME', '').rstrip('/')))
01247     if root_only:
01248         cat('/')
01249     else:
01250         cat(urllib.quote('/' + environ.get('PATH_INFO', '').lstrip('/')))
01251         if not strip_querystring:
01252             qs = environ.get('QUERY_STRING')
01253             if qs:
01254                 cat('?' + qs)
01255     return ''.join(tmp)
01256 

Here is the call graph for this function:

Here is the caller graph for this function:

Return the real host for the given WSGI environment.  This takes care
of the `X-Forwarded-Host` header.

:param environ: the WSGI environment to get the host of.

Definition at line 1204 of file utils.py.

01204 
01205 def get_host(environ):
01206     """Return the real host for the given WSGI environment.  This takes care
01207     of the `X-Forwarded-Host` header.
01208 
01209     :param environ: the WSGI environment to get the host of.
01210     """
01211     if 'HTTP_X_FORWARDED_HOST' in environ:
01212         return environ['HTTP_X_FORWARDED_HOST']
01213     elif 'HTTP_HOST' in environ:
01214         return environ['HTTP_HOST']
01215     result = environ['SERVER_NAME']
01216     if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not \
01217        in (('https', '443'), ('http', '80')):
01218         result += ':' + environ['SERVER_PORT']
01219     return result
01220 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.http_date (   timestamp = None)
Formats the time to match the RFC1123 date format.

Accepts a floating point number expressed in seconds since the epoc in, a
datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
function can be used to parse such a date.

Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.

:param timestamp: If provided that date is used, otherwise the current.

Definition at line 1423 of file utils.py.

01423 
01424 def http_date(timestamp=None):
01425     """Formats the time to match the RFC1123 date format.
01426 
01427     Accepts a floating point number expressed in seconds since the epoc in, a
01428     datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
01429     function can be used to parse such a date.
01430 
01431     Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
01432 
01433     :param timestamp: If provided that date is used, otherwise the current.
01434     """
01435     return _dump_date(timestamp, ' ')
01436 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.import_string (   import_name,
  silent = False 
)
Imports an object based on a string.  This is useful if you want to
use import paths as endpoints or something similar.  An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).

If `silent` is True the return value will be `None` if the import fails.

:param import_name: the dotted name for the object to import.
:param silent: if set to `True` import errors are ignored and
               `None` is returned instead.
:return: imported object

Definition at line 1507 of file utils.py.

01507 
01508 def import_string(import_name, silent=False):
01509     """Imports an object based on a string.  This is useful if you want to
01510     use import paths as endpoints or something similar.  An import path can
01511     be specified either in dotted notation (``xml.sax.saxutils.escape``)
01512     or with a colon as object delimiter (``xml.sax.saxutils:escape``).
01513 
01514     If `silent` is True the return value will be `None` if the import fails.
01515 
01516     :param import_name: the dotted name for the object to import.
01517     :param silent: if set to `True` import errors are ignored and
01518                    `None` is returned instead.
01519     :return: imported object
01520     """
01521     try:
01522         if ':' in import_name:
01523             module, obj = import_name.split(':', 1)
01524         elif '.' in import_name:
01525             module, obj = import_name.rsplit('.', 1)
01526         else:
01527             return __import__(import_name)
01528         return getattr(__import__(module, None, None, [obj]), obj)
01529     except (ImportError, AttributeError):
01530         if not silent:
01531             raise
01532 

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.make_line_iter (   stream,
  limit = None,
  buffer_size = 10 * 1024 
)
Savely iterates line-based over an input stream.  If the input stream
is not a :class:`LimitedStream` the `limit` parameter is mandatory.

This uses the stream's :meth:`~file.read` method internally as opposite
to the :meth:`~file.readline` method that is unsafe and can only be used
in violation of the WSGI specification.  The same problem applies to the
`__iter__` function of the input stream which calls :meth:`~file.readline`
without arguments.

If you need line-by-line processing it's strongly recommended to iterate
over the input stream using this helper function.

:param stream: the stream to iterate over.
:param limit: the limit in bytes for the stream.  (Usually
              content length.  Not necessary if the `stream`
              is a :class:`LimitedStream`.
:param buffer_size: The optional buffer size.

Definition at line 391 of file utils.py.

00391 
00392 def make_line_iter(stream, limit=None, buffer_size=10 * 1024):
00393     """Savely iterates line-based over an input stream.  If the input stream
00394     is not a :class:`LimitedStream` the `limit` parameter is mandatory.
00395 
00396     This uses the stream's :meth:`~file.read` method internally as opposite
00397     to the :meth:`~file.readline` method that is unsafe and can only be used
00398     in violation of the WSGI specification.  The same problem applies to the
00399     `__iter__` function of the input stream which calls :meth:`~file.readline`
00400     without arguments.
00401 
00402     If you need line-by-line processing it's strongly recommended to iterate
00403     over the input stream using this helper function.
00404 
00405     :param stream: the stream to iterate over.
00406     :param limit: the limit in bytes for the stream.  (Usually
00407                   content length.  Not necessary if the `stream`
00408                   is a :class:`LimitedStream`.
00409     :param buffer_size: The optional buffer size.
00410     """
00411     if not isinstance(stream, LimitedStream):
00412         if limit is None:
00413             raise TypeError('stream not limited and no limit provided.')
00414         stream = LimitedStream(stream, limit)
00415     buffer = []
00416     while 1:
00417         if len(buffer) > 1:
00418             yield buffer.pop(0)
00419             continue
00420         chunks = stream.read(buffer_size).splitlines(True)
00421         first_chunk = buffer and buffer[0] or ''
00422         if chunks:
00423             first_chunk += chunks.pop(0)
00424         buffer = chunks
00425         if not first_chunk:
00426             return
00427         yield first_chunk
00428 

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.parse_cookie (   header,
  charset = 'utf-8',
  errors = 'ignore',
  cls = None 
)
Parse a cookie.  Either from a string or WSGI environ.

Per default encoding errors are ignored.  If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
:exc:`HTTPUnicodeError` is raised.

.. versionchanged:: 0.5
   This function now returns a :class:`TypeConversionDict` instead of a
   regular dict.  The `cls` parameter was added.

:param header: the header to be used to parse the cookie.  Alternatively
               this can be a WSGI environment.
:param charset: the charset for the cookie values.
:param errors: the error behavior for the charset decoding.
:param cls: an optional dict class to use.  If this is not specified
                   or `None` the default :class:`TypeConversionDict` is
                   used.

Definition at line 1337 of file utils.py.

01337 
01338                  cls=None):
01339     """Parse a cookie.  Either from a string or WSGI environ.
01340 
01341     Per default encoding errors are ignored.  If you want a different behavior
01342     you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
01343     :exc:`HTTPUnicodeError` is raised.
01344 
01345     .. versionchanged:: 0.5
01346        This function now returns a :class:`TypeConversionDict` instead of a
01347        regular dict.  The `cls` parameter was added.
01348 
01349     :param header: the header to be used to parse the cookie.  Alternatively
01350                    this can be a WSGI environment.
01351     :param charset: the charset for the cookie values.
01352     :param errors: the error behavior for the charset decoding.
01353     :param cls: an optional dict class to use.  If this is not specified
01354                        or `None` the default :class:`TypeConversionDict` is
01355                        used.
01356     """
01357     if isinstance(header, dict):
01358         header = header.get('HTTP_COOKIE', '')
01359     if cls is None:
01360         cls = TypeConversionDict
01361     cookie = _ExtendedCookie()
01362     cookie.load(header)
01363     result = {}
01364 
01365     # decode to unicode and skip broken items.  Our extended morsel
01366     # and extended cookie will catch CookieErrors and convert them to
01367     # `None` items which we have to skip here.
01368     for key, value in cookie.iteritems():
01369         if value.value is not None:
01370             result[key] = _decode_unicode(value.value, charset, errors)
01371 
01372     return cls(result)
01373 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.parse_form_data (   environ,
  stream_factory = None,
  charset = 'utf-8',
  errors = 'ignore',
  max_form_memory_size = None,
  max_content_length = None,
  cls = None,
  silent = True 
)
Parse the form data in the environ and return it as tuple in the form
``(stream, form, files)``.  You should only call this method if the
transport method is `POST` or `PUT`.

If the mimetype of the data transmitted is `multipart/form-data` the
files multidict will be filled with `FileStorage` objects.  If the
mimetype is unknown the input stream is wrapped and returned as first
argument, else the stream is empty.

This function does not raise exceptions, even if the input data is
malformed.

Have a look at :ref:`dealing-with-request-data` for more details.

.. versionadded:: 0.5
   The `max_form_memory_size`, `max_content_length` and
   `cls` parameters were added.

.. versionadded:: 0.5.1
   The optional `silent` flag was added.

:param environ: the WSGI environment to be used for parsing.
:param stream_factory: An optional callable that returns a new read and
                       writeable file descriptor.  This callable works
                       the same as :meth:`~BaseResponse._get_file_stream`.
:param charset: The character set for URL and url encoded form data.
:param errors: The encoding error behavior.
:param max_form_memory_size: the maximum number of bytes to be accepted for
                       in-memory stored form data.  If the data
                       exceeds the value specified an
                       :exc:`~exceptions.RequestURITooLarge`
                       exception is raised.
:param max_content_length: If this is provided and the transmitted data
                           is longer than this value an
                           :exc:`~exceptions.RequestEntityTooLarge`
                           exception is raised.
:param cls: an optional dict class to use.  If this is not specified
                   or `None` the default :class:`MultiDict` is used.
:param silent: If set to False parsing errors will not be catched.
:return: A tuple in the form ``(stream, form, files)``.

Definition at line 821 of file utils.py.

00821 
00822                     silent=True):
00823     """Parse the form data in the environ and return it as tuple in the form
00824     ``(stream, form, files)``.  You should only call this method if the
00825     transport method is `POST` or `PUT`.
00826 
00827     If the mimetype of the data transmitted is `multipart/form-data` the
00828     files multidict will be filled with `FileStorage` objects.  If the
00829     mimetype is unknown the input stream is wrapped and returned as first
00830     argument, else the stream is empty.
00831 
00832     This function does not raise exceptions, even if the input data is
00833     malformed.
00834 
00835     Have a look at :ref:`dealing-with-request-data` for more details.
00836 
00837     .. versionadded:: 0.5
00838        The `max_form_memory_size`, `max_content_length` and
00839        `cls` parameters were added.
00840 
00841     .. versionadded:: 0.5.1
00842        The optional `silent` flag was added.
00843 
00844     :param environ: the WSGI environment to be used for parsing.
00845     :param stream_factory: An optional callable that returns a new read and
00846                            writeable file descriptor.  This callable works
00847                            the same as :meth:`~BaseResponse._get_file_stream`.
00848     :param charset: The character set for URL and url encoded form data.
00849     :param errors: The encoding error behavior.
00850     :param max_form_memory_size: the maximum number of bytes to be accepted for
00851                            in-memory stored form data.  If the data
00852                            exceeds the value specified an
00853                            :exc:`~exceptions.RequestURITooLarge`
00854                            exception is raised.
00855     :param max_content_length: If this is provided and the transmitted data
00856                                is longer than this value an
00857                                :exc:`~exceptions.RequestEntityTooLarge`
00858                                exception is raised.
00859     :param cls: an optional dict class to use.  If this is not specified
00860                        or `None` the default :class:`MultiDict` is used.
00861     :param silent: If set to False parsing errors will not be catched.
00862     :return: A tuple in the form ``(stream, form, files)``.
00863     """
00864     content_type, extra = parse_options_header(environ.get('CONTENT_TYPE', ''))
00865     try:
00866         content_length = int(environ['CONTENT_LENGTH'])
00867     except (KeyError, ValueError):
00868         content_length = 0
00869 
00870     if cls is None:
00871         cls = MultiDict
00872 
00873     if max_content_length is not None and content_length > max_content_length:
00874         raise RequestEntityTooLarge()
00875 
00876     stream = _empty_stream
00877     files = ()
00878 
00879     if content_type == 'multipart/form-data':
00880         try:
00881             form, files = parse_multipart(environ['wsgi.input'],
00882                                           extra.get('boundary'),
00883                                           content_length, stream_factory,
00884                                           charset, errors,
00885                                           max_form_memory_size=max_form_memory_size)
00886         except ValueError, e:
00887             if not silent:
00888                 raise
00889             form = cls()
00890         else:
00891             form = cls(form)
00892     elif content_type == 'application/x-www-form-urlencoded' or \
00893          content_type == 'application/x-url-encoded':
00894         if max_form_memory_size is not None and \
00895            content_length > max_form_memory_size:
00896             raise RequestEntityTooLarge()
00897         form = url_decode(environ['wsgi.input'].read(content_length),
00898                           charset, errors=errors, cls=cls)
00899     else:
00900         form = cls()
00901         stream = LimitedStream(environ['wsgi.input'], content_length)
00902 
00903     return stream, form, cls(files)
00904 

Here is the call graph for this function:

Here is the caller graph for this function:

Returns the next segment on the `PATH_INFO` or `None` if there
is none.  Works like :func:`pop_path_info` without modifying the
environment:

>>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> peek_path_info(env)
'a'
>>> peek_path_info(env)
'a'

.. versionadded:: 0.5

:param environ: the WSGI environment that is checked.

Definition at line 1301 of file utils.py.

01301 
01302 def peek_path_info(environ):
01303     """Returns the next segment on the `PATH_INFO` or `None` if there
01304     is none.  Works like :func:`pop_path_info` without modifying the
01305     environment:
01306 
01307     >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
01308     >>> peek_path_info(env)
01309     'a'
01310     >>> peek_path_info(env)
01311     'a'
01312 
01313     .. versionadded:: 0.5
01314 
01315     :param environ: the WSGI environment that is checked.
01316     """
01317     segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1)
01318     if segments:
01319         return segments[0]
01320 

Removes and returns the next segment of `PATH_INFO`, pushing it onto
`SCRIPT_NAME`.  Returns `None` if there is nothing left on `PATH_INFO`.

If there are empty segments (``'/foo//bar``) these are ignored but
properly pushed to the `SCRIPT_NAME`:

>>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> pop_path_info(env)
'a'
>>> env['SCRIPT_NAME']
'/foo/a'
>>> pop_path_info(env)
'b'
>>> env['SCRIPT_NAME']
'/foo/a/b'

.. versionadded:: 0.5

:param environ: the WSGI environment that is modified.

Definition at line 1257 of file utils.py.

01257 
01258 def pop_path_info(environ):
01259     """Removes and returns the next segment of `PATH_INFO`, pushing it onto
01260     `SCRIPT_NAME`.  Returns `None` if there is nothing left on `PATH_INFO`.
01261 
01262     If there are empty segments (``'/foo//bar``) these are ignored but
01263     properly pushed to the `SCRIPT_NAME`:
01264 
01265     >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
01266     >>> pop_path_info(env)
01267     'a'
01268     >>> env['SCRIPT_NAME']
01269     '/foo/a'
01270     >>> pop_path_info(env)
01271     'b'
01272     >>> env['SCRIPT_NAME']
01273     '/foo/a/b'
01274 
01275     .. versionadded:: 0.5
01276 
01277     :param environ: the WSGI environment that is modified.
01278     """
01279     path = environ.get('PATH_INFO')
01280     if not path:
01281         return None
01282 
01283     script_name = environ.get('SCRIPT_NAME', '')
01284 
01285     # shift multiple leading slashes over
01286     old_path = path
01287     path = path.lstrip('/')
01288     if path != old_path:
01289         script_name += '/' * (len(old_path) - len(path))
01290 
01291     if '/' not in path:
01292         environ['PATH_INFO'] = ''
01293         environ['SCRIPT_NAME'] = script_name + path
01294         return path
01295 
01296     segment, path = path.split('/', 1)
01297     environ['PATH_INFO'] = '/' + path
01298     environ['SCRIPT_NAME'] = script_name + segment
01299     return segment
01300 

def MoinMoin.support.werkzeug.utils.redirect (   location,
  code = 302 
)
Return a response object (a WSGI application) that, if called,
redirects the client to the target location.  Supported codes are 301,
302, 303, 305, and 307.  300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a request
with defined If-Modified-Since headers.

:param location: the location the response should redirect to.
:param code: the redirect status code.

Definition at line 1437 of file utils.py.

01437 
01438 def redirect(location, code=302):
01439     """Return a response object (a WSGI application) that, if called,
01440     redirects the client to the target location.  Supported codes are 301,
01441     302, 303, 305, and 307.  300 is not supported because it's not a real
01442     redirect and 304 because it's the answer for a request with a request
01443     with defined If-Modified-Since headers.
01444 
01445     :param location: the location the response should redirect to.
01446     :param code: the redirect status code.
01447     """
01448     assert code in (301, 302, 303, 305, 307), 'invalid code'
01449     from werkzeug.wrappers import BaseResponse
01450     response = BaseResponse(
01451         '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
01452         '<title>Redirecting...</title>\n'
01453         '<h1>Redirecting...</h1>\n'
01454         '<p>You should be redirected automatically to target URL: '
01455         '<a href="%s">%s</a>.  If not click the link.' %
01456         ((escape(location),) * 2), code, mimetype='text/html')
01457     response.headers['Location'] = location
01458     return response
01459 

Here is the call graph for this function:

Here is the caller graph for this function:

Marks a function as responder.  Decorate a function with it and it
will automatically call the return value as WSGI application.

Example::

    @responder
    def application(environ, start_response):
        return Response('Hello World!')

Definition at line 1475 of file utils.py.

01475 
01476 def responder(f):
01477     """Marks a function as responder.  Decorate a function with it and it
01478     will automatically call the return value as WSGI application.
01479 
01480     Example::
01481 
01482         @responder
01483         def application(environ, start_response):
01484             return Response('Hello World!')
01485     """
01486     return _patch_wrapper(f, lambda *a: f(*a)(*a[-2:]))
01487 

Here is the call graph for this function:

def MoinMoin.support.werkzeug.utils.run_wsgi_app (   args,
  kwargs 
)
backwards compatibility.

Definition at line 1683 of file utils.py.

01683 
01684 def run_wsgi_app(*args, **kwargs):
01685     """backwards compatibility."""
01686     from werkzeug.test import run_wsgi_app
01687     return run_wsgi_app(*args, **kwargs)

Definition at line 1122 of file utils.py.

01122 
01123 def secure_filename(filename):
01124     r"""Pass it a filename and it will return a secure version of it.  This
01125     filename can then savely be stored on a regular file system and passed
01126     to :func:`os.path.join`.  The filename returned is an ASCII only string
01127     for maximum portability.
01128 
01129     On windows system the function also makes sure that the file is not
01130     named after one of the special device files.
01131 
01132     >>> secure_filename("My cool movie.mov")
01133     'My_cool_movie.mov'
01134     >>> secure_filename("../../../etc/passwd")
01135     'etc_passwd'
01136     >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
01137     'i_contain_cool_umlauts.txt'
01138 
01139     .. versionadded:: 0.5
01140 
01141     :param filename: the filename to secure
01142     """
01143     if isinstance(filename, unicode):
01144         from unicodedata import normalize
01145         filename = normalize('NFKD', filename).encode('ascii', 'ignore')
01146     for sep in os.path.sep, os.path.altsep:
01147         if sep:
01148             filename = filename.replace(sep, ' ')
01149     filename = str(_filename_ascii_strip_re.sub('', '_'.join(
01150                    filename.split()))).strip('._')
01151 
01152     # on nt a couple of special files are present in each folder.  We
01153     # have to ensure that the target file is not such a filename.  In
01154     # this case we prepend an underline
01155     if os.name == 'nt':
01156         if filename.split('.')[0].upper() in _windows_device_files:
01157             filename = '_' + filename
01158 
01159     return filename
01160 

The reverse function of `escape`.  This unescapes all the HTML
entities, not only the XML entities inserted by `escape`.

:param s: the string to unescape.

Definition at line 1183 of file utils.py.

01183 
01184 def unescape(s):
01185     """The reverse function of `escape`.  This unescapes all the HTML
01186     entities, not only the XML entities inserted by `escape`.
01187 
01188     :param s: the string to unescape.
01189     """
01190     def handle_match(m):
01191         name = m.group(1)
01192         if name in HTMLBuilder._entities:
01193             return unichr(HTMLBuilder._entities[name])
01194         try:
01195             if name[:2] in ('#x', '#X'):
01196                 return unichr(int(name[2:], 16))
01197             elif name.startswith('#'):
01198                 return unichr(int(name[1:]))
01199         except ValueError:
01200             pass
01201         return u''
01202     return _entity_re.sub(handle_match, s)
01203 

def MoinMoin.support.werkzeug.utils.url_decode (   s,
  charset = 'utf-8',
  decode_keys = False,
  include_empty = True,
  errors = 'ignore',
  separator = '&',
  cls = None 
)
Parse a querystring and return it as :class:`MultiDict`.  Per default
only values are decoded into unicode strings.  If `decode_keys` is set to
`True` the same will happen for keys.

Per default a missing value for a key will default to an empty key.  If
you don't want that behavior you can set `include_empty` to `False`.

Per default encoding errors are ignored.  If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
`HTTPUnicodeError` is raised.

.. versionchanged:: 0.5
   In previous versions ";" and "&" could be used for url decoding.
   This changed in 0.5 where only "&" is supported.  If you want to
   use ";" instead a different `separator` can be provided.

   The `cls` parameter was added.

:param s: a string with the query string to decode.
:param charset: the charset of the query string.
:param decode_keys: set to `True` if you want the keys to be decoded
                    as well.
:param include_empty: Set to `False` if you don't want empty values to
                      appear in the dict.
:param errors: the decoding error behavior.
:param separator: the pair separator to be used, defaults to ``&``
:param cls: an optional dict class to use.  If this is not specified
                   or `None` the default :class:`MultiDict` is used.

Definition at line 944 of file utils.py.

00944 
00945                errors='ignore', separator='&', cls=None):
00946     """Parse a querystring and return it as :class:`MultiDict`.  Per default
00947     only values are decoded into unicode strings.  If `decode_keys` is set to
00948     `True` the same will happen for keys.
00949 
00950     Per default a missing value for a key will default to an empty key.  If
00951     you don't want that behavior you can set `include_empty` to `False`.
00952 
00953     Per default encoding errors are ignored.  If you want a different behavior
00954     you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
00955     `HTTPUnicodeError` is raised.
00956 
00957     .. versionchanged:: 0.5
00958        In previous versions ";" and "&" could be used for url decoding.
00959        This changed in 0.5 where only "&" is supported.  If you want to
00960        use ";" instead a different `separator` can be provided.
00961 
00962        The `cls` parameter was added.
00963 
00964     :param s: a string with the query string to decode.
00965     :param charset: the charset of the query string.
00966     :param decode_keys: set to `True` if you want the keys to be decoded
00967                         as well.
00968     :param include_empty: Set to `False` if you don't want empty values to
00969                           appear in the dict.
00970     :param errors: the decoding error behavior.
00971     :param separator: the pair separator to be used, defaults to ``&``
00972     :param cls: an optional dict class to use.  If this is not specified
00973                        or `None` the default :class:`MultiDict` is used.
00974     """
00975     if cls is None:
00976         cls = MultiDict
00977     result = []
00978     for pair in str(s).split(separator):
00979         if not pair:
00980             continue
00981         if '=' in pair:
00982             key, value = pair.split('=', 1)
00983         else:
00984             key = pair
00985             value = ''
00986         key = urllib.unquote_plus(key)
00987         if decode_keys:
00988             key = _decode_unicode(key, charset, errors)
00989         result.append((key, url_unquote_plus(value, charset, errors)))
00990     return cls(result)
00991 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.url_encode (   obj,
  charset = 'utf-8',
  encode_keys = False,
  sort = False,
  key = None,
  separator = '&' 
)
URL encode a dict/`MultiDict`.  If a value is `None` it will not appear
in the result string.  Per default only values are encoded into the target
charset strings.  If `encode_keys` is set to ``True`` unicode keys are
supported too.

If `sort` is set to `True` the items are sorted by `key` or the default
sorting algorithm.

.. versionadded:: 0.5
    `sort`, `key`, and `separator` were added.

:param obj: the object to encode into a query string.
:param charset: the charset of the query string.
:param encode_keys: set to `True` if you have unicode keys.
:param sort: set to `True` if you want parameters to be sorted by `key`.
:param separator: the separator to be used for the pairs.
:param key: an optional function to be used for sorting.  For more details
            check out the :func:`sorted` documentation.

Definition at line 993 of file utils.py.

00993 
00994                separator='&'):
00995     """URL encode a dict/`MultiDict`.  If a value is `None` it will not appear
00996     in the result string.  Per default only values are encoded into the target
00997     charset strings.  If `encode_keys` is set to ``True`` unicode keys are
00998     supported too.
00999 
01000     If `sort` is set to `True` the items are sorted by `key` or the default
01001     sorting algorithm.
01002 
01003     .. versionadded:: 0.5
01004         `sort`, `key`, and `separator` were added.
01005 
01006     :param obj: the object to encode into a query string.
01007     :param charset: the charset of the query string.
01008     :param encode_keys: set to `True` if you have unicode keys.
01009     :param sort: set to `True` if you want parameters to be sorted by `key`.
01010     :param separator: the separator to be used for the pairs.
01011     :param key: an optional function to be used for sorting.  For more details
01012                 check out the :func:`sorted` documentation.
01013     """
01014     if isinstance(obj, MultiDict):
01015         items = obj.lists()
01016     elif isinstance(obj, dict):
01017         items = []
01018         for k, v in obj.iteritems():
01019             if not isinstance(v, (tuple, list)):
01020                 v = [v]
01021             items.append((k, v))
01022     else:
01023         items = obj or ()
01024     if sort:
01025         items.sort(key=key)
01026     tmp = []
01027     for key, values in items:
01028         if encode_keys and isinstance(key, unicode):
01029             key = key.encode(charset)
01030         else:
01031             key = str(key)
01032         for value in values:
01033             if value is None:
01034                 continue
01035             elif isinstance(value, unicode):
01036                 value = value.encode(charset)
01037             else:
01038                 value = str(value)
01039             tmp.append('%s=%s' % (urllib.quote(key),
01040                                   urllib.quote_plus(value)))
01041     return separator.join(tmp)
01042 

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.url_fix (   s,
  charset = 'utf-8' 
)

Definition at line 1101 of file utils.py.

01101 
01102 def url_fix(s, charset='utf-8'):
01103     r"""Sometimes you get an URL by a user that just isn't a real URL because
01104     it contains unsafe characters like ' ' and so on.  This function can fix
01105     some of the problems in a similar way browsers handle data entered by the
01106     user:
01107 
01108     >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
01109     'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
01110 
01111     :param s: the string with the URL to fix.
01112     :param charset: The target charset for the URL if the url was given as
01113                     unicode string.
01114     """
01115     if isinstance(s, unicode):
01116         s = s.encode(charset, 'ignore')
01117     scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
01118     path = urllib.quote(path, '/%')
01119     qs = urllib.quote_plus(qs, ':&=')
01120     return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
01121 

def MoinMoin.support.werkzeug.utils.url_quote (   s,
  charset = 'utf-8',
  safe = '/:' 
)
URL encode a single string with a given encoding.

:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters.

Definition at line 1043 of file utils.py.

01043 
01044 def url_quote(s, charset='utf-8', safe='/:'):
01045     """URL encode a single string with a given encoding.
01046 
01047     :param s: the string to quote.
01048     :param charset: the charset to be used.
01049     :param safe: an optional sequence of safe characters.
01050     """
01051     if isinstance(s, unicode):
01052         s = s.encode(charset)
01053     elif not isinstance(s, str):
01054         s = str(s)
01055     return urllib.quote(s, safe=safe)
01056 

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.url_quote_plus (   s,
  charset = 'utf-8',
  safe = '' 
)
URL encode a single string with the given encoding and convert
whitespace to "+".

:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters.

Definition at line 1057 of file utils.py.

01057 
01058 def url_quote_plus(s, charset='utf-8', safe=''):
01059     """URL encode a single string with the given encoding and convert
01060     whitespace to "+".
01061 
01062     :param s: the string to quote.
01063     :param charset: the charset to be used.
01064     :param safe: an optional sequence of safe characters.
01065     """
01066     if isinstance(s, unicode):
01067         s = s.encode(charset)
01068     elif not isinstance(s, str):
01069         s = str(s)
01070     return urllib.quote_plus(s, safe=safe)
01071 

def MoinMoin.support.werkzeug.utils.url_unquote (   s,
  charset = 'utf-8',
  errors = 'ignore' 
)
URL decode a single string with a given decoding.

Per default encoding errors are ignored.  If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
`HTTPUnicodeError` is raised.

:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding.

Definition at line 1072 of file utils.py.

01072 
01073 def url_unquote(s, charset='utf-8', errors='ignore'):
01074     """URL decode a single string with a given decoding.
01075 
01076     Per default encoding errors are ignored.  If you want a different behavior
01077     you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
01078     `HTTPUnicodeError` is raised.
01079 
01080     :param s: the string to unquote.
01081     :param charset: the charset to be used.
01082     :param errors: the error handling for the charset decoding.
01083     """
01084     return _decode_unicode(urllib.unquote(s), charset, errors)
01085 

Here is the call graph for this function:

def MoinMoin.support.werkzeug.utils.url_unquote_plus (   s,
  charset = 'utf-8',
  errors = 'ignore' 
)
URL decode a single string with the given decoding and decode
a "+" to whitespace.

Per default encoding errors are ignored.  If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
`HTTPUnicodeError` is raised.

:param s: the string to unquote.
:param charset: the charset to be used.
:param errors: the error handling for the charset decoding.

Definition at line 1086 of file utils.py.

01086 
01087 def url_unquote_plus(s, charset='utf-8', errors='ignore'):
01088     """URL decode a single string with the given decoding and decode
01089     a "+" to whitespace.
01090 
01091     Per default encoding errors are ignored.  If you want a different behavior
01092     you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a
01093     `HTTPUnicodeError` is raised.
01094 
01095     :param s: the string to unquote.
01096     :param charset: the charset to be used.
01097     :param errors: the error handling for the charset decoding.
01098     """
01099     return _decode_unicode(urllib.unquote_plus(s), charset, errors)
01100 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.utils.validate_arguments (   func,
  args,
  kwargs,
  drop_extra = True 
)
Check if the function accepts the arguments and keyword arguments.
Returns a new ``(args, kwargs)`` tuple that can savely be passed to
the function without causing a `TypeError` because the function signature
is incompatible.  If `drop_extra` is set to `True` (which is the default)
any extra positional or keyword arguments are dropped automatically.

The exception raised provides three attributes:

`missing`
    A set of argument names that the function expected but where
    missing.

`extra`
    A dict of keyword arguments that the function can not handle but
    where provided.

`extra_positional`
    A list of values that where given by positional argument but the
    function cannot accept.

This can be useful for decorators that forward user submitted data to
a view function::

    from werkzeug import ArgumentValidationError, validate_arguments

    def sanitize(f):
        def proxy(request):
            data = request.values.to_dict()
            try:
                args, kwargs = validate_arguments(f, (request,), data)
            except ArgumentValidationError:
                raise BadRequest('The browser failed to transmit all '
                                 'the data expected.')
            return f(*args, **kwargs)
        return proxy

:param func: the function the validation is performed against.
:param args: a tuple of positional arguments.
:param kwargs: a dict of keyword arguments.
:param drop_extra: set to `False` if you don't want extra arguments
                   to be silently dropped.
:return: tuple in the form ``(args, kwargs)``.

Definition at line 1565 of file utils.py.

01565 
01566 def validate_arguments(func, args, kwargs, drop_extra=True):
01567     """Check if the function accepts the arguments and keyword arguments.
01568     Returns a new ``(args, kwargs)`` tuple that can savely be passed to
01569     the function without causing a `TypeError` because the function signature
01570     is incompatible.  If `drop_extra` is set to `True` (which is the default)
01571     any extra positional or keyword arguments are dropped automatically.
01572 
01573     The exception raised provides three attributes:
01574 
01575     `missing`
01576         A set of argument names that the function expected but where
01577         missing.
01578 
01579     `extra`
01580         A dict of keyword arguments that the function can not handle but
01581         where provided.
01582 
01583     `extra_positional`
01584         A list of values that where given by positional argument but the
01585         function cannot accept.
01586 
01587     This can be useful for decorators that forward user submitted data to
01588     a view function::
01589 
01590         from werkzeug import ArgumentValidationError, validate_arguments
01591 
01592         def sanitize(f):
01593             def proxy(request):
01594                 data = request.values.to_dict()
01595                 try:
01596                     args, kwargs = validate_arguments(f, (request,), data)
01597                 except ArgumentValidationError:
01598                     raise BadRequest('The browser failed to transmit all '
01599                                      'the data expected.')
01600                 return f(*args, **kwargs)
01601             return proxy
01602 
01603     :param func: the function the validation is performed against.
01604     :param args: a tuple of positional arguments.
01605     :param kwargs: a dict of keyword arguments.
01606     :param drop_extra: set to `False` if you don't want extra arguments
01607                        to be silently dropped.
01608     :return: tuple in the form ``(args, kwargs)``.
01609     """
01610     parser = _parse_signature(func)
01611     args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:5]
01612     if missing:
01613         raise ArgumentValidationError(tuple(missing))
01614     elif (extra or extra_positional) and not drop_extra:
01615         raise ArgumentValidationError(None, extra, extra_positional)
01616     return tuple(args), kwargs
01617 

Here is the call graph for this function:

def MoinMoin.support.werkzeug.utils.wrap_file (   environ,
  file,
  buffer_size = 8192 
)
Wraps a file.  This uses the WSGI server's file wrapper if available
or otherwise the generic :class:`FileWrapper`.

.. versionadded:: 0.5

If the file wrapper from the WSGI server is used it's important to not
iterate over it from inside the application but to pass it through
unchanged.  If you want to pass out a file wrapper inside a response
object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`.

More information about file wrappers are available in :pep:`333`.

:param file: a :class:`file`-like object with a :meth:`~file.read` method.
:param buffer_size: number of bytes for one iteration.

Definition at line 1488 of file utils.py.

01488 
01489 def wrap_file(environ, file, buffer_size=8192):
01490     """Wraps a file.  This uses the WSGI server's file wrapper if available
01491     or otherwise the generic :class:`FileWrapper`.
01492 
01493     .. versionadded:: 0.5
01494 
01495     If the file wrapper from the WSGI server is used it's important to not
01496     iterate over it from inside the application but to pass it through
01497     unchanged.  If you want to pass out a file wrapper inside a response
01498     object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`.
01499 
01500     More information about file wrappers are available in :pep:`333`.
01501 
01502     :param file: a :class:`file`-like object with a :meth:`~file.read` method.
01503     :param buffer_size: number of bytes for one iteration.
01504     """
01505     return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size)
01506 

Here is the caller graph for this function:


Variable Documentation

tuple MoinMoin.support.werkzeug.utils._entity_re = re.compile(r'&([^;]+);')

Definition at line 30 of file utils.py.

tuple MoinMoin.support.werkzeug.utils._filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]')

Definition at line 31 of file utils.py.

tuple MoinMoin.support.werkzeug.utils._format_re = re.compile(r'\$(?:(%s)|\{(%s)\})' % (('[a-zA-Z_][a-zA-Z0-9_]*',) * 2))

Definition at line 29 of file utils.py.

Initial value:
00001 ('CON', 'AUX', 'COM1', 'COM2', 'COM3', 'COM4', 'LPT1',
00002                          'LPT2', 'LPT3', 'PRN', 'NUL')

Definition at line 32 of file utils.py.

Definition at line 814 of file utils.py.

Definition at line 815 of file utils.py.