INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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) |
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.... | 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
... |
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(
... |
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... | 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.
Optionally, verify that the host is trusted usin... | 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.
.. versionadded:: 0.9
:param environ: the WSGI environment object to get the query str... | 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.
If the path info could not be determined, `None` is returned.
Some examples:
>>> extract_path_info... | 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.
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 ... | 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.
.. versionadded:: 0.8
.. versionadded:: 0.9
added support for iterators as input stre... | 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:
... |
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.
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... | 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.
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... | 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:
>>> 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... | 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.
On windows systems the function also makes sure that the file i... | 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.
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 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.
Packages are not returned unless `include_packages` is `True`. This can
also recursive... | 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... | 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 o... | 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.
: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 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.
: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... | 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)``
Always obeys the grammar
parts = ( begin_form cont* end |
begin_file cont* end )* | 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::
@Request.application
def my... | 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 t... | 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.
.. versionadded:: 0.9 | 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... |
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.
:param attrs: Mapping of class attributes
:param type field_class: Base field class
:param bool pop: Remove matching fields | 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__``.
:param type klass: Class whose fields to retrieve
:param type field_class: Base field... | 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
By doing this after constructing the class, we let standard inheritance
do all the hard work. | 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 ... |
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 obj: The actual object(s) from which the fields are taken from
:param dict fields_dict: Mapping of field names to :class:`Field` objects.
:param ErrorStore... | 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... |
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 data passed to ``getter_func``.
:param str field_name: Field name.
:param... | 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... |
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.
:return: A dict of serialized data
:rty... | 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.
: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`` string
:rtype: str
.. versionadded:: 1.0.0... | 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`... |
Deserialize ``data`` based on the schema defined by ``fields_dict``.
:param dict data: The data to deserialize.
:param dict fields_dict: Mapping of field names to :class:`Field` objects.
:param ErrorStore error_store: Structure to store errors.
:param bool many: Set to `True` if ``data`... | def _deserialize(
self, data, fields_dict, error_store, many=False, partial=False,
unknown=RAISE, dict_class=dict, index_errors=True, index=None,
):
"""Deserialize ``data`` based on the schema defined by ``fields_dict``.
:param dict data: The data to deserialize.
:param dict... |
Deserialize a data structure to an object defined by this Schema's fields.
:param dict data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
value for `self.many` is used.
:param bool|tuple partial: Whether to ignore missing f... | def load(self, data, many=None, partial=None, unknown=None):
"""Deserialize a data structure to an object defined by this Schema's fields.
:param dict data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
value for `self.many`... |
Same as :meth:`load`, except it takes a JSON string as input.
:param str json_data: A JSON string of the data to deserialize.
:param bool many: Whether to deserialize `obj` as a collection. If `None`, the
value for `self.many` is used.
:param bool|tuple partial: Whether to ignore mi... | def loads(
self, json_data, many=None, partial=None, unknown=None,
**kwargs
):
"""Same as :meth:`load`, except it takes a JSON string as input.
:param str json_data: A JSON string of the data to deserialize.
:param bool many: Whether to deserialize `obj` as a collection. If ... |
Validate `data` against the schema, returning a dictionary of
validation errors.
:param dict data: The data to validate.
:param bool many: Whether to validate `data` as a collection. If `None`, the
value for `self.many` is used.
:param bool|tuple partial: Whether to ignore m... | def validate(self, data, many=None, partial=None):
"""Validate `data` against the schema, returning a dictionary of
validation errors.
:param dict data: The data to validate.
:param bool many: Whether to validate `data` as a collection. If `None`, the
value for `self.many` i... |
Deserialize `data`, returning the deserialized result.
:param data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
value for `self.many` is used.
:param bool|tuple partial: Whether to validate required fields. If its value is... | def _do_load(
self, data, many=None, partial=None, unknown=None,
postprocess=True,
):
"""Deserialize `data`, returning the deserialized result.
:param data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
v... |
Apply then flatten nested schema options | def _normalize_nested_options(self):
"""Apply then flatten nested schema options"""
if self.only is not None:
# Apply the only option to nested fields.
self.__apply_nested_option('only', self.only, 'intersection')
# Remove the child field names from the only option.
... |
Apply nested options to nested fields | def __apply_nested_option(self, option_name, field_names, set_operation):
"""Apply nested options to nested fields"""
# Split nested field names on the first dot.
nested_fields = [name.split('.', 1) for name in field_names if '.' in name]
# Partition the nested field names by parent fiel... |
Update fields based on schema options. | def _init_fields(self):
"""Update fields based on schema options."""
if self.opts.fields:
available_field_names = self.set_class(self.opts.fields)
else:
available_field_names = self.set_class(self.declared_fields.keys())
if self.opts.additional:
... |
Bind field to the schema, setting any necessary attributes on the
field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was
specified in ``class Meta``. | def _bind_field(self, field_name, field_obj):
"""Bind field to the schema, setting any necessary attributes on the
field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was
specified in ``class Meta``.
"""
try:
if field_nam... |
Register a schema-level validator.
By default, receives a single object at a time, regardless of whether ``many=True``
is passed to the `Schema`. If ``pass_many=True``, the raw data (which may be a collection)
and the value for ``many`` is passed.
If ``pass_original=True``, the original data (before u... | def validates_schema(
fn=None,
pass_many=False,
pass_original=False,
skip_on_field_errors=True,
):
"""Register a schema-level validator.
By default, receives a single object at a time, regardless of whether ``many=True``
is passed to the `Schema`. If ``pass_many=True``, the raw data (which ... |
Register a method to invoke after serializing an object. The method
receives the serialized object and returns the processed object.
By default, receives a single object at a time, transparently handling the ``many``
argument passed to the Schema. If ``pass_many=True``, the raw data
(which may be a col... | def post_dump(fn=None, pass_many=False, pass_original=False):
"""Register a method to invoke after serializing an object. The method
receives the serialized object and returns the processed object.
By default, receives a single object at a time, transparently handling the ``many``
argument passed to th... |
Register a method to invoke after deserializing an object. The method
receives the deserialized data and returns the processed data.
By default, receives a single datum at a time, transparently handling the ``many``
argument passed to the Schema. If ``pass_many=True``, the raw data
(which may be a coll... | def post_load(fn=None, pass_many=False, pass_original=False):
"""Register a method to invoke after deserializing an object. The method
receives the deserialized data and returns the processed data.
By default, receives a single datum at a time, transparently handling the ``many``
argument passed to the... |
Mark decorated function as a hook to be picked up later.
.. note::
Currently only works with functions and instance methods. Class and
static methods are not supported.
:return: Decorated function if supplied, else this decorator with its args
bound. | def set_hook(fn, key, **kwargs):
"""Mark decorated function as a hook to be picked up later.
.. note::
Currently only works with functions and instance methods. Class and
static methods are not supported.
:return: Decorated function if supplied, else this decorator with its args
bo... |
Return a generator over the (value, label) pairs, where value
is a string associated with each choice. This convenience method
is useful to populate, for instance, a form select field.
:param valuegetter: Can be a callable or a string. In the former case, it must
be a one-argument c... | def options(self, valuegetter=text_type):
"""Return a generator over the (value, label) pairs, where value
is a string associated with each choice. This convenience method
is useful to populate, for instance, a form select field.
:param valuegetter: Can be a callable or a string. In the... |
Deeply merge two error messages.
The format of ``errors1`` and ``errors2`` matches the ``message``
parameter of :exc:`marshmallow.exceptions.ValidationError`. | def merge_errors(errors1, errors2):
"""Deeply merge two error messages.
The format of ``errors1`` and ``errors2`` matches the ``message``
parameter of :exc:`marshmallow.exceptions.ValidationError`.
"""
if not errors1:
return errors2
if not errors2:
return errors1
if isinstan... |
Add a class to the registry of serializer classes. When a class is
registered, an entry for both its classname and its full, module-qualified
path are added to the registry.
Example: ::
class MyClass:
pass
register('MyClass', MyClass)
# Registry:
# {
# ... | def register(classname, cls):
"""Add a class to the registry of serializer classes. When a class is
registered, an entry for both its classname and its full, module-qualified
path are added to the registry.
Example: ::
class MyClass:
pass
register('MyClass', MyClass)
... |
Retrieve a class from the registry.
:raises: marshmallow.exceptions.RegistryError if the class cannot be found
or if there are multiple entries for the given class name. | def get_class(classname, all=False):
"""Retrieve a class from the registry.
:raises: marshmallow.exceptions.RegistryError if the class cannot be found
or if there are multiple entries for the given class name.
"""
try:
classes = _registry[classname]
except KeyError:
raise Re... |
Return the value for a given key from an object.
:param object obj: The object to get the value from
:param str attr: The attribute/key in `obj` to get the value from.
:param callable accessor: A callable used to retrieve the value of `attr` from
the object `obj`. Defaults to `marsh... | def get_value(self, obj, attr, accessor=None, default=missing_):
"""Return the value for a given key from an object.
:param object obj: The object to get the value from
:param str attr: The attribute/key in `obj` to get the value from.
:param callable accessor: A callable used to retrie... |
Perform validation on ``value``. Raise a :exc:`ValidationError` if validation
does not succeed. | def _validate(self, value):
"""Perform validation on ``value``. Raise a :exc:`ValidationError` if validation
does not succeed.
"""
errors = []
kwargs = {}
for validator in self.validators:
try:
r = validator(value)
if not isinst... |
Validate missing values. Raise a :exc:`ValidationError` if
`value` should be considered missing. | def _validate_missing(self, value):
"""Validate missing values. Raise a :exc:`ValidationError` if
`value` should be considered missing.
"""
if value is missing_:
if hasattr(self, 'required') and self.required:
self.fail('required')
if value is None:
... |
Pulls the value for the given key from the object, applies the
field's formatting and returns the result.
:param str attr: The attribute or key to get from the object.
:param str obj: The object to pull the key from.
:param callable accessor: Function used to pull values from ``obj``.
... | def serialize(self, attr, obj, accessor=None, **kwargs):
"""Pulls the value for the given key from the object, applies the
field's formatting and returns the result.
:param str attr: The attribute or key to get from the object.
:param str obj: The object to pull the key from.
:p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.