INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
The mimetype ( content type without charset etc. )
def mimetype(self): """The mimetype (content type without charset etc.)""" ct = self.headers.get("content-type") if ct: return ct.split(";")[0].strip()
The mimetype parameters as dict. For example if the content type is text/ html ; charset = utf - 8 the params would be { charset: utf - 8 }.
def mimetype_params(self): """The mimetype parameters as dict. For example if the content type is ``text/html; charset=utf-8`` the params would be ``{'charset': 'utf-8'}``. .. versionadded:: 0.5 """ def on_update(d): self.headers["Content-Type"] = dump_optio...
Index of all pages.
def page_index(request): """Index of all pages.""" letters = {} for page in Page.query.order_by(Page.name): letters.setdefault(page.name.capitalize()[0], []).append(page) return Response( generate_template("page_index.html", letters=sorted(letters.items())) )
Display the recent changes.
def recent_changes(request): """Display the recent changes.""" page = max(1, request.args.get("page", type=int)) query = RevisionedPage.query.order_by(RevisionedPage.revision_id.desc()) return Response( generate_template( "recent_changes.html", pagination=Pagination(query...
Helper function that creates a plnt app.
def make_app(): """Helper function that creates a plnt app.""" from plnt import Plnt database_uri = os.environ.get("PLNT_DATABASE_URI") app = Plnt(database_uri or "sqlite:////tmp/plnt.db") app.bind_to_context() return app
Initialize the database
def initdb(): """Initialize the database""" from plnt.database import Blog, session make_app().init_database() # and now fill in some python blogs everybody should read (shamelessly # added my own blog too) blogs = [ Blog( "Armin Ronacher", "http://lucumr.pocoo.o...
Start a new development server.
def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes): """Start a new development server.""" app = make_app() reloader = not no_reloader evalex = not no_evalex run_simple( hostname, port, app, use_reloader=reloader, use_debugger=...
Iterates over the items of a mapping yielding keys and values without dropping any from more complex structures.
def iter_multi_items(mapping): """Iterates over the items of a mapping yielding keys and values without dropping any from more complex structures. """ if isinstance(mapping, MultiDict): for item in iteritems(mapping, multi=True): yield item elif isinstance(mapping, dict): ...
Return the default value if the requested data doesn t exist. If type is provided and is a callable it should convert the value return it or raise a: exc: ValueError if that is not possible. In this case the function will return the default as if the value was not found:
def get(self, key, default=None, type=None): """Return the default value if the requested data doesn't exist. If `type` is provided and is a callable it should convert the value, return it or raise a :exc:`ValueError` if that is not possible. In this case the function will return the de...
Used internally by the accessor properties.
def _get_cache_value(self, key, empty, type): """Used internally by the accessor properties.""" if type is bool: return key in self if key in self: value = self[key] if value is None: return empty elif type is not None: ...
Used internally by the accessor properties.
def _set_cache_value(self, key, value, type): """Used internally by the accessor properties.""" if type is bool: if value: self[key] = None else: self.pop(key, None) else: if value is None: self.pop(key) ...
Remove a header from the set. This raises an: exc: KeyError if the header is not in the set.
def remove(self, header): """Remove a header from the set. This raises an :exc:`KeyError` if the header is not in the set. .. versionchanged:: 0.5 In older versions a :exc:`IndexError` was raised instead of a :exc:`KeyError` if the object was missing. :param he...
Add all the headers from the iterable to the set.
def update(self, iterable): """Add all the headers from the iterable to the set. :param iterable: updates the set with the items from the iterable. """ inserted_any = False for header in iterable: key = header.lower() if key not in self._set: ...
Return the index of the header in the set or return - 1 if not found.
def find(self, header): """Return the index of the header in the set or return -1 if not found. :param header: the header to be looked up. """ header = header.lower() for idx, item in enumerate(self._headers): if item.lower() == header: return idx ...
Return the index of the header in the set or raise an: exc: IndexError.
def index(self, header): """Return the index of the header in the set or raise an :exc:`IndexError`. :param header: the header to be looked up. """ rv = self.find(header) if rv < 0: raise IndexError(header) return rv
Clear the set.
def clear(self): """Clear the set.""" self._set.clear() del self._headers[:] if self.on_update is not None: self.on_update(self)
Return the set as real python set type. When calling this all the items are converted to lowercase and the ordering is lost.
def as_set(self, preserve_casing=False): """Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. :param preserve_casing: if set to `True` the items in the set returned will have the origina...
Convert the ETags object into a python set. Per default all the weak etags are not part of this set.
def as_set(self, include_weak=False): """Convert the `ETags` object into a python set. Per default all the weak etags are not part of this set.""" rv = set(self._strong) if include_weak: rv.update(self._weak) return rv
When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags otherwise strong only.
def contains_raw(self, etag): """When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.""" etag, weak = unquote_etag(etag) if weak: return self.contains_weak(etag) ...
Convert the etags set into a HTTP header string.
def to_header(self): """Convert the etags set into a HTTP header string.""" if self.star_tag: return "*" return ", ".join( ['"%s"' % x for x in self._strong] + ['W/"%s"' % x for x in self._weak] )
Converts the object back into an HTTP header.
def to_header(self): """Converts the object back into an HTTP header.""" if self.date is not None: return http_date(self.date) if self.etag is not None: return quote_etag(self.etag) return ""
If the range is for bytes the length is not None and there is exactly one range and it is satisfiable it returns a ( start stop ) tuple otherwise None.
def range_for_length(self, length): """If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a ``(start, stop)`` tuple, otherwise `None`. """ if self.units != "bytes" or length is None or len(self.ranges) != 1: ...
Creates a: class: ~werkzeug. datastructures. ContentRange object from the current range and given content length.
def make_content_range(self, length): """Creates a :class:`~werkzeug.datastructures.ContentRange` object from the current range and given content length. """ rng = self.range_for_length(length) if rng is not None: return ContentRange(self.units, rng[0], rng[1], length...
Converts the object back into an HTTP header.
def to_header(self): """Converts the object back into an HTTP header.""" ranges = [] for begin, end in self.ranges: if end is None: ranges.append("%s-" % begin if begin >= 0 else str(begin)) else: ranges.append("%s-%s" % (begin, end - 1)) ...
Converts the object into Content - Range HTTP header based on given length
def to_content_range_header(self, length): """Converts the object into `Content-Range` HTTP header, based on given length """ range_for_length = self.range_for_length(length) if range_for_length is not None: return "%s %d-%d/%d" % ( self.units, ...
Clear the auth info and enable digest auth.
def set_digest( self, realm, nonce, qop=("auth",), opaque=None, algorithm=None, stale=False ): """Clear the auth info and enable digest auth.""" d = { "__auth_type__": "digest", "realm": realm, "nonce": nonce, "qop": dump_header(qop), }...
Convert the stored values into a WWW - Authenticate header.
def to_header(self): """Convert the stored values into a WWW-Authenticate header.""" d = dict(self) auth_type = d.pop("__auth_type__", None) or "basic" return "%s %s" % ( auth_type.title(), ", ".join( [ "%s=%s" ...
A static helper function for subclasses to add extra authentication system properties onto a class::
def auth_property(name, doc=None): # noqa: B902 """A static helper function for subclasses to add extra authentication system properties onto a class:: class FooAuthenticate(WWWAuthenticate): special_realm = auth_property('special_realm') For more information have ...
Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB.
def save(self, dst, buffer_size=16384): """Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. ...
Enforce that the WSGI response is a response object of the current type. Werkzeug will use the: class: BaseResponse internally in many situations like the exceptions. If you call: meth: get_response on an exception you will get back a regular: class: BaseResponse object even if you are using a custom subclass.
def force_type(cls, response, environ=None): """Enforce that the WSGI response is a response object of the current type. Werkzeug will use the :class:`BaseResponse` internally in many situations like the exceptions. If you call :meth:`get_response` on an exception you will get back a r...
Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the write () callable returned by the start_response function. This tries to resolve such edge cases automatically. But if you don t get the expect...
def from_app(cls, app, environ, buffered=False): """Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the `write()` callable returned by the `start_response` funct...
Returns the content length if available or None otherwise.
def calculate_content_length(self): """Returns the content length if available or `None` otherwise.""" try: self._ensure_sequence() except RuntimeError: return None return sum(len(x) for x in self.iter_encoded())
Converts the response iterator in a list. By default this happens automatically if required. If implicit_sequence_conversion is disabled this method is not automatically called and some properties might raise exceptions. This also encodes all the items.
def make_sequence(self): """Converts the response iterator in a list. By default this happens automatically if required. If `implicit_sequence_conversion` is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. ...
Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data too.
def set_cookie( self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None, ): """Sets a cookie. The parameters are the same as in the cookie `Morsel` object in th...
Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.
def close(self): """Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it. .. versionadded:: 0.9 Can now be used in a with statement. """ if hasattr(self.response, "close"): self.response...
This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary.
def get_wsgi_headers(self, environ): """This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the loc...
Returns the final WSGI response as tuple. The first item in the tuple is the application iterator the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment is HEAD the response will be empty an...
def get_wsgi_response(self, environ): """Returns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the...
Returns a binary digest for the PBKDF2 hash algorithm of data with the given salt. It iterates iterations times and produces a key of keylen bytes. By default SHA - 256 is used as hash function ; a different hashlib hashfunc can be provided.
def pbkdf2_bin( data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS, keylen=None, hashfunc=None ): """Returns a binary digest for the PBKDF2 hash algorithm of `data` with the given `salt`. It iterates `iterations` times and produces a key of `keylen` bytes. By default, SHA-256 is used as hash function; ...
Internal password hash helper. Supports plaintext without salt unsalted and salted passwords. In case salted passwords are used hmac is used.
def _hash_internal(method, salt, password): """Internal password hash helper. Supports plaintext without salt, unsalted and salted passwords. In case salted passwords are used hmac is used. """ if method == "plain": return password, method if isinstance(password, text_type): p...
Safely join directory and one or more untrusted pathnames. If this cannot be done this function returns None.
def safe_join(directory, *pathnames): """Safely join `directory` and one or more untrusted `pathnames`. If this cannot be done, this function returns ``None``. :param directory: the base directory. :param pathnames: the untrusted pathnames relative to that directory. """ parts = [directory] ...
Generates an adhoc SSL context for the development server.
def generate_adhoc_ssl_context(): """Generates an adhoc SSL context for the development server.""" crypto = _get_openssl_crypto_module() import tempfile import atexit cert, pkey = generate_adhoc_ssl_pair() cert_handle, cert_file = tempfile.mkstemp() pkey_handle, pkey_file = tempfile.mkstemp...
Loads SSL context from cert/ private key files and optional protocol. Many parameters are directly taken from the API of: py: class: ssl. SSLContext.
def load_ssl_context(cert_file, pkey_file=None, protocol=None): """Loads SSL context from cert/private key files and optional protocol. Many parameters are directly taken from the API of :py:class:`ssl.SSLContext`. :param cert_file: Path of the certificate to use. :param pkey_file: Path of the priv...
Checks if the given error ( or the current one ) is an SSL error.
def is_ssl_error(error=None): """Checks if the given error (or the current one) is an SSL error.""" exc_types = (ssl.SSLError,) try: from OpenSSL.SSL import Error exc_types += (Error,) except ImportError: pass if error is None: error = sys.exc_info()[1] return i...
Return AF_INET4 AF_INET6 or AF_UNIX depending on the host and port.
def select_address_family(host, port): """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on the host and port.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with an...
Return a fully qualified socket address that can be passed to: func: socket. bind.
def get_sockaddr(host, port, family): """Return a fully qualified socket address that can be passed to :func:`socket.bind`.""" if family == af_unix: return host.split("://", 1)[1] try: res = socket.getaddrinfo( host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP ...
Start a WSGI application. Optional features include a reloader multithreading and fork support.
def run_simple( hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, reloader_type="auto", threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, s...
A simple command - line interface for: py: func: run_simple.
def main(): """A simple command-line interface for :py:func:`run_simple`.""" # in contrast to argparse, this works at least under Python < 2.7 import optparse from .utils import import_string parser = optparse.OptionParser(usage="Usage: %prog [options] app_module:app_object") parser.add_option...
Handles a request ignoring dropped connections.
def handle(self): """Handles a request ignoring dropped connections.""" rv = None try: rv = BaseHTTPRequestHandler.handle(self) except (_ConnectionError, socket.timeout) as e: self.connection_dropped(e) except Exception as e: if self.server.ssl...
A horrible horrible way to kill the server for Python 2. 6 and later. It s the best we can do.
def initiate_shutdown(self): """A horrible, horrible way to kill the server for Python 2.6 and later. It's the best we can do. """ # Windows does not provide SIGKILL, go with SIGTERM then. sig = getattr(signal, "SIGKILL", signal.SIGTERM) # reloader active if is_r...
Handle a single HTTP request.
def handle_one_request(self): """Handle a single HTTP request.""" self.raw_requestline = self.rfile.readline() if not self.raw_requestline: self.close_connection = 1 elif self.parse_request(): return self.run_wsgi()
Send the response header and log the response code.
def send_response(self, code, message=None): """Send the response header and log the response code.""" self.log_request(code) if message is None: message = code in self.responses and self.responses[code][0] or "" if self.request_version != "HTTP/0.9": hdr = "%s %d...
Get an iterable list of key/ value pairs representing headers.
def get_header_items(self): """ Get an iterable list of key/value pairs representing headers. This function provides Python 2/3 compatibility as related to the parsing of request headers. Python 2.7 is not compliant with RFC 3875 Section 4.1.18 which requires multiple values for...
Check if there is a handler in the logging chain that will handle the given logger s effective level.
def _has_level_handler(logger): """Check if there is a handler in the logging chain that will handle the given logger's effective level. """ level = logger.getEffectiveLevel() current = logger while current: if any(handler.level <= level for handler in current.handlers): ret...
Log a message to the werkzeug logger.
def _log(type, message, *args, **kwargs): """Log a message to the 'werkzeug' logger. The logger is created the first time it is needed. If there is no level set, it is set to :data:`logging.INFO`. If there is no handler for the logger's effective level, a :class:`logging.StreamHandler` is added. ...
Return a signature object for the function.
def _parse_signature(func): """Return a signature object for the function.""" if hasattr(func, "im_func"): func = func.im_func # if we have a cached validator for this function, return it parse = _signature_cache.get(func) if parse is not None: return parse # inspect the functi...
Converts a timetuple integer or datetime object into the seconds from epoch in utc.
def _date_to_unix(arg): """Converts a timetuple, integer or datetime object into the seconds from epoch in utc. """ if isinstance(arg, datetime): arg = arg.utctimetuple() elif isinstance(arg, integer_types + (float,)): return int(arg) year, month, day, hour, minute, second = arg[...
Lowlevel cookie parsing facility that operates on bytes.
def _cookie_parse_impl(b): """Lowlevel cookie parsing facility that operates on bytes.""" i = 0 n = len(b) while i < n: match = _cookie_re.search(b + b";", i) if not match: break key = match.group("key").strip() value = match.group("val") or b"" i = ...
Like the name says. But who knows how it works?
def _easteregg(app=None): """Like the name says. But who knows how it works?""" def bzzzzzzz(gyver): import base64 import zlib return zlib.decompress(base64.b64decode(gyver)).decode("ascii") gyver = u"\n".join( [ x + (77 - len(x)) * u" " for x in b...
Given an application object this returns a semi - stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns None.
def get_pin_and_cookie_name(app): """Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in th...
The name of the pin cookie.
def pin_cookie_name(self): """The name of the pin cookie.""" if not hasattr(self, "_pin_cookie"): self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app) return self._pin_cookie
Execute a command in a console.
def execute_command(self, request, command, frame): """Execute a command in a console.""" return Response(frame.console.eval(command), mimetype="text/html")
Display a standalone shell.
def display_console(self, request): """Display a standalone shell.""" if 0 not in self.frames: if self.console_init_func is None: ns = {} else: ns = dict(self.console_init_func()) ns.setdefault("app", self.app) self.frames[0...
Return a static resource from the shared folder.
def get_resource(self, request, filename): """Return a static resource from the shared folder.""" filename = join("shared", basename(filename)) try: data = pkgutil.get_data(__package__, filename) except OSError: data = None if data is not None: ...
Checks if the request passed the pin test. This returns True if the request is trusted on a pin/ cookie basis and returns False if not. Additionally if the cookie s stored pin hash is wrong it will return None so that appropriate action can be taken.
def check_pin_trust(self, environ): """Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be...
Authenticates with the pin.
def pin_auth(self, request): """Authenticates with the pin.""" exhausted = False auth = False trust = self.check_pin_trust(request.environ) # If the trust return value is `None` it means that the cookie is # set but the stored pin hash value is bad. This means that the ...
Log the pin if needed.
def log_pin_request(self): """Log the pin if needed.""" if self.pin_logging and self.pin is not None: _log( "info", " * To enable the debugger you need to enter the security pin:" ) _log("info", " * Debugger pin code: %s" % self.pin) return Res...
r Unquotes a header value. ( Reversal of: func: quote_header_value ). This does not use the real unquoting but what browsers are actually using for quoting.
def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. .. versionadded:: 0.5 :param value: the header value to unquote. """ if value a...
The reverse function to: func: parse_options_header.
def dump_options_header(header, options): """The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append. """ segments = [] if header is not None: segments.append(header) for key, value in iteritems(options): ...
Dump an HTTP header again. This is the reversal of: func: parse_list_header: func: parse_set_header and: func: parse_dict_header. This also quotes strings that include an equals sign unless you pass it as dict of key value pairs.
def dump_header(iterable, allow_token=True): """Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_heade...
Parse lists of key value pairs as described by RFC 2068 Section 2 and convert them into a python dict ( or any other mapping object created from the type with a dict like interface provided by the cls argument ):
def parse_dict_header(value, cls=dict): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument): >>> d = parse_dict_header('foo="is a fish", ba...
Parse a Content - Type like header into a tuple with the content type and the options:
def parse_options_header(value, multiple=False): """Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should not be used to parse ``Cache-Control`` like headers that u...
Parses an HTTP Accept - * header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction.
def parse_accept_header(value, cls=None): """Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality w...
Parse a cache control header. The RFC differs between response and request cache control this method does not. It s your responsibility to not use the wrong control statements.
def parse_cache_control_header(value, on_update=None, cls=None): """Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements. .. versionadded:: 0.5 The `cls` was added. If n...
Parse a set - like header and return a: class: ~werkzeug. datastructures. HeaderSet object:
def parse_set_header(value, on_update=None): """Parse a set-like header and return a :class:`~werkzeug.datastructures.HeaderSet` object: >>> hs = parse_set_header('token, "quoted value"') The return value is an object that treats the items case-insensitively and keeps the order of the items: ...
Parse an HTTP basic/ digest authorization header transmitted by the web browser. The return value is either None if the header was invalid or not given otherwise an: class: ~werkzeug. datastructures. Authorization object.
def parse_authorization_header(value): """Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization h...
Parse an HTTP WWW - Authenticate header into a: class: ~werkzeug. datastructures. WWWAuthenticate object.
def parse_www_authenticate_header(value, on_update=None): """Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value ...
Parses an if - range header which can be an etag or a date. Returns a: class: ~werkzeug. datastructures. IfRange object.
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. .. versionadded:: 0.7 """ if not value: return IfRange() date = parse_date(value) if date is not None: return IfRange(d...
Parse one of the following date formats into a datetime object:
def parse_date(value): """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...
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 %02d:%02d:%02d GMT" % ( ("Mon", "Tu...
Parses a base - 10 integer count of seconds into a timedelta.
def parse_age(value=None): """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`. """ if not value: retu...
Formats the duration as a base - 10 integer.
def dump_age(age=None): """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). """ if age is None: return if isinstance(age, timedelt...
Convenience method for conditional requests.
def is_resource_modified( environ, etag=None, data=None, last_modified=None, ignore_if_range=True ): """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 alternativel...
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.
def remove_entity_headers(headers, allowed=("expires", "content-location")): """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...
Remove all HTTP/ 1. 1 Hop - by - Hop headers from a list or: class: Headers object. This operation works in - place.
def remove_hop_by_hop_headers(headers): """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. """ headers[:] = [ (key, value) for key, value in headers...
Parse a cookie. Either from a string or WSGI environ.
def parse_cookie(header, charset="utf-8", errors="replace", cls=None): """Parse a cookie. Either from a string or WSGI environ. Per default encoding errors are ignored. If you want a different behavior you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a :exc:`HTTPUnicodeError` is...
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.
def dump_cookie( key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, charset="utf-8", sync_expires=True, max_size=4093, samesite=None, ): """Creates a new Set-Cookie header without the ``Set-Cookie`` prefix The parameter...
Checks if a given byte content range is valid for the given length.
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 elif start is None: return length is None or length >= 0 elif length is None: ...
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"): try: return unichr(int(name[2:], 16)) ...
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 return ( mt == "application/json" or mt.startswith("application/") and mt.endswith("+...
Parse: attr: data as JSON.
def get_json(self, force=False, silent=False, cache=True): """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 it...
Get the real value from a comma - separated header based on the configured number of trusted proxies.
def _get_trusted_comma(self, trusted, value): """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``...
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 exception # but the bozo bit might be defined. feed = feedparser.parse(blog.feed_...
Precompile the translation table for a URL encoding function.
def _make_fast_url_quote(charset="utf-8", errors="strict", safe="/:", unsafe=""): """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: ...
URL decode a single string with the given charset and decode + to whitespace.
def url_unquote_plus(s, charset="utf-8", errors="replace"): """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:`...
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, e.end
Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.
def url_join(base, url, allow_fragments=True): """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. "...
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 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. ...