INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Ensures that string prices are converted into Price objects.
def price_converter(obj): """Ensures that string prices are converted into Price objects.""" if isinstance(obj, str): obj = PriceClass.parse(obj) return obj
Price field for attrs.
def price(*args, **kwargs): """Price field for attrs. See `help(attr.ib)` for full signature. Usage: >>> from pricing import fields ... @attr.s ... class Test: ... price: Price = fields.price(default='USD 5.00') ... ... Test() Test(price=USD 5.0...
Validate JSON - RPC request.
def validate(self, request): """Validate JSON-RPC request. :param request: RPC request object :type request: dict """ try: validate_version(request) validate_method(request) validate_params(request) validate_id(request) e...
Get request method for service application.
def get_method(self, args): """Get request method for service application.""" try: method = self.app[args['method']] except KeyError: method_not_found(args['id']) else: return method
Apply application method.
def apply(self, method, args): """Apply application method.""" try: params = args['params'] if isinstance(params, dict): result = method(**params) else: result = method(*params) except Exception as error: server_err...
The name of the current module if the request was dispatched to an actual module. This is deprecated functionality use blueprints instead.
def module(self): """The name of the current module if the request was dispatched to an actual module. This is deprecated functionality, use blueprints instead. """ from warnings import warn warn(DeprecationWarning('modules were deprecated in favor of ' ...
The name of the current blueprint
def blueprint(self): """The name of the current blueprint""" if self.url_rule and '.' in self.url_rule.endpoint: return self.url_rule.endpoint.rsplit('.', 1)[0]
Parses the incoming JSON request data and returns it. If parsing fails the: meth: on_json_loading_failed method on the request object will be invoked. By default this function will only load the json data if the mimetype is application/ json but this can be overriden by the force parameter.
def get_json(self, force=False, silent=False, cache=True): """Parses the incoming JSON request data and returns it. If parsing fails the :meth:`on_json_loading_failed` method on the request object will be invoked. By default this function will only load the json data if the mimetype is...
Since Flask 0. 8 we re monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed.
def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key...
Factory to make an abstract dist object.
def make_abstract_dist(req_to_install): """Factory to make an abstract dist object. Preconditions: Either an editable req with a source_dir, or satisfied_by or a wheel link, or a non-editable req with a source_dir. :return: A concrete DistAbstraction. """ if req_to_install.editable: re...
Add install_req as a requirement to install.
def add_requirement(self, install_req, parent_req_name=None): """Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we coul...
Call handler for all pending reqs.
def _walk_req_to_install(self, handler): """Call handler for all pending reqs. :param handler: Handle a single requirement. Should take a requirement to install. Can optionally return an iterable of additional InstallRequirements to cover. """ # The list() here i...
Prepare process. Create temp directories download and/ or unpack files.
def prepare_files(self, finder): """ Prepare process. Create temp directories, download and/or unpack files. """ # make the wheelhouse if self.wheel_download_dir: ensure_dir(self.wheel_download_dir) self._walk_req_to_install( functools.partial(sel...
Check if req_to_install should be skipped.
def _check_skip_installed(self, req_to_install, finder): """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only ...
Prepare a single requirements files.
def _prepare_file(self, finder, req_to_install): """Prepare a single requirements files. :return: A list of addition InstallRequirements to also install. """ # Tell user what we are doing for this requirement: # obtain (editable), skipping, processing (local url), collecting ...
Clean up files remove builds.
def cleanup_files(self): """Clean up files, remove builds.""" logger.debug('Cleaning up...') with indent_log(): for req in self.reqs_to_cleanup: req.remove_temporary_source()
Create the installation order.
def _to_install(self): """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. """ # The current implementation, which we may cha...
Install everything in this set ( after having downloaded and unpacked the packages )
def install(self, install_options, global_options=(), *args, **kwargs): """ Install everything in this set (after having downloaded and unpacked the packages) """ to_install = self._to_install() if to_install: logger.info( 'Installing collecte...
Return sorted list of all package namespaces
def _get_all_ns_packages(self): """Return sorted list of all package namespaces""" nsp = set() for pkg in self.distribution.namespace_packages or []: pkg = pkg.split('.') while pkg: nsp.add('.'.join(pkg)) pkg.pop() return sorted(nsp...
Convert QuerySet objects to their list counter - parts
def default(self, obj): """ Convert QuerySet objects to their list counter-parts """ if isinstance(obj, models.Model): return self.encode(model_to_dict(obj)) elif isinstance(obj, models.query.QuerySet): return serializers.serialize('json', obj) els...
doclist should be ordered from oldest to newest like::
def html_annotate(doclist, markup=default_markup): """ doclist should be ordered from oldest to newest, like:: >>> version1 = 'Hello World' >>> version2 = 'Goodbye World' >>> print(html_annotate([(version1, 'version 1'), ... (version2, 'version 2')])) ...
Tokenize a document and add an annotation attribute to each token
def tokenize_annotated(doc, annotation): """Tokenize a document and add an annotation attribute to each token """ tokens = tokenize(doc, include_hrefs=False) for tok in tokens: tok.annotation = annotation return tokens
Merge the annotations from tokens_old into tokens_new when the tokens in the new document already existed in the old document.
def html_annotate_merge_annotations(tokens_old, tokens_new): """Merge the annotations from tokens_old into tokens_new, when the tokens in the new document already existed in the old document. """ s = InsensitiveSequenceMatcher(a=tokens_old, b=tokens_new) commands = s.get_opcodes() for command,...
Copy annotations from the tokens listed in src to the tokens in dest
def copy_annotations(src, dest): """ Copy annotations from the tokens listed in src to the tokens in dest """ assert len(src) == len(dest) for src_tok, dest_tok in zip(src, dest): dest_tok.annotation = src_tok.annotation
Combine adjacent tokens when there is no HTML between the tokens and they share an annotation
def compress_tokens(tokens): """ Combine adjacent tokens when there is no HTML between the tokens, and they share an annotation """ result = [tokens[0]] for tok in tokens[1:]: if (not result[-1].post_tags and not tok.pre_tags and result[-1].annotation == tok....
Merge tok into the last element of tokens ( modifying the list of tokens in - place ).
def compress_merge_back(tokens, tok): """ Merge tok into the last element of tokens (modifying the list of tokens in-place). """ last = tokens[-1] if type(last) is not token or type(tok) is not token: tokens.append(tok) else: text = _unicode(last) if last.trailing_whitespa...
Serialize the list of tokens into a list of text chunks calling markup_func around text to add annotations.
def markup_serialize_tokens(tokens, markup_func): """ Serialize the list of tokens into a list of text chunks, calling markup_func around text to add annotations. """ for token in tokens: for pre in token.pre_tags: yield pre html = token.html() html = markup_func(...
Do a diff of the old and new document. The documents are HTML * fragments * ( str/ UTF8 or unicode ) they are not complete documents ( i. e. no <html > tag ).
def htmldiff(old_html, new_html): ## FIXME: this should take parsed documents too, and use their body ## or other content. """ Do a diff of the old and new document. The documents are HTML *fragments* (str/UTF8 or unicode), they are not complete documents (i.e., no <html> tag). Returns HTML wi...
Does a diff on the tokens themselves returning a list of text chunks ( not tokens ).
def htmldiff_tokens(html1_tokens, html2_tokens): """ Does a diff on the tokens themselves, returning a list of text chunks (not tokens). """ # There are several passes as we do the differences. The tokens # isolate the portion of the content we care to diff; difflib does # all the actual hard w...
Given a list of tokens return a generator of the chunks of text for the data in the tokens.
def expand_tokens(tokens, equal=False): """Given a list of tokens, return a generator of the chunks of text for the data in the tokens. """ for token in tokens: for pre in token.pre_tags: yield pre if not equal or not token.hide_when_equal: if token.trailing_white...
doc is the already - handled document ( as a list of text chunks ) ; here we add <ins > ins_chunks</ ins > to the end of that.
def merge_insert(ins_chunks, doc): """ doc is the already-handled document (as a list of text chunks); here we add <ins>ins_chunks</ins> to the end of that. """ # Though we don't throw away unbalanced_start or unbalanced_end # (we assume there is accompanying markup later or earlier in the # docume...
Adds the text chunks in del_chunks to the document doc ( another list of text chunks ) with marker to show it is a delete. cleanup_delete later resolves these markers into <del > tags.
def merge_delete(del_chunks, doc): """ Adds the text chunks in del_chunks to the document doc (another list of text chunks) with marker to show it is a delete. cleanup_delete later resolves these markers into <del> tags.""" doc.append(DEL_START) doc.extend(del_chunks) doc.append(DEL_END)
Cleans up any DEL_START/ DEL_END markers in the document replacing them with <del > </ del >. To do this while keeping the document valid it may need to drop some tags ( either start or end tags ).
def cleanup_delete(chunks): """ Cleans up any DEL_START/DEL_END markers in the document, replacing them with <del></del>. To do this while keeping the document valid, it may need to drop some tags (either start or end tags). It may also move the del into adjacent tags to try to move it to a simila...
Return ( unbalanced_start balanced unbalanced_end ) where each is a list of text and tag chunks.
def split_unbalanced(chunks): """Return (unbalanced_start, balanced, unbalanced_end), where each is a list of text and tag chunks. unbalanced_start is a list of all the tags that are opened, but not closed in this span. Similarly, unbalanced_end is a list of tags that are closed but were not opene...
Returns ( stuff_before_DEL_START stuff_inside_DEL_START_END stuff_after_DEL_END ). Returns the first case found ( there may be more DEL_STARTs in stuff_after_DEL_END ). Raises NoDeletes if there s no DEL_START found.
def split_delete(chunks): """ Returns (stuff_before_DEL_START, stuff_inside_DEL_START_END, stuff_after_DEL_END). Returns the first case found (there may be more DEL_STARTs in stuff_after_DEL_END). Raises NoDeletes if there's no DEL_START found. """ try: pos = chunks.index(DEL_START) ex...
pre_delete and post_delete implicitly point to a place in the document ( where the two were split ). This moves that point ( by popping items from one and pushing them onto the other ). It moves the point to try to find a place where unbalanced_start applies.
def locate_unbalanced_start(unbalanced_start, pre_delete, post_delete): """ pre_delete and post_delete implicitly point to a place in the document (where the two were split). This moves that point (by popping items from one and pushing them onto the other). It moves the point to try to find a place wh...
like locate_unbalanced_start except handling end tags and possibly moving the point earlier in the document.
def locate_unbalanced_end(unbalanced_end, pre_delete, post_delete): """ like locate_unbalanced_start, except handling end tags and possibly moving the point earlier in the document. """ while 1: if not unbalanced_end: # Success break finding = unbalanced_end[-1] ...
Parse the given HTML and returns token objects ( words with attached tags ).
def tokenize(html, include_hrefs=True): """ Parse the given HTML and returns token objects (words with attached tags). This parses only the content of a page; anything in the head is ignored, and the <head> and <body> elements are themselves optional. The content is then parsed by lxml, which ensu...
Parses an HTML fragment returning an lxml element. Note that the HTML will be wrapped in a <div > tag that was not in the original document.
def parse_html(html, cleanup=True): """ Parses an HTML fragment, returning an lxml element. Note that the HTML will be wrapped in a <div> tag that was not in the original document. If cleanup is true, make sure there's no <head> or <body>, and get rid of any <ins> and <del> tags. """ if cl...
This cleans the HTML meaning that any page structure is removed ( only the contents of <body > are used if there is any <body ). Also <ins > and <del > tags are removed.
def cleanup_html(html): """ This 'cleans' the HTML, meaning that any page structure is removed (only the contents of <body> are used, if there is any <body). Also <ins> and <del> tags are removed. """ match = _body_re.search(html) if match: html = html[match.end():] match = _end_body_re...
This function takes a word such as test \ n \ n and returns ( test \ n \ n )
def split_trailing_whitespace(word): """ This function takes a word, such as 'test\n\n' and returns ('test','\n\n') """ stripped_length = len(word.rstrip()) return word[0:stripped_length], word[stripped_length:]
This function takes a list of chunks and produces a list of tokens.
def fixup_chunks(chunks): """ This function takes a list of chunks and produces a list of tokens. """ tag_accum = [] cur_word = None result = [] for chunk in chunks: if isinstance(chunk, tuple): if chunk[0] == 'img': src = chunk[1] tag, tra...
Takes an lxml element el and generates all the text chunks for that tag. Each start tag is a chunk each word is a chunk and each end tag is a chunk.
def flatten_el(el, include_hrefs, skip_tag=False): """ Takes an lxml element el, and generates all the text chunks for that tag. Each start tag is a chunk, each word is a chunk, and each end tag is a chunk. If skip_tag is true, then the outermost container tag is not returned (just its contents)."...
Splits some text into words. Includes trailing whitespace on each word when appropriate.
def split_words(text): """ Splits some text into words. Includes trailing whitespace on each word when appropriate. """ if not text or not text.strip(): return [] words = split_words_re.findall(text) return words
The text representation of the start tag for a tag.
def start_tag(el): """ The text representation of the start tag for a tag. """ return '<%s%s>' % ( el.tag, ''.join([' %s="%s"' % (name, html_escape(value, True)) for name, value in el.attrib.items()]))
The text representation of an end tag for a tag. Includes trailing whitespace when appropriate.
def end_tag(el): """ The text representation of an end tag for a tag. Includes trailing whitespace when appropriate. """ if el.tail and start_whitespace_re.search(el.tail): extra = ' ' else: extra = '' return '</%s>%s' % (el.tag, extra)
Given an html string move any <ins > or <del > tags inside of any block - level elements e. g. transform <ins > <p > word</ p > </ ins > to <p > <ins > word</ ins > </ p >
def fixup_ins_del_tags(html): """ Given an html string, move any <ins> or <del> tags inside of any block-level elements, e.g. transform <ins><p>word</p></ins> to <p><ins>word</ins></p> """ doc = parse_html(html, cleanup=False) _fixup_ins_del_tags(doc) html = serialize_html_fragment(doc, skip_out...
Serialize a single lxml element as HTML. The serialized form includes the elements tail.
def serialize_html_fragment(el, skip_outer=False): """ Serialize a single lxml element as HTML. The serialized form includes the elements tail. If skip_outer is true, then don't serialize the outermost tag """ assert not isinstance(el, basestring), ( "You should pass in an element, not a...
fixup_ins_del_tags that works on an lxml document in - place
def _fixup_ins_del_tags(doc): """fixup_ins_del_tags that works on an lxml document in-place """ for tag in ['ins', 'del']: for el in doc.xpath('descendant-or-self::%s' % tag): if not _contains_block_level_tag(el): continue _move_el_inside_block(el, tag=tag) ...
True if the element contains any block - level elements like <p > <td > etc.
def _contains_block_level_tag(el): """True if the element contains any block-level elements, like <p>, <td>, etc. """ if el.tag in block_level_tags or el.tag in block_level_container_tags: return True for child in el: if _contains_block_level_tag(child): return True retur...
helper for _fixup_ins_del_tags ; actually takes the <ins > etc tags and moves them inside any block - level tags.
def _move_el_inside_block(el, tag): """ helper for _fixup_ins_del_tags; actually takes the <ins> etc tags and moves them inside any block-level tags. """ for child in el: if _contains_block_level_tag(child): break else: import sys # No block-level tags in any child ...
Removes an element but merges its contents into its place e. g. given <p > Hi <i > there!</ i > </ p > if you remove the <i > element you get <p > Hi there!</ p >
def _merge_element_contents(el): """ Removes an element, but merges its contents into its place, e.g., given <p>Hi <i>there!</i></p>, if you remove the <i> element you get <p>Hi there!</p> """ parent = el.getparent() text = el.text or '' if el.tail: if not len(el): te...
Yield ( op arg ) pair for each operation in code object code
def _iter_code(code): """Yield '(op,arg)' pair for each operation in code object 'code'""" from array import array from dis import HAVE_ARGUMENT, EXTENDED_ARG bytes = array('b',code.co_code) eof = len(code.co_code) ptr = 0 extended_arg = 0 while ptr<eof: op = bytes[ptr] ...
Extract the constant value of symbol from code
def extract_constant(code, symbol, default=-1): """Extract the constant value of 'symbol' from 'code' If the name 'symbol' is bound to a constant value by the Python code object 'code', return that value. If 'symbol' is bound to an expression, return 'default'. Otherwise, return 'None'. Return v...
A simplified URL to be used for caching the given query.
def cache_url(self, **kwargs): """A simplified URL to be used for caching the given query.""" query = { 'Operation': self.Operation, 'Service': "AWSECommerceService", 'Version': self.Version, } query.update(kwargs) service_domain = SERVICE_DOM...
Turn any URLs into links.
def autolink(el, link_regexes=_link_regexes, avoid_elements=_avoid_elements, avoid_hosts=_avoid_hosts, avoid_classes=_avoid_classes): """ Turn any URLs into links. It will search for links identified by the given regular expressions (by default mailto and http(s) ...
Breaks any long words found in the body of the text ( not attributes ).
def word_break(el, max_width=40, avoid_elements=_avoid_word_break_elements, avoid_classes=_avoid_word_break_classes, break_character=unichr(0x200b)): """ Breaks any long words found in the body of the text (not attributes). Doesn't effect any of the tags in avoi...
IE conditional comments basically embed HTML that the parser doesn t normally see. We can t allow anything like that so we ll kill any comments that could be conditional.
def kill_conditional_comments(self, doc): """ IE conditional comments basically embed HTML that the parser doesn't normally see. We can't allow anything like that, so we'll kill any comments that could be conditional. """ bad = [] self._kill_elements( ...
Depending on the browser stuff like e x p r e s s i o n (... ) can get interpreted or expre/ * stuff */ ssion (... ). This checks for attempt to do stuff like this.
def _has_sneaky_javascript(self, style): """ Depending on the browser, stuff like ``e x p r e s s i o n(...)`` can get interpreted, or ``expre/* stuff */ssion(...)``. This checks for attempt to do stuff like this. Typically the response will be to kill the entire style; if you ...
Parse a whole document into a string.
def document_fromstring(html, guess_charset=True, parser=None): """Parse a whole document into a string.""" if not isinstance(html, _strings): raise TypeError('string required') if parser is None: parser = html_parser return parser.parse(html, useChardet=guess_charset).getroot()
Parses several HTML elements returning a list of elements.
def fragments_fromstring(html, no_leading_text=False, guess_charset=False, parser=None): """Parses several HTML elements, returning a list of elements. The first item in the list may be a string. If no_leading_text is true, then it will be an error if there is leading text, and it...
Parses a single HTML element ; it is an error if there is more than one element or if anything but whitespace precedes or follows the element.
def fragment_fromstring(html, create_parent=False, guess_charset=False, parser=None): """Parses a single HTML element; it is an error if there is more than one element, or if anything but whitespace precedes or follows the element. If create_parent is true (or is a tag name) the...
Parse the html returning a single element/ document.
def fromstring(html, guess_charset=True, parser=None): """Parse the html, returning a single element/document. This tries to minimally parse the chunk of text, without knowing if it is a fragment or a document. base_url will set the document's base_url attribute (and the tree's docinfo.URL) """ ...
Parse a filename URL or file - like object into an HTML document tree. Note: this returns a tree not an element. Use parse (... ). getroot () to get the document root.
def parse(filename_url_or_file, guess_charset=True, parser=None): """Parse a filename, URL, or file-like object into an HTML document tree. Note: this returns a tree, not an element. Use ``parse(...).getroot()`` to get the document root. """ if parser is None: parser = html_parser if n...
Define the accept schema of an API ( GET or POST ).
def api_accepts(fields): """ Define the accept schema of an API (GET or POST). 'fields' is a dict of Django form fields keyed by field name that specifies the form-urlencoded fields that the API accepts*. The view function is then called with GET/POST data that has been cleaned by the Django f...
Define the return schema of an API.
def api_returns(return_values): """ Define the return schema of an API. 'return_values' is a dictionary mapping HTTP return code => documentation In addition to validating that the status code of the response belongs to one of the accepted status codes, it also validates that the returned o...
Wrapper that calls @api_accepts and @api_returns in sequence. For example:
def api(accept_return_dict): """ Wrapper that calls @api_accepts and @api_returns in sequence. For example: @api({ 'accepts': { 'x': forms.IntegerField(min_value=0), 'y': forms.IntegerField(min_value=0), }, 'returns': [ 200: 'Operation success...
Return a decorator that ensures that the request passed to the view function/ method has a valid JSON request body with the given required fields. The dict parsed from the JSON is then passed as the second argument to the decorated function/ method. For example:
def validate_json_request(required_fields): """ Return a decorator that ensures that the request passed to the view function/method has a valid JSON request body with the given required fields. The dict parsed from the JSON is then passed as the second argument to the decorated function/method. Fo...
Get a TreeWalker class for various types of tree with built - in support
def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support treeType - the name of the tree type required (case-insensitive). Supported values are: "dom" - The xml.dom.minidom DOM implementation ...
Returns a list of header include paths ( for lxml itself libxml2 and libxslt ) needed to compile C code against lxml if it was built with statically linked libraries.
def get_include(): """ Returns a list of header include paths (for lxml itself, libxml2 and libxslt) needed to compile C code against lxml if it was built with statically linked libraries. """ import os lxml_path = __path__[0] include_path = os.path.join(lxml_path, 'includes') includ...
Export the svn repository at the url to the destination location
def export(self, location): """Export the svn repository at the url to the destination location""" url, rev = self.get_url_rev() rev_options = get_rev_options(url, rev) logger.info('Exporting svn repository %s to %s', url, location) with indent_log(): if os.path.exist...
Return the maximum revision for all files under a given location
def get_revision(self, location): """ Return the maximum revision for all files under a given location """ # Note: taken from setuptools.command.egg_info revision = 0 for base, dirs, files in os.walk(location): if self.dirname not in dirs: dir...
Wraps a method so that it performs a check in debug mode if the first request was already handled.
def setupmethod(f): """Wraps a method so that it performs a check in debug mode if the first request was already handled. """ def wrapper_func(self, *args, **kwargs): if self.debug and self._got_first_request: raise AssertionError('A setup function was called after the ' ...
The name of the application. This is usually the import name with the difference that it s guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value.
def name(self): """The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to...
Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it s set otherwise a sensible default is returned.
def propagate_exceptions(self): """Returns the value of the `PROPAGATE_EXCEPTIONS` configuration value in case it's set, otherwise a sensible default is returned. .. versionadded:: 0.7 """ rv = self.config['PROPAGATE_EXCEPTIONS'] if rv is not None: return rv ...
A: class: logging. Logger object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to ( surprise ) log messages. Here some examples::
def logger(self): """A :class:`logging.Logger` object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to (surprise) log messages. Here some examples:: app.logger.debug('A value for debugging')...
Used to create the config attribute by the Flask constructor. The instance_relative parameter is passed in from the constructor of Flask ( there named instance_relative_config ) and indicates if the config should be relative to the instance path or the root path of the application.
def make_config(self, instance_relative=False): """Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the ins...
Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named instance next to your main file or the package.
def auto_find_instance_path(self): """Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named ``instance`` next to your main file or the package. .. versionadded:: 0.8 "...
Opens a resource from the application s instance folder (: attr: instance_path ). Otherwise works like: meth: open_resource. Instance resources can also be opened for writing.
def open_instance_resource(self, resource, mode='rb'): """Opens a resource from the application's instance folder (:attr:`instance_path`). Otherwise works like :meth:`open_resource`. Instance resources can also be opened for writing. :param resource: the name of the resource. ...
Creates the Jinja2 environment based on: attr: jinja_options and: meth: select_jinja_autoescape. Since 0. 7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior.
def create_jinja_environment(self): """Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior. .. versiona...
Update the template context with some commonly used variables. This injects request session config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0. 6 the original values in the context will not be overridden if a context processor decides to ...
def update_template_context(self, context): """Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the origin...
Runs the application on a local development server. If the: attr: debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened.
def run(self, host=None, port=None, debug=None, **options): """Runs the application on a local development server. If the :attr:`debug` flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the applicatio...
Saves the session if it needs updates. For the default implementation check: meth: open_session. Instead of overriding this method we recommend replacing the: class: session_interface.
def save_session(self, session, response): """Saves the session if it needs updates. For the default implementation, check :meth:`open_session`. Instead of overriding this method we recommend replacing the :class:`session_interface`. :param session: the session to be saved (a ...
Registers a module with this application. The keyword argument of this function are the same as the ones for the constructor of the: class: Module class and will override the values of the module if provided.
def register_module(self, module, **options): """Registers a module with this application. The keyword argument of this function are the same as the ones for the constructor of the :class:`Module` class and will override the values of the module if provided. .. versionchanged::...
Connects a URL rule. Works exactly like the: meth: route decorator. If a view_func is provided it will be registered with the endpoint.
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def ind...
A decorator to register a function as an endpoint. Example::
def endpoint(self, endpoint): """A decorator to register a function as an endpoint. Example:: @app.endpoint('example.endpoint') def example(): return "example" :param endpoint: the name of the endpoint """ def decorator(f): se...
A decorator that is used to register a function give a given error code. Example::
def errorhandler(self, code_or_exception): """A decorator that is used to register a function give a given error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for ...
A decorator that is used to register custom template filter. You can specify a name for the filter otherwise the function name will be used. Example::
def template_filter(self, name=None): """A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:: @app.template_filter() def reverse(s): return s[::-1] :para...
Register a custom template filter. Works exactly like the: meth: template_filter decorator.
def add_template_filter(self, f, name=None): """Register a custom template filter. Works exactly like the :meth:`template_filter` decorator. :param name: the optional name of the filter, otherwise the function name will be used. """ self.jinja_env.filters[n...
A decorator that is used to register a custom template global function. You can specify a name for the global function otherwise the function name will be used. Example::
def template_global(self, name=None): """A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:: @app.template_global() def double(n): retu...
Register a custom template global function. Works exactly like the: meth: template_global decorator.
def add_template_global(self, f, name=None): """Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be u...
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
def handle_http_exception(self, e): """Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionadded:: 0.3 """ handlers = self.error_handler_spec.get(request.blueprint) ...
Checks if an HTTP exception should be trapped or not. By default this will return False for all exceptions except for a bad request key error if TRAP_BAD_REQUEST_ERRORS is set to True. It also returns True if TRAP_HTTP_EXCEPTIONS is set to True.
def trap_http_exception(self, e): """Checks if an HTTP exception should be trapped or not. By default this will return `False` for all exceptions except for a bad request key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to `True`. It also returns `True` if ``TRAP_HTTP_EXCEPTIONS`` is se...
This method is called whenever an exception occurs that should be handled. A special case are: class: ~werkzeug. exception. HTTPException \ s which are forwarded by this function to the: meth: handle_http_exception method. This function will either return a response value or reraise the exception with the same tracebac...
def handle_user_exception(self, e): """This method is called whenever an exception occurs that should be handled. A special case are :class:`~werkzeug.exception.HTTPException`\s which are forwarded by this function to the :meth:`handle_http_exception` method. This function will...
Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re - raised immediately otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists a default 500 internal server error message is displayed.
def handle_exception(self, e): """Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler ...
Logs an exception. This is called by: meth: handle_exception if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the: attr: logger.
def log_exception(self, exc_info): """Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. .. versionadded:: 0.8 """ ...
Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non GET HEAD or OPTIONS requests and we re raising a different error instead to help debug situations.
def raise_routing_exception(self, request): """Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising a different error instead to help debug sit...
Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object call: func: make_response.
def dispatch_request(self): """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .....
Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
def full_dispatch_request(self): """Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. .. versionadded:: 0.7 """ self.try_trigger_before_first_request_functions() try: ...
Called before each request and will ensure that it triggers the: attr: before_first_request_funcs and only exactly once per application instance ( which means process usually ).
def try_trigger_before_first_request_functions(self): """Called before each request and will ensure that it triggers the :attr:`before_first_request_funcs` and only exactly once per application instance (which means process usually). :internal: """ if self._got_first_req...