INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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(self._split_host()[1]))
if 0 <= rv <= 65535:
return rv
except (ValueError, TypeError... |
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. | def get_file_location(self, pathformat=None):
"""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
... |
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.
"""
result = [(request.script_root if request else "") + "/"]
for idx, arg in enumerate(args):
result.append(("/" if idx els... |
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. | def parse_rule(rule):
"""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:
"""
pos = 0
end = len(rule)
do_match = _rule_re.ma... |
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 provided but endpoints expect it. | def is_endpoint_expecting(self, endpoint, *arguments):
"""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 t... |
Iterate over all rules or the rules of an endpoint. | def iter_rules(self, endpoint=None):
"""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
"""
self.update()
if endpoint is not None:
re... |
Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. | def add(self, rulefactory):
"""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`
"""
for rule in rulefactory.get_rules(self):
rule.bind(self)
... |
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 exceptions raised by Werkzeug will contain the full can... | def bind(
self,
server_name,
script_name=None,
subdomain=None,
url_scheme="http",
default_method="GET",
path_info=None,
query_args=None,
):
"""Return a new :class:`MapAdapter` with the details specified to the
call. Note that `script_n... |
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 will use SERVER_NAME and SERVER_PORT ... | def bind_to_environ(self, environ, server_name=None, subdomain=None):
"""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 re... |
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
with self._remap_lock:
if not self._remap:
return
self._rules.sort(k... |
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 display nicer error messages by just catc... | def dispatch(
self, view_func, path_info=None, method=None, catch_http_exceptions=False
):
"""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 ... |
Returns the valid methods that match for a given path. | 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 MethodNotAllowed as e:
return e.valid_methods
except HTTPException:
... |
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 matching is disabled or
a full host name.
"""
if self.map.host_matching:
if domain_part is None:
return self.serv... |
A helper that returns the URL to redirect to if it finds one. This is used for default redirecting only. | 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 only.
:internal:
"""
assert self.map.redirect_defaults
for r in self.map._rules_by_endpoint[rule.endpoi... |
Creates a redirect URL. | 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(
"%s://%s/%s%s"
% (
... |
Helper for: meth: build. Returns subdomain and path for the rule that accepts this endpoint values and method. | def _partial_build(self, endpoint, values, method, append_unknown):
"""Helper for :meth:`build`. Returns subdomain and path for the
rule that accepts this endpoint, values and method.
:internal:
"""
# in case the method is none, try with the default method first
if meth... |
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. | def build(
self,
endpoint,
values=None,
method=None,
force_external=False,
append_unknown=True,
):
"""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... |
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 None:
old_f = f
def f(**kwargs):
rv ... |
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", None)
if stack is None:
return None
elif len(stack) == 1:
release_local(self._l... |
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_response), self.cleanup)
return application |
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 compared with `If-Range` header.
"""
return (
"HTTP_IF_RANGE" not in environ
or not is_resource_modified(
... |
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. | def _process_range_request(self, environ, complete_length=None, accept_ranges=None):
"""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
... |
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. | def make_conditional(
self, request_or_environ, accept_ranges=False, complete_length=None
):
"""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 eta... |
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
pickeling. This buffers the generator if there is one. This also
sets the etag unless `no_etag` is set to `True`.
"""
if not no_etag:
self.add_etag()
supe... |
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. | def get_host(environ, trusted_hosts=None):
"""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.
... |
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. | def get_query_string(environ):
"""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 e... |
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. | def extract_path_info(
environ_or_baseurl,
path_or_url,
charset="utf-8",
errors="werkzeug.url_quote",
collapse_http_schemes=True,
):
"""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 W... |
Safely iterates line - based over an input stream. If the input stream is not a: class: LimitedStream the limit parameter is mandatory. | def make_line_iter(stream, limit=None, buffer_size=10 * 1024, cap_at_buffer=False):
"""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... |
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. | def make_chunk_iter(
stream, separator, limit=None, buffer_size=10 * 1024, cap_at_buffer=False
):
"""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 ma... |
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 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.
"""
if encoding is None:
return False
try:
... |
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. | def get_filesystem_encoding():
"""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:`filesyste... |
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 from modules, all files in folders of already loaded modules
as well as all files reachable through a package.
"""
# The list call is necessary on Python 3 in case the module
# dictionary... |
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 ():
rv.add(os.path.dirname(os.path.abspath(f... |
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_for_reloading():
"""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 progra... |
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
for chunk in chunks:
node = node.setdefault(chunk, {}... |
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 not sys.stdin.isatty():
return
try:
import termios
except ImportError:
return
attr... |
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.signal(signal.SIGTERM, lambda *args: sys.exit(0))
try:
... |
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", " * Restarting with %s" % self.name)
args = _get_args_for_reloading()
# a weird bug on w... |
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 the database session.
sel... |
Returns the full content type string with charset for a mimetype. | def get_content_type(mimetype, charset):
"""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 char... |
Detect which UTF encoding was used to encode the given bytes. | def detect_utf_encoding(data):
"""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.
:in... |
String - template format a string: | def 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 st... |
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. | def secure_filename(filename):
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 funct... |
Replace special characters & < > and ( ) to HTML - safe sequences. | def escape(s):
"""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.
"""
if s ... |
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. | def find_modules(import_path, include_packages=False, recursive=False):
"""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... |
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 or keyword arguments ar... | def validate_arguments(func, args, kwargs, drop_extra=True):
"""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_ext... |
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 a... | def 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 functi... |
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:
day = date(*entry.pub_date.timetuple()[:3]... |
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._getframe(1).f_locals)
else:
rv = gen.dump_object(obj)
sys.stdout._write(rv) |
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_size, mode="wb+")
if total_content_length is... |
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 = getattr(stream, "exhaust", None)
if exhaust is not None:
... |
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", "\n", b"\r", b"\n"]:
return line[:-1], True
return line, False |
Parses the information from the environment as form data. | def parse_from_environ(self, environ):
"""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)``.
"""
content_type = environ.get("CONTENT_TYPE", "")
con... |
Parses the information from the given stream mimetype content length and mimetype parameters. | def parse(self, stream, mimetype, content_length, options=None):
"""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 ... |
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 at least one application that sends additional newlines
before headers (the python setuptools package).
"""
for line in iterator:
if not line:
... |
Generate parts of ( begin_form ( headers name )) ( begin_file ( headers name filename )) ( cont bytestring ) ( end None ) | def parse_lines(self, file, boundary, content_length, cap_at_buffer=True):
"""Generate parts of
``('begin_form', (headers, name))``
``('begin_file', (headers, name, filename))``
``('cont', bytestring)``
``('end', None)``
Always obeys the grammar
parts = ( begin_f... |
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 {}
app = CoolMagicApplication(config)
# static stuff
app = SharedDataMiddleware(
app, {"/public": path.join(... |
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.communicate()[0].splitlines():
line = line.s... |
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.
import werkze... |
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()
for _ in xrange(round... |
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 to cwd",
)
pars... |
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(80))
print("-" * 80)
def _hg... |
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}},
}
).encode("utf-8... |
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 = []
else:
library_frames = sum(frame.is_lib... |
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",
"evalex_trusted": "true" if evalex_trusted else "fals... |
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),
"lines": self.render_line_c... |
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 = compile(code, "<interactive>", mode)
r... |
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:: | def application(cls, f):
"""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::
@Re... |
Method used internally to retrieve submitted data. After calling this sets form and files on the request object to multi dicts filled with the incoming form data. As a matter of fact the input stream will be empty afterwards. You can also call this method to force the parsing of the form data. | def _load_form_data(self):
"""Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards. You can also call this me... |
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. | def close(self):
"""Closes associated resources of this request object. This
closes all file handles explicitly. You can also use the request
object in a with statement which will automatically close it.
.. versionadded:: 0.9
"""
files = self.__dict__.get("files")
... |
A: class: werkzeug. datastructures. CombinedMultiDict that combines: attr: args and: attr: form. | def values(self):
"""A :class:`werkzeug.datastructures.CombinedMultiDict` that combines
:attr:`args` and :attr:`form`."""
args = []
for d in self.args, self.form:
if not isinstance(d, MultiDict):
d = MultiDict(d)
args.append(d)
return Combi... |
A: class: dict with the contents of all cookies transmitted with the request. | def cookies(self):
"""A :class:`dict` with the contents of all cookies transmitted with
the request."""
return parse_cookie(
self.environ,
self.charset,
self.encoding_errors,
cls=self.dict_storage_class,
) |
Requested path as unicode. This works a bit like the regular path info in the WSGI environment but will always include a leading slash even if the URL root is accessed. | def path(self):
"""Requested path as unicode. This works a bit like the regular path
info in the WSGI environment but will always include a leading slash,
even if the URL root is accessed.
"""
raw_path = wsgi_decoding_dance(
self.environ.get("PATH_INFO") or "", self.... |
Requested path as unicode including the query string. | def full_path(self):
"""Requested path as unicode, including the query string."""
return self.path + u"?" + to_unicode(self.query_string, self.url_charset) |
The root path of the script without the trailing slash. | def script_root(self):
"""The root path of the script without the trailing slash."""
raw_path = wsgi_decoding_dance(
self.environ.get("SCRIPT_NAME") or "", self.charset, self.encoding_errors
)
return raw_path.rstrip("/") |
Like: attr: url but without the querystring See also:: attr: trusted_hosts. | def base_url(self):
"""Like :attr:`url` but without the querystring
See also: :attr:`trusted_hosts`.
"""
return get_current_url(
self.environ, strip_querystring=True, trusted_hosts=self.trusted_hosts
) |
Just the host with scheme as IRI. See also:: attr: trusted_hosts. | def host_url(self):
"""Just the host with scheme as IRI.
See also: :attr:`trusted_hosts`.
"""
return get_current_url(
self.environ, host_only=True, trusted_hosts=self.trusted_hosts
) |
If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server. | def access_route(self):
"""If a forwarded header exists this is a list of all ip addresses
from the client ip to the last proxy server.
"""
if "HTTP_X_FORWARDED_FOR" in self.environ:
addr = self.environ["HTTP_X_FORWARDED_FOR"].split(",")
return self.list_storage_c... |
Displays the page the user requests. | def on_show(request, page_name):
"""Displays the page the user requests."""
revision_id = request.args.get("rev", type=int)
query = RevisionedPage.query.filter_by(name=page_name)
if revision_id:
query = query.filter_by(revision_id=revision_id)
revision_requested = True
else:
... |
Edit the current revision of a page. | def on_edit(request, page_name):
"""Edit the current revision of a page."""
change_note = error = ""
revision = (
Revision.query.filter(
(Page.name == page_name) & (Page.page_id == Revision.page_id)
)
.order_by(Revision.revision_id.desc())
.first()
)
if re... |
Show the list of recent changes. | def on_log(request, page_name):
"""Show the list of recent changes."""
page = Page.query.filter_by(name=page_name).first()
if page is None:
return page_missing(request, page_name, False)
return Response(generate_template("action_log.html", page=page)) |
Show the diff between two revisions. | def on_diff(request, page_name):
"""Show the diff between two revisions."""
old = request.args.get("old", type=int)
new = request.args.get("new", type=int)
error = ""
diff = page = old_rev = new_rev = None
if not (old and new):
error = "No revisions specified."
else:
revisio... |
Revert an old revision. | def on_revert(request, page_name):
"""Revert an old revision."""
rev_id = request.args.get("rev", type=int)
old_revision = page = None
error = "No such revision"
if request.method == "POST" and request.form.get("cancel"):
return redirect(href(page_name))
if rev_id:
old_revisio... |
Displayed if page or revision does not exist. | def page_missing(request, page_name, revision_requested, protected=False):
"""Displayed if page or revision does not exist."""
return Response(
generate_template(
"page_missing.html",
page_name=page_name,
revision_requested=revision_requested,
protected=pr... |
Start a new interactive python session. | def shell(no_ipython):
"""Start a new interactive python session."""
banner = "Interactive Werkzeug Shell"
namespace = make_shell()
if not no_ipython:
try:
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
sh = InteractiveShellEmb... |
Get fields from a class. If ordered = True fields will sorted by creation index. | def _get_fields(attrs, field_class, pop=False, ordered=False):
"""Get fields from a class. If ordered=True, fields will sorted by creation index.
:param attrs: Mapping of class attributes
:param type field_class: Base field class
:param bool pop: Remove matching fields
"""
fields = [
(f... |
Collect fields from a class following its method resolution order. The class itself is excluded from the search ; only its parents are checked. Get fields from _declared_fields if available else use __dict__. | def _get_fields_by_mro(klass, field_class, ordered=False):
"""Collect fields from a class, following its method resolution order. The
class itself is excluded from the search; only its parents are checked. Get
fields from ``_declared_fields`` if available, else use ``__dict__``.
:param type klass: Clas... |
Add in the decorated processors | def resolve_hooks(self):
"""Add in the decorated processors
By doing this after constructing the class, we let standard inheritance
do all the hard work.
"""
mro = inspect.getmro(self)
hooks = defaultdict(list)
for attr_name in dir(self):
# Need to ... |
Call getter_func with data as its argument and store any ValidationErrors. | def _call_and_store(getter_func, data, field_name, error_store, index=None):
"""Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`.
:param callable getter_func: Function for getting the serialized/deserialized
value from ``data``.
:param data: The d... |
Takes raw data ( a dict list or other object ) and a dict of fields to output and serializes the data based on those fields. | def _serialize(
self, obj, fields_dict, error_store, many=False,
accessor=None, dict_class=dict, index_errors=True,
index=None,
):
"""Takes raw data (a dict, list, or other object) and a dict of
fields to output and serializes the data based on those fields.
:param o... |
Serialize an object to native Python data types according to this Schema s fields. | def dump(self, obj, many=None):
"""Serialize an object to native Python data types according to this
Schema's fields.
:param obj: The object to serialize.
:param bool many: Whether to serialize `obj` as a collection. If `None`, the value
for `self.many` is used.
:ret... |
Same as: meth: dump except return a JSON - encoded string. | def dumps(self, obj, many=None, *args, **kwargs):
"""Same as :meth:`dump`, except return a JSON-encoded string.
:param obj: The object to serialize.
:param bool many: Whether to serialize `obj` as a collection. If `None`, the value
for `self.many` is used.
:return: A ``json`... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.