text
stringlengths
81
112k
Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7 def parse_if_range_header(value): """Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. ...
Parse one of the following date formats into a datetime object: .. sourcecode:: text Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format If parsing fail...
Used for `http_date` and `cookie_date`. def _dump_date(d, delim): """Used for `http_date` and `cookie_date`.""" if d is None: d = gmtime() elif isinstance(d, datetime): d = d.utctimetuple() elif isinstance(d, (integer_types, float)): d = gmtime(d) return "%s, %02d%s%s%s%s %0...
Parses a base-10 integer count of seconds into a timedelta. If parsing fails, the return value is `None`. :param value: a string consisting of an integer represented in base-10 :return: a :class:`datetime.timedelta` object or `None`. def parse_age(value=None): """Parses a base-10 integer count of sec...
Formats the duration as a base-10 integer. :param age: should be an integer number of seconds, a :class:`datetime.timedelta` object, or, if the age is unknown, `None` (default). def dump_age(age=None): """Formats the duration as a base-10 integer. :param age: should be an ...
Convenience method for conditional requests. :param environ: the WSGI environment of the request to be checked. :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :...
Remove all entity headers from a list or :class:`Headers` object. This operation works in-place. `Expires` and `Content-Location` headers are by default not removed. The reason for this is :rfc:`2616` section 10.3.5 which specifies some entity headers that should be sent. .. versionchanged:: 0.5 ...
Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or :class:`Headers` object. This operation works in-place. .. versionadded:: 0.5 :param headers: a list or :class:`Headers` object. def remove_hop_by_hop_headers(headers): """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or :class:`Head...
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 :clas...
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. On Python 3 the return value of this function will be a unicode string, on Python 2 it will be a native string. ...
Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 def is_byte_range_valid(start, stop, length): """Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 """ if (start is None) != (stop is None): return False e...
Expose this function to the web layer. def expose(url_rule, endpoint=None, **kwargs): """Expose this function to the web layer.""" def decorate(f): e = endpoint or f.__name__ endpoints[e] = f url_map.add(Rule(url_rule, endpoint=e, **kwargs)) return f return decorate
Render a template into a response. def render_template(template_name, **context): """Render a template into a response.""" tmpl = jinja_env.get_template(template_name) context["url_for"] = url_for return Response(tmpl.render(context), mimetype="text/html")
Add paragraphs to a text. def nl2p(s): """Add paragraphs to a text.""" return u"\n".join(u"<p>%s</p>" % p for p in _par_re.split(s))
Resolve HTML entities and remove tags from a string. def strip_tags(s): """Resolve HTML entities and remove tags from a string.""" def handle_match(m): name = m.group(1) if name in html_entities: return unichr(html_entities[name]) if name[:2] in ("#x", "#X"): tr...
Check if the mimetype indicates JSON data, either :mimetype:`application/json` or :mimetype:`application/*+json`. def is_json(self): """Check if the mimetype indicates JSON data, either :mimetype:`application/json` or :mimetype:`application/*+json`. """ mt = self.mimetype ...
Parse :attr:`data` as JSON. If the mimetype does not indicate JSON (:mimetype:`application/json`, see :meth:`is_json`), this returns ``None``. If parsing fails, :meth:`on_json_loading_failed` is called and its return value is used as the return value. :param force: Ign...
Get the real value from a comma-separated header based on the configured number of trusted proxies. :param trusted: Number of values to trust in the header. :param value: Header value to parse. :return: The real value, or ``None`` if there are fewer values than the number of...
Performs a synchronization. Articles that are already syncronized aren't touched anymore. def sync(): """ Performs a synchronization. Articles that are already syncronized aren't touched anymore. """ for blog in Blog.query.all(): # parse the feed. feedparser.parse will never given an ex...
Precompile the translation table for a URL encoding function. Unlike :func:`url_quote`, the generated function only takes the string to quote. :param charset: The charset to encode the result with. :param errors: How to handle encoding errors. :param safe: An optional sequence of safe characters t...
URL decode a single string with the given `charset` and decode "+" 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 :exc:`HTTPUnicodeError` is raised. :param s: The string to unquote. ...
Used in :func:`uri_to_iri` after unquoting to re-quote any invalid bytes. def _codec_error_url_quote(e): """Used in :func:`uri_to_iri` after unquoting to re-quote any invalid bytes. """ out = _fast_url_quote(e.object[e.start : e.end]) if PY2: out = out.decode("utf-8") return out, ...
Join a base URL and a possibly relative URL to form an absolute interpretation of the latter. :param base: the base URL for the join operation. :param url: the URL to join. :param allow_fragments: indicates whether fragments should be allowed. def url_join(base, url, allow_fragments=True): """Join...
Works exactly like :attr:`host` but will return a result that is restricted to ASCII. If it finds a netloc that is not ASCII it will attempt to idna decode it. This is useful for socket operations when the URL might include internationalized characters. def ascii_host(self): """Works ...
The port in the URL as an integer if it was present, `None` otherwise. This does not fill in default ports. def port(self): """The port in the URL as an integer if it was present, `None` otherwise. This does not fill in default ports. """ try: rv = int(to_native(se...
Returns a tuple with the location of the file in the form ``(server, location)``. If the netloc is empty in the URL or points to localhost, it's represented as ``None``. The `pathformat` by default is autodetection but needs to be set when working with URLs of a specific system. The s...
Load and generate a template. def generate_template(template_name, **context): """Load and generate a template.""" context.update(href=href, format_datetime=format_datetime) return template_loader.load(template_name).generate(**context)
Simple function for URL generation. Position arguments are used for the URL path and keyword arguments are used for the url parameters. def href(*args, **kw): """ Simple function for URL generation. Position arguments are used for the URL path and keyword arguments are used for the url parameters. ...
Parse a rule and return it as generator. Each iteration yields tuples in the form ``(converter, arguments, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic one. :internal: def parse_rule(rule): """Parse a rule and return it as generator. Each iteration yields tu...
Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not pro...
Iterate over all rules or the rules of an endpoint. :param endpoint: if provided only the rules for that endpoint are returned. :return: an iterator def iter_rules(self, endpoint=None): """Iterate over all rules or the rules of an endpoint. :param endpoint: if...
Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. :param rulefactory: a :class:`Rule` or :class:`RuleFactory` def add(self, rulefactory): """Add a new rule or factory to the map and bind it. Requires that the rule is not bound to an...
Return a new :class:`MapAdapter` with the details specified to the call. Note that `script_name` will default to ``'/'`` if not further specified or `None`. The `server_name` at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect excepti...
Like :meth:`bind` but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real `server_name` from the environment. If you don't provide it, Werkzeug...
Called before matching and building to keep the compiled rules in the correct order after things changed. def update(self): """Called before matching and building to keep the compiled rules in the correct order after things changed. """ if not self._remap: return ...
Does the complete dispatching process. `view_func` is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can di...
Returns the valid methods that match for a given path. .. versionadded:: 0.7 def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method="--") except Method...
Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name. def get_host(self, domain_part): """Figures out the full host name for the given domain part. The domain part is a subdomain in case host mat...
A helper that returns the URL to redirect to if it finds one. This is used for default redirecting only. :internal: def get_default_redirect(self, rule, method, values, query_args): """A helper that returns the URL to redirect to if it finds one. This is used for default redirecting on...
Creates a redirect URL. :internal: def make_redirect_url(self, path_info, query_args=None, domain_part=None): """Creates a redirect URL. :internal: """ suffix = "" if query_args: suffix = "?" + self.encode_query_args(query_args) return str( ...
Helper for :meth:`build`. Returns subdomain and path for the rule that accepts this endpoint, values and method. :internal: def _partial_build(self, endpoint, values, method, append_unknown): """Helper for :meth:`build`. Returns subdomain and path for the rule that accepts this endpo...
Building URLs works pretty much the other way round. Instead of `match` you call `build` and pass it the endpoint and a dict of arguments for the placeholders. The `build` function also accepts an argument called `force_external` which, if you set it to `True` will force external URLs....
Decorator for registering view functions and adding templates to it. def export(string, template=None, **extra): """ Decorator for registering view functions and adding templates to it. """ def wrapped(f): endpoint = (f.__module__ + "." + f.__name__)[16:] if template is not Non...
Pushes a new item to the stack def push(self, obj): """Pushes a new item to the stack""" rv = getattr(self._local, "stack", None) if rv is None: self._local.stack = rv = [] rv.append(obj) return rv
Removes the topmost item from the stack, will return the old value or `None` if the stack was already empty. def pop(self): """Removes the topmost item from the stack, will return the old value or `None` if the stack was already empty. """ stack = getattr(self._local, "stack", N...
Wrap a WSGI application so that cleaning up happens after request end. def make_middleware(self, app): """Wrap a WSGI application so that cleaning up happens after request end. """ def application(environ, start_response): return ClosingIterator(app(environ, start_r...
Wrap existing Response in case of Range Request context. def _wrap_response(self, start, length): """Wrap existing Response in case of Range Request context.""" if self.status_code == 206: self.response = _RangeWrapper(self.response, start, length)
Return ``True`` if `Range` header is present and if underlying resource is considered unchanged when compared with `If-Range` header. def _is_range_request_processable(self, environ): """Return ``True`` if `Range` header is present and if underlying resource is considered unchanged when compare...
Handle Range Request related headers (RFC7233). If `Accept-Ranges` header is valid, and Range Request is processable, we set the headers as described by the RFC, and wrap the underlying response in a RangeWrapper. Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise....
Make the response conditional to the request. This method works best if an etag was defined for the response already. The `add_etag` method can be used to do that. If called without etag just the date header is set. This does nothing if the request method in the request or environ is...
Add an etag for the current response if there is none yet. def add_etag(self, overwrite=False, weak=False): """Add an etag for the current response if there is none yet.""" if overwrite or "etag" not in self.headers: self.set_etag(generate_etag(self.get_data()), weak)
Set the etag, and override the old one if there was one. def set_etag(self, etag, weak=False): """Set the etag, and override the old one if there was one.""" self.headers["ETag"] = quote_etag(etag, weak)
Call this method if you want to make your response object ready for pickeling. This buffers the generator if there is one. This also sets the etag unless `no_etag` is set to `True`. def freeze(self, no_etag=False): """Call this method if you want to make your response object ready for ...
Return the host for the given WSGI environment. This first checks the ``Host`` header. If it's not present, then ``SERVER_NAME`` and ``SERVER_PORT`` are used. The host will only contain the port if it is different than the standard port for the protocol. Optionally, verify that the host is trusted usin...
Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the query str...
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info...
Safely 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 ...
Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline markers. .. versionadded:: 0.8 .. versionadded:: 0.9 added support for iterators as input stre...
Given an encoding this figures out if the encoding is actually ASCII (which is something we don't actually want in most cases). This is necessary because ASCII comes under many names such as ANSI_X3.4-1968. def _is_ascii_encoding(encoding): """Given an encoding this figures out if the encoding is actually ...
Returns the filesystem encoding that should be used. Note that this is different from the Python understanding of the filesystem encoding which might be deeply flawed. Do not use this value against Python's unicode APIs because it might be different. See :ref:`filesystem-encoding` for the exact behavior...
This iterates over all relevant Python files. It goes through all loaded files from modules, all files in folders of already loaded modules as well as all files reachable through a package. def _iter_module_files(): """This iterates over all relevant Python files. It goes through all loaded files fro...
Finds all paths that should be observed. def _find_observable_paths(extra_files=None): """Finds all paths that should be observed.""" rv = set( os.path.dirname(os.path.abspath(x)) if os.path.isfile(x) else os.path.abspath(x) for x in sys.path ) for filename in extra_files or (): ...
Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading. This also contains a workaround for linux where the file is executable (possibly with a program other than python) def _get_args_fo...
Out of some paths it finds the common roots that need monitoring. def _find_common_roots(paths): """Out of some paths it finds the common roots that need monitoring.""" paths = [x.split(os.path.sep) for x in paths] root = {} for chunks in sorted(paths, key=len, reverse=True): node = root ...
Ensure that echo mode is enabled. Some tools such as PDB disable it which causes usability issues after reload. def ensure_echo_on(): """Ensure that echo mode is enabled. Some tools such as PDB disable it which causes usability issues after reload.""" # tcgetattr will fail if stdin isn't a tty if n...
Run the given function in an independent python interpreter. def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type="auto"): """Run the given function in an independent python interpreter.""" import signal reloader = reloader_loops[reloader_type](extra_files, interval) signal.sig...
Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log("info", " *...
Dispatch an incoming request. def dispatch_request(self, environ, start_response): """Dispatch an incoming request.""" # set up all the stuff we want to have for this request. That is # creating a request object, propagating the application to the # current context and instanciating th...
Returns the full content type string with charset for a mimetype. If the mimetype represents text, the charset parameter will be appended, otherwise the mimetype is returned unchanged. :param mimetype: The mimetype to be used as content type. :param charset: The charset to be appended for text mimetyp...
Detect which UTF encoding was used to encode the given bytes. The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big or little endian. Some editors or libraries may prepend a BOM. :internal: :param data: Bytes in unk...
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 v...
r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file i...
Replace special characters "&", "<", ">" and (") to HTML-safe sequences. There is a special handling for `None` which escapes to an empty string. .. versionchanged:: 0.9 `quote` is now implicitly on. :param s: the string to escape. :param quote: ignored. def escape(s): """Replace special ...
Finds 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 recursive...
Checks if the function accepts the arguments and keyword arguments. Returns a new ``(args, kwargs)`` tuple that can safely 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...
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 o...
Show the index page or any an offset of it. def index(request, page): """Show the index page or any an offset of it.""" days = [] days_found = set() query = Entry.query.order_by(Entry.pub_date.desc()) pagination = Pagination(query, PER_PAGE, page, "index") for entry in pagination.entries: ...
Print the object details to stdout._write (for the interactive console of the web debugger. def dump(obj=missing): """Print the object details to stdout._write (for the interactive console of the web debugger. """ gen = DebugReprGenerator() if obj is missing: rv = gen.dump_locals(sys._g...
The stream factory that is used per default. def default_stream_factory( total_content_length, filename, content_type, content_length=None ): """The stream factory that is used per default.""" max_size = 1024 * 500 if SpooledTemporaryFile is not None: return SpooledTemporaryFile(max_size=max_si...
Helper decorator for methods that exhausts the stream on return. def exhaust_stream(f): """Helper decorator for methods that exhausts the stream on return.""" def wrapper(self, stream, *args, **kwargs): try: return f(self, stream, *args, **kwargs) finally: exhaust = get...
Removes line ending characters and returns a tuple (`stripped_line`, `is_terminated`). def _line_parse(line): """Removes line ending characters and returns a tuple (`stripped_line`, `is_terminated`). """ if line[-2:] in ["\r\n", b"\r\n"]: return line[:-2], True elif line[-1:] in ["\r", ...
Parses the information from the environment as form data. :param environ: the WSGI environment to be used for parsing. :return: A tuple in the form ``(stream, form, files)``. def parse_from_environ(self, environ): """Parses the information from the environment as form data. :param env...
Parses the information from the given stream, mimetype, content length and mimetype parameters. :param stream: an input stream :param mimetype: the mimetype of the data :param content_length: the content length of the incoming data :param options: optional mimetype parameters (u...
The terminator might have some additional newlines before it. There is at least one application that sends additional newlines before headers (the python setuptools package). def _find_terminator(self, iterator): """The terminator might have some additional newlines before it. There is ...
Generate parts of ``('begin_form', (headers, name))`` ``('begin_file', (headers, name, filename))`` ``('cont', bytestring)`` ``('end', None)`` Always obeys the grammar parts = ( begin_form cont* end | begin_file cont* end )* def parse_lines(self, file,...
Factory function that creates a new `CoolmagicApplication` object. Optional WSGI middlewares should be applied here. def make_app(config=None): """ Factory function that creates a new `CoolmagicApplication` object. Optional WSGI middlewares should be applied here. """ config = config or {} ...
Returns the current node or tag for the given path. def find_hg_tag(path): """Returns the current node or tag for the given path.""" tags = {} try: client = subprocess.Popen( ["hg", "cat", "-r", "tip", ".hgtags"], stdout=subprocess.PIPE, cwd=path ) for line in client.com...
Load werkzeug. def load_werkzeug(path): """Load werkzeug.""" sys.path[0] = path # get rid of already imported stuff wz.__dict__.clear() for key in sys.modules.keys(): if key.startswith("werkzeug.") or key == "werkzeug": sys.modules.pop(key, None) # import werkzeug again. ...
Times a single function. def bench(func): """Times a single function.""" sys.stdout.write("%44s " % format_func(func)) sys.stdout.flush() # figure out how many times we have to run the function to # get reliable timings. for i in xrange(3, 10): rounds = 1 << i t = timer() ...
The main entrypoint. def main(): """The main entrypoint.""" from optparse import OptionParser parser = OptionParser(usage="%prog [options]") parser.add_option( "--werkzeug-path", "-p", dest="path", default="..", help="the path to the werkzeug package. defaults t...
Compares two Werkzeug hg versions. def compare(node1, node2): """Compares two Werkzeug hg versions.""" if not os.path.isdir("a"): print("error: comparison feature not initialized", file=sys.stderr) sys.exit(4) print("=" * 80) print("WERKZEUG INTERNAL BENCHMARK -- COMPARE MODE".center(8...
Remove the frames according to the paste spec. def filter_hidden_frames(self): """Remove the frames according to the paste spec.""" for group in self.groups: group.filter_hidden_frames() self.frames[:] = [frame for group in self.groups for frame in group.frames]
Log the ASCII traceback into a file object. def log(self, logfile=None): """Log the ASCII traceback into a file object.""" if logfile is None: logfile = sys.stderr tb = self.plaintext.rstrip() + u"\n" logfile.write(to_native(tb, "utf-8", "replace"))
Create a paste and return the paste id. def paste(self): """Create a paste and return the paste id.""" data = json.dumps( { "description": "Werkzeug Internal Server Error", "public": False, "files": {"traceback.txt": {"content": self.plaintext...
Render the traceback for the interactive console. def render_summary(self, include_title=True): """Render the traceback for the interactive console.""" title = "" classes = ["traceback"] if not self.frames: classes.append("noframe-traceback") frames = [] ...
Render the Full HTML page with the traceback info. def render_full(self, evalex=False, secret=None, evalex_trusted=True): """Render the Full HTML page with the traceback info.""" exc = escape(self.exception) return PAGE_HTML % { "evalex": "true" if evalex else "false", "...
String representation of the exception. def exception(self): """String representation of the exception.""" buf = traceback.format_exception_only(self.exc_type, self.exc_value) rv = "".join(buf).strip() return to_unicode(rv, "utf-8", "replace")
Render a single frame in a traceback. def render(self, mark_lib=True): """Render a single frame in a traceback.""" return FRAME_HTML % { "id": self.id, "filename": escape(self.filename), "lineno": self.lineno, "function_name": escape(self.function_name), ...
Evaluate code in the context of the frame. def eval(self, code, mode="single"): """Evaluate code in the context of the frame.""" if isinstance(code, string_types): if PY2 and isinstance(code, text_type): # noqa code = UTF8_COOKIE + code.encode("utf-8") code = co...
Decorate a function as responder that accepts the request as first argument. This works like the :func:`responder` decorator but the function is passed the request object as first argument and the request object will be closed automatically:: @Request.application def my...