Skip to content
Myr

Merge pull request #3245 from pallets/src-dir

Before adoption: this commit came in with the history the project adopted, so no landing records it.

move to src directory

authored by David Lord · committed by GitHub · parents 09392e0, ca278a8 · Browse files · 42 files+8167 added−8165 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

42 files+8167 added−8165 removed

  • other:+8167 added−8165 removed

42 files+8167 added−8165 removed

deleted:flask/json/__init__.py-375 removed
1# -*- coding: utf-8 -*-2"""3flask.json4~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""9import codecs10import io11import uuid12from datetime import date, datetime13from flask.globals import current_app, request14from flask._compat import text_type, PY21516from werkzeug.http import http_date17from jinja2 import Markup1819# Use the same json implementation as itsdangerous on which we20# depend anyways.21from itsdangerous import json as _json2223try:24 import dataclasses25except ImportError:26 dataclasses = None2728# Figure out if simplejson escapes slashes. This behavior was changed29# from one version to another without reason.30_slash_escape = "\\/" not in _json.dumps("/")313233__all__ = [34 "dump",35 "dumps",36 "load",37 "loads",38 "htmlsafe_dump",39 "htmlsafe_dumps",40 "JSONDecoder",41 "JSONEncoder",42 "jsonify",43]444546def _wrap_reader_for_text(fp, encoding):47 if isinstance(fp.read(0), bytes):48 fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)49 return fp505152def _wrap_writer_for_text(fp, encoding):53 try:54 fp.write("")55 except TypeError:56 fp = io.TextIOWrapper(fp, encoding)57 return fp585960class JSONEncoder(_json.JSONEncoder):61 """The default Flask JSON encoder. This one extends the default62 encoder by also supporting ``datetime``, ``UUID``, ``dataclasses``,63 and ``Markup`` objects.6465 ``datetime`` objects are serialized as RFC 822 datetime strings.66 This is the same as the HTTP date format.6768 In order to support more data types, override the :meth:`default`69 method.70 """7172 def default(self, o):73 """Implement this method in a subclass such that it returns a74 serializable object for ``o``, or calls the base implementation (to75 raise a :exc:`TypeError`).7677 For example, to support arbitrary iterators, you could implement78 default like this::7980 def default(self, o):81 try:82 iterable = iter(o)83 except TypeError:84 pass85 else:86 return list(iterable)87 return JSONEncoder.default(self, o)88 """89 if isinstance(o, datetime):90 return http_date(o.utctimetuple())91 if isinstance(o, date):92 return http_date(o.timetuple())93 if isinstance(o, uuid.UUID):94 return str(o)95 if dataclasses and dataclasses.is_dataclass(o):96 return dataclasses.asdict(o)97 if hasattr(o, "__html__"):98 return text_type(o.__html__())99 return _json.JSONEncoder.default(self, o)100101102class JSONDecoder(_json.JSONDecoder):103 """The default JSON decoder. This one does not change the behavior from104 the default simplejson decoder. Consult the :mod:`json` documentation105 for more information. This decoder is not only used for the load106 functions of this module but also :attr:`~flask.Request`.107 """108109110def _dump_arg_defaults(kwargs, app=None):111 """Inject default arguments for dump functions."""112 if app is None:113 app = current_app114115 if app:116 bp = app.blueprints.get(request.blueprint) if request else None117 kwargs.setdefault(118 "cls", bp.json_encoder if bp and bp.json_encoder else app.json_encoder119 )120121 if not app.config["JSON_AS_ASCII"]:122 kwargs.setdefault("ensure_ascii", False)123124 kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])125 else:126 kwargs.setdefault("sort_keys", True)127 kwargs.setdefault("cls", JSONEncoder)128129130def _load_arg_defaults(kwargs, app=None):131 """Inject default arguments for load functions."""132 if app is None:133 app = current_app134135 if app:136 bp = app.blueprints.get(request.blueprint) if request else None137 kwargs.setdefault(138 "cls", bp.json_decoder if bp and bp.json_decoder else app.json_decoder139 )140 else:141 kwargs.setdefault("cls", JSONDecoder)142143144def detect_encoding(data):145 """Detect which UTF codec was used to encode the given bytes.146147 The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is148 accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big149 or little endian. Some editors or libraries may prepend a BOM.150151 :param data: Bytes in unknown UTF encoding.152 :return: UTF encoding name153 """154 head = data[:4]155156 if head[:3] == codecs.BOM_UTF8:157 return "utf-8-sig"158159 if b"\x00" not in head:160 return "utf-8"161162 if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):163 return "utf-32"164165 if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):166 return "utf-16"167168 if len(head) == 4:169 if head[:3] == b"\x00\x00\x00":170 return "utf-32-be"171172 if head[::2] == b"\x00\x00":173 return "utf-16-be"174175 if head[1:] == b"\x00\x00\x00":176 return "utf-32-le"177178 if head[1::2] == b"\x00\x00":179 return "utf-16-le"180181 if len(head) == 2:182 return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"183184 return "utf-8"185186187def dumps(obj, app=None, **kwargs):188 """Serialize ``obj`` to a JSON-formatted string. If there is an189 app context pushed, use the current app's configured encoder190 (:attr:`~flask.Flask.json_encoder`), or fall back to the default191 :class:`JSONEncoder`.192193 Takes the same arguments as the built-in :func:`json.dumps`, and194 does some extra configuration based on the application. If the195 simplejson package is installed, it is preferred.196197 :param obj: Object to serialize to JSON.198 :param app: App instance to use to configure the JSON encoder.199 Uses ``current_app`` if not given, and falls back to the default200 encoder when not in an app context.201 :param kwargs: Extra arguments passed to :func:`json.dumps`.202203 .. versionchanged:: 1.0.3204205 ``app`` can be passed directly, rather than requiring an app206 context for configuration.207 """208 _dump_arg_defaults(kwargs, app=app)209 encoding = kwargs.pop("encoding", None)210 rv = _json.dumps(obj, **kwargs)211 if encoding is not None and isinstance(rv, text_type):212 rv = rv.encode(encoding)213 return rv214215216def dump(obj, fp, app=None, **kwargs):217 """Like :func:`dumps` but writes into a file object."""218 _dump_arg_defaults(kwargs, app=app)219 encoding = kwargs.pop("encoding", None)220 if encoding is not None:221 fp = _wrap_writer_for_text(fp, encoding)222 _json.dump(obj, fp, **kwargs)223224225def loads(s, app=None, **kwargs):226 """Deserialize an object from a JSON-formatted string ``s``. If227 there is an app context pushed, use the current app's configured228 decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the229 default :class:`JSONDecoder`.230231 Takes the same arguments as the built-in :func:`json.loads`, and232 does some extra configuration based on the application. If the233 simplejson package is installed, it is preferred.234235 :param s: JSON string to deserialize.236 :param app: App instance to use to configure the JSON decoder.237 Uses ``current_app`` if not given, and falls back to the default238 encoder when not in an app context.239 :param kwargs: Extra arguments passed to :func:`json.dumps`.240241 .. versionchanged:: 1.0.3242243 ``app`` can be passed directly, rather than requiring an app244 context for configuration.245 """246 _load_arg_defaults(kwargs, app=app)247 if isinstance(s, bytes):248 encoding = kwargs.pop("encoding", None)249 if encoding is None:250 encoding = detect_encoding(s)251 s = s.decode(encoding)252 return _json.loads(s, **kwargs)253254255def load(fp, app=None, **kwargs):256 """Like :func:`loads` but reads from a file object."""257 _load_arg_defaults(kwargs, app=app)258 if not PY2:259 fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")260 return _json.load(fp, **kwargs)261262263def htmlsafe_dumps(obj, **kwargs):264 """Works exactly like :func:`dumps` but is safe for use in ``<script>``265 tags. It accepts the same arguments and returns a JSON string. Note that266 this is available in templates through the ``|tojson`` filter which will267 also mark the result as safe. Due to how this function escapes certain268 characters this is safe even if used outside of ``<script>`` tags.269270 The following characters are escaped in strings:271272 - ``<``273 - ``>``274 - ``&``275 - ``'``276277 This makes it safe to embed such strings in any place in HTML with the278 notable exception of double quoted attributes. In that case single279 quote your attributes or HTML escape it in addition.280281 .. versionchanged:: 0.10282 This function's return value is now always safe for HTML usage, even283 if outside of script tags or if used in XHTML. This rule does not284 hold true when using this function in HTML attributes that are double285 quoted. Always single quote attributes if you use the ``|tojson``286 filter. Alternatively use ``|tojson|forceescape``.287 """288 rv = (289 dumps(obj, **kwargs)290 .replace(u"<", u"\\u003c")291 .replace(u">", u"\\u003e")292 .replace(u"&", u"\\u0026")293 .replace(u"'", u"\\u0027")294 )295 if not _slash_escape:296 rv = rv.replace("\\/", "/")297 return rv298299300def htmlsafe_dump(obj, fp, **kwargs):301 """Like :func:`htmlsafe_dumps` but writes into a file object."""302 fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))303304305def jsonify(*args, **kwargs):306 """This function wraps :func:`dumps` to add a few enhancements that make307 life easier. It turns the JSON output into a :class:`~flask.Response`308 object with the :mimetype:`application/json` mimetype. For convenience, it309 also converts multiple arguments into an array or multiple keyword arguments310 into a dict. This means that both ``jsonify(1,2,3)`` and311 ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.312313 For clarity, the JSON serialization behavior has the following differences314 from :func:`dumps`:315316 1. Single argument: Passed straight through to :func:`dumps`.317 2. Multiple arguments: Converted to an array before being passed to318 :func:`dumps`.319 3. Multiple keyword arguments: Converted to a dict before being passed to320 :func:`dumps`.321 4. Both args and kwargs: Behavior undefined and will throw an exception.322323 Example usage::324325 from flask import jsonify326327 @app.route('/_get_current_user')328 def get_current_user():329 return jsonify(username=g.user.username,330 email=g.user.email,331 id=g.user.id)332333 This will send a JSON response like this to the browser::334335 {336 "username": "admin",337 "email": "admin@localhost",338 "id": 42339 }340341342 .. versionchanged:: 0.11343 Added support for serializing top-level arrays. This introduces a344 security risk in ancient browsers. See :ref:`json-security` for details.345346 This function's response will be pretty printed if the347 ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the348 Flask app is running in debug mode. Compressed (not pretty) formatting349 currently means no indents and no spaces after separators.350351 .. versionadded:: 0.2352 """353354 indent = None355 separators = (",", ":")356357 if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:358 indent = 2359 separators = (", ", ": ")360361 if args and kwargs:362 raise TypeError("jsonify() behavior undefined when passed both args and kwargs")363 elif len(args) == 1: # single args are passed directly to dumps()364 data = args[0]365 else:366 data = args or kwargs367368 return current_app.response_class(369 dumps(data, indent=indent, separators=separators) + "\n",370 mimetype=current_app.config["JSONIFY_MIMETYPE"],371 )372373374def tojson_filter(obj, **kwargs):375 return Markup(htmlsafe_dumps(obj, **kwargs))
deleted:flask/json/tag.py-306 removed
1# -*- coding: utf-8 -*-2"""3Tagged JSON4~~~~~~~~~~~56A compact representation for lossless serialization of non-standard JSON types.7:class:`~flask.sessions.SecureCookieSessionInterface` uses this to serialize8the session data, but it may be useful in other places. It can be extended to9support other types.1011.. autoclass:: TaggedJSONSerializer12 :members:1314.. autoclass:: JSONTag15 :members:1617Let's seen an example that adds support for :class:`~collections.OrderedDict`.18Dicts don't have an order in Python or JSON, so to handle this we will dump19the items as a list of ``[key, value]`` pairs. Subclass :class:`JSONTag` and20give it the new key ``' od'`` to identify the type. The session serializer21processes dicts first, so insert the new tag at the front of the order since22``OrderedDict`` must be processed before ``dict``. ::2324 from flask.json.tag import JSONTag2526 class TagOrderedDict(JSONTag):27 __slots__ = ('serializer',)28 key = ' od'2930 def check(self, value):31 return isinstance(value, OrderedDict)3233 def to_json(self, value):34 return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]3536 def to_python(self, value):37 return OrderedDict(value)3839 app.session_interface.serializer.register(TagOrderedDict, index=0)4041:copyright: © 2010 by the Pallets team.42:license: BSD, see LICENSE for more details.43"""4445from base64 import b64decode, b64encode46from datetime import datetime47from uuid import UUID4849from jinja2 import Markup50from werkzeug.http import http_date, parse_date5152from flask._compat import iteritems, text_type53from flask.json import dumps, loads545556class JSONTag(object):57 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""5859 __slots__ = ("serializer",)6061 #: The tag to mark the serialized object with. If ``None``, this tag is62 #: only used as an intermediate step during tagging.63 key = None6465 def __init__(self, serializer):66 """Create a tagger for the given serializer."""67 self.serializer = serializer6869 def check(self, value):70 """Check if the given value should be tagged by this tag."""71 raise NotImplementedError7273 def to_json(self, value):74 """Convert the Python object to an object that is a valid JSON type.75 The tag will be added later."""76 raise NotImplementedError7778 def to_python(self, value):79 """Convert the JSON representation back to the correct type. The tag80 will already be removed."""81 raise NotImplementedError8283 def tag(self, value):84 """Convert the value to a valid JSON type and add the tag structure85 around it."""86 return {self.key: self.to_json(value)}878889class TagDict(JSONTag):90 """Tag for 1-item dicts whose only key matches a registered tag.9192 Internally, the dict key is suffixed with `__`, and the suffix is removed93 when deserializing.94 """9596 __slots__ = ()97 key = " di"9899 def check(self, value):100 return (101 isinstance(value, dict)102 and len(value) == 1103 and next(iter(value)) in self.serializer.tags104 )105106 def to_json(self, value):107 key = next(iter(value))108 return {key + "__": self.serializer.tag(value[key])}109110 def to_python(self, value):111 key = next(iter(value))112 return {key[:-2]: value[key]}113114115class PassDict(JSONTag):116 __slots__ = ()117118 def check(self, value):119 return isinstance(value, dict)120121 def to_json(self, value):122 # JSON objects may only have string keys, so don't bother tagging the123 # key here.124 return dict((k, self.serializer.tag(v)) for k, v in iteritems(value))125126 tag = to_json127128129class TagTuple(JSONTag):130 __slots__ = ()131 key = " t"132133 def check(self, value):134 return isinstance(value, tuple)135136 def to_json(self, value):137 return [self.serializer.tag(item) for item in value]138139 def to_python(self, value):140 return tuple(value)141142143class PassList(JSONTag):144 __slots__ = ()145146 def check(self, value):147 return isinstance(value, list)148149 def to_json(self, value):150 return [self.serializer.tag(item) for item in value]151152 tag = to_json153154155class TagBytes(JSONTag):156 __slots__ = ()157 key = " b"158159 def check(self, value):160 return isinstance(value, bytes)161162 def to_json(self, value):163 return b64encode(value).decode("ascii")164165 def to_python(self, value):166 return b64decode(value)167168169class TagMarkup(JSONTag):170 """Serialize anything matching the :class:`~flask.Markup` API by171 having a ``__html__`` method to the result of that method. Always172 deserializes to an instance of :class:`~flask.Markup`."""173174 __slots__ = ()175 key = " m"176177 def check(self, value):178 return callable(getattr(value, "__html__", None))179180 def to_json(self, value):181 return text_type(value.__html__())182183 def to_python(self, value):184 return Markup(value)185186187class TagUUID(JSONTag):188 __slots__ = ()189 key = " u"190191 def check(self, value):192 return isinstance(value, UUID)193194 def to_json(self, value):195 return value.hex196197 def to_python(self, value):198 return UUID(value)199200201class TagDateTime(JSONTag):202 __slots__ = ()203 key = " d"204205 def check(self, value):206 return isinstance(value, datetime)207208 def to_json(self, value):209 return http_date(value)210211 def to_python(self, value):212 return parse_date(value)213214215class TaggedJSONSerializer(object):216 """Serializer that uses a tag system to compactly represent objects that217 are not JSON types. Passed as the intermediate serializer to218 :class:`itsdangerous.Serializer`.219220 The following extra types are supported:221222 * :class:`dict`223 * :class:`tuple`224 * :class:`bytes`225 * :class:`~flask.Markup`226 * :class:`~uuid.UUID`227 * :class:`~datetime.datetime`228 """229230 __slots__ = ("tags", "order")231232 #: Tag classes to bind when creating the serializer. Other tags can be233 #: added later using :meth:`~register`.234 default_tags = [235 TagDict,236 PassDict,237 TagTuple,238 PassList,239 TagBytes,240 TagMarkup,241 TagUUID,242 TagDateTime,243 ]244245 def __init__(self):246 self.tags = {}247 self.order = []248249 for cls in self.default_tags:250 self.register(cls)251252 def register(self, tag_class, force=False, index=None):253 """Register a new tag with this serializer.254255 :param tag_class: tag class to register. Will be instantiated with this256 serializer instance.257 :param force: overwrite an existing tag. If false (default), a258 :exc:`KeyError` is raised.259 :param index: index to insert the new tag in the tag order. Useful when260 the new tag is a special case of an existing tag. If ``None``261 (default), the tag is appended to the end of the order.262263 :raise KeyError: if the tag key is already registered and ``force`` is264 not true.265 """266 tag = tag_class(self)267 key = tag.key268269 if key is not None:270 if not force and key in self.tags:271 raise KeyError("Tag '{0}' is already registered.".format(key))272273 self.tags[key] = tag274275 if index is None:276 self.order.append(tag)277 else:278 self.order.insert(index, tag)279280 def tag(self, value):281 """Convert a value to a tagged representation if necessary."""282 for tag in self.order:283 if tag.check(value):284 return tag.tag(value)285286 return value287288 def untag(self, value):289 """Convert a tagged representation back to the original type."""290 if len(value) != 1:291 return value292293 key = next(iter(value))294295 if key not in self.tags:296 return value297298 return self.tags[key].to_python(value[key])299300 def dumps(self, value):301 """Tag the value and dump it to a compact JSON string."""302 return dumps(self.tag(value), separators=(",", ":"))303304 def loads(self, value):305 """Load data from a JSON string and deserialized any tagged objects."""306 return loads(value, object_hook=self.untag)
deleted:flask/__init__.py-72 removed
1# -*- coding: utf-8 -*-2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213__version__ = "1.1.dev"1415# utilities we import from Werkzeug and Jinja2 that are unused16# in the module but are exported as public interface.17from werkzeug.exceptions import abort18from werkzeug.utils import redirect19from jinja2 import Markup, escape2021from .app import Flask, Request, Response22from .config import Config23from .helpers import (24 url_for,25 flash,26 send_file,27 send_from_directory,28 get_flashed_messages,29 get_template_attribute,30 make_response,31 safe_join,32 stream_with_context,33)34from .globals import (35 current_app,36 g,37 request,38 session,39 _request_ctx_stack,40 _app_ctx_stack,41)42from .ctx import (43 has_request_context,44 has_app_context,45 after_this_request,46 copy_current_request_context,47)48from .blueprints import Blueprint49from .templating import render_template, render_template_string5051# the signals52from .signals import (53 signals_available,54 template_rendered,55 request_started,56 request_finished,57 got_request_exception,58 request_tearing_down,59 appcontext_tearing_down,60 appcontext_pushed,61 appcontext_popped,62 message_flashed,63 before_render_template,64)6566# We're not exposing the actual json module but a convenient wrapper around67# it.68from . import json6970# This was the only thing that Flask used to export at one point and it had71# a more generic name.72jsonify = json.jsonify
deleted:flask/__main__.py-15 removed
1# -*- coding: utf-8 -*-2"""3 flask.__main__4 ~~~~~~~~~~~~~~56 Alias for flask.run for the command line.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112if __name__ == "__main__":13 from .cli import main1415 main(as_module=True)
deleted:flask/_compat.py-116 removed
1# -*- coding: utf-8 -*-2"""3 flask._compat4 ~~~~~~~~~~~~~56 Some py2/py3 compatibility support based on a stripped down7 version of six so we don't have to depend on a specific version8 of it.910 :copyright: © 2010 by the Pallets team.11 :license: BSD, see LICENSE for more details.12"""1314import sys1516PY2 = sys.version_info[0] == 217_identity = lambda x: x1819try: # Python 220 text_type = unicode21 string_types = (str, unicode)22 integer_types = (int, long)23except NameError: # Python 324 text_type = str25 string_types = (str,)26 integer_types = (int,)2728if not PY2:29 iterkeys = lambda d: iter(d.keys())30 itervalues = lambda d: iter(d.values())31 iteritems = lambda d: iter(d.items())3233 from inspect import getfullargspec as getargspec34 from io import StringIO35 import collections.abc as collections_abc3637 def reraise(tp, value, tb=None):38 if value.__traceback__ is not tb:39 raise value.with_traceback(tb)40 raise value4142 implements_to_string = _identity4344else:45 iterkeys = lambda d: d.iterkeys()46 itervalues = lambda d: d.itervalues()47 iteritems = lambda d: d.iteritems()4849 from inspect import getargspec50 from cStringIO import StringIO51 import collections as collections_abc5253 exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")5455 def implements_to_string(cls):56 cls.__unicode__ = cls.__str__57 cls.__str__ = lambda x: x.__unicode__().encode("utf-8")58 return cls596061def with_metaclass(meta, *bases):62 """Create a base class with a metaclass."""63 # This requires a bit of explanation: the basic idea is to make a64 # dummy metaclass for one level of class instantiation that replaces65 # itself with the actual metaclass.66 class metaclass(type):67 def __new__(mcs, name, this_bases, d):68 return meta(name, bases, d)6970 return type.__new__(metaclass, "temporary_class", (), {})717273# Certain versions of pypy have a bug where clearing the exception stack74# breaks the __exit__ function in a very peculiar way. The second level of75# exception blocks is necessary because pypy seems to forget to check if an76# exception happened until the next bytecode instruction?77#78# Relevant PyPy bugfix commit:79# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df400330180# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later81# versions.82#83# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.84BROKEN_PYPY_CTXMGR_EXIT = False85if hasattr(sys, "pypy_version_info"):8687 class _Mgr(object):88 def __enter__(self):89 return self9091 def __exit__(self, *args):92 if hasattr(sys, "exc_clear"):93 # Python 3 (PyPy3) doesn't have exc_clear94 sys.exc_clear()9596 try:97 try:98 with _Mgr():99 raise AssertionError()100 except: # noqa: B001101 # We intentionally use a bare except here. See the comment above102 # regarding a pypy bug as to why.103 raise104 except TypeError:105 BROKEN_PYPY_CTXMGR_EXIT = True106 except AssertionError:107 pass108109110try:111 from os import fspath112except ImportError:113 # Backwards compatibility as proposed in PEP 0519:114 # https://www.python.org/dev/peps/pep-0519/#backwards-compatibility115 def fspath(path):116 return path.__fspath__() if hasattr(path, "__fspath__") else path
deleted:flask/app.py-2418 removed
1# -*- coding: utf-8 -*-2"""3 flask.app4 ~~~~~~~~~56 This module implements the central WSGI application object.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import os13import sys14import warnings15from datetime import timedelta16from functools import update_wrapper17from itertools import chain18from threading import Lock1920from werkzeug.datastructures import Headers, ImmutableDict21from werkzeug.exceptions import (22 BadRequest,23 BadRequestKeyError,24 HTTPException,25 InternalServerError,26 MethodNotAllowed,27 default_exceptions,28)29from werkzeug.routing import BuildError, Map, RequestRedirect, RoutingException, Rule30from werkzeug.wrappers import BaseResponse3132from . import cli, json33from ._compat import integer_types, reraise, string_types, text_type34from .config import Config, ConfigAttribute35from .ctx import AppContext, RequestContext, _AppCtxGlobals36from .globals import _request_ctx_stack, g, request, session37from .helpers import (38 _PackageBoundObject,39 _endpoint_from_view_func,40 find_package,41 get_env,42 get_debug_flag,43 get_flashed_messages,44 locked_cached_property,45 url_for,46 get_load_dotenv,47)48from .json import jsonify49from .logging import create_logger50from .sessions import SecureCookieSessionInterface51from .signals import (52 appcontext_tearing_down,53 got_request_exception,54 request_finished,55 request_started,56 request_tearing_down,57)58from .templating import (59 DispatchingJinjaLoader,60 Environment,61 _default_template_ctx_processor,62)63from .wrappers import Request, Response6465# a singleton sentinel value for parameter defaults66_sentinel = object()676869def _make_timedelta(value):70 if not isinstance(value, timedelta):71 return timedelta(seconds=value)72 return value737475def setupmethod(f):76 """Wraps a method so that it performs a check in debug mode if the77 first request was already handled.78 """7980 def wrapper_func(self, *args, **kwargs):81 if self.debug and self._got_first_request:82 raise AssertionError(83 "A setup function was called after the "84 "first request was handled. This usually indicates a bug "85 "in the application where a module was not imported "86 "and decorators or other functionality was called too late.\n"87 "To fix this make sure to import all your view modules, "88 "database models and everything related at a central place "89 "before the application starts serving requests."90 )91 return f(self, *args, **kwargs)9293 return update_wrapper(wrapper_func, f)949596class Flask(_PackageBoundObject):97 """The flask object implements a WSGI application and acts as the central98 object. It is passed the name of the module or package of the99 application. Once it is created it will act as a central registry for100 the view functions, the URL rules, template configuration and much more.101102 The name of the package is used to resolve resources from inside the103 package or the folder the module is contained in depending on if the104 package parameter resolves to an actual python package (a folder with105 an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).106107 For more information about resource loading, see :func:`open_resource`.108109 Usually you create a :class:`Flask` instance in your main module or110 in the :file:`__init__.py` file of your package like this::111112 from flask import Flask113 app = Flask(__name__)114115 .. admonition:: About the First Parameter116117 The idea of the first parameter is to give Flask an idea of what118 belongs to your application. This name is used to find resources119 on the filesystem, can be used by extensions to improve debugging120 information and a lot more.121122 So it's important what you provide there. If you are using a single123 module, `__name__` is always the correct value. If you however are124 using a package, it's usually recommended to hardcode the name of125 your package there.126127 For example if your application is defined in :file:`yourapplication/app.py`128 you should create it with one of the two versions below::129130 app = Flask('yourapplication')131 app = Flask(__name__.split('.')[0])132133 Why is that? The application will work even with `__name__`, thanks134 to how resources are looked up. However it will make debugging more135 painful. Certain extensions can make assumptions based on the136 import name of your application. For example the Flask-SQLAlchemy137 extension will look for the code in your application that triggered138 an SQL query in debug mode. If the import name is not properly set139 up, that debugging information is lost. (For example it would only140 pick up SQL queries in `yourapplication.app` and not141 `yourapplication.views.frontend`)142143 .. versionadded:: 0.7144 The `static_url_path`, `static_folder`, and `template_folder`145 parameters were added.146147 .. versionadded:: 0.8148 The `instance_path` and `instance_relative_config` parameters were149 added.150151 .. versionadded:: 0.11152 The `root_path` parameter was added.153154 .. versionadded:: 1.0155 The ``host_matching`` and ``static_host`` parameters were added.156157 .. versionadded:: 1.0158 The ``subdomain_matching`` parameter was added. Subdomain159 matching needs to be enabled manually now. Setting160 :data:`SERVER_NAME` does not implicitly enable it.161162 :param import_name: the name of the application package163 :param static_url_path: can be used to specify a different path for the164 static files on the web. Defaults to the name165 of the `static_folder` folder.166 :param static_folder: the folder with static files that should be served167 at `static_url_path`. Defaults to the ``'static'``168 folder in the root path of the application.169 :param static_host: the host to use when adding the static route.170 Defaults to None. Required when using ``host_matching=True``171 with a ``static_folder`` configured.172 :param host_matching: set ``url_map.host_matching`` attribute.173 Defaults to False.174 :param subdomain_matching: consider the subdomain relative to175 :data:`SERVER_NAME` when matching routes. Defaults to False.176 :param template_folder: the folder that contains the templates that should177 be used by the application. Defaults to178 ``'templates'`` folder in the root path of the179 application.180 :param instance_path: An alternative instance path for the application.181 By default the folder ``'instance'`` next to the182 package or module is assumed to be the instance183 path.184 :param instance_relative_config: if set to ``True`` relative filenames185 for loading the config are assumed to186 be relative to the instance path instead187 of the application root.188 :param root_path: Flask by default will automatically calculate the path189 to the root of the application. In certain situations190 this cannot be achieved (for instance if the package191 is a Python 3 namespace package) and needs to be192 manually defined.193 """194195 #: The class that is used for request objects. See :class:`~flask.Request`196 #: for more information.197 request_class = Request198199 #: The class that is used for response objects. See200 #: :class:`~flask.Response` for more information.201 response_class = Response202203 #: The class that is used for the Jinja environment.204 #:205 #: .. versionadded:: 0.11206 jinja_environment = Environment207208 #: The class that is used for the :data:`~flask.g` instance.209 #:210 #: Example use cases for a custom class:211 #:212 #: 1. Store arbitrary attributes on flask.g.213 #: 2. Add a property for lazy per-request database connectors.214 #: 3. Return None instead of AttributeError on unexpected attributes.215 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.216 #:217 #: In Flask 0.9 this property was called `request_globals_class` but it218 #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the219 #: flask.g object is now application context scoped.220 #:221 #: .. versionadded:: 0.10222 app_ctx_globals_class = _AppCtxGlobals223224 #: The class that is used for the ``config`` attribute of this app.225 #: Defaults to :class:`~flask.Config`.226 #:227 #: Example use cases for a custom class:228 #:229 #: 1. Default values for certain config options.230 #: 2. Access to config values through attributes in addition to keys.231 #:232 #: .. versionadded:: 0.11233 config_class = Config234235 #: The testing flag. Set this to ``True`` to enable the test mode of236 #: Flask extensions (and in the future probably also Flask itself).237 #: For example this might activate test helpers that have an238 #: additional runtime cost which should not be enabled by default.239 #:240 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the241 #: default it's implicitly enabled.242 #:243 #: This attribute can also be configured from the config with the244 #: ``TESTING`` configuration key. Defaults to ``False``.245 testing = ConfigAttribute("TESTING")246247 #: If a secret key is set, cryptographic components can use this to248 #: sign cookies and other things. Set this to a complex random value249 #: when you want to use the secure cookie for instance.250 #:251 #: This attribute can also be configured from the config with the252 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.253 secret_key = ConfigAttribute("SECRET_KEY")254255 #: The secure cookie uses this for the name of the session cookie.256 #:257 #: This attribute can also be configured from the config with the258 #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``259 session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")260261 #: A :class:`~datetime.timedelta` which is used to set the expiration262 #: date of a permanent session. The default is 31 days which makes a263 #: permanent session survive for roughly one month.264 #:265 #: This attribute can also be configured from the config with the266 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to267 #: ``timedelta(days=31)``268 permanent_session_lifetime = ConfigAttribute(269 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta270 )271272 #: A :class:`~datetime.timedelta` which is used as default cache_timeout273 #: for the :func:`send_file` functions. The default is 12 hours.274 #:275 #: This attribute can also be configured from the config with the276 #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration277 #: variable can also be set with an integer value used as seconds.278 #: Defaults to ``timedelta(hours=12)``279 send_file_max_age_default = ConfigAttribute(280 "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta281 )282283 #: Enable this if you want to use the X-Sendfile feature. Keep in284 #: mind that the server has to support this. This only affects files285 #: sent with the :func:`send_file` method.286 #:287 #: .. versionadded:: 0.2288 #:289 #: This attribute can also be configured from the config with the290 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.291 use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")292293 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.294 #:295 #: .. versionadded:: 0.10296 json_encoder = json.JSONEncoder297298 #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.299 #:300 #: .. versionadded:: 0.10301 json_decoder = json.JSONDecoder302303 #: Options that are passed to the Jinja environment in304 #: :meth:`create_jinja_environment`. Changing these options after305 #: the environment is created (accessing :attr:`jinja_env`) will306 #: have no effect.307 #:308 #: .. versionchanged:: 1.1.0309 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow310 #: easier configuration.311 #:312 jinja_options = {"extensions": ["jinja2.ext.autoescape", "jinja2.ext.with_"]}313314 #: Default configuration parameters.315 default_config = ImmutableDict(316 {317 "ENV": None,318 "DEBUG": None,319 "TESTING": False,320 "PROPAGATE_EXCEPTIONS": None,321 "PRESERVE_CONTEXT_ON_EXCEPTION": None,322 "SECRET_KEY": None,323 "PERMANENT_SESSION_LIFETIME": timedelta(days=31),324 "USE_X_SENDFILE": False,325 "SERVER_NAME": None,326 "APPLICATION_ROOT": "/",327 "SESSION_COOKIE_NAME": "session",328 "SESSION_COOKIE_DOMAIN": None,329 "SESSION_COOKIE_PATH": None,330 "SESSION_COOKIE_HTTPONLY": True,331 "SESSION_COOKIE_SECURE": False,332 "SESSION_COOKIE_SAMESITE": None,333 "SESSION_REFRESH_EACH_REQUEST": True,334 "MAX_CONTENT_LENGTH": None,335 "SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),336 "TRAP_BAD_REQUEST_ERRORS": None,337 "TRAP_HTTP_EXCEPTIONS": False,338 "EXPLAIN_TEMPLATE_LOADING": False,339 "PREFERRED_URL_SCHEME": "http",340 "JSON_AS_ASCII": True,341 "JSON_SORT_KEYS": True,342 "JSONIFY_PRETTYPRINT_REGULAR": False,343 "JSONIFY_MIMETYPE": "application/json",344 "TEMPLATES_AUTO_RELOAD": None,345 "MAX_COOKIE_SIZE": 4093,346 }347 )348349 #: The rule object to use for URL rules created. This is used by350 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.351 #:352 #: .. versionadded:: 0.7353 url_rule_class = Rule354355 #: The map object to use for storing the URL rules and routing356 #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.357 #:358 #: .. versionadded:: 1.1.0359 url_map_class = Map360361 #: the test client that is used with when `test_client` is used.362 #:363 #: .. versionadded:: 0.7364 test_client_class = None365366 #: The :class:`~click.testing.CliRunner` subclass, by default367 #: :class:`~flask.testing.FlaskCliRunner` that is used by368 #: :meth:`test_cli_runner`. Its ``__init__`` method should take a369 #: Flask app object as the first argument.370 #:371 #: .. versionadded:: 1.0372 test_cli_runner_class = None373374 #: the session interface to use. By default an instance of375 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.376 #:377 #: .. versionadded:: 0.8378 session_interface = SecureCookieSessionInterface()379380 # TODO remove the next three attrs when Sphinx :inherited-members: works381 # https://github.com/sphinx-doc/sphinx/issues/741382383 #: The name of the package or module that this app belongs to. Do not384 #: change this once it is set by the constructor.385 import_name = None386387 #: Location of the template files to be added to the template lookup.388 #: ``None`` if templates should not be added.389 template_folder = None390391 #: Absolute path to the package on the filesystem. Used to look up392 #: resources contained in the package.393 root_path = None394395 def __init__(396 self,397 import_name,398 static_url_path=None,399 static_folder="static",400 static_host=None,401 host_matching=False,402 subdomain_matching=False,403 template_folder="templates",404 instance_path=None,405 instance_relative_config=False,406 root_path=None,407 ):408 _PackageBoundObject.__init__(409 self, import_name, template_folder=template_folder, root_path=root_path410 )411412 self.static_url_path = static_url_path413 self.static_folder = static_folder414415 if instance_path is None:416 instance_path = self.auto_find_instance_path()417 elif not os.path.isabs(instance_path):418 raise ValueError(419 "If an instance path is provided it must be absolute."420 " A relative path was given instead."421 )422423 #: Holds the path to the instance folder.424 #:425 #: .. versionadded:: 0.8426 self.instance_path = instance_path427428 #: The configuration dictionary as :class:`Config`. This behaves429 #: exactly like a regular dictionary but supports additional methods430 #: to load a config from files.431 self.config = self.make_config(instance_relative_config)432433 #: A dictionary of all view functions registered. The keys will434 #: be function names which are also used to generate URLs and435 #: the values are the function objects themselves.436 #: To register a view function, use the :meth:`route` decorator.437 self.view_functions = {}438439 #: A dictionary of all registered error handlers. The key is ``None``440 #: for error handlers active on the application, otherwise the key is441 #: the name of the blueprint. Each key points to another dictionary442 #: where the key is the status code of the http exception. The443 #: special key ``None`` points to a list of tuples where the first item444 #: is the class for the instance check and the second the error handler445 #: function.446 #:447 #: To register an error handler, use the :meth:`errorhandler`448 #: decorator.449 self.error_handler_spec = {}450451 #: A list of functions that are called when :meth:`url_for` raises a452 #: :exc:`~werkzeug.routing.BuildError`. Each function registered here453 #: is called with `error`, `endpoint` and `values`. If a function454 #: returns ``None`` or raises a :exc:`BuildError` the next function is455 #: tried.456 #:457 #: .. versionadded:: 0.9458 self.url_build_error_handlers = []459460 #: A dictionary with lists of functions that will be called at the461 #: beginning of each request. The key of the dictionary is the name of462 #: the blueprint this function is active for, or ``None`` for all463 #: requests. To register a function, use the :meth:`before_request`464 #: decorator.465 self.before_request_funcs = {}466467 #: A list of functions that will be called at the beginning of the468 #: first request to this instance. To register a function, use the469 #: :meth:`before_first_request` decorator.470 #:471 #: .. versionadded:: 0.8472 self.before_first_request_funcs = []473474 #: A dictionary with lists of functions that should be called after475 #: each request. The key of the dictionary is the name of the blueprint476 #: this function is active for, ``None`` for all requests. This can for477 #: example be used to close database connections. To register a function478 #: here, use the :meth:`after_request` decorator.479 self.after_request_funcs = {}480481 #: A dictionary with lists of functions that are called after482 #: each request, even if an exception has occurred. The key of the483 #: dictionary is the name of the blueprint this function is active for,484 #: ``None`` for all requests. These functions are not allowed to modify485 #: the request, and their return values are ignored. If an exception486 #: occurred while processing the request, it gets passed to each487 #: teardown_request function. To register a function here, use the488 #: :meth:`teardown_request` decorator.489 #:490 #: .. versionadded:: 0.7491 self.teardown_request_funcs = {}492493 #: A list of functions that are called when the application context494 #: is destroyed. Since the application context is also torn down495 #: if the request ends this is the place to store code that disconnects496 #: from databases.497 #:498 #: .. versionadded:: 0.9499 self.teardown_appcontext_funcs = []500501 #: A dictionary with lists of functions that are called before the502 #: :attr:`before_request_funcs` functions. The key of the dictionary is503 #: the name of the blueprint this function is active for, or ``None``504 #: for all requests. To register a function, use505 #: :meth:`url_value_preprocessor`.506 #:507 #: .. versionadded:: 0.7508 self.url_value_preprocessors = {}509510 #: A dictionary with lists of functions that can be used as URL value511 #: preprocessors. The key ``None`` here is used for application wide512 #: callbacks, otherwise the key is the name of the blueprint.513 #: Each of these functions has the chance to modify the dictionary514 #: of URL values before they are used as the keyword arguments of the515 #: view function. For each function registered this one should also516 #: provide a :meth:`url_defaults` function that adds the parameters517 #: automatically again that were removed that way.518 #:519 #: .. versionadded:: 0.7520 self.url_default_functions = {}521522 #: A dictionary with list of functions that are called without argument523 #: to populate the template context. The key of the dictionary is the524 #: name of the blueprint this function is active for, ``None`` for all525 #: requests. Each returns a dictionary that the template context is526 #: updated with. To register a function here, use the527 #: :meth:`context_processor` decorator.528 self.template_context_processors = {None: [_default_template_ctx_processor]}529530 #: A list of shell context processor functions that should be run531 #: when a shell context is created.532 #:533 #: .. versionadded:: 0.11534 self.shell_context_processors = []535536 #: all the attached blueprints in a dictionary by name. Blueprints537 #: can be attached multiple times so this dictionary does not tell538 #: you how often they got attached.539 #:540 #: .. versionadded:: 0.7541 self.blueprints = {}542 self._blueprint_order = []543544 #: a place where extensions can store application specific state. For545 #: example this is where an extension could store database engines and546 #: similar things. For backwards compatibility extensions should register547 #: themselves like this::548 #:549 #: if not hasattr(app, 'extensions'):550 #: app.extensions = {}551 #: app.extensions['extensionname'] = SomeObject()552 #:553 #: The key must match the name of the extension module. For example in554 #: case of a "Flask-Foo" extension in `flask_foo`, the key would be555 #: ``'foo'``.556 #:557 #: .. versionadded:: 0.7558 self.extensions = {}559560 #: The :class:`~werkzeug.routing.Map` for this instance. You can use561 #: this to change the routing converters after the class was created562 #: but before any routes are connected. Example::563 #:564 #: from werkzeug.routing import BaseConverter565 #:566 #: class ListConverter(BaseConverter):567 #: def to_python(self, value):568 #: return value.split(',')569 #: def to_url(self, values):570 #: return ','.join(super(ListConverter, self).to_url(value)571 #: for value in values)572 #:573 #: app = Flask(__name__)574 #: app.url_map.converters['list'] = ListConverter575 self.url_map = self.url_map_class()576577 self.url_map.host_matching = host_matching578 self.subdomain_matching = subdomain_matching579580 # tracks internally if the application already handled at least one581 # request.582 self._got_first_request = False583 self._before_request_lock = Lock()584585 # Add a static route using the provided static_url_path, static_host,586 # and static_folder if there is a configured static_folder.587 # Note we do this without checking if static_folder exists.588 # For one, it might be created while the server is running (e.g. during589 # development). Also, Google App Engine stores static files somewhere590 if self.has_static_folder:591 assert (592 bool(static_host) == host_matching593 ), "Invalid static_host/host_matching combination"594 self.add_url_rule(595 self.static_url_path + "/<path:filename>",596 endpoint="static",597 host=static_host,598 view_func=self.send_static_file,599 )600601 # Set the name of the Click group in case someone wants to add602 # the app's commands to another CLI tool.603 self.cli.name = self.name604605 @locked_cached_property606 def name(self):607 """The name of the application. This is usually the import name608 with the difference that it's guessed from the run file if the609 import name is main. This name is used as a display name when610 Flask needs the name of the application. It can be set and overridden611 to change the value.612613 .. versionadded:: 0.8614 """615 if self.import_name == "__main__":616 fn = getattr(sys.modules["__main__"], "__file__", None)617 if fn is None:618 return "__main__"619 return os.path.splitext(os.path.basename(fn))[0]620 return self.import_name621622 @property623 def propagate_exceptions(self):624 """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration625 value in case it's set, otherwise a sensible default is returned.626627 .. versionadded:: 0.7628 """629 rv = self.config["PROPAGATE_EXCEPTIONS"]630 if rv is not None:631 return rv632 return self.testing or self.debug633634 @property635 def preserve_context_on_exception(self):636 """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``637 configuration value in case it's set, otherwise a sensible default638 is returned.639640 .. versionadded:: 0.7641 """642 rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]643 if rv is not None:644 return rv645 return self.debug646647 @locked_cached_property648 def logger(self):649 """The ``'flask.app'`` logger, a standard Python650 :class:`~logging.Logger`.651652 In debug mode, the logger's :attr:`~logging.Logger.level` will be set653 to :data:`~logging.DEBUG`.654655 If there are no handlers configured, a default handler will be added.656 See :ref:`logging` for more information.657658 .. versionchanged:: 1.0659 Behavior was simplified. The logger is always named660 ``flask.app``. The level is only set during configuration, it661 doesn't check ``app.debug`` each time. Only one format is used,662 not different ones depending on ``app.debug``. No handlers are663 removed, and a handler is only added if no handlers are already664 configured.665666 .. versionadded:: 0.3667 """668 return create_logger(self)669670 @locked_cached_property671 def jinja_env(self):672 """The Jinja environment used to load templates.673674 The environment is created the first time this property is675 accessed. Changing :attr:`jinja_options` after that will have no676 effect.677 """678 return self.create_jinja_environment()679680 @property681 def got_first_request(self):682 """This attribute is set to ``True`` if the application started683 handling the first request.684685 .. versionadded:: 0.8686 """687 return self._got_first_request688689 def make_config(self, instance_relative=False):690 """Used to create the config attribute by the Flask constructor.691 The `instance_relative` parameter is passed in from the constructor692 of Flask (there named `instance_relative_config`) and indicates if693 the config should be relative to the instance path or the root path694 of the application.695696 .. versionadded:: 0.8697 """698 root_path = self.root_path699 if instance_relative:700 root_path = self.instance_path701 defaults = dict(self.default_config)702 defaults["ENV"] = get_env()703 defaults["DEBUG"] = get_debug_flag()704 return self.config_class(root_path, defaults)705706 def auto_find_instance_path(self):707 """Tries to locate the instance path if it was not provided to the708 constructor of the application class. It will basically calculate709 the path to a folder named ``instance`` next to your main file or710 the package.711712 .. versionadded:: 0.8713 """714 prefix, package_path = find_package(self.import_name)715 if prefix is None:716 return os.path.join(package_path, "instance")717 return os.path.join(prefix, "var", self.name + "-instance")718719 def open_instance_resource(self, resource, mode="rb"):720 """Opens a resource from the application's instance folder721 (:attr:`instance_path`). Otherwise works like722 :meth:`open_resource`. Instance resources can also be opened for723 writing.724725 :param resource: the name of the resource. To access resources within726 subfolders use forward slashes as separator.727 :param mode: resource file opening mode, default is 'rb'.728 """729 return open(os.path.join(self.instance_path, resource), mode)730731 @property732 def templates_auto_reload(self):733 """Reload templates when they are changed. Used by734 :meth:`create_jinja_environment`.735736 This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If737 not set, it will be enabled in debug mode.738739 .. versionadded:: 1.0740 This property was added but the underlying config and behavior741 already existed.742 """743 rv = self.config["TEMPLATES_AUTO_RELOAD"]744 return rv if rv is not None else self.debug745746 @templates_auto_reload.setter747 def templates_auto_reload(self, value):748 self.config["TEMPLATES_AUTO_RELOAD"] = value749750 def create_jinja_environment(self):751 """Create the Jinja environment based on :attr:`jinja_options`752 and the various Jinja-related methods of the app. Changing753 :attr:`jinja_options` after this will have no effect. Also adds754 Flask-related globals and filters to the environment.755756 .. versionchanged:: 0.11757 ``Environment.auto_reload`` set in accordance with758 ``TEMPLATES_AUTO_RELOAD`` configuration option.759760 .. versionadded:: 0.5761 """762 options = dict(self.jinja_options)763764 if "autoescape" not in options:765 options["autoescape"] = self.select_jinja_autoescape766767 if "auto_reload" not in options:768 options["auto_reload"] = self.templates_auto_reload769770 rv = self.jinja_environment(self, **options)771 rv.globals.update(772 url_for=url_for,773 get_flashed_messages=get_flashed_messages,774 config=self.config,775 # request, session and g are normally added with the776 # context processor for efficiency reasons but for imported777 # templates we also want the proxies in there.778 request=request,779 session=session,780 g=g,781 )782 rv.filters["tojson"] = json.tojson_filter783 return rv784785 def create_global_jinja_loader(self):786 """Creates the loader for the Jinja2 environment. Can be used to787 override just the loader and keeping the rest unchanged. It's788 discouraged to override this function. Instead one should override789 the :meth:`jinja_loader` function instead.790791 The global loader dispatches between the loaders of the application792 and the individual blueprints.793794 .. versionadded:: 0.7795 """796 return DispatchingJinjaLoader(self)797798 def select_jinja_autoescape(self, filename):799 """Returns ``True`` if autoescaping should be active for the given800 template name. If no template name is given, returns `True`.801802 .. versionadded:: 0.5803 """804 if filename is None:805 return True806 return filename.endswith((".html", ".htm", ".xml", ".xhtml"))807808 def update_template_context(self, context):809 """Update the template context with some commonly used variables.810 This injects request, session, config and g into the template811 context as well as everything template context processors want812 to inject. Note that the as of Flask 0.6, the original values813 in the context will not be overridden if a context processor814 decides to return a value with the same key.815816 :param context: the context as a dictionary that is updated in place817 to add extra variables.818 """819 funcs = self.template_context_processors[None]820 reqctx = _request_ctx_stack.top821 if reqctx is not None:822 bp = reqctx.request.blueprint823 if bp is not None and bp in self.template_context_processors:824 funcs = chain(funcs, self.template_context_processors[bp])825 orig_ctx = context.copy()826 for func in funcs:827 context.update(func())828 # make sure the original values win. This makes it possible to829 # easier add new variables in context processors without breaking830 # existing views.831 context.update(orig_ctx)832833 def make_shell_context(self):834 """Returns the shell context for an interactive shell for this835 application. This runs all the registered shell context836 processors.837838 .. versionadded:: 0.11839 """840 rv = {"app": self, "g": g}841 for processor in self.shell_context_processors:842 rv.update(processor())843 return rv844845 #: What environment the app is running in. Flask and extensions may846 #: enable behaviors based on the environment, such as enabling debug847 #: mode. This maps to the :data:`ENV` config key. This is set by the848 #: :envvar:`FLASK_ENV` environment variable and may not behave as849 #: expected if set in code.850 #:851 #: **Do not enable development when deploying in production.**852 #:853 #: Default: ``'production'``854 env = ConfigAttribute("ENV")855856 @property857 def debug(self):858 """Whether debug mode is enabled. When using ``flask run`` to start859 the development server, an interactive debugger will be shown for860 unhandled exceptions, and the server will be reloaded when code861 changes. This maps to the :data:`DEBUG` config key. This is862 enabled when :attr:`env` is ``'development'`` and is overridden863 by the ``FLASK_DEBUG`` environment variable. It may not behave as864 expected if set in code.865866 **Do not enable debug mode when deploying in production.**867868 Default: ``True`` if :attr:`env` is ``'development'``, or869 ``False`` otherwise.870 """871 return self.config["DEBUG"]872873 @debug.setter874 def debug(self, value):875 self.config["DEBUG"] = value876 self.jinja_env.auto_reload = self.templates_auto_reload877878 def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):879 """Runs the application on a local development server.880881 Do not use ``run()`` in a production setting. It is not intended to882 meet security and performance requirements for a production server.883 Instead, see :ref:`deployment` for WSGI server recommendations.884885 If the :attr:`debug` flag is set the server will automatically reload886 for code changes and show a debugger in case an exception happened.887888 If you want to run the application in debug mode, but disable the889 code execution on the interactive debugger, you can pass890 ``use_evalex=False`` as parameter. This will keep the debugger's891 traceback screen active, but disable code execution.892893 It is not recommended to use this function for development with894 automatic reloading as this is badly supported. Instead you should895 be using the :command:`flask` command line script's ``run`` support.896897 .. admonition:: Keep in Mind898899 Flask will suppress any server error with a generic error page900 unless it is in debug mode. As such to enable just the901 interactive debugger without the code reloading, you have to902 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.903 Setting ``use_debugger`` to ``True`` without being in debug mode904 won't catch any exceptions because there won't be any to905 catch.906907 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to908 have the server available externally as well. Defaults to909 ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable910 if present.911 :param port: the port of the webserver. Defaults to ``5000`` or the912 port defined in the ``SERVER_NAME`` config variable if present.913 :param debug: if given, enable or disable debug mode. See914 :attr:`debug`.915 :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`916 files to set environment variables. Will also change the working917 directory to the directory containing the first file found.918 :param options: the options to be forwarded to the underlying Werkzeug919 server. See :func:`werkzeug.serving.run_simple` for more920 information.921922 .. versionchanged:: 1.0923 If installed, python-dotenv will be used to load environment924 variables from :file:`.env` and :file:`.flaskenv` files.925926 If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`927 environment variables will override :attr:`env` and928 :attr:`debug`.929930 Threaded mode is enabled by default.931932 .. versionchanged:: 0.10933 The default port is now picked from the ``SERVER_NAME``934 variable.935 """936 # Change this into a no-op if the server is invoked from the937 # command line. Have a look at cli.py for more information.938 if os.environ.get("FLASK_RUN_FROM_CLI") == "true":939 from .debughelpers import explain_ignored_app_run940941 explain_ignored_app_run()942 return943944 if get_load_dotenv(load_dotenv):945 cli.load_dotenv()946947 # if set, let env vars override previous values948 if "FLASK_ENV" in os.environ:949 self.env = get_env()950 self.debug = get_debug_flag()951 elif "FLASK_DEBUG" in os.environ:952 self.debug = get_debug_flag()953954 # debug passed to method overrides all other sources955 if debug is not None:956 self.debug = bool(debug)957958 _host = "127.0.0.1"959 _port = 5000960 server_name = self.config.get("SERVER_NAME")961 sn_host, sn_port = None, None962963 if server_name:964 sn_host, _, sn_port = server_name.partition(":")965966 host = host or sn_host or _host967 # pick the first value that's not None (0 is allowed)968 port = int(next((p for p in (port, sn_port) if p is not None), _port))969970 options.setdefault("use_reloader", self.debug)971 options.setdefault("use_debugger", self.debug)972 options.setdefault("threaded", True)973974 cli.show_server_banner(self.env, self.debug, self.name, False)975976 from werkzeug.serving import run_simple977978 try:979 run_simple(host, port, self, **options)980 finally:981 # reset the first request information if the development server982 # reset normally. This makes it possible to restart the server983 # without reloader and that stuff from an interactive shell.984 self._got_first_request = False985986 def test_client(self, use_cookies=True, **kwargs):987 """Creates a test client for this application. For information988 about unit testing head over to :ref:`testing`.989990 Note that if you are testing for assertions or exceptions in your991 application code, you must set ``app.testing = True`` in order for the992 exceptions to propagate to the test client. Otherwise, the exception993 will be handled by the application (not visible to the test client) and994 the only indication of an AssertionError or other exception will be a995 500 status code response to the test client. See the :attr:`testing`996 attribute. For example::997998 app.testing = True999 client = app.test_client()10001001 The test client can be used in a ``with`` block to defer the closing down1002 of the context until the end of the ``with`` block. This is useful if1003 you want to access the context locals for testing::10041005 with app.test_client() as c:1006 rv = c.get('/?vodka=42')1007 assert request.args['vodka'] == '42'10081009 Additionally, you may pass optional keyword arguments that will then1010 be passed to the application's :attr:`test_client_class` constructor.1011 For example::10121013 from flask.testing import FlaskClient10141015 class CustomClient(FlaskClient):1016 def __init__(self, *args, **kwargs):1017 self._authentication = kwargs.pop("authentication")1018 super(CustomClient,self).__init__( *args, **kwargs)10191020 app.test_client_class = CustomClient1021 client = app.test_client(authentication='Basic ....')10221023 See :class:`~flask.testing.FlaskClient` for more information.10241025 .. versionchanged:: 0.41026 added support for ``with`` block usage for the client.10271028 .. versionadded:: 0.71029 The `use_cookies` parameter was added as well as the ability1030 to override the client to be used by setting the1031 :attr:`test_client_class` attribute.10321033 .. versionchanged:: 0.111034 Added `**kwargs` to support passing additional keyword arguments to1035 the constructor of :attr:`test_client_class`.1036 """1037 cls = self.test_client_class1038 if cls is None:1039 from flask.testing import FlaskClient as cls1040 return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)10411042 def test_cli_runner(self, **kwargs):1043 """Create a CLI runner for testing CLI commands.1044 See :ref:`testing-cli`.10451046 Returns an instance of :attr:`test_cli_runner_class`, by default1047 :class:`~flask.testing.FlaskCliRunner`. The Flask app object is1048 passed as the first argument.10491050 .. versionadded:: 1.01051 """1052 cls = self.test_cli_runner_class10531054 if cls is None:1055 from flask.testing import FlaskCliRunner as cls10561057 return cls(self, **kwargs)10581059 def open_session(self, request):1060 """Creates or opens a new session. Default implementation stores all1061 session data in a signed cookie. This requires that the1062 :attr:`secret_key` is set. Instead of overriding this method1063 we recommend replacing the :class:`session_interface`.10641065 .. deprecated: 1.01066 Will be removed in 1.1. Use ``session_interface.open_session``1067 instead.10681069 :param request: an instance of :attr:`request_class`.1070 """10711072 warnings.warn(1073 DeprecationWarning(1074 '"open_session" is deprecated and will be removed in 1.1. Use'1075 ' "session_interface.open_session" instead.'1076 )1077 )1078 return self.session_interface.open_session(self, request)10791080 def save_session(self, session, response):1081 """Saves the session if it needs updates. For the default1082 implementation, check :meth:`open_session`. Instead of overriding this1083 method we recommend replacing the :class:`session_interface`.10841085 .. deprecated: 1.01086 Will be removed in 1.1. Use ``session_interface.save_session``1087 instead.10881089 :param session: the session to be saved (a1090 :class:`~werkzeug.contrib.securecookie.SecureCookie`1091 object)1092 :param response: an instance of :attr:`response_class`1093 """10941095 warnings.warn(1096 DeprecationWarning(1097 '"save_session" is deprecated and will be removed in 1.1. Use'1098 ' "session_interface.save_session" instead.'1099 )1100 )1101 return self.session_interface.save_session(self, session, response)11021103 def make_null_session(self):1104 """Creates a new instance of a missing session. Instead of overriding1105 this method we recommend replacing the :class:`session_interface`.11061107 .. deprecated: 1.01108 Will be removed in 1.1. Use ``session_interface.make_null_session``1109 instead.11101111 .. versionadded:: 0.71112 """11131114 warnings.warn(1115 DeprecationWarning(1116 '"make_null_session" is deprecated and will be removed in 1.1. Use'1117 ' "session_interface.make_null_session" instead.'1118 )1119 )1120 return self.session_interface.make_null_session(self)11211122 @setupmethod1123 def register_blueprint(self, blueprint, **options):1124 """Register a :class:`~flask.Blueprint` on the application. Keyword1125 arguments passed to this method will override the defaults set on the1126 blueprint.11271128 Calls the blueprint's :meth:`~flask.Blueprint.register` method after1129 recording the blueprint in the application's :attr:`blueprints`.11301131 :param blueprint: The blueprint to register.1132 :param url_prefix: Blueprint routes will be prefixed with this.1133 :param subdomain: Blueprint routes will match on this subdomain.1134 :param url_defaults: Blueprint routes will use these default values for1135 view arguments.1136 :param options: Additional keyword arguments are passed to1137 :class:`~flask.blueprints.BlueprintSetupState`. They can be1138 accessed in :meth:`~flask.Blueprint.record` callbacks.11391140 .. versionadded:: 0.71141 """1142 first_registration = False11431144 if blueprint.name in self.blueprints:1145 assert self.blueprints[blueprint.name] is blueprint, (1146 "A name collision occurred between blueprints %r and %r. Both"1147 ' share the same name "%s". Blueprints that are created on the'1148 " fly need unique names."1149 % (blueprint, self.blueprints[blueprint.name], blueprint.name)1150 )1151 else:1152 self.blueprints[blueprint.name] = blueprint1153 self._blueprint_order.append(blueprint)1154 first_registration = True11551156 blueprint.register(self, options, first_registration)11571158 def iter_blueprints(self):1159 """Iterates over all blueprints by the order they were registered.11601161 .. versionadded:: 0.111162 """1163 return iter(self._blueprint_order)11641165 @setupmethod1166 def add_url_rule(1167 self,1168 rule,1169 endpoint=None,1170 view_func=None,1171 provide_automatic_options=None,1172 **options1173 ):1174 """Connects a URL rule. Works exactly like the :meth:`route`1175 decorator. If a view_func is provided it will be registered with the1176 endpoint.11771178 Basically this example::11791180 @app.route('/')1181 def index():1182 pass11831184 Is equivalent to the following::11851186 def index():1187 pass1188 app.add_url_rule('/', 'index', index)11891190 If the view_func is not provided you will need to connect the endpoint1191 to a view function like so::11921193 app.view_functions['index'] = index11941195 Internally :meth:`route` invokes :meth:`add_url_rule` so if you want1196 to customize the behavior via subclassing you only need to change1197 this method.11981199 For more information refer to :ref:`url-route-registrations`.12001201 .. versionchanged:: 0.21202 `view_func` parameter added.12031204 .. versionchanged:: 0.61205 ``OPTIONS`` is added automatically as method.12061207 :param rule: the URL rule as string1208 :param endpoint: the endpoint for the registered URL rule. Flask1209 itself assumes the name of the view function as1210 endpoint1211 :param view_func: the function to call when serving a request to the1212 provided endpoint1213 :param provide_automatic_options: controls whether the ``OPTIONS``1214 method should be added automatically. This can also be controlled1215 by setting the ``view_func.provide_automatic_options = False``1216 before adding the rule.1217 :param options: the options to be forwarded to the underlying1218 :class:`~werkzeug.routing.Rule` object. A change1219 to Werkzeug is handling of method options. methods1220 is a list of methods this rule should be limited1221 to (``GET``, ``POST`` etc.). By default a rule1222 just listens for ``GET`` (and implicitly ``HEAD``).1223 Starting with Flask 0.6, ``OPTIONS`` is implicitly1224 added and handled by the standard request handling.1225 """1226 if endpoint is None:1227 endpoint = _endpoint_from_view_func(view_func)1228 options["endpoint"] = endpoint1229 methods = options.pop("methods", None)12301231 # if the methods are not given and the view_func object knows its1232 # methods we can use that instead. If neither exists, we go with1233 # a tuple of only ``GET`` as default.1234 if methods is None:1235 methods = getattr(view_func, "methods", None) or ("GET",)1236 if isinstance(methods, string_types):1237 raise TypeError(1238 "Allowed methods have to be iterables of strings, "1239 'for example: @app.route(..., methods=["POST"])'1240 )1241 methods = set(item.upper() for item in methods)12421243 # Methods that should always be added1244 required_methods = set(getattr(view_func, "required_methods", ()))12451246 # starting with Flask 0.8 the view_func object can disable and1247 # force-enable the automatic options handling.1248 if provide_automatic_options is None:1249 provide_automatic_options = getattr(1250 view_func, "provide_automatic_options", None1251 )12521253 if provide_automatic_options is None:1254 if "OPTIONS" not in methods:1255 provide_automatic_options = True1256 required_methods.add("OPTIONS")1257 else:1258 provide_automatic_options = False12591260 # Add the required methods now.1261 methods |= required_methods12621263 rule = self.url_rule_class(rule, methods=methods, **options)1264 rule.provide_automatic_options = provide_automatic_options12651266 self.url_map.add(rule)1267 if view_func is not None:1268 old_func = self.view_functions.get(endpoint)1269 if old_func is not None and old_func != view_func:1270 raise AssertionError(1271 "View function mapping is overwriting an "1272 "existing endpoint function: %s" % endpoint1273 )1274 self.view_functions[endpoint] = view_func12751276 def route(self, rule, **options):1277 """A decorator that is used to register a view function for a1278 given URL rule. This does the same thing as :meth:`add_url_rule`1279 but is intended for decorator usage::12801281 @app.route('/')1282 def index():1283 return 'Hello World'12841285 For more information refer to :ref:`url-route-registrations`.12861287 :param rule: the URL rule as string1288 :param endpoint: the endpoint for the registered URL rule. Flask1289 itself assumes the name of the view function as1290 endpoint1291 :param options: the options to be forwarded to the underlying1292 :class:`~werkzeug.routing.Rule` object. A change1293 to Werkzeug is handling of method options. methods1294 is a list of methods this rule should be limited1295 to (``GET``, ``POST`` etc.). By default a rule1296 just listens for ``GET`` (and implicitly ``HEAD``).1297 Starting with Flask 0.6, ``OPTIONS`` is implicitly1298 added and handled by the standard request handling.1299 """13001301 def decorator(f):1302 endpoint = options.pop("endpoint", None)1303 self.add_url_rule(rule, endpoint, f, **options)1304 return f13051306 return decorator13071308 @setupmethod1309 def endpoint(self, endpoint):1310 """A decorator to register a function as an endpoint.1311 Example::13121313 @app.endpoint('example.endpoint')1314 def example():1315 return "example"13161317 :param endpoint: the name of the endpoint1318 """13191320 def decorator(f):1321 self.view_functions[endpoint] = f1322 return f13231324 return decorator13251326 @staticmethod1327 def _get_exc_class_and_code(exc_class_or_code):1328 """Ensure that we register only exceptions as handler keys"""1329 if isinstance(exc_class_or_code, integer_types):1330 exc_class = default_exceptions[exc_class_or_code]1331 else:1332 exc_class = exc_class_or_code13331334 assert issubclass(exc_class, Exception)13351336 if issubclass(exc_class, HTTPException):1337 return exc_class, exc_class.code1338 else:1339 return exc_class, None13401341 @setupmethod1342 def errorhandler(self, code_or_exception):1343 """Register a function to handle errors by code or exception class.13441345 A decorator that is used to register a function given an1346 error code. Example::13471348 @app.errorhandler(404)1349 def page_not_found(error):1350 return 'This page does not exist', 40413511352 You can also register handlers for arbitrary exceptions::13531354 @app.errorhandler(DatabaseError)1355 def special_exception_handler(error):1356 return 'Database connection failed', 50013571358 .. versionadded:: 0.71359 Use :meth:`register_error_handler` instead of modifying1360 :attr:`error_handler_spec` directly, for application wide error1361 handlers.13621363 .. versionadded:: 0.71364 One can now additionally also register custom exception types1365 that do not necessarily have to be a subclass of the1366 :class:`~werkzeug.exceptions.HTTPException` class.13671368 :param code_or_exception: the code as integer for the handler, or1369 an arbitrary exception1370 """13711372 def decorator(f):1373 self._register_error_handler(None, code_or_exception, f)1374 return f13751376 return decorator13771378 @setupmethod1379 def register_error_handler(self, code_or_exception, f):1380 """Alternative error attach function to the :meth:`errorhandler`1381 decorator that is more straightforward to use for non decorator1382 usage.13831384 .. versionadded:: 0.71385 """1386 self._register_error_handler(None, code_or_exception, f)13871388 @setupmethod1389 def _register_error_handler(self, key, code_or_exception, f):1390 """1391 :type key: None|str1392 :type code_or_exception: int|T<=Exception1393 :type f: callable1394 """1395 if isinstance(code_or_exception, HTTPException): # old broken behavior1396 raise ValueError(1397 "Tried to register a handler for an exception instance {0!r}."1398 " Handlers can only be registered for exception classes or"1399 " HTTP error codes.".format(code_or_exception)1400 )14011402 try:1403 exc_class, code = self._get_exc_class_and_code(code_or_exception)1404 except KeyError:1405 raise KeyError(1406 "'{0}' is not a recognized HTTP error code. Use a subclass of"1407 " HTTPException with that code instead.".format(code_or_exception)1408 )14091410 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1411 handlers[exc_class] = f14121413 @setupmethod1414 def template_filter(self, name=None):1415 """A decorator that is used to register custom template filter.1416 You can specify a name for the filter, otherwise the function1417 name will be used. Example::14181419 @app.template_filter()1420 def reverse(s):1421 return s[::-1]14221423 :param name: the optional name of the filter, otherwise the1424 function name will be used.1425 """14261427 def decorator(f):1428 self.add_template_filter(f, name=name)1429 return f14301431 return decorator14321433 @setupmethod1434 def add_template_filter(self, f, name=None):1435 """Register a custom template filter. Works exactly like the1436 :meth:`template_filter` decorator.14371438 :param name: the optional name of the filter, otherwise the1439 function name will be used.1440 """1441 self.jinja_env.filters[name or f.__name__] = f14421443 @setupmethod1444 def template_test(self, name=None):1445 """A decorator that is used to register custom template test.1446 You can specify a name for the test, otherwise the function1447 name will be used. Example::14481449 @app.template_test()1450 def is_prime(n):1451 if n == 2:1452 return True1453 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):1454 if n % i == 0:1455 return False1456 return True14571458 .. versionadded:: 0.1014591460 :param name: the optional name of the test, otherwise the1461 function name will be used.1462 """14631464 def decorator(f):1465 self.add_template_test(f, name=name)1466 return f14671468 return decorator14691470 @setupmethod1471 def add_template_test(self, f, name=None):1472 """Register a custom template test. Works exactly like the1473 :meth:`template_test` decorator.14741475 .. versionadded:: 0.1014761477 :param name: the optional name of the test, otherwise the1478 function name will be used.1479 """1480 self.jinja_env.tests[name or f.__name__] = f14811482 @setupmethod1483 def template_global(self, name=None):1484 """A decorator that is used to register a custom template global function.1485 You can specify a name for the global function, otherwise the function1486 name will be used. Example::14871488 @app.template_global()1489 def double(n):1490 return 2 * n14911492 .. versionadded:: 0.1014931494 :param name: the optional name of the global function, otherwise the1495 function name will be used.1496 """14971498 def decorator(f):1499 self.add_template_global(f, name=name)1500 return f15011502 return decorator15031504 @setupmethod1505 def add_template_global(self, f, name=None):1506 """Register a custom template global function. Works exactly like the1507 :meth:`template_global` decorator.15081509 .. versionadded:: 0.1015101511 :param name: the optional name of the global function, otherwise the1512 function name will be used.1513 """1514 self.jinja_env.globals[name or f.__name__] = f15151516 @setupmethod1517 def before_request(self, f):1518 """Registers a function to run before each request.15191520 For example, this can be used to open a database connection, or to load1521 the logged in user from the session.15221523 The function will be called without any arguments. If it returns a1524 non-None value, the value is handled as if it was the return value from1525 the view, and further request handling is stopped.1526 """1527 self.before_request_funcs.setdefault(None, []).append(f)1528 return f15291530 @setupmethod1531 def before_first_request(self, f):1532 """Registers a function to be run before the first request to this1533 instance of the application.15341535 The function will be called without any arguments and its return1536 value is ignored.15371538 .. versionadded:: 0.81539 """1540 self.before_first_request_funcs.append(f)1541 return f15421543 @setupmethod1544 def after_request(self, f):1545 """Register a function to be run after each request.15461547 Your function must take one parameter, an instance of1548 :attr:`response_class` and return a new response object or the1549 same (see :meth:`process_response`).15501551 As of Flask 0.7 this function might not be executed at the end of the1552 request in case an unhandled exception occurred.1553 """1554 self.after_request_funcs.setdefault(None, []).append(f)1555 return f15561557 @setupmethod1558 def teardown_request(self, f):1559 """Register a function to be run at the end of each request,1560 regardless of whether there was an exception or not. These functions1561 are executed when the request context is popped, even if not an1562 actual request was performed.15631564 Example::15651566 ctx = app.test_request_context()1567 ctx.push()1568 ...1569 ctx.pop()15701571 When ``ctx.pop()`` is executed in the above example, the teardown1572 functions are called just before the request context moves from the1573 stack of active contexts. This becomes relevant if you are using1574 such constructs in tests.15751576 Generally teardown functions must take every necessary step to avoid1577 that they will fail. If they do execute code that might fail they1578 will have to surround the execution of these code by try/except1579 statements and log occurring errors.15801581 When a teardown function was called because of an exception it will1582 be passed an error object.15831584 The return values of teardown functions are ignored.15851586 .. admonition:: Debug Note15871588 In debug mode Flask will not tear down a request on an exception1589 immediately. Instead it will keep it alive so that the interactive1590 debugger can still access it. This behavior can be controlled1591 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.1592 """1593 self.teardown_request_funcs.setdefault(None, []).append(f)1594 return f15951596 @setupmethod1597 def teardown_appcontext(self, f):1598 """Registers a function to be called when the application context1599 ends. These functions are typically also called when the request1600 context is popped.16011602 Example::16031604 ctx = app.app_context()1605 ctx.push()1606 ...1607 ctx.pop()16081609 When ``ctx.pop()`` is executed in the above example, the teardown1610 functions are called just before the app context moves from the1611 stack of active contexts. This becomes relevant if you are using1612 such constructs in tests.16131614 Since a request context typically also manages an application1615 context it would also be called when you pop a request context.16161617 When a teardown function was called because of an unhandled exception1618 it will be passed an error object. If an :meth:`errorhandler` is1619 registered, it will handle the exception and the teardown will not1620 receive it.16211622 The return values of teardown functions are ignored.16231624 .. versionadded:: 0.91625 """1626 self.teardown_appcontext_funcs.append(f)1627 return f16281629 @setupmethod1630 def context_processor(self, f):1631 """Registers a template context processor function."""1632 self.template_context_processors[None].append(f)1633 return f16341635 @setupmethod1636 def shell_context_processor(self, f):1637 """Registers a shell context processor function.16381639 .. versionadded:: 0.111640 """1641 self.shell_context_processors.append(f)1642 return f16431644 @setupmethod1645 def url_value_preprocessor(self, f):1646 """Register a URL value preprocessor function for all view1647 functions in the application. These functions will be called before the1648 :meth:`before_request` functions.16491650 The function can modify the values captured from the matched url before1651 they are passed to the view. For example, this can be used to pop a1652 common language code value and place it in ``g`` rather than pass it to1653 every view.16541655 The function is passed the endpoint name and values dict. The return1656 value is ignored.1657 """1658 self.url_value_preprocessors.setdefault(None, []).append(f)1659 return f16601661 @setupmethod1662 def url_defaults(self, f):1663 """Callback function for URL defaults for all view functions of the1664 application. It's called with the endpoint and values and should1665 update the values passed in place.1666 """1667 self.url_default_functions.setdefault(None, []).append(f)1668 return f16691670 def _find_error_handler(self, e):1671 """Return a registered error handler for an exception in this order:1672 blueprint handler for a specific code, app handler for a specific code,1673 blueprint handler for an exception class, app handler for an exception1674 class, or ``None`` if a suitable handler is not found.1675 """1676 exc_class, code = self._get_exc_class_and_code(type(e))16771678 for name, c in (1679 (request.blueprint, code),1680 (None, code),1681 (request.blueprint, None),1682 (None, None),1683 ):1684 handler_map = self.error_handler_spec.setdefault(name, {}).get(c)16851686 if not handler_map:1687 continue16881689 for cls in exc_class.__mro__:1690 handler = handler_map.get(cls)16911692 if handler is not None:1693 return handler16941695 def handle_http_exception(self, e):1696 """Handles an HTTP exception. By default this will invoke the1697 registered error handlers and fall back to returning the1698 exception as response.16991700 .. versionchanged:: 1.0.31701 ``RoutingException``, used internally for actions such as1702 slash redirects during routing, is not passed to error1703 handlers.17041705 .. versionchanged:: 1.01706 Exceptions are looked up by code *and* by MRO, so1707 ``HTTPExcpetion`` subclasses can be handled with a catch-all1708 handler for the base ``HTTPException``.17091710 .. versionadded:: 0.31711 """1712 # Proxy exceptions don't have error codes. We want to always return1713 # those unchanged as errors1714 if e.code is None:1715 return e17161717 # RoutingExceptions are used internally to trigger routing1718 # actions, such as slash redirects raising RequestRedirect. They1719 # are not raised or handled in user code.1720 if isinstance(e, RoutingException):1721 return e17221723 handler = self._find_error_handler(e)1724 if handler is None:1725 return e1726 return handler(e)17271728 def trap_http_exception(self, e):1729 """Checks if an HTTP exception should be trapped or not. By default1730 this will return ``False`` for all exceptions except for a bad request1731 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It1732 also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.17331734 This is called for all HTTP exceptions raised by a view function.1735 If it returns ``True`` for any exception the error handler for this1736 exception is not called and it shows up as regular exception in the1737 traceback. This is helpful for debugging implicitly raised HTTP1738 exceptions.17391740 .. versionchanged:: 1.01741 Bad request errors are not trapped by default in debug mode.17421743 .. versionadded:: 0.81744 """1745 if self.config["TRAP_HTTP_EXCEPTIONS"]:1746 return True17471748 trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]17491750 # if unset, trap key errors in debug mode1751 if (1752 trap_bad_request is None1753 and self.debug1754 and isinstance(e, BadRequestKeyError)1755 ):1756 return True17571758 if trap_bad_request:1759 return isinstance(e, BadRequest)17601761 return False17621763 def handle_user_exception(self, e):1764 """This method is called whenever an exception occurs that1765 should be handled. A special case is :class:`~werkzeug1766 .exceptions.HTTPException` which is forwarded to the1767 :meth:`handle_http_exception` method. This function will either1768 return a response value or reraise the exception with the same1769 traceback.17701771 .. versionchanged:: 1.01772 Key errors raised from request data like ``form`` show the1773 bad key in debug mode rather than a generic bad request1774 message.17751776 .. versionadded:: 0.71777 """1778 exc_type, exc_value, tb = sys.exc_info()1779 assert exc_value is e1780 # ensure not to trash sys.exc_info() at that point in case someone1781 # wants the traceback preserved in handle_http_exception. Of course1782 # we cannot prevent users from trashing it themselves in a custom1783 # trap_http_exception method so that's their fault then.17841785 if isinstance(e, BadRequestKeyError):1786 if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]:1787 # Werkzeug < 0.15 doesn't add the KeyError to the 4001788 # message, add it in manually.1789 description = e.get_description()17901791 if e.args[0] not in description:1792 e.description = "KeyError: '{}'".format(*e.args)1793 else:1794 # Werkzeug >= 0.15 does add it, remove it in production1795 e.args = ()17961797 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1798 return self.handle_http_exception(e)17991800 handler = self._find_error_handler(e)18011802 if handler is None:1803 reraise(exc_type, exc_value, tb)1804 return handler(e)18051806 def handle_exception(self, e):1807 """Default exception handling that kicks in when an exception1808 occurs that is not caught. In debug mode the exception will1809 be re-raised immediately, otherwise it is logged and the handler1810 for a 500 internal server error is used. If no such handler1811 exists, a default 500 internal server error message is displayed.18121813 .. versionadded:: 0.31814 """1815 exc_type, exc_value, tb = sys.exc_info()1816 got_request_exception.send(self, exception=e)18171818 if self.propagate_exceptions:1819 # if we want to repropagate the exception, we can attempt to1820 # raise it with the whole traceback in case we can do that1821 # (the function was actually called from the except part)1822 # otherwise, we just raise the error again1823 if exc_value is e:1824 reraise(exc_type, exc_value, tb)1825 else:1826 raise e18271828 self.log_exception((exc_type, exc_value, tb))1829 handler = self._find_error_handler(InternalServerError())1830 if handler is None:1831 return InternalServerError()1832 return self.finalize_request(handler(e), from_error_handler=True)18331834 def log_exception(self, exc_info):1835 """Logs an exception. This is called by :meth:`handle_exception`1836 if debugging is disabled and right before the handler is called.1837 The default implementation logs the exception as error on the1838 :attr:`logger`.18391840 .. versionadded:: 0.81841 """1842 self.logger.error(1843 "Exception on %s [%s]" % (request.path, request.method), exc_info=exc_info1844 )18451846 def raise_routing_exception(self, request):1847 """Exceptions that are recording during routing are reraised with1848 this method. During debug we are not reraising redirect requests1849 for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising1850 a different error instead to help debug situations.18511852 :internal:1853 """1854 if (1855 not self.debug1856 or not isinstance(request.routing_exception, RequestRedirect)1857 or request.method in ("GET", "HEAD", "OPTIONS")1858 ):1859 raise request.routing_exception18601861 from .debughelpers import FormDataRoutingRedirect18621863 raise FormDataRoutingRedirect(request)18641865 def dispatch_request(self):1866 """Does the request dispatching. Matches the URL and returns the1867 return value of the view or error handler. This does not have to1868 be a response object. In order to convert the return value to a1869 proper response object, call :func:`make_response`.18701871 .. versionchanged:: 0.71872 This no longer does the exception handling, this code was1873 moved to the new :meth:`full_dispatch_request`.1874 """1875 req = _request_ctx_stack.top.request1876 if req.routing_exception is not None:1877 self.raise_routing_exception(req)1878 rule = req.url_rule1879 # if we provide automatic options for this URL and the1880 # request came with the OPTIONS method, reply automatically1881 if (1882 getattr(rule, "provide_automatic_options", False)1883 and req.method == "OPTIONS"1884 ):1885 return self.make_default_options_response()1886 # otherwise dispatch to the handler for that endpoint1887 return self.view_functions[rule.endpoint](**req.view_args)18881889 def full_dispatch_request(self):1890 """Dispatches the request and on top of that performs request1891 pre and postprocessing as well as HTTP exception catching and1892 error handling.18931894 .. versionadded:: 0.71895 """1896 self.try_trigger_before_first_request_functions()1897 try:1898 request_started.send(self)1899 rv = self.preprocess_request()1900 if rv is None:1901 rv = self.dispatch_request()1902 except Exception as e:1903 rv = self.handle_user_exception(e)1904 return self.finalize_request(rv)19051906 def finalize_request(self, rv, from_error_handler=False):1907 """Given the return value from a view function this finalizes1908 the request by converting it into a response and invoking the1909 postprocessing functions. This is invoked for both normal1910 request dispatching as well as error handlers.19111912 Because this means that it might be called as a result of a1913 failure a special safe mode is available which can be enabled1914 with the `from_error_handler` flag. If enabled, failures in1915 response processing will be logged and otherwise ignored.19161917 :internal:1918 """1919 response = self.make_response(rv)1920 try:1921 response = self.process_response(response)1922 request_finished.send(self, response=response)1923 except Exception:1924 if not from_error_handler:1925 raise1926 self.logger.exception(1927 "Request finalizing failed with an " "error while handling an error"1928 )1929 return response19301931 def try_trigger_before_first_request_functions(self):1932 """Called before each request and will ensure that it triggers1933 the :attr:`before_first_request_funcs` and only exactly once per1934 application instance (which means process usually).19351936 :internal:1937 """1938 if self._got_first_request:1939 return1940 with self._before_request_lock:1941 if self._got_first_request:1942 return1943 for func in self.before_first_request_funcs:1944 func()1945 self._got_first_request = True19461947 def make_default_options_response(self):1948 """This method is called to create the default ``OPTIONS`` response.1949 This can be changed through subclassing to change the default1950 behavior of ``OPTIONS`` responses.19511952 .. versionadded:: 0.71953 """1954 adapter = _request_ctx_stack.top.url_adapter1955 if hasattr(adapter, "allowed_methods"):1956 methods = adapter.allowed_methods()1957 else:1958 # fallback for Werkzeug < 0.71959 methods = []1960 try:1961 adapter.match(method="--")1962 except MethodNotAllowed as e:1963 methods = e.valid_methods1964 except HTTPException:1965 pass1966 rv = self.response_class()1967 rv.allow.update(methods)1968 return rv19691970 def should_ignore_error(self, error):1971 """This is called to figure out if an error should be ignored1972 or not as far as the teardown system is concerned. If this1973 function returns ``True`` then the teardown handlers will not be1974 passed the error.19751976 .. versionadded:: 0.101977 """1978 return False19791980 def make_response(self, rv):1981 """Convert the return value from a view function to an instance of1982 :attr:`response_class`.19831984 :param rv: the return value from the view function. The view function1985 must return a response. Returning ``None``, or the view ending1986 without returning, is not allowed. The following types are allowed1987 for ``view_rv``:19881989 ``str`` (``unicode`` in Python 2)1990 A response object is created with the string encoded to UTF-81991 as the body.19921993 ``bytes`` (``str`` in Python 2)1994 A response object is created with the bytes as the body.19951996 ``dict``1997 A dictionary that will be jsonify'd before being returned.19981999 ``tuple``2000 Either ``(body, status, headers)``, ``(body, status)``, or2001 ``(body, headers)``, where ``body`` is any of the other types2002 allowed here, ``status`` is a string or an integer, and2003 ``headers`` is a dictionary or a list of ``(key, value)``2004 tuples. If ``body`` is a :attr:`response_class` instance,2005 ``status`` overwrites the exiting value and ``headers`` are2006 extended.20072008 :attr:`response_class`2009 The object is returned unchanged.20102011 other :class:`~werkzeug.wrappers.Response` class2012 The object is coerced to :attr:`response_class`.20132014 :func:`callable`2015 The function is called as a WSGI application. The result is2016 used to create a response object.20172018 .. versionchanged:: 0.92019 Previously a tuple was interpreted as the arguments for the2020 response object.2021 """20222023 status = headers = None20242025 # unpack tuple returns2026 if isinstance(rv, tuple):2027 len_rv = len(rv)20282029 # a 3-tuple is unpacked directly2030 if len_rv == 3:2031 rv, status, headers = rv2032 # decide if a 2-tuple has status or headers2033 elif len_rv == 2:2034 if isinstance(rv[1], (Headers, dict, tuple, list)):2035 rv, headers = rv2036 else:2037 rv, status = rv2038 # other sized tuples are not allowed2039 else:2040 raise TypeError(2041 "The view function did not return a valid response tuple."2042 " The tuple must have the form (body, status, headers),"2043 " (body, status), or (body, headers)."2044 )20452046 # the body must not be None2047 if rv is None:2048 raise TypeError(2049 "The view function did not return a valid response. The"2050 " function either returned None or ended without a return"2051 " statement."2052 )20532054 # make sure the body is an instance of the response class2055 if not isinstance(rv, self.response_class):2056 if isinstance(rv, (text_type, bytes, bytearray)):2057 # let the response class set the status and headers instead of2058 # waiting to do it manually, so that the class can handle any2059 # special logic2060 rv = self.response_class(rv, status=status, headers=headers)2061 status = headers = None2062 elif isinstance(rv, dict):2063 rv = jsonify(rv)2064 elif isinstance(rv, BaseResponse) or callable(rv):2065 # evaluate a WSGI callable, or coerce a different response2066 # class to the correct type2067 try:2068 rv = self.response_class.force_type(rv, request.environ)2069 except TypeError as e:2070 new_error = TypeError(2071 "{e}\nThe view function did not return a valid"2072 " response. The return type must be a string, dict, tuple,"2073 " Response instance, or WSGI callable, but it was a"2074 " {rv.__class__.__name__}.".format(e=e, rv=rv)2075 )2076 reraise(TypeError, new_error, sys.exc_info()[2])2077 else:2078 raise TypeError(2079 "The view function did not return a valid"2080 " response. The return type must be a string, dict, tuple,"2081 " Response instance, or WSGI callable, but it was a"2082 " {rv.__class__.__name__}.".format(rv=rv)2083 )20842085 # prefer the status if it was provided2086 if status is not None:2087 if isinstance(status, (text_type, bytes, bytearray)):2088 rv.status = status2089 else:2090 rv.status_code = status20912092 # extend existing headers with provided headers2093 if headers:2094 rv.headers.extend(headers)20952096 return rv20972098 def create_url_adapter(self, request):2099 """Creates a URL adapter for the given request. The URL adapter2100 is created at a point where the request context is not yet set2101 up so the request is passed explicitly.21022103 .. versionadded:: 0.621042105 .. versionchanged:: 0.92106 This can now also be called without a request object when the2107 URL adapter is created for the application context.21082109 .. versionchanged:: 1.02110 :data:`SERVER_NAME` no longer implicitly enables subdomain2111 matching. Use :attr:`subdomain_matching` instead.2112 """2113 if request is not None:2114 # If subdomain matching is disabled (the default), use the2115 # default subdomain in all cases. This should be the default2116 # in Werkzeug but it currently does not have that feature.2117 subdomain = (2118 (self.url_map.default_subdomain or None)2119 if not self.subdomain_matching2120 else None2121 )2122 return self.url_map.bind_to_environ(2123 request.environ,2124 server_name=self.config["SERVER_NAME"],2125 subdomain=subdomain,2126 )2127 # We need at the very least the server name to be set for this2128 # to work.2129 if self.config["SERVER_NAME"] is not None:2130 return self.url_map.bind(2131 self.config["SERVER_NAME"],2132 script_name=self.config["APPLICATION_ROOT"],2133 url_scheme=self.config["PREFERRED_URL_SCHEME"],2134 )21352136 def inject_url_defaults(self, endpoint, values):2137 """Injects the URL defaults for the given endpoint directly into2138 the values dictionary passed. This is used internally and2139 automatically called on URL building.21402141 .. versionadded:: 0.72142 """2143 funcs = self.url_default_functions.get(None, ())2144 if "." in endpoint:2145 bp = endpoint.rsplit(".", 1)[0]2146 funcs = chain(funcs, self.url_default_functions.get(bp, ()))2147 for func in funcs:2148 func(endpoint, values)21492150 def handle_url_build_error(self, error, endpoint, values):2151 """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.2152 """2153 exc_type, exc_value, tb = sys.exc_info()2154 for handler in self.url_build_error_handlers:2155 try:2156 rv = handler(error, endpoint, values)2157 if rv is not None:2158 return rv2159 except BuildError as e:2160 # make error available outside except block (py3)2161 error = e21622163 # At this point we want to reraise the exception. If the error is2164 # still the same one we can reraise it with the original traceback,2165 # otherwise we raise it from here.2166 if error is exc_value:2167 reraise(exc_type, exc_value, tb)2168 raise error21692170 def preprocess_request(self):2171 """Called before the request is dispatched. Calls2172 :attr:`url_value_preprocessors` registered with the app and the2173 current blueprint (if any). Then calls :attr:`before_request_funcs`2174 registered with the app and the blueprint.21752176 If any :meth:`before_request` handler returns a non-None value, the2177 value is handled as if it was the return value from the view, and2178 further request handling is stopped.2179 """21802181 bp = _request_ctx_stack.top.request.blueprint21822183 funcs = self.url_value_preprocessors.get(None, ())2184 if bp is not None and bp in self.url_value_preprocessors:2185 funcs = chain(funcs, self.url_value_preprocessors[bp])2186 for func in funcs:2187 func(request.endpoint, request.view_args)21882189 funcs = self.before_request_funcs.get(None, ())2190 if bp is not None and bp in self.before_request_funcs:2191 funcs = chain(funcs, self.before_request_funcs[bp])2192 for func in funcs:2193 rv = func()2194 if rv is not None:2195 return rv21962197 def process_response(self, response):2198 """Can be overridden in order to modify the response object2199 before it's sent to the WSGI server. By default this will2200 call all the :meth:`after_request` decorated functions.22012202 .. versionchanged:: 0.52203 As of Flask 0.5 the functions registered for after request2204 execution are called in reverse order of registration.22052206 :param response: a :attr:`response_class` object.2207 :return: a new response object or the same, has to be an2208 instance of :attr:`response_class`.2209 """2210 ctx = _request_ctx_stack.top2211 bp = ctx.request.blueprint2212 funcs = ctx._after_request_functions2213 if bp is not None and bp in self.after_request_funcs:2214 funcs = chain(funcs, reversed(self.after_request_funcs[bp]))2215 if None in self.after_request_funcs:2216 funcs = chain(funcs, reversed(self.after_request_funcs[None]))2217 for handler in funcs:2218 response = handler(response)2219 if not self.session_interface.is_null_session(ctx.session):2220 self.session_interface.save_session(self, ctx.session, response)2221 return response22222223 def do_teardown_request(self, exc=_sentinel):2224 """Called after the request is dispatched and the response is2225 returned, right before the request context is popped.22262227 This calls all functions decorated with2228 :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`2229 if a blueprint handled the request. Finally, the2230 :data:`request_tearing_down` signal is sent.22312232 This is called by2233 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2234 which may be delayed during testing to maintain access to2235 resources.22362237 :param exc: An unhandled exception raised while dispatching the2238 request. Detected from the current exception information if2239 not passed. Passed to each teardown function.22402241 .. versionchanged:: 0.92242 Added the ``exc`` argument.2243 """2244 if exc is _sentinel:2245 exc = sys.exc_info()[1]2246 funcs = reversed(self.teardown_request_funcs.get(None, ()))2247 bp = _request_ctx_stack.top.request.blueprint2248 if bp is not None and bp in self.teardown_request_funcs:2249 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))2250 for func in funcs:2251 func(exc)2252 request_tearing_down.send(self, exc=exc)22532254 def do_teardown_appcontext(self, exc=_sentinel):2255 """Called right before the application context is popped.22562257 When handling a request, the application context is popped2258 after the request context. See :meth:`do_teardown_request`.22592260 This calls all functions decorated with2261 :meth:`teardown_appcontext`. Then the2262 :data:`appcontext_tearing_down` signal is sent.22632264 This is called by2265 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.22662267 .. versionadded:: 0.92268 """2269 if exc is _sentinel:2270 exc = sys.exc_info()[1]2271 for func in reversed(self.teardown_appcontext_funcs):2272 func(exc)2273 appcontext_tearing_down.send(self, exc=exc)22742275 def app_context(self):2276 """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``2277 block to push the context, which will make :data:`current_app`2278 point at this application.22792280 An application context is automatically pushed by2281 :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`2282 when handling a request, and when running a CLI command. Use2283 this to manually create a context outside of these situations.22842285 ::22862287 with app.app_context():2288 init_db()22892290 See :doc:`/appcontext`.22912292 .. versionadded:: 0.92293 """2294 return AppContext(self)22952296 def request_context(self, environ):2297 """Create a :class:`~flask.ctx.RequestContext` representing a2298 WSGI environment. Use a ``with`` block to push the context,2299 which will make :data:`request` point at this request.23002301 See :doc:`/reqcontext`.23022303 Typically you should not call this from your own code. A request2304 context is automatically pushed by the :meth:`wsgi_app` when2305 handling a request. Use :meth:`test_request_context` to create2306 an environment and context instead of this method.23072308 :param environ: a WSGI environment2309 """2310 return RequestContext(self, environ)23112312 def test_request_context(self, *args, **kwargs):2313 """Create a :class:`~flask.ctx.RequestContext` for a WSGI2314 environment created from the given values. This is mostly useful2315 during testing, where you may want to run a function that uses2316 request data without dispatching a full request.23172318 See :doc:`/reqcontext`.23192320 Use a ``with`` block to push the context, which will make2321 :data:`request` point at the request for the created2322 environment. ::23232324 with test_request_context(...):2325 generate_report()23262327 When using the shell, it may be easier to push and pop the2328 context manually to avoid indentation. ::23292330 ctx = app.test_request_context(...)2331 ctx.push()2332 ...2333 ctx.pop()23342335 Takes the same arguments as Werkzeug's2336 :class:`~werkzeug.test.EnvironBuilder`, with some defaults from2337 the application. See the linked Werkzeug docs for most of the2338 available arguments. Flask-specific behavior is listed here.23392340 :param path: URL path being requested.2341 :param base_url: Base URL where the app is being served, which2342 ``path`` is relative to. If not given, built from2343 :data:`PREFERRED_URL_SCHEME`, ``subdomain``,2344 :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.2345 :param subdomain: Subdomain name to append to2346 :data:`SERVER_NAME`.2347 :param url_scheme: Scheme to use instead of2348 :data:`PREFERRED_URL_SCHEME`.2349 :param data: The request body, either as a string or a dict of2350 form keys and values.2351 :param json: If given, this is serialized as JSON and passed as2352 ``data``. Also defaults ``content_type`` to2353 ``application/json``.2354 :param args: other positional arguments passed to2355 :class:`~werkzeug.test.EnvironBuilder`.2356 :param kwargs: other keyword arguments passed to2357 :class:`~werkzeug.test.EnvironBuilder`.2358 """2359 from flask.testing import EnvironBuilder23602361 builder = EnvironBuilder(self, *args, **kwargs)23622363 try:2364 return self.request_context(builder.get_environ())2365 finally:2366 builder.close()23672368 def wsgi_app(self, environ, start_response):2369 """The actual WSGI application. This is not implemented in2370 :meth:`__call__` so that middlewares can be applied without2371 losing a reference to the app object. Instead of doing this::23722373 app = MyMiddleware(app)23742375 It's a better idea to do this instead::23762377 app.wsgi_app = MyMiddleware(app.wsgi_app)23782379 Then you still have the original application object around and2380 can continue to call methods on it.23812382 .. versionchanged:: 0.72383 Teardown events for the request and app contexts are called2384 even if an unhandled error occurs. Other events may not be2385 called depending on when an error occurs during dispatch.2386 See :ref:`callbacks-and-errors`.23872388 :param environ: A WSGI environment.2389 :param start_response: A callable accepting a status code,2390 a list of headers, and an optional exception context to2391 start the response.2392 """2393 ctx = self.request_context(environ)2394 error = None2395 try:2396 try:2397 ctx.push()2398 response = self.full_dispatch_request()2399 except Exception as e:2400 error = e2401 response = self.handle_exception(e)2402 except: # noqa: B0012403 error = sys.exc_info()[1]2404 raise2405 return response(environ, start_response)2406 finally:2407 if self.should_ignore_error(error):2408 error = None2409 ctx.auto_pop(error)24102411 def __call__(self, environ, start_response):2412 """The WSGI server calls the Flask application object as the2413 WSGI application. This calls :meth:`wsgi_app` which can be2414 wrapped to applying middleware."""2415 return self.wsgi_app(environ, start_response)24162417 def __repr__(self):2418 return "<%s %r>" % (self.__class__.__name__, self.name)
deleted:flask/blueprints.py-530 removed
1# -*- coding: utf-8 -*-2"""3 flask.blueprints4 ~~~~~~~~~~~~~~~~56 Blueprints are the recommended way to implement larger or more7 pluggable applications in Flask 0.7 and later.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""12from functools import update_wrapper1314from .helpers import _PackageBoundObject, _endpoint_from_view_func1516# a singleton sentinel value for parameter defaults17_sentinel = object()181920class BlueprintSetupState(object):21 """Temporary holder object for registering a blueprint with the22 application. An instance of this class is created by the23 :meth:`~flask.Blueprint.make_setup_state` method and later passed24 to all register callback functions.25 """2627 def __init__(self, blueprint, app, options, first_registration):28 #: a reference to the current application29 self.app = app3031 #: a reference to the blueprint that created this setup state.32 self.blueprint = blueprint3334 #: a dictionary with all options that were passed to the35 #: :meth:`~flask.Flask.register_blueprint` method.36 self.options = options3738 #: as blueprints can be registered multiple times with the39 #: application and not everything wants to be registered40 #: multiple times on it, this attribute can be used to figure41 #: out if the blueprint was registered in the past already.42 self.first_registration = first_registration4344 subdomain = self.options.get("subdomain")45 if subdomain is None:46 subdomain = self.blueprint.subdomain4748 #: The subdomain that the blueprint should be active for, ``None``49 #: otherwise.50 self.subdomain = subdomain5152 url_prefix = self.options.get("url_prefix")53 if url_prefix is None:54 url_prefix = self.blueprint.url_prefix55 #: The prefix that should be used for all URLs defined on the56 #: blueprint.57 self.url_prefix = url_prefix5859 #: A dictionary with URL defaults that is added to each and every60 #: URL that was defined with the blueprint.61 self.url_defaults = dict(self.blueprint.url_values_defaults)62 self.url_defaults.update(self.options.get("url_defaults", ()))6364 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):65 """A helper method to register a rule (and optionally a view function)66 to the application. The endpoint is automatically prefixed with the67 blueprint's name.68 """69 if self.url_prefix is not None:70 if rule:71 rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))72 else:73 rule = self.url_prefix74 options.setdefault("subdomain", self.subdomain)75 if endpoint is None:76 endpoint = _endpoint_from_view_func(view_func)77 defaults = self.url_defaults78 if "defaults" in options:79 defaults = dict(defaults, **options.pop("defaults"))80 self.app.add_url_rule(81 rule,82 "%s.%s" % (self.blueprint.name, endpoint),83 view_func,84 defaults=defaults,85 **options86 )878889class Blueprint(_PackageBoundObject):90 """Represents a blueprint. A blueprint is an object that records91 functions that will be called with the92 :class:`~flask.blueprints.BlueprintSetupState` later to register functions93 or other things on the main application. See :ref:`blueprints` for more94 information.9596 .. versionchanged:: 1.1.097 Blueprints have a ``cli`` group to register nested CLI commands.98 The ``cli_group`` parameter controls the name of the group under99 the ``flask`` command.100101 .. versionadded:: 0.7102 """103104 warn_on_modifications = False105 _got_registered_once = False106107 #: Blueprint local JSON decoder class to use.108 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.109 json_encoder = None110 #: Blueprint local JSON decoder class to use.111 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.112 json_decoder = None113114 # TODO remove the next three attrs when Sphinx :inherited-members: works115 # https://github.com/sphinx-doc/sphinx/issues/741116117 #: The name of the package or module that this app belongs to. Do not118 #: change this once it is set by the constructor.119 import_name = None120121 #: Location of the template files to be added to the template lookup.122 #: ``None`` if templates should not be added.123 template_folder = None124125 #: Absolute path to the package on the filesystem. Used to look up126 #: resources contained in the package.127 root_path = None128129 def __init__(130 self,131 name,132 import_name,133 static_folder=None,134 static_url_path=None,135 template_folder=None,136 url_prefix=None,137 subdomain=None,138 url_defaults=None,139 root_path=None,140 cli_group=_sentinel,141 ):142 _PackageBoundObject.__init__(143 self, import_name, template_folder, root_path=root_path144 )145 self.name = name146 self.url_prefix = url_prefix147 self.subdomain = subdomain148 self.static_folder = static_folder149 self.static_url_path = static_url_path150 self.deferred_functions = []151 if url_defaults is None:152 url_defaults = {}153 self.url_values_defaults = url_defaults154 self.cli_group = cli_group155156 def record(self, func):157 """Registers a function that is called when the blueprint is158 registered on the application. This function is called with the159 state as argument as returned by the :meth:`make_setup_state`160 method.161 """162 if self._got_registered_once and self.warn_on_modifications:163 from warnings import warn164165 warn(166 Warning(167 "The blueprint was already registered once "168 "but is getting modified now. These changes "169 "will not show up."170 )171 )172 self.deferred_functions.append(func)173174 def record_once(self, func):175 """Works like :meth:`record` but wraps the function in another176 function that will ensure the function is only called once. If the177 blueprint is registered a second time on the application, the178 function passed is not called.179 """180181 def wrapper(state):182 if state.first_registration:183 func(state)184185 return self.record(update_wrapper(wrapper, func))186187 def make_setup_state(self, app, options, first_registration=False):188 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`189 object that is later passed to the register callback functions.190 Subclasses can override this to return a subclass of the setup state.191 """192 return BlueprintSetupState(self, app, options, first_registration)193194 def register(self, app, options, first_registration=False):195 """Called by :meth:`Flask.register_blueprint` to register all views196 and callbacks registered on the blueprint with the application. Creates197 a :class:`.BlueprintSetupState` and calls each :meth:`record` callback198 with it.199200 :param app: The application this blueprint is being registered with.201 :param options: Keyword arguments forwarded from202 :meth:`~Flask.register_blueprint`.203 :param first_registration: Whether this is the first time this204 blueprint has been registered on the application.205 """206 self._got_registered_once = True207 state = self.make_setup_state(app, options, first_registration)208209 if self.has_static_folder:210 state.add_url_rule(211 self.static_url_path + "/<path:filename>",212 view_func=self.send_static_file,213 endpoint="static",214 )215216 for deferred in self.deferred_functions:217 deferred(state)218219 cli_resolved_group = options.get("cli_group", self.cli_group)220221 if not self.cli.commands:222 return223224 if cli_resolved_group is None:225 app.cli.commands.update(self.cli.commands)226 elif cli_resolved_group is _sentinel:227 self.cli.name = self.name228 app.cli.add_command(self.cli)229 else:230 self.cli.name = cli_resolved_group231 app.cli.add_command(self.cli)232233 def route(self, rule, **options):234 """Like :meth:`Flask.route` but for a blueprint. The endpoint for the235 :func:`url_for` function is prefixed with the name of the blueprint.236 """237238 def decorator(f):239 endpoint = options.pop("endpoint", f.__name__)240 self.add_url_rule(rule, endpoint, f, **options)241 return f242243 return decorator244245 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):246 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for247 the :func:`url_for` function is prefixed with the name of the blueprint.248 """249 if endpoint:250 assert "." not in endpoint, "Blueprint endpoints should not contain dots"251 if view_func and hasattr(view_func, "__name__"):252 assert (253 "." not in view_func.__name__254 ), "Blueprint view function name should not contain dots"255 self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))256257 def endpoint(self, endpoint):258 """Like :meth:`Flask.endpoint` but for a blueprint. This does not259 prefix the endpoint with the blueprint name, this has to be done260 explicitly by the user of this method. If the endpoint is prefixed261 with a `.` it will be registered to the current blueprint, otherwise262 it's an application independent endpoint.263 """264265 def decorator(f):266 def register_endpoint(state):267 state.app.view_functions[endpoint] = f268269 self.record_once(register_endpoint)270 return f271272 return decorator273274 def app_template_filter(self, name=None):275 """Register a custom template filter, available application wide. Like276 :meth:`Flask.template_filter` but for a blueprint.277278 :param name: the optional name of the filter, otherwise the279 function name will be used.280 """281282 def decorator(f):283 self.add_app_template_filter(f, name=name)284 return f285286 return decorator287288 def add_app_template_filter(self, f, name=None):289 """Register a custom template filter, available application wide. Like290 :meth:`Flask.add_template_filter` but for a blueprint. Works exactly291 like the :meth:`app_template_filter` decorator.292293 :param name: the optional name of the filter, otherwise the294 function name will be used.295 """296297 def register_template(state):298 state.app.jinja_env.filters[name or f.__name__] = f299300 self.record_once(register_template)301302 def app_template_test(self, name=None):303 """Register a custom template test, available application wide. Like304 :meth:`Flask.template_test` but for a blueprint.305306 .. versionadded:: 0.10307308 :param name: the optional name of the test, otherwise the309 function name will be used.310 """311312 def decorator(f):313 self.add_app_template_test(f, name=name)314 return f315316 return decorator317318 def add_app_template_test(self, f, name=None):319 """Register a custom template test, available application wide. Like320 :meth:`Flask.add_template_test` but for a blueprint. Works exactly321 like the :meth:`app_template_test` decorator.322323 .. versionadded:: 0.10324325 :param name: the optional name of the test, otherwise the326 function name will be used.327 """328329 def register_template(state):330 state.app.jinja_env.tests[name or f.__name__] = f331332 self.record_once(register_template)333334 def app_template_global(self, name=None):335 """Register a custom template global, available application wide. Like336 :meth:`Flask.template_global` but for a blueprint.337338 .. versionadded:: 0.10339340 :param name: the optional name of the global, otherwise the341 function name will be used.342 """343344 def decorator(f):345 self.add_app_template_global(f, name=name)346 return f347348 return decorator349350 def add_app_template_global(self, f, name=None):351 """Register a custom template global, available application wide. Like352 :meth:`Flask.add_template_global` but for a blueprint. Works exactly353 like the :meth:`app_template_global` decorator.354355 .. versionadded:: 0.10356357 :param name: the optional name of the global, otherwise the358 function name will be used.359 """360361 def register_template(state):362 state.app.jinja_env.globals[name or f.__name__] = f363364 self.record_once(register_template)365366 def before_request(self, f):367 """Like :meth:`Flask.before_request` but for a blueprint. This function368 is only executed before each request that is handled by a function of369 that blueprint.370 """371 self.record_once(372 lambda s: s.app.before_request_funcs.setdefault(self.name, []).append(f)373 )374 return f375376 def before_app_request(self, f):377 """Like :meth:`Flask.before_request`. Such a function is executed378 before each request, even if outside of a blueprint.379 """380 self.record_once(381 lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)382 )383 return f384385 def before_app_first_request(self, f):386 """Like :meth:`Flask.before_first_request`. Such a function is387 executed before the first request to the application.388 """389 self.record_once(lambda s: s.app.before_first_request_funcs.append(f))390 return f391392 def after_request(self, f):393 """Like :meth:`Flask.after_request` but for a blueprint. This function394 is only executed after each request that is handled by a function of395 that blueprint.396 """397 self.record_once(398 lambda s: s.app.after_request_funcs.setdefault(self.name, []).append(f)399 )400 return f401402 def after_app_request(self, f):403 """Like :meth:`Flask.after_request` but for a blueprint. Such a function404 is executed after each request, even if outside of the blueprint.405 """406 self.record_once(407 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)408 )409 return f410411 def teardown_request(self, f):412 """Like :meth:`Flask.teardown_request` but for a blueprint. This413 function is only executed when tearing down requests handled by a414 function of that blueprint. Teardown request functions are executed415 when the request context is popped, even when no actual request was416 performed.417 """418 self.record_once(419 lambda s: s.app.teardown_request_funcs.setdefault(self.name, []).append(f)420 )421 return f422423 def teardown_app_request(self, f):424 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a425 function is executed when tearing down each request, even if outside of426 the blueprint.427 """428 self.record_once(429 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)430 )431 return f432433 def context_processor(self, f):434 """Like :meth:`Flask.context_processor` but for a blueprint. This435 function is only executed for requests handled by a blueprint.436 """437 self.record_once(438 lambda s: s.app.template_context_processors.setdefault(439 self.name, []440 ).append(f)441 )442 return f443444 def app_context_processor(self, f):445 """Like :meth:`Flask.context_processor` but for a blueprint. Such a446 function is executed each request, even if outside of the blueprint.447 """448 self.record_once(449 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)450 )451 return f452453 def app_errorhandler(self, code):454 """Like :meth:`Flask.errorhandler` but for a blueprint. This455 handler is used for all requests, even if outside of the blueprint.456 """457458 def decorator(f):459 self.record_once(lambda s: s.app.errorhandler(code)(f))460 return f461462 return decorator463464 def url_value_preprocessor(self, f):465 """Registers a function as URL value preprocessor for this466 blueprint. It's called before the view functions are called and467 can modify the url values provided.468 """469 self.record_once(470 lambda s: s.app.url_value_preprocessors.setdefault(self.name, []).append(f)471 )472 return f473474 def url_defaults(self, f):475 """Callback function for URL defaults for this blueprint. It's called476 with the endpoint and values and should update the values passed477 in place.478 """479 self.record_once(480 lambda s: s.app.url_default_functions.setdefault(self.name, []).append(f)481 )482 return f483484 def app_url_value_preprocessor(self, f):485 """Same as :meth:`url_value_preprocessor` but application wide.486 """487 self.record_once(488 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)489 )490 return f491492 def app_url_defaults(self, f):493 """Same as :meth:`url_defaults` but application wide.494 """495 self.record_once(496 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)497 )498 return f499500 def errorhandler(self, code_or_exception):501 """Registers an error handler that becomes active for this blueprint502 only. Please be aware that routing does not happen local to a503 blueprint so an error handler for 404 usually is not handled by504 a blueprint unless it is caused inside a view function. Another505 special case is the 500 internal server error which is always looked506 up from the application.507508 Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator509 of the :class:`~flask.Flask` object.510 """511512 def decorator(f):513 self.record_once(514 lambda s: s.app._register_error_handler(self.name, code_or_exception, f)515 )516 return f517518 return decorator519520 def register_error_handler(self, code_or_exception, f):521 """Non-decorator version of the :meth:`errorhandler` error attach522 function, akin to the :meth:`~flask.Flask.register_error_handler`523 application-wide function of the :class:`~flask.Flask` object but524 for error handlers limited to this blueprint.525526 .. versionadded:: 0.11527 """528 self.record_once(529 lambda s: s.app._register_error_handler(self.name, code_or_exception, f)530 )
deleted:flask/cli.py-963 removed
1# -*- coding: utf-8 -*-2"""3 flask.cli4 ~~~~~~~~~56 A simple command line application to run flask apps.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import print_function1314import ast15import inspect16import os17import platform18import re19import sys20import traceback21from functools import update_wrapper22from operator import attrgetter23from threading import Lock, Thread2425import click26from werkzeug.utils import import_string2728from . import __version__29from ._compat import getargspec, itervalues, reraise, text_type30from .globals import current_app31from .helpers import get_debug_flag, get_env, get_load_dotenv3233try:34 import dotenv35except ImportError:36 dotenv = None3738try:39 import ssl40except ImportError:41 ssl = None424344class NoAppException(click.UsageError):45 """Raised if an application cannot be found or loaded."""464748def find_best_app(script_info, module):49 """Given a module instance this tries to find the best possible50 application in the module or raises an exception.51 """52 from . import Flask5354 # Search for the most common names first.55 for attr_name in ("app", "application"):56 app = getattr(module, attr_name, None)5758 if isinstance(app, Flask):59 return app6061 # Otherwise find the only object that is a Flask instance.62 matches = [v for v in itervalues(module.__dict__) if isinstance(v, Flask)]6364 if len(matches) == 1:65 return matches[0]66 elif len(matches) > 1:67 raise NoAppException(68 'Detected multiple Flask applications in module "{module}". Use '69 '"FLASK_APP={module}:name" to specify the correct '70 "one.".format(module=module.__name__)71 )7273 # Search for app factory functions.74 for attr_name in ("create_app", "make_app"):75 app_factory = getattr(module, attr_name, None)7677 if inspect.isfunction(app_factory):78 try:79 app = call_factory(script_info, app_factory)8081 if isinstance(app, Flask):82 return app83 except TypeError:84 if not _called_with_wrong_args(app_factory):85 raise86 raise NoAppException(87 'Detected factory "{factory}" in module "{module}", but '88 "could not call it without arguments. Use "89 "\"FLASK_APP='{module}:{factory}(args)'\" to specify "90 "arguments.".format(factory=attr_name, module=module.__name__)91 )9293 raise NoAppException(94 'Failed to find Flask application or factory in module "{module}". '95 'Use "FLASK_APP={module}:name to specify one.'.format(module=module.__name__)96 )979899def call_factory(script_info, app_factory, arguments=()):100 """Takes an app factory, a ``script_info` object and optionally a tuple101 of arguments. Checks for the existence of a script_info argument and calls102 the app_factory depending on that and the arguments provided.103 """104 args_spec = getargspec(app_factory)105 arg_names = args_spec.args106 arg_defaults = args_spec.defaults107108 if "script_info" in arg_names:109 return app_factory(*arguments, script_info=script_info)110 elif arguments:111 return app_factory(*arguments)112 elif not arguments and len(arg_names) == 1 and arg_defaults is None:113 return app_factory(script_info)114115 return app_factory()116117118def _called_with_wrong_args(factory):119 """Check whether calling a function raised a ``TypeError`` because120 the call failed or because something in the factory raised the121 error.122123 :param factory: the factory function that was called124 :return: true if the call failed125 """126 tb = sys.exc_info()[2]127128 try:129 while tb is not None:130 if tb.tb_frame.f_code is factory.__code__:131 # in the factory, it was called successfully132 return False133134 tb = tb.tb_next135136 # didn't reach the factory137 return True138 finally:139 # explicitly delete tb as it is circular referenced140 # https://docs.python.org/2/library/sys.html#sys.exc_info141 del tb142143144def find_app_by_string(script_info, module, app_name):145 """Checks if the given string is a variable name or a function. If it is a146 function, it checks for specified arguments and whether it takes a147 ``script_info`` argument and calls the function with the appropriate148 arguments.149 """150 from flask import Flask151152 match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name)153154 if not match:155 raise NoAppException(156 '"{name}" is not a valid variable name or function '157 "expression.".format(name=app_name)158 )159160 name, args = match.groups()161162 try:163 attr = getattr(module, name)164 except AttributeError as e:165 raise NoAppException(e.args[0])166167 if inspect.isfunction(attr):168 if args:169 try:170 args = ast.literal_eval("({args},)".format(args=args))171 except (ValueError, SyntaxError) as e:172 raise NoAppException(173 "Could not parse the arguments in "174 '"{app_name}".'.format(e=e, app_name=app_name)175 )176 else:177 args = ()178179 try:180 app = call_factory(script_info, attr, args)181 except TypeError as e:182 if not _called_with_wrong_args(attr):183 raise184185 raise NoAppException(186 '{e}\nThe factory "{app_name}" in module "{module}" could not '187 "be called with the specified arguments.".format(188 e=e, app_name=app_name, module=module.__name__189 )190 )191 else:192 app = attr193194 if isinstance(app, Flask):195 return app196197 raise NoAppException(198 "A valid Flask application was not obtained from "199 '"{module}:{app_name}".'.format(module=module.__name__, app_name=app_name)200 )201202203def prepare_import(path):204 """Given a filename this will try to calculate the python path, add it205 to the search path and return the actual module name that is expected.206 """207 path = os.path.realpath(path)208209 fname, ext = os.path.splitext(path)210 if ext == ".py":211 path = fname212213 if os.path.basename(path) == "__init__":214 path = os.path.dirname(path)215216 module_name = []217218 # move up until outside package structure (no __init__.py)219 while True:220 path, name = os.path.split(path)221 module_name.append(name)222223 if not os.path.exists(os.path.join(path, "__init__.py")):224 break225226 if sys.path[0] != path:227 sys.path.insert(0, path)228229 return ".".join(module_name[::-1])230231232def locate_app(script_info, module_name, app_name, raise_if_not_found=True):233 __traceback_hide__ = True # noqa: F841234235 try:236 __import__(module_name)237 except ImportError:238 # Reraise the ImportError if it occurred within the imported module.239 # Determine this by checking whether the trace has a depth > 1.240 if sys.exc_info()[-1].tb_next:241 raise NoAppException(242 'While importing "{name}", an ImportError was raised:'243 "\n\n{tb}".format(name=module_name, tb=traceback.format_exc())244 )245 elif raise_if_not_found:246 raise NoAppException('Could not import "{name}".'.format(name=module_name))247 else:248 return249250 module = sys.modules[module_name]251252 if app_name is None:253 return find_best_app(script_info, module)254 else:255 return find_app_by_string(script_info, module, app_name)256257258def get_version(ctx, param, value):259 if not value or ctx.resilient_parsing:260 return261 import werkzeug262263 message = "Python %(python)s\n" "Flask %(flask)s\n" "Werkzeug %(werkzeug)s"264 click.echo(265 message266 % {267 "python": platform.python_version(),268 "flask": __version__,269 "werkzeug": werkzeug.__version__,270 },271 color=ctx.color,272 )273 ctx.exit()274275276version_option = click.Option(277 ["--version"],278 help="Show the flask version",279 expose_value=False,280 callback=get_version,281 is_flag=True,282 is_eager=True,283)284285286class DispatchingApp(object):287 """Special application that dispatches to a Flask application which288 is imported by name in a background thread. If an error happens289 it is recorded and shown as part of the WSGI handling which in case290 of the Werkzeug debugger means that it shows up in the browser.291 """292293 def __init__(self, loader, use_eager_loading=False):294 self.loader = loader295 self._app = None296 self._lock = Lock()297 self._bg_loading_exc_info = None298 if use_eager_loading:299 self._load_unlocked()300 else:301 self._load_in_background()302303 def _load_in_background(self):304 def _load_app():305 __traceback_hide__ = True # noqa: F841306 with self._lock:307 try:308 self._load_unlocked()309 except Exception:310 self._bg_loading_exc_info = sys.exc_info()311312 t = Thread(target=_load_app, args=())313 t.start()314315 def _flush_bg_loading_exception(self):316 __traceback_hide__ = True # noqa: F841317 exc_info = self._bg_loading_exc_info318 if exc_info is not None:319 self._bg_loading_exc_info = None320 reraise(*exc_info)321322 def _load_unlocked(self):323 __traceback_hide__ = True # noqa: F841324 self._app = rv = self.loader()325 self._bg_loading_exc_info = None326 return rv327328 def __call__(self, environ, start_response):329 __traceback_hide__ = True # noqa: F841330 if self._app is not None:331 return self._app(environ, start_response)332 self._flush_bg_loading_exception()333 with self._lock:334 if self._app is not None:335 rv = self._app336 else:337 rv = self._load_unlocked()338 return rv(environ, start_response)339340341class ScriptInfo(object):342 """Helper object to deal with Flask applications. This is usually not343 necessary to interface with as it's used internally in the dispatching344 to click. In future versions of Flask this object will most likely play345 a bigger role. Typically it's created automatically by the346 :class:`FlaskGroup` but you can also manually create it and pass it347 onwards as click object.348 """349350 def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):351 #: Optionally the import path for the Flask application.352 self.app_import_path = app_import_path or os.environ.get("FLASK_APP")353 #: Optionally a function that is passed the script info to create354 #: the instance of the application.355 self.create_app = create_app356 #: A dictionary with arbitrary data that can be associated with357 #: this script info.358 self.data = {}359 self.set_debug_flag = set_debug_flag360 self._loaded_app = None361362 def load_app(self):363 """Loads the Flask app (if not yet loaded) and returns it. Calling364 this multiple times will just result in the already loaded app to365 be returned.366 """367 __traceback_hide__ = True # noqa: F841368369 if self._loaded_app is not None:370 return self._loaded_app371372 app = None373374 if self.create_app is not None:375 app = call_factory(self, self.create_app)376 else:377 if self.app_import_path:378 path, name = (379 re.split(r":(?![\\/])", self.app_import_path, 1) + [None]380 )[:2]381 import_name = prepare_import(path)382 app = locate_app(self, import_name, name)383 else:384 for path in ("wsgi.py", "app.py"):385 import_name = prepare_import(path)386 app = locate_app(self, import_name, None, raise_if_not_found=False)387388 if app:389 break390391 if not app:392 raise NoAppException(393 "Could not locate a Flask application. You did not provide "394 'the "FLASK_APP" environment variable, and a "wsgi.py" or '395 '"app.py" module was not found in the current directory.'396 )397398 if self.set_debug_flag:399 # Update the app's debug flag through the descriptor so that400 # other values repopulate as well.401 app.debug = get_debug_flag()402403 self._loaded_app = app404 return app405406407pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)408409410def with_appcontext(f):411 """Wraps a callback so that it's guaranteed to be executed with the412 script's application context. If callbacks are registered directly413 to the ``app.cli`` object then they are wrapped with this function414 by default unless it's disabled.415 """416417 @click.pass_context418 def decorator(__ctx, *args, **kwargs):419 with __ctx.ensure_object(ScriptInfo).load_app().app_context():420 return __ctx.invoke(f, *args, **kwargs)421422 return update_wrapper(decorator, f)423424425class AppGroup(click.Group):426 """This works similar to a regular click :class:`~click.Group` but it427 changes the behavior of the :meth:`command` decorator so that it428 automatically wraps the functions in :func:`with_appcontext`.429430 Not to be confused with :class:`FlaskGroup`.431 """432433 def command(self, *args, **kwargs):434 """This works exactly like the method of the same name on a regular435 :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`436 unless it's disabled by passing ``with_appcontext=False``.437 """438 wrap_for_ctx = kwargs.pop("with_appcontext", True)439440 def decorator(f):441 if wrap_for_ctx:442 f = with_appcontext(f)443 return click.Group.command(self, *args, **kwargs)(f)444445 return decorator446447 def group(self, *args, **kwargs):448 """This works exactly like the method of the same name on a regular449 :class:`click.Group` but it defaults the group class to450 :class:`AppGroup`.451 """452 kwargs.setdefault("cls", AppGroup)453 return click.Group.group(self, *args, **kwargs)454455456class FlaskGroup(AppGroup):457 """Special subclass of the :class:`AppGroup` group that supports458 loading more commands from the configured Flask app. Normally a459 developer does not have to interface with this class but there are460 some very advanced use cases for which it makes sense to create an461 instance of this.462463 For information as of why this is useful see :ref:`custom-scripts`.464465 :param add_default_commands: if this is True then the default run and466 shell commands wil be added.467 :param add_version_option: adds the ``--version`` option.468 :param create_app: an optional callback that is passed the script info and469 returns the loaded app.470 :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`471 files to set environment variables. Will also change the working472 directory to the directory containing the first file found.473 :param set_debug_flag: Set the app's debug flag based on the active474 environment475476 .. versionchanged:: 1.0477 If installed, python-dotenv will be used to load environment variables478 from :file:`.env` and :file:`.flaskenv` files.479 """480481 def __init__(482 self,483 add_default_commands=True,484 create_app=None,485 add_version_option=True,486 load_dotenv=True,487 set_debug_flag=True,488 **extra489 ):490 params = list(extra.pop("params", None) or ())491492 if add_version_option:493 params.append(version_option)494495 AppGroup.__init__(self, params=params, **extra)496 self.create_app = create_app497 self.load_dotenv = load_dotenv498 self.set_debug_flag = set_debug_flag499500 if add_default_commands:501 self.add_command(run_command)502 self.add_command(shell_command)503 self.add_command(routes_command)504505 self._loaded_plugin_commands = False506507 def _load_plugin_commands(self):508 if self._loaded_plugin_commands:509 return510 try:511 import pkg_resources512 except ImportError:513 self._loaded_plugin_commands = True514 return515516 for ep in pkg_resources.iter_entry_points("flask.commands"):517 self.add_command(ep.load(), ep.name)518 self._loaded_plugin_commands = True519520 def get_command(self, ctx, name):521 self._load_plugin_commands()522523 # We load built-in commands first as these should always be the524 # same no matter what the app does. If the app does want to525 # override this it needs to make a custom instance of this group526 # and not attach the default commands.527 #528 # This also means that the script stays functional in case the529 # application completely fails.530 rv = AppGroup.get_command(self, ctx, name)531 if rv is not None:532 return rv533534 info = ctx.ensure_object(ScriptInfo)535 try:536 rv = info.load_app().cli.get_command(ctx, name)537 if rv is not None:538 return rv539 except NoAppException:540 pass541542 def list_commands(self, ctx):543 self._load_plugin_commands()544545 # The commands available is the list of both the application (if546 # available) plus the builtin commands.547 rv = set(click.Group.list_commands(self, ctx))548 info = ctx.ensure_object(ScriptInfo)549 try:550 rv.update(info.load_app().cli.list_commands(ctx))551 except Exception:552 # Here we intentionally swallow all exceptions as we don't553 # want the help page to break if the app does not exist.554 # If someone attempts to use the command we try to create555 # the app again and this will give us the error.556 # However, we will not do so silently because that would confuse557 # users.558 traceback.print_exc()559 return sorted(rv)560561 def main(self, *args, **kwargs):562 # Set a global flag that indicates that we were invoked from the563 # command line interface. This is detected by Flask.run to make the564 # call into a no-op. This is necessary to avoid ugly errors when the565 # script that is loaded here also attempts to start a server.566 os.environ["FLASK_RUN_FROM_CLI"] = "true"567568 if get_load_dotenv(self.load_dotenv):569 load_dotenv()570571 obj = kwargs.get("obj")572573 if obj is None:574 obj = ScriptInfo(575 create_app=self.create_app, set_debug_flag=self.set_debug_flag576 )577578 kwargs["obj"] = obj579 kwargs.setdefault("auto_envvar_prefix", "FLASK")580 return super(FlaskGroup, self).main(*args, **kwargs)581582583def _path_is_ancestor(path, other):584 """Take ``other`` and remove the length of ``path`` from it. Then join it585 to ``path``. If it is the original value, ``path`` is an ancestor of586 ``other``."""587 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other588589590def load_dotenv(path=None):591 """Load "dotenv" files in order of precedence to set environment variables.592593 If an env var is already set it is not overwritten, so earlier files in the594 list are preferred over later files.595596 Changes the current working directory to the location of the first file597 found, with the assumption that it is in the top level project directory598 and will be where the Python path should import local packages from.599600 This is a no-op if `python-dotenv`_ is not installed.601602 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme603604 :param path: Load the file at this location instead of searching.605 :return: ``True`` if a file was loaded.606607 .. versionchanged:: 1.1.0608 Returns ``False`` when python-dotenv is not installed, or when609 the given path isn't a file.610611 .. versionadded:: 1.0612 """613 if dotenv is None:614 if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):615 click.secho(616 " * Tip: There are .env or .flaskenv files present."617 ' Do "pip install python-dotenv" to use them.',618 fg="yellow",619 )620621 return False622623 # if the given path specifies the actual file then return True,624 # else False625 if path is not None:626 if os.path.isfile(path):627 return dotenv.load_dotenv(path)628629 return False630631 new_dir = None632633 for name in (".env", ".flaskenv"):634 path = dotenv.find_dotenv(name, usecwd=True)635636 if not path:637 continue638639 if new_dir is None:640 new_dir = os.path.dirname(path)641642 dotenv.load_dotenv(path)643644 if new_dir and os.getcwd() != new_dir:645 os.chdir(new_dir)646647 return new_dir is not None # at least one file was located and loaded648649650def show_server_banner(env, debug, app_import_path, eager_loading):651 """Show extra startup messages the first time the server is run,652 ignoring the reloader.653 """654 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":655 return656657 if app_import_path is not None:658 message = ' * Serving Flask app "{0}"'.format(app_import_path)659660 if not eager_loading:661 message += " (lazy loading)"662663 click.echo(message)664665 click.echo(" * Environment: {0}".format(env))666667 if env == "production":668 click.secho(669 " WARNING: This is a development server. "670 "Do not use it in a production deployment.",671 fg="red",672 )673 click.secho(" Use a production WSGI server instead.", dim=True)674675 if debug is not None:676 click.echo(" * Debug mode: {0}".format("on" if debug else "off"))677678679class CertParamType(click.ParamType):680 """Click option type for the ``--cert`` option. Allows either an681 existing file, the string ``'adhoc'``, or an import for a682 :class:`~ssl.SSLContext` object.683 """684685 name = "path"686687 def __init__(self):688 self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)689690 def convert(self, value, param, ctx):691 if ssl is None:692 raise click.BadParameter(693 'Using "--cert" requires Python to be compiled with SSL support.',694 ctx,695 param,696 )697698 try:699 return self.path_type(value, param, ctx)700 except click.BadParameter:701 value = click.STRING(value, param, ctx).lower()702703 if value == "adhoc":704 try:705 import OpenSSL # noqa: F401706 except ImportError:707 raise click.BadParameter(708 "Using ad-hoc certificates requires pyOpenSSL.", ctx, param709 )710711 return value712713 obj = import_string(value, silent=True)714715 if sys.version_info < (2, 7, 9):716 if obj:717 return obj718 else:719 if isinstance(obj, ssl.SSLContext):720 return obj721722 raise723724725def _validate_key(ctx, param, value):726 """The ``--key`` option must be specified when ``--cert`` is a file.727 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.728 """729 cert = ctx.params.get("cert")730 is_adhoc = cert == "adhoc"731732 if sys.version_info < (2, 7, 9):733 is_context = cert and not isinstance(cert, (text_type, bytes))734 else:735 is_context = isinstance(cert, ssl.SSLContext)736737 if value is not None:738 if is_adhoc:739 raise click.BadParameter(740 'When "--cert" is "adhoc", "--key" is not used.', ctx, param741 )742743 if is_context:744 raise click.BadParameter(745 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param746 )747748 if not cert:749 raise click.BadParameter('"--cert" must also be specified.', ctx, param)750751 ctx.params["cert"] = cert, value752753 else:754 if cert and not (is_adhoc or is_context):755 raise click.BadParameter('Required when using "--cert".', ctx, param)756757 return value758759760class SeparatedPathType(click.Path):761 """Click option type that accepts a list of values separated by the762 OS's path separator (``:``, ``;`` on Windows). Each value is763 validated as a :class:`click.Path` type.764 """765766 def convert(self, value, param, ctx):767 items = self.split_envvar_value(value)768 super_convert = super(SeparatedPathType, self).convert769 return [super_convert(item, param, ctx) for item in items]770771772@click.command("run", short_help="Run a development server.")773@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")774@click.option("--port", "-p", default=5000, help="The port to bind to.")775@click.option(776 "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS."777)778@click.option(779 "--key",780 type=click.Path(exists=True, dir_okay=False, resolve_path=True),781 callback=_validate_key,782 expose_value=False,783 help="The key file to use when specifying a certificate.",784)785@click.option(786 "--reload/--no-reload",787 default=None,788 help="Enable or disable the reloader. By default the reloader "789 "is active if debug is enabled.",790)791@click.option(792 "--debugger/--no-debugger",793 default=None,794 help="Enable or disable the debugger. By default the debugger "795 "is active if debug is enabled.",796)797@click.option(798 "--eager-loading/--lazy-loader",799 default=None,800 help="Enable or disable eager loading. By default eager "801 "loading is enabled if the reloader is disabled.",802)803@click.option(804 "--with-threads/--without-threads",805 default=True,806 help="Enable or disable multithreading.",807)808@click.option(809 "--extra-files",810 default=None,811 type=SeparatedPathType(),812 help=(813 "Extra files that trigger a reload on change. Multiple paths"814 " are separated by '{}'.".format(os.path.pathsep)815 ),816)817@pass_script_info818def run_command(819 info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files820):821 """Run a local development server.822823 This server is for development purposes only. It does not provide824 the stability, security, or performance of production WSGI servers.825826 The reloader and debugger are enabled by default if827 FLASK_ENV=development or FLASK_DEBUG=1.828 """829 debug = get_debug_flag()830831 if reload is None:832 reload = debug833834 if debugger is None:835 debugger = debug836837 if eager_loading is None:838 eager_loading = not reload839840 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)841 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)842843 from werkzeug.serving import run_simple844845 run_simple(846 host,847 port,848 app,849 use_reloader=reload,850 use_debugger=debugger,851 threaded=with_threads,852 ssl_context=cert,853 extra_files=extra_files,854 )855856857@click.command("shell", short_help="Run a shell in the app context.")858@with_appcontext859def shell_command():860 """Run an interactive Python shell in the context of a given861 Flask application. The application will populate the default862 namespace of this shell according to it's configuration.863864 This is useful for executing small snippets of management code865 without having to manually configure the application.866 """867 import code868 from flask.globals import _app_ctx_stack869870 app = _app_ctx_stack.top.app871 banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % (872 sys.version,873 sys.platform,874 app.import_name,875 app.env,876 app.instance_path,877 )878 ctx = {}879880 # Support the regular Python interpreter startup script if someone881 # is using it.882 startup = os.environ.get("PYTHONSTARTUP")883 if startup and os.path.isfile(startup):884 with open(startup, "r") as f:885 eval(compile(f.read(), startup, "exec"), ctx)886887 ctx.update(app.make_shell_context())888889 code.interact(banner=banner, local=ctx)890891892@click.command("routes", short_help="Show the routes for the app.")893@click.option(894 "--sort",895 "-s",896 type=click.Choice(("endpoint", "methods", "rule", "match")),897 default="endpoint",898 help=(899 'Method to sort routes by. "match" is the order that Flask will match '900 "routes when dispatching a request."901 ),902)903@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")904@with_appcontext905def routes_command(sort, all_methods):906 """Show all registered routes with endpoints and methods."""907908 rules = list(current_app.url_map.iter_rules())909 if not rules:910 click.echo("No routes were registered.")911 return912913 ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))914915 if sort in ("endpoint", "rule"):916 rules = sorted(rules, key=attrgetter(sort))917 elif sort == "methods":918 rules = sorted(rules, key=lambda rule: sorted(rule.methods))919920 rule_methods = [", ".join(sorted(rule.methods - ignored_methods)) for rule in rules]921922 headers = ("Endpoint", "Methods", "Rule")923 widths = (924 max(len(rule.endpoint) for rule in rules),925 max(len(methods) for methods in rule_methods),926 max(len(rule.rule) for rule in rules),927 )928 widths = [max(len(h), w) for h, w in zip(headers, widths)]929 row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)930931 click.echo(row.format(*headers).strip())932 click.echo(row.format(*("-" * width for width in widths)))933934 for rule, methods in zip(rules, rule_methods):935 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())936937938cli = FlaskGroup(939 help="""\940A general utility script for Flask applications.941942Provides commands from Flask, extensions, and the application. Loads the943application defined in the FLASK_APP environment variable, or from a wsgi.py944file. Setting the FLASK_ENV environment variable to 'development' will enable945debug mode.946947\b948 {prefix}{cmd} FLASK_APP=hello.py949 {prefix}{cmd} FLASK_ENV=development950 {prefix}flask run951""".format(952 cmd="export" if os.name == "posix" else "set",953 prefix="$ " if os.name == "posix" else "> ",954 )955)956957958def main(as_module=False):959 cli.main(prog_name="python -m flask" if as_module else None)960961962if __name__ == "__main__":963 main(as_module=True)
deleted:flask/config.py-268 removed
1# -*- coding: utf-8 -*-2"""3 flask.config4 ~~~~~~~~~~~~56 Implements the configuration related objects.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import os13import types14import errno1516from werkzeug.utils import import_string17from ._compat import string_types, iteritems18from . import json192021class ConfigAttribute(object):22 """Makes an attribute forward to the config"""2324 def __init__(self, name, get_converter=None):25 self.__name__ = name26 self.get_converter = get_converter2728 def __get__(self, obj, type=None):29 if obj is None:30 return self31 rv = obj.config[self.__name__]32 if self.get_converter is not None:33 rv = self.get_converter(rv)34 return rv3536 def __set__(self, obj, value):37 obj.config[self.__name__] = value383940class Config(dict):41 """Works exactly like a dict but provides ways to fill it from files42 or special dictionaries. There are two common patterns to populate the43 config.4445 Either you can fill the config from a config file::4647 app.config.from_pyfile('yourconfig.cfg')4849 Or alternatively you can define the configuration options in the50 module that calls :meth:`from_object` or provide an import path to51 a module that should be loaded. It is also possible to tell it to52 use the same module and with that provide the configuration values53 just before the call::5455 DEBUG = True56 SECRET_KEY = 'development key'57 app.config.from_object(__name__)5859 In both cases (loading from any Python file or loading from modules),60 only uppercase keys are added to the config. This makes it possible to use61 lowercase values in the config file for temporary values that are not added62 to the config or to define the config keys in the same file that implements63 the application.6465 Probably the most interesting way to load configurations is from an66 environment variable pointing to a file::6768 app.config.from_envvar('YOURAPPLICATION_SETTINGS')6970 In this case before launching the application you have to set this71 environment variable to the file you want to use. On Linux and OS X72 use the export statement::7374 export YOURAPPLICATION_SETTINGS='/path/to/config/file'7576 On windows use `set` instead.7778 :param root_path: path to which files are read relative from. When the79 config object is created by the application, this is80 the application's :attr:`~flask.Flask.root_path`.81 :param defaults: an optional dictionary of default values82 """8384 def __init__(self, root_path, defaults=None):85 dict.__init__(self, defaults or {})86 self.root_path = root_path8788 def from_envvar(self, variable_name, silent=False):89 """Loads a configuration from an environment variable pointing to90 a configuration file. This is basically just a shortcut with nicer91 error messages for this line of code::9293 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])9495 :param variable_name: name of the environment variable96 :param silent: set to ``True`` if you want silent failure for missing97 files.98 :return: bool. ``True`` if able to load config, ``False`` otherwise.99 """100 rv = os.environ.get(variable_name)101 if not rv:102 if silent:103 return False104 raise RuntimeError(105 "The environment variable %r is not set "106 "and as such configuration could not be "107 "loaded. Set this variable and make it "108 "point to a configuration file" % variable_name109 )110 return self.from_pyfile(rv, silent=silent)111112 def from_pyfile(self, filename, silent=False):113 """Updates the values in the config from a Python file. This function114 behaves as if the file was imported as module with the115 :meth:`from_object` function.116117 :param filename: the filename of the config. This can either be an118 absolute filename or a filename relative to the119 root path.120 :param silent: set to ``True`` if you want silent failure for missing121 files.122123 .. versionadded:: 0.7124 `silent` parameter.125 """126 filename = os.path.join(self.root_path, filename)127 d = types.ModuleType("config")128 d.__file__ = filename129 try:130 with open(filename, mode="rb") as config_file:131 exec(compile(config_file.read(), filename, "exec"), d.__dict__)132 except IOError as e:133 if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):134 return False135 e.strerror = "Unable to load configuration file (%s)" % e.strerror136 raise137 self.from_object(d)138 return True139140 def from_object(self, obj):141 """Updates the values from the given object. An object can be of one142 of the following two types:143144 - a string: in this case the object with that name will be imported145 - an actual object reference: that object is used directly146147 Objects are usually either modules or classes. :meth:`from_object`148 loads only the uppercase attributes of the module/class. A ``dict``149 object will not work with :meth:`from_object` because the keys of a150 ``dict`` are not attributes of the ``dict`` class.151152 Example of module-based configuration::153154 app.config.from_object('yourapplication.default_config')155 from yourapplication import default_config156 app.config.from_object(default_config)157158 Nothing is done to the object before loading. If the object is a159 class and has ``@property`` attributes, it needs to be160 instantiated before being passed to this method.161162 You should not use this function to load the actual configuration but163 rather configuration defaults. The actual config should be loaded164 with :meth:`from_pyfile` and ideally from a location not within the165 package because the package might be installed system wide.166167 See :ref:`config-dev-prod` for an example of class-based configuration168 using :meth:`from_object`.169170 :param obj: an import name or object171 """172 if isinstance(obj, string_types):173 obj = import_string(obj)174 for key in dir(obj):175 if key.isupper():176 self[key] = getattr(obj, key)177178 def from_json(self, filename, silent=False):179 """Updates the values in the config from a JSON file. This function180 behaves as if the JSON object was a dictionary and passed to the181 :meth:`from_mapping` function.182183 :param filename: the filename of the JSON file. This can either be an184 absolute filename or a filename relative to the185 root path.186 :param silent: set to ``True`` if you want silent failure for missing187 files.188189 .. versionadded:: 0.11190 """191 filename = os.path.join(self.root_path, filename)192193 try:194 with open(filename) as json_file:195 obj = json.loads(json_file.read())196 except IOError as e:197 if silent and e.errno in (errno.ENOENT, errno.EISDIR):198 return False199 e.strerror = "Unable to load configuration file (%s)" % e.strerror200 raise201 return self.from_mapping(obj)202203 def from_mapping(self, *mapping, **kwargs):204 """Updates the config like :meth:`update` ignoring items with non-upper205 keys.206207 .. versionadded:: 0.11208 """209 mappings = []210 if len(mapping) == 1:211 if hasattr(mapping[0], "items"):212 mappings.append(mapping[0].items())213 else:214 mappings.append(mapping[0])215 elif len(mapping) > 1:216 raise TypeError(217 "expected at most 1 positional argument, got %d" % len(mapping)218 )219 mappings.append(kwargs.items())220 for mapping in mappings:221 for (key, value) in mapping:222 if key.isupper():223 self[key] = value224 return True225226 def get_namespace(self, namespace, lowercase=True, trim_namespace=True):227 """Returns a dictionary containing a subset of configuration options228 that match the specified namespace/prefix. Example usage::229230 app.config['IMAGE_STORE_TYPE'] = 'fs'231 app.config['IMAGE_STORE_PATH'] = '/var/app/images'232 app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'233 image_store_config = app.config.get_namespace('IMAGE_STORE_')234235 The resulting dictionary `image_store_config` would look like::236237 {238 'type': 'fs',239 'path': '/var/app/images',240 'base_url': 'http://img.website.com'241 }242243 This is often useful when configuration options map directly to244 keyword arguments in functions or class constructors.245246 :param namespace: a configuration namespace247 :param lowercase: a flag indicating if the keys of the resulting248 dictionary should be lowercase249 :param trim_namespace: a flag indicating if the keys of the resulting250 dictionary should not include the namespace251252 .. versionadded:: 0.11253 """254 rv = {}255 for k, v in iteritems(self):256 if not k.startswith(namespace):257 continue258 if trim_namespace:259 key = k[len(namespace) :]260 else:261 key = k262 if lowercase:263 key = key.lower()264 rv[key] = v265 return rv266267 def __repr__(self):268 return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))
deleted:flask/ctx.py-472 removed
1# -*- coding: utf-8 -*-2"""3 flask.ctx4 ~~~~~~~~~56 Implements the objects required to keep the context.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import sys13from functools import update_wrapper1415from werkzeug.exceptions import HTTPException1617from .globals import _request_ctx_stack, _app_ctx_stack18from .signals import appcontext_pushed, appcontext_popped19from ._compat import BROKEN_PYPY_CTXMGR_EXIT, reraise202122# a singleton sentinel value for parameter defaults23_sentinel = object()242526class _AppCtxGlobals(object):27 """A plain object. Used as a namespace for storing data during an28 application context.2930 Creating an app context automatically creates this object, which is31 made available as the :data:`g` proxy.3233 .. describe:: 'key' in g3435 Check whether an attribute is present.3637 .. versionadded:: 0.103839 .. describe:: iter(g)4041 Return an iterator over the attribute names.4243 .. versionadded:: 0.1044 """4546 def get(self, name, default=None):47 """Get an attribute by name, or a default value. Like48 :meth:`dict.get`.4950 :param name: Name of attribute to get.51 :param default: Value to return if the attribute is not present.5253 .. versionadded:: 0.1054 """55 return self.__dict__.get(name, default)5657 def pop(self, name, default=_sentinel):58 """Get and remove an attribute by name. Like :meth:`dict.pop`.5960 :param name: Name of attribute to pop.61 :param default: Value to return if the attribute is not present,62 instead of raise a ``KeyError``.6364 .. versionadded:: 0.1165 """66 if default is _sentinel:67 return self.__dict__.pop(name)68 else:69 return self.__dict__.pop(name, default)7071 def setdefault(self, name, default=None):72 """Get the value of an attribute if it is present, otherwise73 set and return a default value. Like :meth:`dict.setdefault`.7475 :param name: Name of attribute to get.76 :param: default: Value to set and return if the attribute is not77 present.7879 .. versionadded:: 0.1180 """81 return self.__dict__.setdefault(name, default)8283 def __contains__(self, item):84 return item in self.__dict__8586 def __iter__(self):87 return iter(self.__dict__)8889 def __repr__(self):90 top = _app_ctx_stack.top91 if top is not None:92 return "<flask.g of %r>" % top.app.name93 return object.__repr__(self)949596def after_this_request(f):97 """Executes a function after this request. This is useful to modify98 response objects. The function is passed the response object and has99 to return the same or a new one.100101 Example::102103 @app.route('/')104 def index():105 @after_this_request106 def add_header(response):107 response.headers['X-Foo'] = 'Parachute'108 return response109 return 'Hello World!'110111 This is more useful if a function other than the view function wants to112 modify a response. For instance think of a decorator that wants to add113 some headers without converting the return value into a response object.114115 .. versionadded:: 0.9116 """117 _request_ctx_stack.top._after_request_functions.append(f)118 return f119120121def copy_current_request_context(f):122 """A helper function that decorates a function to retain the current123 request context. This is useful when working with greenlets. The moment124 the function is decorated a copy of the request context is created and125 then pushed when the function is called. The current session is also126 included in the copied request context.127128 Example::129130 import gevent131 from flask import copy_current_request_context132133 @app.route('/')134 def index():135 @copy_current_request_context136 def do_some_work():137 # do some work here, it can access flask.request or138 # flask.session like you would otherwise in the view function.139 ...140 gevent.spawn(do_some_work)141 return 'Regular response'142143 .. versionadded:: 0.10144 """145 top = _request_ctx_stack.top146 if top is None:147 raise RuntimeError(148 "This decorator can only be used at local scopes "149 "when a request context is on the stack. For instance within "150 "view functions."151 )152 reqctx = top.copy()153154 def wrapper(*args, **kwargs):155 with reqctx:156 return f(*args, **kwargs)157158 return update_wrapper(wrapper, f)159160161def has_request_context():162 """If you have code that wants to test if a request context is there or163 not this function can be used. For instance, you may want to take advantage164 of request information if the request object is available, but fail165 silently if it is unavailable.166167 ::168169 class User(db.Model):170171 def __init__(self, username, remote_addr=None):172 self.username = username173 if remote_addr is None and has_request_context():174 remote_addr = request.remote_addr175 self.remote_addr = remote_addr176177 Alternatively you can also just test any of the context bound objects178 (such as :class:`request` or :class:`g`) for truthness::179180 class User(db.Model):181182 def __init__(self, username, remote_addr=None):183 self.username = username184 if remote_addr is None and request:185 remote_addr = request.remote_addr186 self.remote_addr = remote_addr187188 .. versionadded:: 0.7189 """190 return _request_ctx_stack.top is not None191192193def has_app_context():194 """Works like :func:`has_request_context` but for the application195 context. You can also just do a boolean check on the196 :data:`current_app` object instead.197198 .. versionadded:: 0.9199 """200 return _app_ctx_stack.top is not None201202203class AppContext(object):204 """The application context binds an application object implicitly205 to the current thread or greenlet, similar to how the206 :class:`RequestContext` binds request information. The application207 context is also implicitly created if a request context is created208 but the application is not on top of the individual application209 context.210 """211212 def __init__(self, app):213 self.app = app214 self.url_adapter = app.create_url_adapter(None)215 self.g = app.app_ctx_globals_class()216217 # Like request context, app contexts can be pushed multiple times218 # but there a basic "refcount" is enough to track them.219 self._refcnt = 0220221 def push(self):222 """Binds the app context to the current context."""223 self._refcnt += 1224 if hasattr(sys, "exc_clear"):225 sys.exc_clear()226 _app_ctx_stack.push(self)227 appcontext_pushed.send(self.app)228229 def pop(self, exc=_sentinel):230 """Pops the app context."""231 try:232 self._refcnt -= 1233 if self._refcnt <= 0:234 if exc is _sentinel:235 exc = sys.exc_info()[1]236 self.app.do_teardown_appcontext(exc)237 finally:238 rv = _app_ctx_stack.pop()239 assert rv is self, "Popped wrong app context. (%r instead of %r)" % (rv, self)240 appcontext_popped.send(self.app)241242 def __enter__(self):243 self.push()244 return self245246 def __exit__(self, exc_type, exc_value, tb):247 self.pop(exc_value)248249 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:250 reraise(exc_type, exc_value, tb)251252253class RequestContext(object):254 """The request context contains all request relevant information. It is255 created at the beginning of the request and pushed to the256 `_request_ctx_stack` and removed at the end of it. It will create the257 URL adapter and request object for the WSGI environment provided.258259 Do not attempt to use this class directly, instead use260 :meth:`~flask.Flask.test_request_context` and261 :meth:`~flask.Flask.request_context` to create this object.262263 When the request context is popped, it will evaluate all the264 functions registered on the application for teardown execution265 (:meth:`~flask.Flask.teardown_request`).266267 The request context is automatically popped at the end of the request268 for you. In debug mode the request context is kept around if269 exceptions happen so that interactive debuggers have a chance to270 introspect the data. With 0.4 this can also be forced for requests271 that did not fail and outside of ``DEBUG`` mode. By setting272 ``'flask._preserve_context'`` to ``True`` on the WSGI environment the273 context will not pop itself at the end of the request. This is used by274 the :meth:`~flask.Flask.test_client` for example to implement the275 deferred cleanup functionality.276277 You might find this helpful for unittests where you need the278 information from the context local around for a little longer. Make279 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in280 that situation, otherwise your unittests will leak memory.281 """282283 def __init__(self, app, environ, request=None, session=None):284 self.app = app285 if request is None:286 request = app.request_class(environ)287 self.request = request288 self.url_adapter = None289 try:290 self.url_adapter = app.create_url_adapter(self.request)291 except HTTPException as e:292 self.request.routing_exception = e293 self.flashes = None294 self.session = session295296 # Request contexts can be pushed multiple times and interleaved with297 # other request contexts. Now only if the last level is popped we298 # get rid of them. Additionally if an application context is missing299 # one is created implicitly so for each level we add this information300 self._implicit_app_ctx_stack = []301302 # indicator if the context was preserved. Next time another context303 # is pushed the preserved context is popped.304 self.preserved = False305306 # remembers the exception for pop if there is one in case the context307 # preservation kicks in.308 self._preserved_exc = None309310 # Functions that should be executed after the request on the response311 # object. These will be called before the regular "after_request"312 # functions.313 self._after_request_functions = []314315 if self.url_adapter is not None:316 self.match_request()317318 @property319 def g(self):320 return _app_ctx_stack.top.g321322 @g.setter323 def g(self, value):324 _app_ctx_stack.top.g = value325326 def copy(self):327 """Creates a copy of this request context with the same request object.328 This can be used to move a request context to a different greenlet.329 Because the actual request object is the same this cannot be used to330 move a request context to a different thread unless access to the331 request object is locked.332333 .. versionadded:: 0.10334335 .. versionchanged:: 1.1336 The current session object is used instead of reloading the original337 data. This prevents `flask.session` pointing to an out-of-date object.338 """339 return self.__class__(340 self.app,341 environ=self.request.environ,342 request=self.request,343 session=self.session,344 )345346 def match_request(self):347 """Can be overridden by a subclass to hook into the matching348 of the request.349 """350 try:351 url_rule, self.request.view_args = self.url_adapter.match(return_rule=True)352 self.request.url_rule = url_rule353 except HTTPException as e:354 self.request.routing_exception = e355356 def push(self):357 """Binds the request context to the current context."""358 # If an exception occurs in debug mode or if context preservation is359 # activated under exception situations exactly one context stays360 # on the stack. The rationale is that you want to access that361 # information under debug situations. However if someone forgets to362 # pop that context again we want to make sure that on the next push363 # it's invalidated, otherwise we run at risk that something leaks364 # memory. This is usually only a problem in test suite since this365 # functionality is not active in production environments.366 top = _request_ctx_stack.top367 if top is not None and top.preserved:368 top.pop(top._preserved_exc)369370 # Before we push the request context we have to ensure that there371 # is an application context.372 app_ctx = _app_ctx_stack.top373 if app_ctx is None or app_ctx.app != self.app:374 app_ctx = self.app.app_context()375 app_ctx.push()376 self._implicit_app_ctx_stack.append(app_ctx)377 else:378 self._implicit_app_ctx_stack.append(None)379380 if hasattr(sys, "exc_clear"):381 sys.exc_clear()382383 _request_ctx_stack.push(self)384385 # Open the session at the moment that the request context is available.386 # This allows a custom open_session method to use the request context.387 # Only open a new session if this is the first time the request was388 # pushed, otherwise stream_with_context loses the session.389 if self.session is None:390 session_interface = self.app.session_interface391 self.session = session_interface.open_session(self.app, self.request)392393 if self.session is None:394 self.session = session_interface.make_null_session(self.app)395396 def pop(self, exc=_sentinel):397 """Pops the request context and unbinds it by doing that. This will398 also trigger the execution of functions registered by the399 :meth:`~flask.Flask.teardown_request` decorator.400401 .. versionchanged:: 0.9402 Added the `exc` argument.403 """404 app_ctx = self._implicit_app_ctx_stack.pop()405406 try:407 clear_request = False408 if not self._implicit_app_ctx_stack:409 self.preserved = False410 self._preserved_exc = None411 if exc is _sentinel:412 exc = sys.exc_info()[1]413 self.app.do_teardown_request(exc)414415 # If this interpreter supports clearing the exception information416 # we do that now. This will only go into effect on Python 2.x,417 # on 3.x it disappears automatically at the end of the exception418 # stack.419 if hasattr(sys, "exc_clear"):420 sys.exc_clear()421422 request_close = getattr(self.request, "close", None)423 if request_close is not None:424 request_close()425 clear_request = True426 finally:427 rv = _request_ctx_stack.pop()428429 # get rid of circular dependencies at the end of the request430 # so that we don't require the GC to be active.431 if clear_request:432 rv.request.environ["werkzeug.request"] = None433434 # Get rid of the app as well if necessary.435 if app_ctx is not None:436 app_ctx.pop(exc)437438 assert (439 rv is self440 ), "Popped wrong request context. " "(%r instead of %r)" % (rv, self)441442 def auto_pop(self, exc):443 if self.request.environ.get("flask._preserve_context") or (444 exc is not None and self.app.preserve_context_on_exception445 ):446 self.preserved = True447 self._preserved_exc = exc448 else:449 self.pop(exc)450451 def __enter__(self):452 self.push()453 return self454455 def __exit__(self, exc_type, exc_value, tb):456 # do not pop the request stack if we are in debug mode and an457 # exception happened. This will allow the debugger to still458 # access the request object in the interactive shell. Furthermore459 # the context can be force kept alive for the test client.460 # See flask.testing for how this works.461 self.auto_pop(exc_value)462463 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:464 reraise(exc_type, exc_value, tb)465466 def __repr__(self):467 return "<%s '%s' [%s] of %s>" % (468 self.__class__.__name__,469 self.request.url,470 self.request.method,471 self.app.name,472 )
deleted:flask/debughelpers.py-183 removed
1# -*- coding: utf-8 -*-2"""3 flask.debughelpers4 ~~~~~~~~~~~~~~~~~~56 Various helpers to make the development experience better.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import os13from warnings import warn1415from ._compat import implements_to_string, text_type16from .app import Flask17from .blueprints import Blueprint18from .globals import _request_ctx_stack192021class UnexpectedUnicodeError(AssertionError, UnicodeError):22 """Raised in places where we want some better error reporting for23 unexpected unicode or binary data.24 """252627@implements_to_string28class DebugFilesKeyError(KeyError, AssertionError):29 """Raised from request.files during debugging. The idea is that it can30 provide a better error message than just a generic KeyError/BadRequest.31 """3233 def __init__(self, request, key):34 form_matches = request.form.getlist(key)35 buf = [36 'You tried to access the file "%s" in the request.files '37 "dictionary but it does not exist. The mimetype for the request "38 'is "%s" instead of "multipart/form-data" which means that no '39 "file contents were transmitted. To fix this error you should "40 'provide enctype="multipart/form-data" in your form.'41 % (key, request.mimetype)42 ]43 if form_matches:44 buf.append(45 "\n\nThe browser instead transmitted some file names. "46 "This was submitted: %s" % ", ".join('"%s"' % x for x in form_matches)47 )48 self.msg = "".join(buf)4950 def __str__(self):51 return self.msg525354class FormDataRoutingRedirect(AssertionError):55 """This exception is raised by Flask in debug mode if it detects a56 redirect caused by the routing system when the request method is not57 GET, HEAD or OPTIONS. Reasoning: form data will be dropped.58 """5960 def __init__(self, request):61 exc = request.routing_exception62 buf = [63 "A request was sent to this URL (%s) but a redirect was "64 'issued automatically by the routing system to "%s".'65 % (request.url, exc.new_url)66 ]6768 # In case just a slash was appended we can be extra helpful69 if request.base_url + "/" == exc.new_url.split("?")[0]:70 buf.append(71 " The URL was defined with a trailing slash so "72 "Flask will automatically redirect to the URL "73 "with the trailing slash if it was accessed "74 "without one."75 )7677 buf.append(78 " Make sure to directly send your %s-request to this URL "79 "since we can't make browsers or HTTP clients redirect "80 "with form data reliably or without user interaction." % request.method81 )82 buf.append("\n\nNote: this exception is only raised in debug mode")83 AssertionError.__init__(self, "".join(buf).encode("utf-8"))848586def attach_enctype_error_multidict(request):87 """Since Flask 0.8 we're monkeypatching the files object in case a88 request is detected that does not use multipart form data but the files89 object is accessed.90 """91 oldcls = request.files.__class__9293 class newcls(oldcls):94 def __getitem__(self, key):95 try:96 return oldcls.__getitem__(self, key)97 except KeyError:98 if key not in request.form:99 raise100 raise DebugFilesKeyError(request, key)101102 newcls.__name__ = oldcls.__name__103 newcls.__module__ = oldcls.__module__104 request.files.__class__ = newcls105106107def _dump_loader_info(loader):108 yield "class: %s.%s" % (type(loader).__module__, type(loader).__name__)109 for key, value in sorted(loader.__dict__.items()):110 if key.startswith("_"):111 continue112 if isinstance(value, (tuple, list)):113 if not all(isinstance(x, (str, text_type)) for x in value):114 continue115 yield "%s:" % key116 for item in value:117 yield " - %s" % item118 continue119 elif not isinstance(value, (str, text_type, int, float, bool)):120 continue121 yield "%s: %r" % (key, value)122123124def explain_template_loading_attempts(app, template, attempts):125 """This should help developers understand what failed"""126 info = ['Locating template "%s":' % template]127 total_found = 0128 blueprint = None129 reqctx = _request_ctx_stack.top130 if reqctx is not None and reqctx.request.blueprint is not None:131 blueprint = reqctx.request.blueprint132133 for idx, (loader, srcobj, triple) in enumerate(attempts):134 if isinstance(srcobj, Flask):135 src_info = 'application "%s"' % srcobj.import_name136 elif isinstance(srcobj, Blueprint):137 src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name)138 else:139 src_info = repr(srcobj)140141 info.append("% 5d: trying loader of %s" % (idx + 1, src_info))142143 for line in _dump_loader_info(loader):144 info.append(" %s" % line)145146 if triple is None:147 detail = "no match"148 else:149 detail = "found (%r)" % (triple[1] or "<string>")150 total_found += 1151 info.append(" -> %s" % detail)152153 seems_fishy = False154 if total_found == 0:155 info.append("Error: the template could not be found.")156 seems_fishy = True157 elif total_found > 1:158 info.append("Warning: multiple loaders returned a match for the template.")159 seems_fishy = True160161 if blueprint is not None and seems_fishy:162 info.append(163 " The template was looked up from an endpoint that "164 'belongs to the blueprint "%s".' % blueprint165 )166 info.append(" Maybe you did not place a template in the right folder?")167 info.append(" See http://flask.pocoo.org/docs/blueprints/#templates")168169 app.logger.info("\n".join(info))170171172def explain_ignored_app_run():173 if os.environ.get("WERKZEUG_RUN_MAIN") != "true":174 warn(175 Warning(176 "Silently ignoring app.run() because the "177 "application is run from the flask command line "178 "executable. Consider putting app.run() behind an "179 'if __name__ == "__main__" guard to silence this '180 "warning."181 ),182 stacklevel=3,183 )
deleted:flask/globals.py-61 removed
1# -*- coding: utf-8 -*-2"""3 flask.globals4 ~~~~~~~~~~~~~56 Defines all the global objects that are proxies to the current7 active context.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213from functools import partial14from werkzeug.local import LocalStack, LocalProxy151617_request_ctx_err_msg = """\18Working outside of request context.1920This typically means that you attempted to use functionality that needed21an active HTTP request. Consult the documentation on testing for22information about how to avoid this problem.\23"""24_app_ctx_err_msg = """\25Working outside of application context.2627This typically means that you attempted to use functionality that needed28to interface with the current application object in some way. To solve29this, set up an application context with app.app_context(). See the30documentation for more information.\31"""323334def _lookup_req_object(name):35 top = _request_ctx_stack.top36 if top is None:37 raise RuntimeError(_request_ctx_err_msg)38 return getattr(top, name)394041def _lookup_app_object(name):42 top = _app_ctx_stack.top43 if top is None:44 raise RuntimeError(_app_ctx_err_msg)45 return getattr(top, name)464748def _find_app():49 top = _app_ctx_stack.top50 if top is None:51 raise RuntimeError(_app_ctx_err_msg)52 return top.app535455# context locals56_request_ctx_stack = LocalStack()57_app_ctx_stack = LocalStack()58current_app = LocalProxy(_find_app)59request = LocalProxy(partial(_lookup_req_object, "request"))60session = LocalProxy(partial(_lookup_req_object, "session"))61g = LocalProxy(partial(_lookup_app_object, "g"))
deleted:flask/helpers.py-1115 removed
1# -*- coding: utf-8 -*-2"""3 flask.helpers4 ~~~~~~~~~~~~~56 Implements various helpers.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""11import io12import os13import socket14import sys15import pkgutil16import posixpath17import mimetypes18from time import time19from zlib import adler3220from threading import RLock21import unicodedata22from werkzeug.routing import BuildError23from functools import update_wrapper2425from werkzeug.urls import url_quote26from werkzeug.datastructures import Headers27from werkzeug.exceptions import BadRequest, NotFound, RequestedRangeNotSatisfiable2829from werkzeug.wsgi import wrap_file30from jinja2 import FileSystemLoader3132from .signals import message_flashed33from .globals import session, _request_ctx_stack, _app_ctx_stack, current_app, request34from ._compat import string_types, text_type, PY2, fspath3536# sentinel37_missing = object()383940# what separators does this operating system provide that are not a slash?41# this is used by the send_from_directory function to ensure that nobody is42# able to access files from outside the filesystem.43_os_alt_seps = list(44 sep for sep in [os.path.sep, os.path.altsep] if sep not in (None, "/")45)464748def get_env():49 """Get the environment the app is running in, indicated by the50 :envvar:`FLASK_ENV` environment variable. The default is51 ``'production'``.52 """53 return os.environ.get("FLASK_ENV") or "production"545556def get_debug_flag():57 """Get whether debug mode should be enabled for the app, indicated58 by the :envvar:`FLASK_DEBUG` environment variable. The default is59 ``True`` if :func:`.get_env` returns ``'development'``, or ``False``60 otherwise.61 """62 val = os.environ.get("FLASK_DEBUG")6364 if not val:65 return get_env() == "development"6667 return val.lower() not in ("0", "false", "no")686970def get_load_dotenv(default=True):71 """Get whether the user has disabled loading dotenv files by setting72 :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the73 files.7475 :param default: What to return if the env var isn't set.76 """77 val = os.environ.get("FLASK_SKIP_DOTENV")7879 if not val:80 return default8182 return val.lower() in ("0", "false", "no")838485def _endpoint_from_view_func(view_func):86 """Internal helper that returns the default endpoint for a given87 function. This always is the function name.88 """89 assert view_func is not None, "expected view func if endpoint " "is not provided."90 return view_func.__name__919293def stream_with_context(generator_or_function):94 """Request contexts disappear when the response is started on the server.95 This is done for efficiency reasons and to make it less likely to encounter96 memory leaks with badly written WSGI middlewares. The downside is that if97 you are using streamed responses, the generator cannot access request bound98 information any more.99100 This function however can help you keep the context around for longer::101102 from flask import stream_with_context, request, Response103104 @app.route('/stream')105 def streamed_response():106 @stream_with_context107 def generate():108 yield 'Hello '109 yield request.args['name']110 yield '!'111 return Response(generate())112113 Alternatively it can also be used around a specific generator::114115 from flask import stream_with_context, request, Response116117 @app.route('/stream')118 def streamed_response():119 def generate():120 yield 'Hello '121 yield request.args['name']122 yield '!'123 return Response(stream_with_context(generate()))124125 .. versionadded:: 0.9126 """127 try:128 gen = iter(generator_or_function)129 except TypeError:130131 def decorator(*args, **kwargs):132 gen = generator_or_function(*args, **kwargs)133 return stream_with_context(gen)134135 return update_wrapper(decorator, generator_or_function)136137 def generator():138 ctx = _request_ctx_stack.top139 if ctx is None:140 raise RuntimeError(141 "Attempted to stream with context but "142 "there was no context in the first place to keep around."143 )144 with ctx:145 # Dummy sentinel. Has to be inside the context block or we're146 # not actually keeping the context around.147 yield None148149 # The try/finally is here so that if someone passes a WSGI level150 # iterator in we're still running the cleanup logic. Generators151 # don't need that because they are closed on their destruction152 # automatically.153 try:154 for item in gen:155 yield item156 finally:157 if hasattr(gen, "close"):158 gen.close()159160 # The trick is to start the generator. Then the code execution runs until161 # the first dummy None is yielded at which point the context was already162 # pushed. This item is discarded. Then when the iteration continues the163 # real generator is executed.164 wrapped_g = generator()165 next(wrapped_g)166 return wrapped_g167168169def make_response(*args):170 """Sometimes it is necessary to set additional headers in a view. Because171 views do not have to return response objects but can return a value that172 is converted into a response object by Flask itself, it becomes tricky to173 add headers to it. This function can be called instead of using a return174 and you will get a response object which you can use to attach headers.175176 If view looked like this and you want to add a new header::177178 def index():179 return render_template('index.html', foo=42)180181 You can now do something like this::182183 def index():184 response = make_response(render_template('index.html', foo=42))185 response.headers['X-Parachutes'] = 'parachutes are cool'186 return response187188 This function accepts the very same arguments you can return from a189 view function. This for example creates a response with a 404 error190 code::191192 response = make_response(render_template('not_found.html'), 404)193194 The other use case of this function is to force the return value of a195 view function into a response which is helpful with view196 decorators::197198 response = make_response(view_function())199 response.headers['X-Parachutes'] = 'parachutes are cool'200201 Internally this function does the following things:202203 - if no arguments are passed, it creates a new response argument204 - if one argument is passed, :meth:`flask.Flask.make_response`205 is invoked with it.206 - if more than one argument is passed, the arguments are passed207 to the :meth:`flask.Flask.make_response` function as tuple.208209 .. versionadded:: 0.6210 """211 if not args:212 return current_app.response_class()213 if len(args) == 1:214 args = args[0]215 return current_app.make_response(args)216217218def url_for(endpoint, **values):219 """Generates a URL to the given endpoint with the method provided.220221 Variable arguments that are unknown to the target endpoint are appended222 to the generated URL as query arguments. If the value of a query argument223 is ``None``, the whole pair is skipped. In case blueprints are active224 you can shortcut references to the same blueprint by prefixing the225 local endpoint with a dot (``.``).226227 This will reference the index function local to the current blueprint::228229 url_for('.index')230231 For more information, head over to the :ref:`Quickstart <url-building>`.232233 Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when234 generating URLs outside of a request context.235236 To integrate applications, :class:`Flask` has a hook to intercept URL build237 errors through :attr:`Flask.url_build_error_handlers`. The `url_for`238 function results in a :exc:`~werkzeug.routing.BuildError` when the current239 app does not have a URL for the given endpoint and values. When it does, the240 :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if241 it is not ``None``, which can return a string to use as the result of242 `url_for` (instead of `url_for`'s default to raise the243 :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.244 An example::245246 def external_url_handler(error, endpoint, values):247 "Looks up an external URL when `url_for` cannot build a URL."248 # This is an example of hooking the build_error_handler.249 # Here, lookup_url is some utility function you've built250 # which looks up the endpoint in some external URL registry.251 url = lookup_url(endpoint, **values)252 if url is None:253 # External lookup did not have a URL.254 # Re-raise the BuildError, in context of original traceback.255 exc_type, exc_value, tb = sys.exc_info()256 if exc_value is error:257 raise exc_type, exc_value, tb258 else:259 raise error260 # url_for will use this result, instead of raising BuildError.261 return url262263 app.url_build_error_handlers.append(external_url_handler)264265 Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and266 `endpoint` and `values` are the arguments passed into `url_for`. Note267 that this is for building URLs outside the current application, and not for268 handling 404 NotFound errors.269270 .. versionadded:: 0.10271 The `_scheme` parameter was added.272273 .. versionadded:: 0.9274 The `_anchor` and `_method` parameters were added.275276 .. versionadded:: 0.9277 Calls :meth:`Flask.handle_build_error` on278 :exc:`~werkzeug.routing.BuildError`.279280 :param endpoint: the endpoint of the URL (name of the function)281 :param values: the variable arguments of the URL rule282 :param _external: if set to ``True``, an absolute URL is generated. Server283 address can be changed via ``SERVER_NAME`` configuration variable which284 falls back to the `Host` header, then to the IP and port of the request.285 :param _scheme: a string specifying the desired URL scheme. The `_external`286 parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default287 behavior uses the same scheme as the current request, or288 ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no289 request context is available. As of Werkzeug 0.10, this also can be set290 to an empty string to build protocol-relative URLs.291 :param _anchor: if provided this is added as anchor to the URL.292 :param _method: if provided this explicitly specifies an HTTP method.293 """294 appctx = _app_ctx_stack.top295 reqctx = _request_ctx_stack.top296297 if appctx is None:298 raise RuntimeError(299 "Attempted to generate a URL without the application context being"300 " pushed. This has to be executed when application context is"301 " available."302 )303304 # If request specific information is available we have some extra305 # features that support "relative" URLs.306 if reqctx is not None:307 url_adapter = reqctx.url_adapter308 blueprint_name = request.blueprint309310 if endpoint[:1] == ".":311 if blueprint_name is not None:312 endpoint = blueprint_name + endpoint313 else:314 endpoint = endpoint[1:]315316 external = values.pop("_external", False)317318 # Otherwise go with the url adapter from the appctx and make319 # the URLs external by default.320 else:321 url_adapter = appctx.url_adapter322323 if url_adapter is None:324 raise RuntimeError(325 "Application was not able to create a URL adapter for request"326 " independent URL generation. You might be able to fix this by"327 " setting the SERVER_NAME config variable."328 )329330 external = values.pop("_external", True)331332 anchor = values.pop("_anchor", None)333 method = values.pop("_method", None)334 scheme = values.pop("_scheme", None)335 appctx.app.inject_url_defaults(endpoint, values)336337 # This is not the best way to deal with this but currently the338 # underlying Werkzeug router does not support overriding the scheme on339 # a per build call basis.340 old_scheme = None341 if scheme is not None:342 if not external:343 raise ValueError("When specifying _scheme, _external must be True")344 old_scheme = url_adapter.url_scheme345 url_adapter.url_scheme = scheme346347 try:348 try:349 rv = url_adapter.build(350 endpoint, values, method=method, force_external=external351 )352 finally:353 if old_scheme is not None:354 url_adapter.url_scheme = old_scheme355 except BuildError as error:356 # We need to inject the values again so that the app callback can357 # deal with that sort of stuff.358 values["_external"] = external359 values["_anchor"] = anchor360 values["_method"] = method361 values["_scheme"] = scheme362 return appctx.app.handle_url_build_error(error, endpoint, values)363364 if anchor is not None:365 rv += "#" + url_quote(anchor)366 return rv367368369def get_template_attribute(template_name, attribute):370 """Loads a macro (or variable) a template exports. This can be used to371 invoke a macro from within Python code. If you for example have a372 template named :file:`_cider.html` with the following contents:373374 .. sourcecode:: html+jinja375376 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}377378 You can access this from Python code like this::379380 hello = get_template_attribute('_cider.html', 'hello')381 return hello('World')382383 .. versionadded:: 0.2384385 :param template_name: the name of the template386 :param attribute: the name of the variable of macro to access387 """388 return getattr(current_app.jinja_env.get_template(template_name).module, attribute)389390391def flash(message, category="message"):392 """Flashes a message to the next request. In order to remove the393 flashed message from the session and to display it to the user,394 the template has to call :func:`get_flashed_messages`.395396 .. versionchanged:: 0.3397 `category` parameter added.398399 :param message: the message to be flashed.400 :param category: the category for the message. The following values401 are recommended: ``'message'`` for any kind of message,402 ``'error'`` for errors, ``'info'`` for information403 messages and ``'warning'`` for warnings. However any404 kind of string can be used as category.405 """406 # Original implementation:407 #408 # session.setdefault('_flashes', []).append((category, message))409 #410 # This assumed that changes made to mutable structures in the session are411 # always in sync with the session object, which is not true for session412 # implementations that use external storage for keeping their keys/values.413 flashes = session.get("_flashes", [])414 flashes.append((category, message))415 session["_flashes"] = flashes416 message_flashed.send(417 current_app._get_current_object(), message=message, category=category418 )419420421def get_flashed_messages(with_categories=False, category_filter=()):422 """Pulls all flashed messages from the session and returns them.423 Further calls in the same request to the function will return424 the same messages. By default just the messages are returned,425 but when `with_categories` is set to ``True``, the return value will426 be a list of tuples in the form ``(category, message)`` instead.427428 Filter the flashed messages to one or more categories by providing those429 categories in `category_filter`. This allows rendering categories in430 separate html blocks. The `with_categories` and `category_filter`431 arguments are distinct:432433 * `with_categories` controls whether categories are returned with message434 text (``True`` gives a tuple, where ``False`` gives just the message text).435 * `category_filter` filters the messages down to only those matching the436 provided categories.437438 See :ref:`message-flashing-pattern` for examples.439440 .. versionchanged:: 0.3441 `with_categories` parameter added.442443 .. versionchanged:: 0.9444 `category_filter` parameter added.445446 :param with_categories: set to ``True`` to also receive categories.447 :param category_filter: whitelist of categories to limit return values448 """449 flashes = _request_ctx_stack.top.flashes450 if flashes is None:451 _request_ctx_stack.top.flashes = flashes = (452 session.pop("_flashes") if "_flashes" in session else []453 )454 if category_filter:455 flashes = list(filter(lambda f: f[0] in category_filter, flashes))456 if not with_categories:457 return [x[1] for x in flashes]458 return flashes459460461def send_file(462 filename_or_fp,463 mimetype=None,464 as_attachment=False,465 attachment_filename=None,466 add_etags=True,467 cache_timeout=None,468 conditional=False,469 last_modified=None,470):471 """Sends the contents of a file to the client. This will use the472 most efficient method available and configured. By default it will473 try to use the WSGI server's file_wrapper support. Alternatively474 you can set the application's :attr:`~Flask.use_x_sendfile` attribute475 to ``True`` to directly emit an ``X-Sendfile`` header. This however476 requires support of the underlying webserver for ``X-Sendfile``.477478 By default it will try to guess the mimetype for you, but you can479 also explicitly provide one. For extra security you probably want480 to send certain files as attachment (HTML for instance). The mimetype481 guessing requires a `filename` or an `attachment_filename` to be482 provided.483484 ETags will also be attached automatically if a `filename` is provided. You485 can turn this off by setting `add_etags=False`.486487 If `conditional=True` and `filename` is provided, this method will try to488 upgrade the response stream to support range requests. This will allow489 the request to be answered with partial content response.490491 Please never pass filenames to this function from user sources;492 you should use :func:`send_from_directory` instead.493494 .. versionadded:: 0.2495496 .. versionadded:: 0.5497 The `add_etags`, `cache_timeout` and `conditional` parameters were498 added. The default behavior is now to attach etags.499500 .. versionchanged:: 0.7501 mimetype guessing and etag support for file objects was502 deprecated because it was unreliable. Pass a filename if you are503 able to, otherwise attach an etag yourself. This functionality504 will be removed in Flask 1.0505506 .. versionchanged:: 0.9507 cache_timeout pulls its default from application config, when None.508509 .. versionchanged:: 0.12510 The filename is no longer automatically inferred from file objects. If511 you want to use automatic mimetype and etag support, pass a filepath via512 `filename_or_fp` or `attachment_filename`.513514 .. versionchanged:: 0.12515 The `attachment_filename` is preferred over `filename` for MIME-type516 detection.517518 .. versionchanged:: 1.0519 UTF-8 filenames, as specified in `RFC 2231`_, are supported.520521 .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4522523 .. versionchanged:: 1.0.3524 Filenames are encoded with ASCII instead of Latin-1 for broader525 compatibility with WSGI servers.526527 .. versionchanged:: 1.1528 Filename may be a :class:`~os.PathLike` object.529530 .. versionadded:: 1.1531 Partial content supports :class:`~io.BytesIO`.532533 :param filename_or_fp: the filename of the file to send.534 This is relative to the :attr:`~Flask.root_path`535 if a relative path is specified.536 Alternatively a file object might be provided in537 which case ``X-Sendfile`` might not work and fall538 back to the traditional method. Make sure that the539 file pointer is positioned at the start of data to540 send before calling :func:`send_file`.541 :param mimetype: the mimetype of the file if provided. If a file path is542 given, auto detection happens as fallback, otherwise an543 error will be raised.544 :param as_attachment: set to ``True`` if you want to send this file with545 a ``Content-Disposition: attachment`` header.546 :param attachment_filename: the filename for the attachment if it547 differs from the file's filename.548 :param add_etags: set to ``False`` to disable attaching of etags.549 :param conditional: set to ``True`` to enable conditional responses.550551 :param cache_timeout: the timeout in seconds for the headers. When ``None``552 (default), this value is set by553 :meth:`~Flask.get_send_file_max_age` of554 :data:`~flask.current_app`.555 :param last_modified: set the ``Last-Modified`` header to this value,556 a :class:`~datetime.datetime` or timestamp.557 If a file was passed, this overrides its mtime.558 """559 mtime = None560 fsize = None561562 if hasattr(filename_or_fp, "__fspath__"):563 filename_or_fp = fspath(filename_or_fp)564565 if isinstance(filename_or_fp, string_types):566 filename = filename_or_fp567 if not os.path.isabs(filename):568 filename = os.path.join(current_app.root_path, filename)569 file = None570 if attachment_filename is None:571 attachment_filename = os.path.basename(filename)572 else:573 file = filename_or_fp574 filename = None575576 if mimetype is None:577 if attachment_filename is not None:578 mimetype = (579 mimetypes.guess_type(attachment_filename)[0]580 or "application/octet-stream"581 )582583 if mimetype is None:584 raise ValueError(585 "Unable to infer MIME-type because no filename is available. "586 "Please set either `attachment_filename`, pass a filepath to "587 "`filename_or_fp` or set your own MIME-type via `mimetype`."588 )589590 headers = Headers()591 if as_attachment:592 if attachment_filename is None:593 raise TypeError(594 "filename unavailable, required for " "sending as attachment"595 )596597 if not isinstance(attachment_filename, text_type):598 attachment_filename = attachment_filename.decode("utf-8")599600 try:601 attachment_filename = attachment_filename.encode("ascii")602 except UnicodeEncodeError:603 filenames = {604 "filename": unicodedata.normalize("NFKD", attachment_filename).encode(605 "ascii", "ignore"606 ),607 "filename*": "UTF-8''%s" % url_quote(attachment_filename),608 }609 else:610 filenames = {"filename": attachment_filename}611612 headers.add("Content-Disposition", "attachment", **filenames)613614 if current_app.use_x_sendfile and filename:615 if file is not None:616 file.close()617 headers["X-Sendfile"] = filename618 fsize = os.path.getsize(filename)619 headers["Content-Length"] = fsize620 data = None621 else:622 if file is None:623 file = open(filename, "rb")624 mtime = os.path.getmtime(filename)625 fsize = os.path.getsize(filename)626 headers["Content-Length"] = fsize627 elif isinstance(file, io.BytesIO):628 try:629 fsize = file.getbuffer().nbytes630 except AttributeError:631 # Python 2 doesn't have getbuffer632 fsize = len(file.getvalue())633 headers["Content-Length"] = fsize634 data = wrap_file(request.environ, file)635636 rv = current_app.response_class(637 data, mimetype=mimetype, headers=headers, direct_passthrough=True638 )639640 if last_modified is not None:641 rv.last_modified = last_modified642 elif mtime is not None:643 rv.last_modified = mtime644645 rv.cache_control.public = True646 if cache_timeout is None:647 cache_timeout = current_app.get_send_file_max_age(filename)648 if cache_timeout is not None:649 rv.cache_control.max_age = cache_timeout650 rv.expires = int(time() + cache_timeout)651652 if add_etags and filename is not None:653 from warnings import warn654655 try:656 rv.set_etag(657 "%s-%s-%s"658 % (659 os.path.getmtime(filename),660 os.path.getsize(filename),661 adler32(662 filename.encode("utf-8")663 if isinstance(filename, text_type)664 else filename665 )666 & 0xFFFFFFFF,667 )668 )669 except OSError:670 warn(671 "Access %s failed, maybe it does not exist, so ignore etags in "672 "headers" % filename,673 stacklevel=2,674 )675676 if conditional:677 try:678 rv = rv.make_conditional(request, accept_ranges=True, complete_length=fsize)679 except RequestedRangeNotSatisfiable:680 if file is not None:681 file.close()682 raise683 # make sure we don't send x-sendfile for servers that684 # ignore the 304 status code for x-sendfile.685 if rv.status_code == 304:686 rv.headers.pop("x-sendfile", None)687 return rv688689690def safe_join(directory, *pathnames):691 """Safely join `directory` and zero or more untrusted `pathnames`692 components.693694 Example usage::695696 @app.route('/wiki/<path:filename>')697 def wiki_page(filename):698 filename = safe_join(app.config['WIKI_FOLDER'], filename)699 with open(filename, 'rb') as fd:700 content = fd.read() # Read and process the file content...701702 :param directory: the trusted base directory.703 :param pathnames: the untrusted pathnames relative to that directory.704 :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed705 paths fall out of its boundaries.706 """707708 parts = [directory]709710 for filename in pathnames:711 if filename != "":712 filename = posixpath.normpath(filename)713714 if (715 any(sep in filename for sep in _os_alt_seps)716 or os.path.isabs(filename)717 or filename == ".."718 or filename.startswith("../")719 ):720 raise NotFound()721722 parts.append(filename)723724 return posixpath.join(*parts)725726727def send_from_directory(directory, filename, **options):728 """Send a file from a given directory with :func:`send_file`. This729 is a secure way to quickly expose static files from an upload folder730 or something similar.731732 Example usage::733734 @app.route('/uploads/<path:filename>')735 def download_file(filename):736 return send_from_directory(app.config['UPLOAD_FOLDER'],737 filename, as_attachment=True)738739 .. admonition:: Sending files and Performance740741 It is strongly recommended to activate either ``X-Sendfile`` support in742 your webserver or (if no authentication happens) to tell the webserver743 to serve files for the given path on its own without calling into the744 web application for improved performance.745746 .. versionadded:: 0.5747748 :param directory: the directory where all the files are stored.749 :param filename: the filename relative to that directory to750 download.751 :param options: optional keyword arguments that are directly752 forwarded to :func:`send_file`.753 """754 filename = fspath(filename)755 directory = fspath(directory)756 filename = safe_join(directory, filename)757 if not os.path.isabs(filename):758 filename = os.path.join(current_app.root_path, filename)759 try:760 if not os.path.isfile(filename):761 raise NotFound()762 except (TypeError, ValueError):763 raise BadRequest()764 options.setdefault("conditional", True)765 return send_file(filename, **options)766767768def get_root_path(import_name):769 """Returns the path to a package or cwd if that cannot be found. This770 returns the path of a package or the folder that contains a module.771772 Not to be confused with the package path returned by :func:`find_package`.773 """774 # Module already imported and has a file attribute. Use that first.775 mod = sys.modules.get(import_name)776 if mod is not None and hasattr(mod, "__file__"):777 return os.path.dirname(os.path.abspath(mod.__file__))778779 # Next attempt: check the loader.780 loader = pkgutil.get_loader(import_name)781782 # Loader does not exist or we're referring to an unloaded main module783 # or a main module without path (interactive sessions), go with the784 # current working directory.785 if loader is None or import_name == "__main__":786 return os.getcwd()787788 # For .egg, zipimporter does not have get_filename until Python 2.7.789 # Some other loaders might exhibit the same behavior.790 if hasattr(loader, "get_filename"):791 filepath = loader.get_filename(import_name)792 else:793 # Fall back to imports.794 __import__(import_name)795 mod = sys.modules[import_name]796 filepath = getattr(mod, "__file__", None)797798 # If we don't have a filepath it might be because we are a799 # namespace package. In this case we pick the root path from the800 # first module that is contained in our package.801 if filepath is None:802 raise RuntimeError(803 "No root path can be found for the provided "804 'module "%s". This can happen because the '805 "module came from an import hook that does "806 "not provide file name information or because "807 "it's a namespace package. In this case "808 "the root path needs to be explicitly "809 "provided." % import_name810 )811812 # filepath is import_name.py for a module, or __init__.py for a package.813 return os.path.dirname(os.path.abspath(filepath))814815816def _matching_loader_thinks_module_is_package(loader, mod_name):817 """Given the loader that loaded a module and the module this function818 attempts to figure out if the given module is actually a package.819 """820 # If the loader can tell us if something is a package, we can821 # directly ask the loader.822 if hasattr(loader, "is_package"):823 return loader.is_package(mod_name)824 # importlib's namespace loaders do not have this functionality but825 # all the modules it loads are packages, so we can take advantage of826 # this information.827 elif (828 loader.__class__.__module__ == "_frozen_importlib"829 and loader.__class__.__name__ == "NamespaceLoader"830 ):831 return True832 # Otherwise we need to fail with an error that explains what went833 # wrong.834 raise AttributeError(835 (836 "%s.is_package() method is missing but is required by Flask of "837 "PEP 302 import hooks. If you do not use import hooks and "838 "you encounter this error please file a bug against Flask."839 )840 % loader.__class__.__name__841 )842843844def find_package(import_name):845 """Finds a package and returns the prefix (or None if the package is846 not installed) as well as the folder that contains the package or847 module as a tuple. The package path returned is the module that would848 have to be added to the pythonpath in order to make it possible to849 import the module. The prefix is the path below which a UNIX like850 folder structure exists (lib, share etc.).851 """852 root_mod_name = import_name.split(".")[0]853 loader = pkgutil.get_loader(root_mod_name)854 if loader is None or import_name == "__main__":855 # import name is not found, or interactive/main module856 package_path = os.getcwd()857 else:858 # For .egg, zipimporter does not have get_filename until Python 2.7.859 if hasattr(loader, "get_filename"):860 filename = loader.get_filename(root_mod_name)861 elif hasattr(loader, "archive"):862 # zipimporter's loader.archive points to the .egg or .zip863 # archive filename is dropped in call to dirname below.864 filename = loader.archive865 else:866 # At least one loader is missing both get_filename and archive:867 # Google App Engine's HardenedModulesHook868 #869 # Fall back to imports.870 __import__(import_name)871 filename = sys.modules[import_name].__file__872 package_path = os.path.abspath(os.path.dirname(filename))873874 # In case the root module is a package we need to chop of the875 # rightmost part. This needs to go through a helper function876 # because of python 3.3 namespace packages.877 if _matching_loader_thinks_module_is_package(loader, root_mod_name):878 package_path = os.path.dirname(package_path)879880 site_parent, site_folder = os.path.split(package_path)881 py_prefix = os.path.abspath(sys.prefix)882 if package_path.startswith(py_prefix):883 return py_prefix, package_path884 elif site_folder.lower() == "site-packages":885 parent, folder = os.path.split(site_parent)886 # Windows like installations887 if folder.lower() == "lib":888 base_dir = parent889 # UNIX like installations890 elif os.path.basename(parent).lower() == "lib":891 base_dir = os.path.dirname(parent)892 else:893 base_dir = site_parent894 return base_dir, package_path895 return None, package_path896897898class locked_cached_property(object):899 """A decorator that converts a function into a lazy property. The900 function wrapped is called the first time to retrieve the result901 and then that calculated result is used the next time you access902 the value. Works like the one in Werkzeug but has a lock for903 thread safety.904 """905906 def __init__(self, func, name=None, doc=None):907 self.__name__ = name or func.__name__908 self.__module__ = func.__module__909 self.__doc__ = doc or func.__doc__910 self.func = func911 self.lock = RLock()912913 def __get__(self, obj, type=None):914 if obj is None:915 return self916 with self.lock:917 value = obj.__dict__.get(self.__name__, _missing)918 if value is _missing:919 value = self.func(obj)920 obj.__dict__[self.__name__] = value921 return value922923924class _PackageBoundObject(object):925 #: The name of the package or module that this app belongs to. Do not926 #: change this once it is set by the constructor.927 import_name = None928929 #: Location of the template files to be added to the template lookup.930 #: ``None`` if templates should not be added.931 template_folder = None932933 #: Absolute path to the package on the filesystem. Used to look up934 #: resources contained in the package.935 root_path = None936937 def __init__(self, import_name, template_folder=None, root_path=None):938 self.import_name = import_name939 self.template_folder = template_folder940941 if root_path is None:942 root_path = get_root_path(self.import_name)943944 self.root_path = root_path945 self._static_folder = None946 self._static_url_path = None947948 # circular import949 from .cli import AppGroup950951 #: The Click command group for registration of CLI commands952 #: on the application and associated blueprints. These commands953 #: are accessible via the :command:`flask` command once the954 #: application has been discovered and blueprints registered.955 self.cli = AppGroup()956957 @property958 def static_folder(self):959 """The absolute path to the configured static folder."""960 if self._static_folder is not None:961 return os.path.join(self.root_path, self._static_folder)962963 @static_folder.setter964 def static_folder(self, value):965 self._static_folder = value966967 @property968 def static_url_path(self):969 """The URL prefix that the static route will be accessible from.970971 If it was not configured during init, it is derived from972 :attr:`static_folder`.973 """974 if self._static_url_path is not None:975 return self._static_url_path976977 if self.static_folder is not None:978 basename = os.path.basename(self.static_folder)979 return ("/" + basename).rstrip("/")980981 @static_url_path.setter982 def static_url_path(self, value):983 if value is not None:984 value = value.rstrip("/")985986 self._static_url_path = value987988 @property989 def has_static_folder(self):990 """This is ``True`` if the package bound object's container has a991 folder for static files.992993 .. versionadded:: 0.5994 """995 return self.static_folder is not None996997 @locked_cached_property998 def jinja_loader(self):999 """The Jinja loader for this package bound object.10001001 .. versionadded:: 0.51002 """1003 if self.template_folder is not None:1004 return FileSystemLoader(os.path.join(self.root_path, self.template_folder))10051006 def get_send_file_max_age(self, filename):1007 """Provides default cache_timeout for the :func:`send_file` functions.10081009 By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from1010 the configuration of :data:`~flask.current_app`.10111012 Static file functions such as :func:`send_from_directory` use this1013 function, and :func:`send_file` calls this function on1014 :data:`~flask.current_app` when the given cache_timeout is ``None``. If a1015 cache_timeout is given in :func:`send_file`, that timeout is used;1016 otherwise, this method is called.10171018 This allows subclasses to change the behavior when sending files based1019 on the filename. For example, to set the cache timeout for .js files1020 to 60 seconds::10211022 class MyFlask(flask.Flask):1023 def get_send_file_max_age(self, name):1024 if name.lower().endswith('.js'):1025 return 601026 return flask.Flask.get_send_file_max_age(self, name)10271028 .. versionadded:: 0.91029 """1030 return total_seconds(current_app.send_file_max_age_default)10311032 def send_static_file(self, filename):1033 """Function used internally to send static files from the static1034 folder to the browser.10351036 .. versionadded:: 0.51037 """1038 if not self.has_static_folder:1039 raise RuntimeError("No static folder for this object")1040 # Ensure get_send_file_max_age is called in all cases.1041 # Here, we ensure get_send_file_max_age is called for Blueprints.1042 cache_timeout = self.get_send_file_max_age(filename)1043 return send_from_directory(1044 self.static_folder, filename, cache_timeout=cache_timeout1045 )10461047 def open_resource(self, resource, mode="rb"):1048 """Opens a resource from the application's resource folder. To see1049 how this works, consider the following folder structure::10501051 /myapplication.py1052 /schema.sql1053 /static1054 /style.css1055 /templates1056 /layout.html1057 /index.html10581059 If you want to open the :file:`schema.sql` file you would do the1060 following::10611062 with app.open_resource('schema.sql') as f:1063 contents = f.read()1064 do_something_with(contents)10651066 :param resource: the name of the resource. To access resources within1067 subfolders use forward slashes as separator.1068 :param mode: Open file in this mode. Only reading is supported,1069 valid values are "r" (or "rt") and "rb".1070 """1071 if mode not in {"r", "rt", "rb"}:1072 raise ValueError("Resources can only be opened for reading")10731074 return open(os.path.join(self.root_path, resource), mode)107510761077def total_seconds(td):1078 """Returns the total seconds from a timedelta object.10791080 :param timedelta td: the timedelta to be converted in seconds10811082 :returns: number of seconds1083 :rtype: int1084 """1085 return td.days * 60 * 60 * 24 + td.seconds108610871088def is_ip(value):1089 """Determine if the given string is an IP address.10901091 Python 2 on Windows doesn't provide ``inet_pton``, so this only1092 checks IPv4 addresses in that environment.10931094 :param value: value to check1095 :type value: str10961097 :return: True if string is an IP address1098 :rtype: bool1099 """1100 if PY2 and os.name == "nt":1101 try:1102 socket.inet_aton(value)1103 return True1104 except socket.error:1105 return False11061107 for family in (socket.AF_INET, socket.AF_INET6):1108 try:1109 socket.inet_pton(family, value)1110 except socket.error:1111 pass1112 else:1113 return True11141115 return False
deleted:flask/logging.py-78 removed
1# -*- coding: utf-8 -*-2"""3flask.logging4~~~~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""910from __future__ import absolute_import1112import logging13import sys1415from werkzeug.local import LocalProxy1617from .globals import request181920@LocalProxy21def wsgi_errors_stream():22 """Find the most appropriate error stream for the application. If a request23 is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.2425 If you configure your own :class:`logging.StreamHandler`, you may want to26 use this for the stream. If you are using file or dict configuration and27 can't import this directly, you can refer to it as28 ``ext://flask.logging.wsgi_errors_stream``.29 """30 return request.environ["wsgi.errors"] if request else sys.stderr313233def has_level_handler(logger):34 """Check if there is a handler in the logging chain that will handle the35 given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.36 """37 level = logger.getEffectiveLevel()38 current = logger3940 while current:41 if any(handler.level <= level for handler in current.handlers):42 return True4344 if not current.propagate:45 break4647 current = current.parent4849 return False505152#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format53#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.54default_handler = logging.StreamHandler(wsgi_errors_stream)55default_handler.setFormatter(56 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")57)585960def create_logger(app):61 """Get the ``'flask.app'`` logger and configure it if needed.6263 When :attr:`~flask.Flask.debug` is enabled, set the logger level to64 :data:`logging.DEBUG` if it is not set.6566 If there is no handler for the logger's effective level, add a67 :class:`~logging.StreamHandler` for68 :func:`~flask.logging.wsgi_errors_stream` with a basic format.69 """70 logger = logging.getLogger("flask.app")7172 if app.debug and logger.level == logging.NOTSET:73 logger.setLevel(logging.DEBUG)7475 if not has_level_handler(logger):76 logger.addHandler(default_handler)7778 return logger
deleted:flask/sessions.py-387 removed
1# -*- coding: utf-8 -*-2"""3 flask.sessions4 ~~~~~~~~~~~~~~56 Implements cookie based sessions based on itsdangerous.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import hashlib13import warnings14from datetime import datetime1516from itsdangerous import BadSignature, URLSafeTimedSerializer17from werkzeug.datastructures import CallbackDict1819from flask._compat import collections_abc20from flask.helpers import is_ip, total_seconds21from flask.json.tag import TaggedJSONSerializer222324class SessionMixin(collections_abc.MutableMapping):25 """Expands a basic dictionary with session attributes."""2627 @property28 def permanent(self):29 """This reflects the ``'_permanent'`` key in the dict."""30 return self.get("_permanent", False)3132 @permanent.setter33 def permanent(self, value):34 self["_permanent"] = bool(value)3536 #: Some implementations can detect whether a session is newly37 #: created, but that is not guaranteed. Use with caution. The mixin38 # default is hard-coded ``False``.39 new = False4041 #: Some implementations can detect changes to the session and set42 #: this when that happens. The mixin default is hard coded to43 #: ``True``.44 modified = True4546 #: Some implementations can detect when session data is read or47 #: written and set this when that happens. The mixin default is hard48 #: coded to ``True``.49 accessed = True505152class SecureCookieSession(CallbackDict, SessionMixin):53 """Base class for sessions based on signed cookies.5455 This session backend will set the :attr:`modified` and56 :attr:`accessed` attributes. It cannot reliably track whether a57 session is new (vs. empty), so :attr:`new` remains hard coded to58 ``False``.59 """6061 #: When data is changed, this is set to ``True``. Only the session62 #: dictionary itself is tracked; if the session contains mutable63 #: data (for example a nested dict) then this must be set to64 #: ``True`` manually when modifying that data. The session cookie65 #: will only be written to the response if this is ``True``.66 modified = False6768 #: When data is read or written, this is set to ``True``. Used by69 # :class:`.SecureCookieSessionInterface` to add a ``Vary: Cookie``70 #: header, which allows caching proxies to cache different pages for71 #: different users.72 accessed = False7374 def __init__(self, initial=None):75 def on_update(self):76 self.modified = True77 self.accessed = True7879 super(SecureCookieSession, self).__init__(initial, on_update)8081 def __getitem__(self, key):82 self.accessed = True83 return super(SecureCookieSession, self).__getitem__(key)8485 def get(self, key, default=None):86 self.accessed = True87 return super(SecureCookieSession, self).get(key, default)8889 def setdefault(self, key, default=None):90 self.accessed = True91 return super(SecureCookieSession, self).setdefault(key, default)929394class NullSession(SecureCookieSession):95 """Class used to generate nicer error messages if sessions are not96 available. Will still allow read-only access to the empty session97 but fail on setting.98 """99100 def _fail(self, *args, **kwargs):101 raise RuntimeError(102 "The session is unavailable because no secret "103 "key was set. Set the secret_key on the "104 "application to something unique and secret."105 )106107 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail108 del _fail109110111class SessionInterface(object):112 """The basic interface you have to implement in order to replace the113 default session interface which uses werkzeug's securecookie114 implementation. The only methods you have to implement are115 :meth:`open_session` and :meth:`save_session`, the others have116 useful defaults which you don't need to change.117118 The session object returned by the :meth:`open_session` method has to119 provide a dictionary like interface plus the properties and methods120 from the :class:`SessionMixin`. We recommend just subclassing a dict121 and adding that mixin::122123 class Session(dict, SessionMixin):124 pass125126 If :meth:`open_session` returns ``None`` Flask will call into127 :meth:`make_null_session` to create a session that acts as replacement128 if the session support cannot work because some requirement is not129 fulfilled. The default :class:`NullSession` class that is created130 will complain that the secret key was not set.131132 To replace the session interface on an application all you have to do133 is to assign :attr:`flask.Flask.session_interface`::134135 app = Flask(__name__)136 app.session_interface = MySessionInterface()137138 .. versionadded:: 0.8139 """140141 #: :meth:`make_null_session` will look here for the class that should142 #: be created when a null session is requested. Likewise the143 #: :meth:`is_null_session` method will perform a typecheck against144 #: this type.145 null_session_class = NullSession146147 #: A flag that indicates if the session interface is pickle based.148 #: This can be used by Flask extensions to make a decision in regards149 #: to how to deal with the session object.150 #:151 #: .. versionadded:: 0.10152 pickle_based = False153154 def make_null_session(self, app):155 """Creates a null session which acts as a replacement object if the156 real session support could not be loaded due to a configuration157 error. This mainly aids the user experience because the job of the158 null session is to still support lookup without complaining but159 modifications are answered with a helpful error message of what160 failed.161162 This creates an instance of :attr:`null_session_class` by default.163 """164 return self.null_session_class()165166 def is_null_session(self, obj):167 """Checks if a given object is a null session. Null sessions are168 not asked to be saved.169170 This checks if the object is an instance of :attr:`null_session_class`171 by default.172 """173 return isinstance(obj, self.null_session_class)174175 def get_cookie_domain(self, app):176 """Returns the domain that should be set for the session cookie.177178 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise179 falls back to detecting the domain based on ``SERVER_NAME``.180181 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is182 updated to avoid re-running the logic.183 """184185 rv = app.config["SESSION_COOKIE_DOMAIN"]186187 # set explicitly, or cached from SERVER_NAME detection188 # if False, return None189 if rv is not None:190 return rv if rv else None191192 rv = app.config["SERVER_NAME"]193194 # server name not set, cache False to return none next time195 if not rv:196 app.config["SESSION_COOKIE_DOMAIN"] = False197 return None198199 # chop off the port which is usually not supported by browsers200 # remove any leading '.' since we'll add that later201 rv = rv.rsplit(":", 1)[0].lstrip(".")202203 if "." not in rv:204 # Chrome doesn't allow names without a '.'205 # this should only come up with localhost206 # hack around this by not setting the name, and show a warning207 warnings.warn(208 '"{rv}" is not a valid cookie domain, it must contain a ".".'209 " Add an entry to your hosts file, for example"210 ' "{rv}.localdomain", and use that instead.'.format(rv=rv)211 )212 app.config["SESSION_COOKIE_DOMAIN"] = False213 return None214215 ip = is_ip(rv)216217 if ip:218 warnings.warn(219 "The session cookie domain is an IP address. This may not work"220 " as intended in some browsers. Add an entry to your hosts"221 ' file, for example "localhost.localdomain", and use that'222 " instead."223 )224225 # if this is not an ip and app is mounted at the root, allow subdomain226 # matching by adding a '.' prefix227 if self.get_cookie_path(app) == "/" and not ip:228 rv = "." + rv229230 app.config["SESSION_COOKIE_DOMAIN"] = rv231 return rv232233 def get_cookie_path(self, app):234 """Returns the path for which the cookie should be valid. The235 default implementation uses the value from the ``SESSION_COOKIE_PATH``236 config var if it's set, and falls back to ``APPLICATION_ROOT`` or237 uses ``/`` if it's ``None``.238 """239 return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]240241 def get_cookie_httponly(self, app):242 """Returns True if the session cookie should be httponly. This243 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``244 config var.245 """246 return app.config["SESSION_COOKIE_HTTPONLY"]247248 def get_cookie_secure(self, app):249 """Returns True if the cookie should be secure. This currently250 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.251 """252 return app.config["SESSION_COOKIE_SECURE"]253254 def get_cookie_samesite(self, app):255 """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the256 ``SameSite`` attribute. This currently just returns the value of257 the :data:`SESSION_COOKIE_SAMESITE` setting.258 """259 return app.config["SESSION_COOKIE_SAMESITE"]260261 def get_expiration_time(self, app, session):262 """A helper method that returns an expiration date for the session263 or ``None`` if the session is linked to the browser session. The264 default implementation returns now + the permanent session265 lifetime configured on the application.266 """267 if session.permanent:268 return datetime.utcnow() + app.permanent_session_lifetime269270 def should_set_cookie(self, app, session):271 """Used by session backends to determine if a ``Set-Cookie`` header272 should be set for this session cookie for this response. If the session273 has been modified, the cookie is set. If the session is permanent and274 the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is275 always set.276277 This check is usually skipped if the session was deleted.278279 .. versionadded:: 0.11280 """281282 return session.modified or (283 session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]284 )285286 def open_session(self, app, request):287 """This method has to be implemented and must either return ``None``288 in case the loading failed because of a configuration error or an289 instance of a session object which implements a dictionary like290 interface + the methods and attributes on :class:`SessionMixin`.291 """292 raise NotImplementedError()293294 def save_session(self, app, session, response):295 """This is called for actual sessions returned by :meth:`open_session`296 at the end of the request. This is still called during a request297 context so if you absolutely need access to the request you can do298 that.299 """300 raise NotImplementedError()301302303session_json_serializer = TaggedJSONSerializer()304305306class SecureCookieSessionInterface(SessionInterface):307 """The default session interface that stores sessions in signed cookies308 through the :mod:`itsdangerous` module.309 """310311 #: the salt that should be applied on top of the secret key for the312 #: signing of cookie based sessions.313 salt = "cookie-session"314 #: the hash function to use for the signature. The default is sha1315 digest_method = staticmethod(hashlib.sha1)316 #: the name of the itsdangerous supported key derivation. The default317 #: is hmac.318 key_derivation = "hmac"319 #: A python serializer for the payload. The default is a compact320 #: JSON derived serializer with support for some extra Python types321 #: such as datetime objects or tuples.322 serializer = session_json_serializer323 session_class = SecureCookieSession324325 def get_signing_serializer(self, app):326 if not app.secret_key:327 return None328 signer_kwargs = dict(329 key_derivation=self.key_derivation, digest_method=self.digest_method330 )331 return URLSafeTimedSerializer(332 app.secret_key,333 salt=self.salt,334 serializer=self.serializer,335 signer_kwargs=signer_kwargs,336 )337338 def open_session(self, app, request):339 s = self.get_signing_serializer(app)340 if s is None:341 return None342 val = request.cookies.get(app.session_cookie_name)343 if not val:344 return self.session_class()345 max_age = total_seconds(app.permanent_session_lifetime)346 try:347 data = s.loads(val, max_age=max_age)348 return self.session_class(data)349 except BadSignature:350 return self.session_class()351352 def save_session(self, app, session, response):353 domain = self.get_cookie_domain(app)354 path = self.get_cookie_path(app)355356 # If the session is modified to be empty, remove the cookie.357 # If the session is empty, return without setting the cookie.358 if not session:359 if session.modified:360 response.delete_cookie(361 app.session_cookie_name, domain=domain, path=path362 )363364 return365366 # Add a "Vary: Cookie" header if the session was accessed at all.367 if session.accessed:368 response.vary.add("Cookie")369370 if not self.should_set_cookie(app, session):371 return372373 httponly = self.get_cookie_httponly(app)374 secure = self.get_cookie_secure(app)375 samesite = self.get_cookie_samesite(app)376 expires = self.get_expiration_time(app, session)377 val = self.get_signing_serializer(app).dumps(dict(session))378 response.set_cookie(379 app.session_cookie_name,380 val,381 expires=expires,382 httponly=httponly,383 domain=domain,384 path=path,385 secure=secure,386 samesite=samesite,387 )
deleted:flask/signals.py-66 removed
1# -*- coding: utf-8 -*-2"""3 flask.signals4 ~~~~~~~~~~~~~56 Implements signals based on blinker if available, otherwise7 falls silently back to a noop.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213signals_available = False14try:15 from blinker import Namespace1617 signals_available = True18except ImportError:1920 class Namespace(object):21 def signal(self, name, doc=None):22 return _FakeSignal(name, doc)2324 class _FakeSignal(object):25 """If blinker is unavailable, create a fake class with the same26 interface that allows sending of signals but will fail with an27 error on anything else. Instead of doing anything on send, it28 will just ignore the arguments and do nothing instead.29 """3031 def __init__(self, name, doc=None):32 self.name = name33 self.__doc__ = doc3435 def send(self, *args, **kwargs):36 pass3738 def _fail(self, *args, **kwargs):39 raise RuntimeError(40 "Signalling support is unavailable because the blinker"41 " library is not installed."42 )4344 connect = connect_via = connected_to = temporarily_connected_to = _fail45 disconnect = _fail46 has_receivers_for = receivers_for = _fail47 del _fail484950# The namespace for code signals. If you are not Flask code, do51# not put signals in here. Create your own namespace instead.52_signals = Namespace()535455# Core signals. For usage examples grep the source code or consult56# the API documentation in docs/api.rst as well as docs/signals.rst57template_rendered = _signals.signal("template-rendered")58before_render_template = _signals.signal("before-render-template")59request_started = _signals.signal("request-started")60request_finished = _signals.signal("request-finished")61request_tearing_down = _signals.signal("request-tearing-down")62got_request_exception = _signals.signal("got-request-exception")63appcontext_tearing_down = _signals.signal("appcontext-tearing-down")64appcontext_pushed = _signals.signal("appcontext-pushed")65appcontext_popped = _signals.signal("appcontext-popped")66message_flashed = _signals.signal("message-flashed")
deleted:flask/templating.py-152 removed
1# -*- coding: utf-8 -*-2"""3 flask.templating4 ~~~~~~~~~~~~~~~~56 Implements the bridge to Jinja2.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from jinja2 import BaseLoader, Environment as BaseEnvironment, TemplateNotFound1314from .globals import _request_ctx_stack, _app_ctx_stack15from .signals import template_rendered, before_render_template161718def _default_template_ctx_processor():19 """Default template context processor. Injects `request`,20 `session` and `g`.21 """22 reqctx = _request_ctx_stack.top23 appctx = _app_ctx_stack.top24 rv = {}25 if appctx is not None:26 rv["g"] = appctx.g27 if reqctx is not None:28 rv["request"] = reqctx.request29 rv["session"] = reqctx.session30 return rv313233class Environment(BaseEnvironment):34 """Works like a regular Jinja2 environment but has some additional35 knowledge of how Flask's blueprint works so that it can prepend the36 name of the blueprint to referenced templates if necessary.37 """3839 def __init__(self, app, **options):40 if "loader" not in options:41 options["loader"] = app.create_global_jinja_loader()42 BaseEnvironment.__init__(self, **options)43 self.app = app444546class DispatchingJinjaLoader(BaseLoader):47 """A loader that looks for templates in the application and all48 the blueprint folders.49 """5051 def __init__(self, app):52 self.app = app5354 def get_source(self, environment, template):55 if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:56 return self._get_source_explained(environment, template)57 return self._get_source_fast(environment, template)5859 def _get_source_explained(self, environment, template):60 attempts = []61 trv = None6263 for srcobj, loader in self._iter_loaders(template):64 try:65 rv = loader.get_source(environment, template)66 if trv is None:67 trv = rv68 except TemplateNotFound:69 rv = None70 attempts.append((loader, srcobj, rv))7172 from .debughelpers import explain_template_loading_attempts7374 explain_template_loading_attempts(self.app, template, attempts)7576 if trv is not None:77 return trv78 raise TemplateNotFound(template)7980 def _get_source_fast(self, environment, template):81 for _srcobj, loader in self._iter_loaders(template):82 try:83 return loader.get_source(environment, template)84 except TemplateNotFound:85 continue86 raise TemplateNotFound(template)8788 def _iter_loaders(self, template):89 loader = self.app.jinja_loader90 if loader is not None:91 yield self.app, loader9293 for blueprint in self.app.iter_blueprints():94 loader = blueprint.jinja_loader95 if loader is not None:96 yield blueprint, loader9798 def list_templates(self):99 result = set()100 loader = self.app.jinja_loader101 if loader is not None:102 result.update(loader.list_templates())103104 for blueprint in self.app.iter_blueprints():105 loader = blueprint.jinja_loader106 if loader is not None:107 for template in loader.list_templates():108 result.add(template)109110 return list(result)111112113def _render(template, context, app):114 """Renders the template and fires the signal"""115116 before_render_template.send(app, template=template, context=context)117 rv = template.render(context)118 template_rendered.send(app, template=template, context=context)119 return rv120121122def render_template(template_name_or_list, **context):123 """Renders a template from the template folder with the given124 context.125126 :param template_name_or_list: the name of the template to be127 rendered, or an iterable with template names128 the first one existing will be rendered129 :param context: the variables that should be available in the130 context of the template.131 """132 ctx = _app_ctx_stack.top133 ctx.app.update_template_context(context)134 return _render(135 ctx.app.jinja_env.get_or_select_template(template_name_or_list),136 context,137 ctx.app,138 )139140141def render_template_string(source, **context):142 """Renders a template from the given template source string143 with the given context. Template variables will be autoescaped.144145 :param source: the source code of the template to be146 rendered147 :param context: the variables that should be available in the148 context of the template.149 """150 ctx = _app_ctx_stack.top151 ctx.app.update_template_context(context)152 return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)
deleted:flask/testing.py-283 removed
1# -*- coding: utf-8 -*-2"""3 flask.testing4 ~~~~~~~~~~~~~56 Implements test support helpers. This module is lazily imported7 and usually not used in production environments.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""12import warnings13import werkzeug14import werkzeug.test15from contextlib import contextmanager1617from click.testing import CliRunner18from flask.cli import ScriptInfo19from werkzeug.test import Client20from flask import _request_ctx_stack21from flask.json import dumps as json_dumps22from werkzeug.urls import url_parse232425class EnvironBuilder(werkzeug.test.EnvironBuilder):26 """An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the27 application.2829 :param app: The Flask application to configure the environment from.30 :param path: URL path being requested.31 :param base_url: Base URL where the app is being served, which32 ``path`` is relative to. If not given, built from33 :data:`PREFERRED_URL_SCHEME`, ``subdomain``,34 :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.35 :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.36 :param url_scheme: Scheme to use instead of37 :data:`PREFERRED_URL_SCHEME`.38 :param json: If given, this is serialized as JSON and passed as39 ``data``. Also defaults ``content_type`` to40 ``application/json``.41 :param args: other positional arguments passed to42 :class:`~werkzeug.test.EnvironBuilder`.43 :param kwargs: other keyword arguments passed to44 :class:`~werkzeug.test.EnvironBuilder`.45 """4647 def __init__(48 self,49 app,50 path="/",51 base_url=None,52 subdomain=None,53 url_scheme=None,54 *args,55 **kwargs56 ):57 assert not (base_url or subdomain or url_scheme) or (58 base_url is not None59 ) != bool(60 subdomain or url_scheme61 ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'6263 if base_url is None:64 http_host = app.config.get("SERVER_NAME") or "localhost"65 app_root = app.config["APPLICATION_ROOT"]6667 if subdomain:68 http_host = "{0}.{1}".format(subdomain, http_host)6970 if url_scheme is None:71 url_scheme = app.config["PREFERRED_URL_SCHEME"]7273 url = url_parse(path)74 base_url = "{scheme}://{netloc}/{path}".format(75 scheme=url.scheme or url_scheme,76 netloc=url.netloc or http_host,77 path=app_root.lstrip("/"),78 )79 path = url.path8081 if url.query:82 sep = b"?" if isinstance(url.query, bytes) else "?"83 path += sep + url.query8485 self.app = app86 super(EnvironBuilder, self).__init__(path, base_url, *args, **kwargs)8788 def json_dumps(self, obj, **kwargs):89 """Serialize ``obj`` to a JSON-formatted string.9091 The serialization will be configured according to the config associated92 with this EnvironBuilder's ``app``.93 """94 kwargs.setdefault("app", self.app)95 return json_dumps(obj, **kwargs)969798def make_test_environ_builder(*args, **kwargs):99 """Create a :class:`flask.testing.EnvironBuilder`.100101 .. deprecated: 1.1102 Will be removed in 1.2. Construct ``flask.testing.EnvironBuilder``103 directly instead.104 """105 warnings.warn(106 DeprecationWarning(107 '"make_test_environ_builder()" is deprecated and will be removed '108 'in 1.2. Construct "flask.testing.EnvironBuilder" directly '109 "instead."110 )111 )112 return EnvironBuilder(*args, **kwargs)113114115class FlaskClient(Client):116 """Works like a regular Werkzeug test client but has some knowledge about117 how Flask works to defer the cleanup of the request context stack to the118 end of a ``with`` body when used in a ``with`` statement. For general119 information about how to use this class refer to120 :class:`werkzeug.test.Client`.121122 .. versionchanged:: 0.12123 `app.test_client()` includes preset default environment, which can be124 set after instantiation of the `app.test_client()` object in125 `client.environ_base`.126127 Basic usage is outlined in the :ref:`testing` chapter.128 """129130 preserve_context = False131132 def __init__(self, *args, **kwargs):133 super(FlaskClient, self).__init__(*args, **kwargs)134 self.environ_base = {135 "REMOTE_ADDR": "127.0.0.1",136 "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,137 }138139 @contextmanager140 def session_transaction(self, *args, **kwargs):141 """When used in combination with a ``with`` statement this opens a142 session transaction. This can be used to modify the session that143 the test client uses. Once the ``with`` block is left the session is144 stored back.145146 ::147148 with client.session_transaction() as session:149 session['value'] = 42150151 Internally this is implemented by going through a temporary test152 request context and since session handling could depend on153 request variables this function accepts the same arguments as154 :meth:`~flask.Flask.test_request_context` which are directly155 passed through.156 """157 if self.cookie_jar is None:158 raise RuntimeError(159 "Session transactions only make sense " "with cookies enabled."160 )161 app = self.application162 environ_overrides = kwargs.setdefault("environ_overrides", {})163 self.cookie_jar.inject_wsgi(environ_overrides)164 outer_reqctx = _request_ctx_stack.top165 with app.test_request_context(*args, **kwargs) as c:166 session_interface = app.session_interface167 sess = session_interface.open_session(app, c.request)168 if sess is None:169 raise RuntimeError(170 "Session backend did not open a session. " "Check the configuration"171 )172173 # Since we have to open a new request context for the session174 # handling we want to make sure that we hide out own context175 # from the caller. By pushing the original request context176 # (or None) on top of this and popping it we get exactly that177 # behavior. It's important to not use the push and pop178 # methods of the actual request context object since that would179 # mean that cleanup handlers are called180 _request_ctx_stack.push(outer_reqctx)181 try:182 yield sess183 finally:184 _request_ctx_stack.pop()185186 resp = app.response_class()187 if not session_interface.is_null_session(sess):188 session_interface.save_session(app, sess, resp)189 headers = resp.get_wsgi_headers(c.request.environ)190 self.cookie_jar.extract_wsgi(c.request.environ, headers)191192 def open(self, *args, **kwargs):193 as_tuple = kwargs.pop("as_tuple", False)194 buffered = kwargs.pop("buffered", False)195 follow_redirects = kwargs.pop("follow_redirects", False)196197 if (198 not kwargs199 and len(args) == 1200 and isinstance(args[0], (werkzeug.test.EnvironBuilder, dict))201 ):202 environ = self.environ_base.copy()203204 if isinstance(args[0], werkzeug.test.EnvironBuilder):205 environ.update(args[0].get_environ())206 else:207 environ.update(args[0])208209 environ["flask._preserve_context"] = self.preserve_context210 else:211 kwargs.setdefault("environ_overrides", {})[212 "flask._preserve_context"213 ] = self.preserve_context214 kwargs.setdefault("environ_base", self.environ_base)215 builder = EnvironBuilder(self.application, *args, **kwargs)216217 try:218 environ = builder.get_environ()219 finally:220 builder.close()221222 return Client.open(223 self,224 environ,225 as_tuple=as_tuple,226 buffered=buffered,227 follow_redirects=follow_redirects,228 )229230 def __enter__(self):231 if self.preserve_context:232 raise RuntimeError("Cannot nest client invocations")233 self.preserve_context = True234 return self235236 def __exit__(self, exc_type, exc_value, tb):237 self.preserve_context = False238239 # Normally the request context is preserved until the next240 # request in the same thread comes. When the client exits we241 # want to clean up earlier. Pop request contexts until the stack242 # is empty or a non-preserved one is found.243 while True:244 top = _request_ctx_stack.top245246 if top is not None and top.preserved:247 top.pop()248 else:249 break250251252class FlaskCliRunner(CliRunner):253 """A :class:`~click.testing.CliRunner` for testing a Flask app's254 CLI commands. Typically created using255 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.256 """257258 def __init__(self, app, **kwargs):259 self.app = app260 super(FlaskCliRunner, self).__init__(**kwargs)261262 def invoke(self, cli=None, args=None, **kwargs):263 """Invokes a CLI command in an isolated environment. See264 :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for265 full method documentation. See :ref:`testing-cli` for examples.266267 If the ``obj`` argument is not given, passes an instance of268 :class:`~flask.cli.ScriptInfo` that knows how to load the Flask269 app being tested.270271 :param cli: Command object to invoke. Default is the app's272 :attr:`~flask.app.Flask.cli` group.273 :param args: List of strings to invoke the command with.274275 :return: a :class:`~click.testing.Result` object.276 """277 if cli is None:278 cli = self.app.cli279280 if "obj" not in kwargs:281 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)282283 return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)
deleted:flask/views.py-164 removed
1# -*- coding: utf-8 -*-2"""3 flask.views4 ~~~~~~~~~~~56 This module provides class-based views inspired by the ones in Django.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from .globals import request13from ._compat import with_metaclass141516http_method_funcs = frozenset(17 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]18)192021class View(object):22 """Alternative way to use view functions. A subclass has to implement23 :meth:`dispatch_request` which is called with the view arguments from24 the URL routing system. If :attr:`methods` is provided the methods25 do not have to be passed to the :meth:`~flask.Flask.add_url_rule`26 method explicitly::2728 class MyView(View):29 methods = ['GET']3031 def dispatch_request(self, name):32 return 'Hello %s!' % name3334 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))3536 When you want to decorate a pluggable view you will have to either do that37 when the view function is created (by wrapping the return value of38 :meth:`as_view`) or you can use the :attr:`decorators` attribute::3940 class SecretView(View):41 methods = ['GET']42 decorators = [superuser_required]4344 def dispatch_request(self):45 ...4647 The decorators stored in the decorators list are applied one after another48 when the view function is created. Note that you can *not* use the class49 based decorators since those would decorate the view class and not the50 generated view function!51 """5253 #: A list of methods this view can handle.54 methods = None5556 #: Setting this disables or force-enables the automatic options handling.57 provide_automatic_options = None5859 #: The canonical way to decorate class-based views is to decorate the60 #: return value of as_view(). However since this moves parts of the61 #: logic from the class declaration to the place where it's hooked62 #: into the routing system.63 #:64 #: You can place one or more decorators in this list and whenever the65 #: view function is created the result is automatically decorated.66 #:67 #: .. versionadded:: 0.868 decorators = ()6970 def dispatch_request(self):71 """Subclasses have to override this method to implement the72 actual view function code. This method is called with all73 the arguments from the URL rule.74 """75 raise NotImplementedError()7677 @classmethod78 def as_view(cls, name, *class_args, **class_kwargs):79 """Converts the class into an actual view function that can be used80 with the routing system. Internally this generates a function on the81 fly which will instantiate the :class:`View` on each request and call82 the :meth:`dispatch_request` method on it.8384 The arguments passed to :meth:`as_view` are forwarded to the85 constructor of the class.86 """8788 def view(*args, **kwargs):89 self = view.view_class(*class_args, **class_kwargs)90 return self.dispatch_request(*args, **kwargs)9192 if cls.decorators:93 view.__name__ = name94 view.__module__ = cls.__module__95 for decorator in cls.decorators:96 view = decorator(view)9798 # We attach the view class to the view function for two reasons:99 # first of all it allows us to easily figure out what class-based100 # view this thing came from, secondly it's also used for instantiating101 # the view class so you can actually replace it with something else102 # for testing purposes and debugging.103 view.view_class = cls104 view.__name__ = name105 view.__doc__ = cls.__doc__106 view.__module__ = cls.__module__107 view.methods = cls.methods108 view.provide_automatic_options = cls.provide_automatic_options109 return view110111112class MethodViewType(type):113 """Metaclass for :class:`MethodView` that determines what methods the view114 defines.115 """116117 def __init__(cls, name, bases, d):118 super(MethodViewType, cls).__init__(name, bases, d)119120 if "methods" not in d:121 methods = set()122123 for base in bases:124 if getattr(base, "methods", None):125 methods.update(base.methods)126127 for key in http_method_funcs:128 if hasattr(cls, key):129 methods.add(key.upper())130131 # If we have no method at all in there we don't want to add a132 # method list. This is for instance the case for the base class133 # or another subclass of a base method view that does not introduce134 # new methods.135 if methods:136 cls.methods = methods137138139class MethodView(with_metaclass(MethodViewType, View)):140 """A class-based view that dispatches request methods to the corresponding141 class methods. For example, if you implement a ``get`` method, it will be142 used to handle ``GET`` requests. ::143144 class CounterAPI(MethodView):145 def get(self):146 return session.get('counter', 0)147148 def post(self):149 session['counter'] = session.get('counter', 0) + 1150 return 'OK'151152 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))153 """154155 def dispatch_request(self, *args, **kwargs):156 meth = getattr(self, request.method.lower(), None)157158 # If the request method is HEAD and we don't have a handler for it159 # retry with GET.160 if meth is None and request.method == "HEAD":161 meth = getattr(self, "get", None)162163 assert meth is not None, "Unimplemented method %r" % request.method164 return meth(*args, **kwargs)
deleted:flask/wrappers.py-137 removed
1# -*- coding: utf-8 -*-2"""3 flask.wrappers4 ~~~~~~~~~~~~~~56 Implements the WSGI wrappers (request and response).78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from werkzeug.exceptions import BadRequest13from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase14from werkzeug.wrappers.json import JSONMixin as _JSONMixin1516from flask import json17from flask.globals import current_app181920class JSONMixin(_JSONMixin):21 json_module = json2223 def on_json_loading_failed(self, e):24 if current_app and current_app.debug:25 raise BadRequest("Failed to decode JSON object: {0}".format(e))2627 raise BadRequest()282930class Request(RequestBase, JSONMixin):31 """The request object used by default in Flask. Remembers the32 matched endpoint and view arguments.3334 It is what ends up as :class:`~flask.request`. If you want to replace35 the request object used you can subclass this and set36 :attr:`~flask.Flask.request_class` to your subclass.3738 The request object is a :class:`~werkzeug.wrappers.Request` subclass and39 provides all of the attributes Werkzeug defines plus a few Flask40 specific ones.41 """4243 #: The internal URL rule that matched the request. This can be44 #: useful to inspect which methods are allowed for the URL from45 #: a before/after handler (``request.url_rule.methods``) etc.46 #: Though if the request's method was invalid for the URL rule,47 #: the valid list is available in ``routing_exception.valid_methods``48 #: instead (an attribute of the Werkzeug exception49 #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)50 #: because the request was never internally bound.51 #:52 #: .. versionadded:: 0.653 url_rule = None5455 #: A dict of view arguments that matched the request. If an exception56 #: happened when matching, this will be ``None``.57 view_args = None5859 #: If matching the URL failed, this is the exception that will be60 #: raised / was raised as part of the request handling. This is61 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or62 #: something similar.63 routing_exception = None6465 @property66 def max_content_length(self):67 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""68 if current_app:69 return current_app.config["MAX_CONTENT_LENGTH"]7071 @property72 def endpoint(self):73 """The endpoint that matched the request. This in combination with74 :attr:`view_args` can be used to reconstruct the same or a75 modified URL. If an exception happened when matching, this will76 be ``None``.77 """78 if self.url_rule is not None:79 return self.url_rule.endpoint8081 @property82 def blueprint(self):83 """The name of the current blueprint"""84 if self.url_rule and "." in self.url_rule.endpoint:85 return self.url_rule.endpoint.rsplit(".", 1)[0]8687 def _load_form_data(self):88 RequestBase._load_form_data(self)8990 # In debug mode we're replacing the files multidict with an ad-hoc91 # subclass that raises a different error for key errors.92 if (93 current_app94 and current_app.debug95 and self.mimetype != "multipart/form-data"96 and not self.files97 ):98 from .debughelpers import attach_enctype_error_multidict99100 attach_enctype_error_multidict(self)101102103class Response(ResponseBase, JSONMixin):104 """The response object that is used by default in Flask. Works like the105 response object from Werkzeug but is set to have an HTML mimetype by106 default. Quite often you don't have to create this object yourself because107 :meth:`~flask.Flask.make_response` will take care of that for you.108109 If you want to replace the response object used you can subclass this and110 set :attr:`~flask.Flask.response_class` to your subclass.111112 .. versionchanged:: 1.0113 JSON support is added to the response, like the request. This is useful114 when testing to get the test client response data as JSON.115116 .. versionchanged:: 1.0117118 Added :attr:`max_cookie_size`.119 """120121 default_mimetype = "text/html"122123 def _get_data_for_json(self, cache):124 return self.get_data()125126 @property127 def max_cookie_size(self):128 """Read-only view of the :data:`MAX_COOKIE_SIZE` config key.129130 See :attr:`~werkzeug.wrappers.BaseResponse.max_cookie_size` in131 Werkzeug's docs.132 """133 if current_app:134 return current_app.config["MAX_COOKIE_SIZE"]135136 # return Werkzeug's default when not in an app context137 return super(Response, self).max_cookie_size
added:src/flask/json/__init__.py+375 added
1# -*- coding: utf-8 -*-2"""3flask.json4~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""9import codecs10import io11import uuid12from datetime import date, datetime13from flask.globals import current_app, request14from flask._compat import text_type, PY21516from werkzeug.http import http_date17from jinja2 import Markup1819# Use the same json implementation as itsdangerous on which we20# depend anyways.21from itsdangerous import json as _json2223try:24 import dataclasses25except ImportError:26 dataclasses = None2728# Figure out if simplejson escapes slashes. This behavior was changed29# from one version to another without reason.30_slash_escape = "\\/" not in _json.dumps("/")313233__all__ = [34 "dump",35 "dumps",36 "load",37 "loads",38 "htmlsafe_dump",39 "htmlsafe_dumps",40 "JSONDecoder",41 "JSONEncoder",42 "jsonify",43]444546def _wrap_reader_for_text(fp, encoding):47 if isinstance(fp.read(0), bytes):48 fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)49 return fp505152def _wrap_writer_for_text(fp, encoding):53 try:54 fp.write("")55 except TypeError:56 fp = io.TextIOWrapper(fp, encoding)57 return fp585960class JSONEncoder(_json.JSONEncoder):61 """The default Flask JSON encoder. This one extends the default62 encoder by also supporting ``datetime``, ``UUID``, ``dataclasses``,63 and ``Markup`` objects.6465 ``datetime`` objects are serialized as RFC 822 datetime strings.66 This is the same as the HTTP date format.6768 In order to support more data types, override the :meth:`default`69 method.70 """7172 def default(self, o):73 """Implement this method in a subclass such that it returns a74 serializable object for ``o``, or calls the base implementation (to75 raise a :exc:`TypeError`).7677 For example, to support arbitrary iterators, you could implement78 default like this::7980 def default(self, o):81 try:82 iterable = iter(o)83 except TypeError:84 pass85 else:86 return list(iterable)87 return JSONEncoder.default(self, o)88 """89 if isinstance(o, datetime):90 return http_date(o.utctimetuple())91 if isinstance(o, date):92 return http_date(o.timetuple())93 if isinstance(o, uuid.UUID):94 return str(o)95 if dataclasses and dataclasses.is_dataclass(o):96 return dataclasses.asdict(o)97 if hasattr(o, "__html__"):98 return text_type(o.__html__())99 return _json.JSONEncoder.default(self, o)100101102class JSONDecoder(_json.JSONDecoder):103 """The default JSON decoder. This one does not change the behavior from104 the default simplejson decoder. Consult the :mod:`json` documentation105 for more information. This decoder is not only used for the load106 functions of this module but also :attr:`~flask.Request`.107 """108109110def _dump_arg_defaults(kwargs, app=None):111 """Inject default arguments for dump functions."""112 if app is None:113 app = current_app114115 if app:116 bp = app.blueprints.get(request.blueprint) if request else None117 kwargs.setdefault(118 "cls", bp.json_encoder if bp and bp.json_encoder else app.json_encoder119 )120121 if not app.config["JSON_AS_ASCII"]:122 kwargs.setdefault("ensure_ascii", False)123124 kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])125 else:126 kwargs.setdefault("sort_keys", True)127 kwargs.setdefault("cls", JSONEncoder)128129130def _load_arg_defaults(kwargs, app=None):131 """Inject default arguments for load functions."""132 if app is None:133 app = current_app134135 if app:136 bp = app.blueprints.get(request.blueprint) if request else None137 kwargs.setdefault(138 "cls", bp.json_decoder if bp and bp.json_decoder else app.json_decoder139 )140 else:141 kwargs.setdefault("cls", JSONDecoder)142143144def detect_encoding(data):145 """Detect which UTF codec was used to encode the given bytes.146147 The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is148 accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big149 or little endian. Some editors or libraries may prepend a BOM.150151 :param data: Bytes in unknown UTF encoding.152 :return: UTF encoding name153 """154 head = data[:4]155156 if head[:3] == codecs.BOM_UTF8:157 return "utf-8-sig"158159 if b"\x00" not in head:160 return "utf-8"161162 if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):163 return "utf-32"164165 if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):166 return "utf-16"167168 if len(head) == 4:169 if head[:3] == b"\x00\x00\x00":170 return "utf-32-be"171172 if head[::2] == b"\x00\x00":173 return "utf-16-be"174175 if head[1:] == b"\x00\x00\x00":176 return "utf-32-le"177178 if head[1::2] == b"\x00\x00":179 return "utf-16-le"180181 if len(head) == 2:182 return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"183184 return "utf-8"185186187def dumps(obj, app=None, **kwargs):188 """Serialize ``obj`` to a JSON-formatted string. If there is an189 app context pushed, use the current app's configured encoder190 (:attr:`~flask.Flask.json_encoder`), or fall back to the default191 :class:`JSONEncoder`.192193 Takes the same arguments as the built-in :func:`json.dumps`, and194 does some extra configuration based on the application. If the195 simplejson package is installed, it is preferred.196197 :param obj: Object to serialize to JSON.198 :param app: App instance to use to configure the JSON encoder.199 Uses ``current_app`` if not given, and falls back to the default200 encoder when not in an app context.201 :param kwargs: Extra arguments passed to :func:`json.dumps`.202203 .. versionchanged:: 1.0.3204205 ``app`` can be passed directly, rather than requiring an app206 context for configuration.207 """208 _dump_arg_defaults(kwargs, app=app)209 encoding = kwargs.pop("encoding", None)210 rv = _json.dumps(obj, **kwargs)211 if encoding is not None and isinstance(rv, text_type):212 rv = rv.encode(encoding)213 return rv214215216def dump(obj, fp, app=None, **kwargs):217 """Like :func:`dumps` but writes into a file object."""218 _dump_arg_defaults(kwargs, app=app)219 encoding = kwargs.pop("encoding", None)220 if encoding is not None:221 fp = _wrap_writer_for_text(fp, encoding)222 _json.dump(obj, fp, **kwargs)223224225def loads(s, app=None, **kwargs):226 """Deserialize an object from a JSON-formatted string ``s``. If227 there is an app context pushed, use the current app's configured228 decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the229 default :class:`JSONDecoder`.230231 Takes the same arguments as the built-in :func:`json.loads`, and232 does some extra configuration based on the application. If the233 simplejson package is installed, it is preferred.234235 :param s: JSON string to deserialize.236 :param app: App instance to use to configure the JSON decoder.237 Uses ``current_app`` if not given, and falls back to the default238 encoder when not in an app context.239 :param kwargs: Extra arguments passed to :func:`json.dumps`.240241 .. versionchanged:: 1.0.3242243 ``app`` can be passed directly, rather than requiring an app244 context for configuration.245 """246 _load_arg_defaults(kwargs, app=app)247 if isinstance(s, bytes):248 encoding = kwargs.pop("encoding", None)249 if encoding is None:250 encoding = detect_encoding(s)251 s = s.decode(encoding)252 return _json.loads(s, **kwargs)253254255def load(fp, app=None, **kwargs):256 """Like :func:`loads` but reads from a file object."""257 _load_arg_defaults(kwargs, app=app)258 if not PY2:259 fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")260 return _json.load(fp, **kwargs)261262263def htmlsafe_dumps(obj, **kwargs):264 """Works exactly like :func:`dumps` but is safe for use in ``<script>``265 tags. It accepts the same arguments and returns a JSON string. Note that266 this is available in templates through the ``|tojson`` filter which will267 also mark the result as safe. Due to how this function escapes certain268 characters this is safe even if used outside of ``<script>`` tags.269270 The following characters are escaped in strings:271272 - ``<``273 - ``>``274 - ``&``275 - ``'``276277 This makes it safe to embed such strings in any place in HTML with the278 notable exception of double quoted attributes. In that case single279 quote your attributes or HTML escape it in addition.280281 .. versionchanged:: 0.10282 This function's return value is now always safe for HTML usage, even283 if outside of script tags or if used in XHTML. This rule does not284 hold true when using this function in HTML attributes that are double285 quoted. Always single quote attributes if you use the ``|tojson``286 filter. Alternatively use ``|tojson|forceescape``.287 """288 rv = (289 dumps(obj, **kwargs)290 .replace(u"<", u"\\u003c")291 .replace(u">", u"\\u003e")292 .replace(u"&", u"\\u0026")293 .replace(u"'", u"\\u0027")294 )295 if not _slash_escape:296 rv = rv.replace("\\/", "/")297 return rv298299300def htmlsafe_dump(obj, fp, **kwargs):301 """Like :func:`htmlsafe_dumps` but writes into a file object."""302 fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))303304305def jsonify(*args, **kwargs):306 """This function wraps :func:`dumps` to add a few enhancements that make307 life easier. It turns the JSON output into a :class:`~flask.Response`308 object with the :mimetype:`application/json` mimetype. For convenience, it309 also converts multiple arguments into an array or multiple keyword arguments310 into a dict. This means that both ``jsonify(1,2,3)`` and311 ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.312313 For clarity, the JSON serialization behavior has the following differences314 from :func:`dumps`:315316 1. Single argument: Passed straight through to :func:`dumps`.317 2. Multiple arguments: Converted to an array before being passed to318 :func:`dumps`.319 3. Multiple keyword arguments: Converted to a dict before being passed to320 :func:`dumps`.321 4. Both args and kwargs: Behavior undefined and will throw an exception.322323 Example usage::324325 from flask import jsonify326327 @app.route('/_get_current_user')328 def get_current_user():329 return jsonify(username=g.user.username,330 email=g.user.email,331 id=g.user.id)332333 This will send a JSON response like this to the browser::334335 {336 "username": "admin",337 "email": "admin@localhost",338 "id": 42339 }340341342 .. versionchanged:: 0.11343 Added support for serializing top-level arrays. This introduces a344 security risk in ancient browsers. See :ref:`json-security` for details.345346 This function's response will be pretty printed if the347 ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the348 Flask app is running in debug mode. Compressed (not pretty) formatting349 currently means no indents and no spaces after separators.350351 .. versionadded:: 0.2352 """353354 indent = None355 separators = (",", ":")356357 if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:358 indent = 2359 separators = (", ", ": ")360361 if args and kwargs:362 raise TypeError("jsonify() behavior undefined when passed both args and kwargs")363 elif len(args) == 1: # single args are passed directly to dumps()364 data = args[0]365 else:366 data = args or kwargs367368 return current_app.response_class(369 dumps(data, indent=indent, separators=separators) + "\n",370 mimetype=current_app.config["JSONIFY_MIMETYPE"],371 )372373374def tojson_filter(obj, **kwargs):375 return Markup(htmlsafe_dumps(obj, **kwargs))
added:src/flask/json/tag.py+306 added
1# -*- coding: utf-8 -*-2"""3Tagged JSON4~~~~~~~~~~~56A compact representation for lossless serialization of non-standard JSON types.7:class:`~flask.sessions.SecureCookieSessionInterface` uses this to serialize8the session data, but it may be useful in other places. It can be extended to9support other types.1011.. autoclass:: TaggedJSONSerializer12 :members:1314.. autoclass:: JSONTag15 :members:1617Let's seen an example that adds support for :class:`~collections.OrderedDict`.18Dicts don't have an order in Python or JSON, so to handle this we will dump19the items as a list of ``[key, value]`` pairs. Subclass :class:`JSONTag` and20give it the new key ``' od'`` to identify the type. The session serializer21processes dicts first, so insert the new tag at the front of the order since22``OrderedDict`` must be processed before ``dict``. ::2324 from flask.json.tag import JSONTag2526 class TagOrderedDict(JSONTag):27 __slots__ = ('serializer',)28 key = ' od'2930 def check(self, value):31 return isinstance(value, OrderedDict)3233 def to_json(self, value):34 return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]3536 def to_python(self, value):37 return OrderedDict(value)3839 app.session_interface.serializer.register(TagOrderedDict, index=0)4041:copyright: © 2010 by the Pallets team.42:license: BSD, see LICENSE for more details.43"""4445from base64 import b64decode, b64encode46from datetime import datetime47from uuid import UUID4849from jinja2 import Markup50from werkzeug.http import http_date, parse_date5152from flask._compat import iteritems, text_type53from flask.json import dumps, loads545556class JSONTag(object):57 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""5859 __slots__ = ("serializer",)6061 #: The tag to mark the serialized object with. If ``None``, this tag is62 #: only used as an intermediate step during tagging.63 key = None6465 def __init__(self, serializer):66 """Create a tagger for the given serializer."""67 self.serializer = serializer6869 def check(self, value):70 """Check if the given value should be tagged by this tag."""71 raise NotImplementedError7273 def to_json(self, value):74 """Convert the Python object to an object that is a valid JSON type.75 The tag will be added later."""76 raise NotImplementedError7778 def to_python(self, value):79 """Convert the JSON representation back to the correct type. The tag80 will already be removed."""81 raise NotImplementedError8283 def tag(self, value):84 """Convert the value to a valid JSON type and add the tag structure85 around it."""86 return {self.key: self.to_json(value)}878889class TagDict(JSONTag):90 """Tag for 1-item dicts whose only key matches a registered tag.9192 Internally, the dict key is suffixed with `__`, and the suffix is removed93 when deserializing.94 """9596 __slots__ = ()97 key = " di"9899 def check(self, value):100 return (101 isinstance(value, dict)102 and len(value) == 1103 and next(iter(value)) in self.serializer.tags104 )105106 def to_json(self, value):107 key = next(iter(value))108 return {key + "__": self.serializer.tag(value[key])}109110 def to_python(self, value):111 key = next(iter(value))112 return {key[:-2]: value[key]}113114115class PassDict(JSONTag):116 __slots__ = ()117118 def check(self, value):119 return isinstance(value, dict)120121 def to_json(self, value):122 # JSON objects may only have string keys, so don't bother tagging the123 # key here.124 return dict((k, self.serializer.tag(v)) for k, v in iteritems(value))125126 tag = to_json127128129class TagTuple(JSONTag):130 __slots__ = ()131 key = " t"132133 def check(self, value):134 return isinstance(value, tuple)135136 def to_json(self, value):137 return [self.serializer.tag(item) for item in value]138139 def to_python(self, value):140 return tuple(value)141142143class PassList(JSONTag):144 __slots__ = ()145146 def check(self, value):147 return isinstance(value, list)148149 def to_json(self, value):150 return [self.serializer.tag(item) for item in value]151152 tag = to_json153154155class TagBytes(JSONTag):156 __slots__ = ()157 key = " b"158159 def check(self, value):160 return isinstance(value, bytes)161162 def to_json(self, value):163 return b64encode(value).decode("ascii")164165 def to_python(self, value):166 return b64decode(value)167168169class TagMarkup(JSONTag):170 """Serialize anything matching the :class:`~flask.Markup` API by171 having a ``__html__`` method to the result of that method. Always172 deserializes to an instance of :class:`~flask.Markup`."""173174 __slots__ = ()175 key = " m"176177 def check(self, value):178 return callable(getattr(value, "__html__", None))179180 def to_json(self, value):181 return text_type(value.__html__())182183 def to_python(self, value):184 return Markup(value)185186187class TagUUID(JSONTag):188 __slots__ = ()189 key = " u"190191 def check(self, value):192 return isinstance(value, UUID)193194 def to_json(self, value):195 return value.hex196197 def to_python(self, value):198 return UUID(value)199200201class TagDateTime(JSONTag):202 __slots__ = ()203 key = " d"204205 def check(self, value):206 return isinstance(value, datetime)207208 def to_json(self, value):209 return http_date(value)210211 def to_python(self, value):212 return parse_date(value)213214215class TaggedJSONSerializer(object):216 """Serializer that uses a tag system to compactly represent objects that217 are not JSON types. Passed as the intermediate serializer to218 :class:`itsdangerous.Serializer`.219220 The following extra types are supported:221222 * :class:`dict`223 * :class:`tuple`224 * :class:`bytes`225 * :class:`~flask.Markup`226 * :class:`~uuid.UUID`227 * :class:`~datetime.datetime`228 """229230 __slots__ = ("tags", "order")231232 #: Tag classes to bind when creating the serializer. Other tags can be233 #: added later using :meth:`~register`.234 default_tags = [235 TagDict,236 PassDict,237 TagTuple,238 PassList,239 TagBytes,240 TagMarkup,241 TagUUID,242 TagDateTime,243 ]244245 def __init__(self):246 self.tags = {}247 self.order = []248249 for cls in self.default_tags:250 self.register(cls)251252 def register(self, tag_class, force=False, index=None):253 """Register a new tag with this serializer.254255 :param tag_class: tag class to register. Will be instantiated with this256 serializer instance.257 :param force: overwrite an existing tag. If false (default), a258 :exc:`KeyError` is raised.259 :param index: index to insert the new tag in the tag order. Useful when260 the new tag is a special case of an existing tag. If ``None``261 (default), the tag is appended to the end of the order.262263 :raise KeyError: if the tag key is already registered and ``force`` is264 not true.265 """266 tag = tag_class(self)267 key = tag.key268269 if key is not None:270 if not force and key in self.tags:271 raise KeyError("Tag '{0}' is already registered.".format(key))272273 self.tags[key] = tag274275 if index is None:276 self.order.append(tag)277 else:278 self.order.insert(index, tag)279280 def tag(self, value):281 """Convert a value to a tagged representation if necessary."""282 for tag in self.order:283 if tag.check(value):284 return tag.tag(value)285286 return value287288 def untag(self, value):289 """Convert a tagged representation back to the original type."""290 if len(value) != 1:291 return value292293 key = next(iter(value))294295 if key not in self.tags:296 return value297298 return self.tags[key].to_python(value[key])299300 def dumps(self, value):301 """Tag the value and dump it to a compact JSON string."""302 return dumps(self.tag(value), separators=(",", ":"))303304 def loads(self, value):305 """Load data from a JSON string and deserialized any tagged objects."""306 return loads(value, object_hook=self.untag)
added:src/flask/__init__.py+72 added
1# -*- coding: utf-8 -*-2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213__version__ = "1.1.dev"1415# utilities we import from Werkzeug and Jinja2 that are unused16# in the module but are exported as public interface.17from werkzeug.exceptions import abort18from werkzeug.utils import redirect19from jinja2 import Markup, escape2021from .app import Flask, Request, Response22from .config import Config23from .helpers import (24 url_for,25 flash,26 send_file,27 send_from_directory,28 get_flashed_messages,29 get_template_attribute,30 make_response,31 safe_join,32 stream_with_context,33)34from .globals import (35 current_app,36 g,37 request,38 session,39 _request_ctx_stack,40 _app_ctx_stack,41)42from .ctx import (43 has_request_context,44 has_app_context,45 after_this_request,46 copy_current_request_context,47)48from .blueprints import Blueprint49from .templating import render_template, render_template_string5051# the signals52from .signals import (53 signals_available,54 template_rendered,55 request_started,56 request_finished,57 got_request_exception,58 request_tearing_down,59 appcontext_tearing_down,60 appcontext_pushed,61 appcontext_popped,62 message_flashed,63 before_render_template,64)6566# We're not exposing the actual json module but a convenient wrapper around67# it.68from . import json6970# This was the only thing that Flask used to export at one point and it had71# a more generic name.72jsonify = json.jsonify
added:src/flask/__main__.py+15 added
1# -*- coding: utf-8 -*-2"""3 flask.__main__4 ~~~~~~~~~~~~~~56 Alias for flask.run for the command line.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112if __name__ == "__main__":13 from .cli import main1415 main(as_module=True)
added:src/flask/_compat.py+116 added
1# -*- coding: utf-8 -*-2"""3 flask._compat4 ~~~~~~~~~~~~~56 Some py2/py3 compatibility support based on a stripped down7 version of six so we don't have to depend on a specific version8 of it.910 :copyright: © 2010 by the Pallets team.11 :license: BSD, see LICENSE for more details.12"""1314import sys1516PY2 = sys.version_info[0] == 217_identity = lambda x: x1819try: # Python 220 text_type = unicode21 string_types = (str, unicode)22 integer_types = (int, long)23except NameError: # Python 324 text_type = str25 string_types = (str,)26 integer_types = (int,)2728if not PY2:29 iterkeys = lambda d: iter(d.keys())30 itervalues = lambda d: iter(d.values())31 iteritems = lambda d: iter(d.items())3233 from inspect import getfullargspec as getargspec34 from io import StringIO35 import collections.abc as collections_abc3637 def reraise(tp, value, tb=None):38 if value.__traceback__ is not tb:39 raise value.with_traceback(tb)40 raise value4142 implements_to_string = _identity4344else:45 iterkeys = lambda d: d.iterkeys()46 itervalues = lambda d: d.itervalues()47 iteritems = lambda d: d.iteritems()4849 from inspect import getargspec50 from cStringIO import StringIO51 import collections as collections_abc5253 exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")5455 def implements_to_string(cls):56 cls.__unicode__ = cls.__str__57 cls.__str__ = lambda x: x.__unicode__().encode("utf-8")58 return cls596061def with_metaclass(meta, *bases):62 """Create a base class with a metaclass."""63 # This requires a bit of explanation: the basic idea is to make a64 # dummy metaclass for one level of class instantiation that replaces65 # itself with the actual metaclass.66 class metaclass(type):67 def __new__(mcs, name, this_bases, d):68 return meta(name, bases, d)6970 return type.__new__(metaclass, "temporary_class", (), {})717273# Certain versions of pypy have a bug where clearing the exception stack74# breaks the __exit__ function in a very peculiar way. The second level of75# exception blocks is necessary because pypy seems to forget to check if an76# exception happened until the next bytecode instruction?77#78# Relevant PyPy bugfix commit:79# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df400330180# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later81# versions.82#83# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.84BROKEN_PYPY_CTXMGR_EXIT = False85if hasattr(sys, "pypy_version_info"):8687 class _Mgr(object):88 def __enter__(self):89 return self9091 def __exit__(self, *args):92 if hasattr(sys, "exc_clear"):93 # Python 3 (PyPy3) doesn't have exc_clear94 sys.exc_clear()9596 try:97 try:98 with _Mgr():99 raise AssertionError()100 except: # noqa: B001101 # We intentionally use a bare except here. See the comment above102 # regarding a pypy bug as to why.103 raise104 except TypeError:105 BROKEN_PYPY_CTXMGR_EXIT = True106 except AssertionError:107 pass108109110try:111 from os import fspath112except ImportError:113 # Backwards compatibility as proposed in PEP 0519:114 # https://www.python.org/dev/peps/pep-0519/#backwards-compatibility115 def fspath(path):116 return path.__fspath__() if hasattr(path, "__fspath__") else path
added:src/flask/app.py+2418 added
1# -*- coding: utf-8 -*-2"""3 flask.app4 ~~~~~~~~~56 This module implements the central WSGI application object.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import os13import sys14import warnings15from datetime import timedelta16from functools import update_wrapper17from itertools import chain18from threading import Lock1920from werkzeug.datastructures import Headers, ImmutableDict21from werkzeug.exceptions import (22 BadRequest,23 BadRequestKeyError,24 HTTPException,25 InternalServerError,26 MethodNotAllowed,27 default_exceptions,28)29from werkzeug.routing import BuildError, Map, RequestRedirect, RoutingException, Rule30from werkzeug.wrappers import BaseResponse3132from . import cli, json33from ._compat import integer_types, reraise, string_types, text_type34from .config import Config, ConfigAttribute35from .ctx import AppContext, RequestContext, _AppCtxGlobals36from .globals import _request_ctx_stack, g, request, session37from .helpers import (38 _PackageBoundObject,39 _endpoint_from_view_func,40 find_package,41 get_env,42 get_debug_flag,43 get_flashed_messages,44 locked_cached_property,45 url_for,46 get_load_dotenv,47)48from .json import jsonify49from .logging import create_logger50from .sessions import SecureCookieSessionInterface51from .signals import (52 appcontext_tearing_down,53 got_request_exception,54 request_finished,55 request_started,56 request_tearing_down,57)58from .templating import (59 DispatchingJinjaLoader,60 Environment,61 _default_template_ctx_processor,62)63from .wrappers import Request, Response6465# a singleton sentinel value for parameter defaults66_sentinel = object()676869def _make_timedelta(value):70 if not isinstance(value, timedelta):71 return timedelta(seconds=value)72 return value737475def setupmethod(f):76 """Wraps a method so that it performs a check in debug mode if the77 first request was already handled.78 """7980 def wrapper_func(self, *args, **kwargs):81 if self.debug and self._got_first_request:82 raise AssertionError(83 "A setup function was called after the "84 "first request was handled. This usually indicates a bug "85 "in the application where a module was not imported "86 "and decorators or other functionality was called too late.\n"87 "To fix this make sure to import all your view modules, "88 "database models and everything related at a central place "89 "before the application starts serving requests."90 )91 return f(self, *args, **kwargs)9293 return update_wrapper(wrapper_func, f)949596class Flask(_PackageBoundObject):97 """The flask object implements a WSGI application and acts as the central98 object. It is passed the name of the module or package of the99 application. Once it is created it will act as a central registry for100 the view functions, the URL rules, template configuration and much more.101102 The name of the package is used to resolve resources from inside the103 package or the folder the module is contained in depending on if the104 package parameter resolves to an actual python package (a folder with105 an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).106107 For more information about resource loading, see :func:`open_resource`.108109 Usually you create a :class:`Flask` instance in your main module or110 in the :file:`__init__.py` file of your package like this::111112 from flask import Flask113 app = Flask(__name__)114115 .. admonition:: About the First Parameter116117 The idea of the first parameter is to give Flask an idea of what118 belongs to your application. This name is used to find resources119 on the filesystem, can be used by extensions to improve debugging120 information and a lot more.121122 So it's important what you provide there. If you are using a single123 module, `__name__` is always the correct value. If you however are124 using a package, it's usually recommended to hardcode the name of125 your package there.126127 For example if your application is defined in :file:`yourapplication/app.py`128 you should create it with one of the two versions below::129130 app = Flask('yourapplication')131 app = Flask(__name__.split('.')[0])132133 Why is that? The application will work even with `__name__`, thanks134 to how resources are looked up. However it will make debugging more135 painful. Certain extensions can make assumptions based on the136 import name of your application. For example the Flask-SQLAlchemy137 extension will look for the code in your application that triggered138 an SQL query in debug mode. If the import name is not properly set139 up, that debugging information is lost. (For example it would only140 pick up SQL queries in `yourapplication.app` and not141 `yourapplication.views.frontend`)142143 .. versionadded:: 0.7144 The `static_url_path`, `static_folder`, and `template_folder`145 parameters were added.146147 .. versionadded:: 0.8148 The `instance_path` and `instance_relative_config` parameters were149 added.150151 .. versionadded:: 0.11152 The `root_path` parameter was added.153154 .. versionadded:: 1.0155 The ``host_matching`` and ``static_host`` parameters were added.156157 .. versionadded:: 1.0158 The ``subdomain_matching`` parameter was added. Subdomain159 matching needs to be enabled manually now. Setting160 :data:`SERVER_NAME` does not implicitly enable it.161162 :param import_name: the name of the application package163 :param static_url_path: can be used to specify a different path for the164 static files on the web. Defaults to the name165 of the `static_folder` folder.166 :param static_folder: the folder with static files that should be served167 at `static_url_path`. Defaults to the ``'static'``168 folder in the root path of the application.169 :param static_host: the host to use when adding the static route.170 Defaults to None. Required when using ``host_matching=True``171 with a ``static_folder`` configured.172 :param host_matching: set ``url_map.host_matching`` attribute.173 Defaults to False.174 :param subdomain_matching: consider the subdomain relative to175 :data:`SERVER_NAME` when matching routes. Defaults to False.176 :param template_folder: the folder that contains the templates that should177 be used by the application. Defaults to178 ``'templates'`` folder in the root path of the179 application.180 :param instance_path: An alternative instance path for the application.181 By default the folder ``'instance'`` next to the182 package or module is assumed to be the instance183 path.184 :param instance_relative_config: if set to ``True`` relative filenames185 for loading the config are assumed to186 be relative to the instance path instead187 of the application root.188 :param root_path: Flask by default will automatically calculate the path189 to the root of the application. In certain situations190 this cannot be achieved (for instance if the package191 is a Python 3 namespace package) and needs to be192 manually defined.193 """194195 #: The class that is used for request objects. See :class:`~flask.Request`196 #: for more information.197 request_class = Request198199 #: The class that is used for response objects. See200 #: :class:`~flask.Response` for more information.201 response_class = Response202203 #: The class that is used for the Jinja environment.204 #:205 #: .. versionadded:: 0.11206 jinja_environment = Environment207208 #: The class that is used for the :data:`~flask.g` instance.209 #:210 #: Example use cases for a custom class:211 #:212 #: 1. Store arbitrary attributes on flask.g.213 #: 2. Add a property for lazy per-request database connectors.214 #: 3. Return None instead of AttributeError on unexpected attributes.215 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.216 #:217 #: In Flask 0.9 this property was called `request_globals_class` but it218 #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the219 #: flask.g object is now application context scoped.220 #:221 #: .. versionadded:: 0.10222 app_ctx_globals_class = _AppCtxGlobals223224 #: The class that is used for the ``config`` attribute of this app.225 #: Defaults to :class:`~flask.Config`.226 #:227 #: Example use cases for a custom class:228 #:229 #: 1. Default values for certain config options.230 #: 2. Access to config values through attributes in addition to keys.231 #:232 #: .. versionadded:: 0.11233 config_class = Config234235 #: The testing flag. Set this to ``True`` to enable the test mode of236 #: Flask extensions (and in the future probably also Flask itself).237 #: For example this might activate test helpers that have an238 #: additional runtime cost which should not be enabled by default.239 #:240 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the241 #: default it's implicitly enabled.242 #:243 #: This attribute can also be configured from the config with the244 #: ``TESTING`` configuration key. Defaults to ``False``.245 testing = ConfigAttribute("TESTING")246247 #: If a secret key is set, cryptographic components can use this to248 #: sign cookies and other things. Set this to a complex random value249 #: when you want to use the secure cookie for instance.250 #:251 #: This attribute can also be configured from the config with the252 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.253 secret_key = ConfigAttribute("SECRET_KEY")254255 #: The secure cookie uses this for the name of the session cookie.256 #:257 #: This attribute can also be configured from the config with the258 #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``259 session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")260261 #: A :class:`~datetime.timedelta` which is used to set the expiration262 #: date of a permanent session. The default is 31 days which makes a263 #: permanent session survive for roughly one month.264 #:265 #: This attribute can also be configured from the config with the266 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to267 #: ``timedelta(days=31)``268 permanent_session_lifetime = ConfigAttribute(269 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta270 )271272 #: A :class:`~datetime.timedelta` which is used as default cache_timeout273 #: for the :func:`send_file` functions. The default is 12 hours.274 #:275 #: This attribute can also be configured from the config with the276 #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration277 #: variable can also be set with an integer value used as seconds.278 #: Defaults to ``timedelta(hours=12)``279 send_file_max_age_default = ConfigAttribute(280 "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta281 )282283 #: Enable this if you want to use the X-Sendfile feature. Keep in284 #: mind that the server has to support this. This only affects files285 #: sent with the :func:`send_file` method.286 #:287 #: .. versionadded:: 0.2288 #:289 #: This attribute can also be configured from the config with the290 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.291 use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")292293 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.294 #:295 #: .. versionadded:: 0.10296 json_encoder = json.JSONEncoder297298 #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.299 #:300 #: .. versionadded:: 0.10301 json_decoder = json.JSONDecoder302303 #: Options that are passed to the Jinja environment in304 #: :meth:`create_jinja_environment`. Changing these options after305 #: the environment is created (accessing :attr:`jinja_env`) will306 #: have no effect.307 #:308 #: .. versionchanged:: 1.1.0309 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow310 #: easier configuration.311 #:312 jinja_options = {"extensions": ["jinja2.ext.autoescape", "jinja2.ext.with_"]}313314 #: Default configuration parameters.315 default_config = ImmutableDict(316 {317 "ENV": None,318 "DEBUG": None,319 "TESTING": False,320 "PROPAGATE_EXCEPTIONS": None,321 "PRESERVE_CONTEXT_ON_EXCEPTION": None,322 "SECRET_KEY": None,323 "PERMANENT_SESSION_LIFETIME": timedelta(days=31),324 "USE_X_SENDFILE": False,325 "SERVER_NAME": None,326 "APPLICATION_ROOT": "/",327 "SESSION_COOKIE_NAME": "session",328 "SESSION_COOKIE_DOMAIN": None,329 "SESSION_COOKIE_PATH": None,330 "SESSION_COOKIE_HTTPONLY": True,331 "SESSION_COOKIE_SECURE": False,332 "SESSION_COOKIE_SAMESITE": None,333 "SESSION_REFRESH_EACH_REQUEST": True,334 "MAX_CONTENT_LENGTH": None,335 "SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),336 "TRAP_BAD_REQUEST_ERRORS": None,337 "TRAP_HTTP_EXCEPTIONS": False,338 "EXPLAIN_TEMPLATE_LOADING": False,339 "PREFERRED_URL_SCHEME": "http",340 "JSON_AS_ASCII": True,341 "JSON_SORT_KEYS": True,342 "JSONIFY_PRETTYPRINT_REGULAR": False,343 "JSONIFY_MIMETYPE": "application/json",344 "TEMPLATES_AUTO_RELOAD": None,345 "MAX_COOKIE_SIZE": 4093,346 }347 )348349 #: The rule object to use for URL rules created. This is used by350 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.351 #:352 #: .. versionadded:: 0.7353 url_rule_class = Rule354355 #: The map object to use for storing the URL rules and routing356 #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.357 #:358 #: .. versionadded:: 1.1.0359 url_map_class = Map360361 #: the test client that is used with when `test_client` is used.362 #:363 #: .. versionadded:: 0.7364 test_client_class = None365366 #: The :class:`~click.testing.CliRunner` subclass, by default367 #: :class:`~flask.testing.FlaskCliRunner` that is used by368 #: :meth:`test_cli_runner`. Its ``__init__`` method should take a369 #: Flask app object as the first argument.370 #:371 #: .. versionadded:: 1.0372 test_cli_runner_class = None373374 #: the session interface to use. By default an instance of375 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.376 #:377 #: .. versionadded:: 0.8378 session_interface = SecureCookieSessionInterface()379380 # TODO remove the next three attrs when Sphinx :inherited-members: works381 # https://github.com/sphinx-doc/sphinx/issues/741382383 #: The name of the package or module that this app belongs to. Do not384 #: change this once it is set by the constructor.385 import_name = None386387 #: Location of the template files to be added to the template lookup.388 #: ``None`` if templates should not be added.389 template_folder = None390391 #: Absolute path to the package on the filesystem. Used to look up392 #: resources contained in the package.393 root_path = None394395 def __init__(396 self,397 import_name,398 static_url_path=None,399 static_folder="static",400 static_host=None,401 host_matching=False,402 subdomain_matching=False,403 template_folder="templates",404 instance_path=None,405 instance_relative_config=False,406 root_path=None,407 ):408 _PackageBoundObject.__init__(409 self, import_name, template_folder=template_folder, root_path=root_path410 )411412 self.static_url_path = static_url_path413 self.static_folder = static_folder414415 if instance_path is None:416 instance_path = self.auto_find_instance_path()417 elif not os.path.isabs(instance_path):418 raise ValueError(419 "If an instance path is provided it must be absolute."420 " A relative path was given instead."421 )422423 #: Holds the path to the instance folder.424 #:425 #: .. versionadded:: 0.8426 self.instance_path = instance_path427428 #: The configuration dictionary as :class:`Config`. This behaves429 #: exactly like a regular dictionary but supports additional methods430 #: to load a config from files.431 self.config = self.make_config(instance_relative_config)432433 #: A dictionary of all view functions registered. The keys will434 #: be function names which are also used to generate URLs and435 #: the values are the function objects themselves.436 #: To register a view function, use the :meth:`route` decorator.437 self.view_functions = {}438439 #: A dictionary of all registered error handlers. The key is ``None``440 #: for error handlers active on the application, otherwise the key is441 #: the name of the blueprint. Each key points to another dictionary442 #: where the key is the status code of the http exception. The443 #: special key ``None`` points to a list of tuples where the first item444 #: is the class for the instance check and the second the error handler445 #: function.446 #:447 #: To register an error handler, use the :meth:`errorhandler`448 #: decorator.449 self.error_handler_spec = {}450451 #: A list of functions that are called when :meth:`url_for` raises a452 #: :exc:`~werkzeug.routing.BuildError`. Each function registered here453 #: is called with `error`, `endpoint` and `values`. If a function454 #: returns ``None`` or raises a :exc:`BuildError` the next function is455 #: tried.456 #:457 #: .. versionadded:: 0.9458 self.url_build_error_handlers = []459460 #: A dictionary with lists of functions that will be called at the461 #: beginning of each request. The key of the dictionary is the name of462 #: the blueprint this function is active for, or ``None`` for all463 #: requests. To register a function, use the :meth:`before_request`464 #: decorator.465 self.before_request_funcs = {}466467 #: A list of functions that will be called at the beginning of the468 #: first request to this instance. To register a function, use the469 #: :meth:`before_first_request` decorator.470 #:471 #: .. versionadded:: 0.8472 self.before_first_request_funcs = []473474 #: A dictionary with lists of functions that should be called after475 #: each request. The key of the dictionary is the name of the blueprint476 #: this function is active for, ``None`` for all requests. This can for477 #: example be used to close database connections. To register a function478 #: here, use the :meth:`after_request` decorator.479 self.after_request_funcs = {}480481 #: A dictionary with lists of functions that are called after482 #: each request, even if an exception has occurred. The key of the483 #: dictionary is the name of the blueprint this function is active for,484 #: ``None`` for all requests. These functions are not allowed to modify485 #: the request, and their return values are ignored. If an exception486 #: occurred while processing the request, it gets passed to each487 #: teardown_request function. To register a function here, use the488 #: :meth:`teardown_request` decorator.489 #:490 #: .. versionadded:: 0.7491 self.teardown_request_funcs = {}492493 #: A list of functions that are called when the application context494 #: is destroyed. Since the application context is also torn down495 #: if the request ends this is the place to store code that disconnects496 #: from databases.497 #:498 #: .. versionadded:: 0.9499 self.teardown_appcontext_funcs = []500501 #: A dictionary with lists of functions that are called before the502 #: :attr:`before_request_funcs` functions. The key of the dictionary is503 #: the name of the blueprint this function is active for, or ``None``504 #: for all requests. To register a function, use505 #: :meth:`url_value_preprocessor`.506 #:507 #: .. versionadded:: 0.7508 self.url_value_preprocessors = {}509510 #: A dictionary with lists of functions that can be used as URL value511 #: preprocessors. The key ``None`` here is used for application wide512 #: callbacks, otherwise the key is the name of the blueprint.513 #: Each of these functions has the chance to modify the dictionary514 #: of URL values before they are used as the keyword arguments of the515 #: view function. For each function registered this one should also516 #: provide a :meth:`url_defaults` function that adds the parameters517 #: automatically again that were removed that way.518 #:519 #: .. versionadded:: 0.7520 self.url_default_functions = {}521522 #: A dictionary with list of functions that are called without argument523 #: to populate the template context. The key of the dictionary is the524 #: name of the blueprint this function is active for, ``None`` for all525 #: requests. Each returns a dictionary that the template context is526 #: updated with. To register a function here, use the527 #: :meth:`context_processor` decorator.528 self.template_context_processors = {None: [_default_template_ctx_processor]}529530 #: A list of shell context processor functions that should be run531 #: when a shell context is created.532 #:533 #: .. versionadded:: 0.11534 self.shell_context_processors = []535536 #: all the attached blueprints in a dictionary by name. Blueprints537 #: can be attached multiple times so this dictionary does not tell538 #: you how often they got attached.539 #:540 #: .. versionadded:: 0.7541 self.blueprints = {}542 self._blueprint_order = []543544 #: a place where extensions can store application specific state. For545 #: example this is where an extension could store database engines and546 #: similar things. For backwards compatibility extensions should register547 #: themselves like this::548 #:549 #: if not hasattr(app, 'extensions'):550 #: app.extensions = {}551 #: app.extensions['extensionname'] = SomeObject()552 #:553 #: The key must match the name of the extension module. For example in554 #: case of a "Flask-Foo" extension in `flask_foo`, the key would be555 #: ``'foo'``.556 #:557 #: .. versionadded:: 0.7558 self.extensions = {}559560 #: The :class:`~werkzeug.routing.Map` for this instance. You can use561 #: this to change the routing converters after the class was created562 #: but before any routes are connected. Example::563 #:564 #: from werkzeug.routing import BaseConverter565 #:566 #: class ListConverter(BaseConverter):567 #: def to_python(self, value):568 #: return value.split(',')569 #: def to_url(self, values):570 #: return ','.join(super(ListConverter, self).to_url(value)571 #: for value in values)572 #:573 #: app = Flask(__name__)574 #: app.url_map.converters['list'] = ListConverter575 self.url_map = self.url_map_class()576577 self.url_map.host_matching = host_matching578 self.subdomain_matching = subdomain_matching579580 # tracks internally if the application already handled at least one581 # request.582 self._got_first_request = False583 self._before_request_lock = Lock()584585 # Add a static route using the provided static_url_path, static_host,586 # and static_folder if there is a configured static_folder.587 # Note we do this without checking if static_folder exists.588 # For one, it might be created while the server is running (e.g. during589 # development). Also, Google App Engine stores static files somewhere590 if self.has_static_folder:591 assert (592 bool(static_host) == host_matching593 ), "Invalid static_host/host_matching combination"594 self.add_url_rule(595 self.static_url_path + "/<path:filename>",596 endpoint="static",597 host=static_host,598 view_func=self.send_static_file,599 )600601 # Set the name of the Click group in case someone wants to add602 # the app's commands to another CLI tool.603 self.cli.name = self.name604605 @locked_cached_property606 def name(self):607 """The name of the application. This is usually the import name608 with the difference that it's guessed from the run file if the609 import name is main. This name is used as a display name when610 Flask needs the name of the application. It can be set and overridden611 to change the value.612613 .. versionadded:: 0.8614 """615 if self.import_name == "__main__":616 fn = getattr(sys.modules["__main__"], "__file__", None)617 if fn is None:618 return "__main__"619 return os.path.splitext(os.path.basename(fn))[0]620 return self.import_name621622 @property623 def propagate_exceptions(self):624 """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration625 value in case it's set, otherwise a sensible default is returned.626627 .. versionadded:: 0.7628 """629 rv = self.config["PROPAGATE_EXCEPTIONS"]630 if rv is not None:631 return rv632 return self.testing or self.debug633634 @property635 def preserve_context_on_exception(self):636 """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``637 configuration value in case it's set, otherwise a sensible default638 is returned.639640 .. versionadded:: 0.7641 """642 rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]643 if rv is not None:644 return rv645 return self.debug646647 @locked_cached_property648 def logger(self):649 """The ``'flask.app'`` logger, a standard Python650 :class:`~logging.Logger`.651652 In debug mode, the logger's :attr:`~logging.Logger.level` will be set653 to :data:`~logging.DEBUG`.654655 If there are no handlers configured, a default handler will be added.656 See :ref:`logging` for more information.657658 .. versionchanged:: 1.0659 Behavior was simplified. The logger is always named660 ``flask.app``. The level is only set during configuration, it661 doesn't check ``app.debug`` each time. Only one format is used,662 not different ones depending on ``app.debug``. No handlers are663 removed, and a handler is only added if no handlers are already664 configured.665666 .. versionadded:: 0.3667 """668 return create_logger(self)669670 @locked_cached_property671 def jinja_env(self):672 """The Jinja environment used to load templates.673674 The environment is created the first time this property is675 accessed. Changing :attr:`jinja_options` after that will have no676 effect.677 """678 return self.create_jinja_environment()679680 @property681 def got_first_request(self):682 """This attribute is set to ``True`` if the application started683 handling the first request.684685 .. versionadded:: 0.8686 """687 return self._got_first_request688689 def make_config(self, instance_relative=False):690 """Used to create the config attribute by the Flask constructor.691 The `instance_relative` parameter is passed in from the constructor692 of Flask (there named `instance_relative_config`) and indicates if693 the config should be relative to the instance path or the root path694 of the application.695696 .. versionadded:: 0.8697 """698 root_path = self.root_path699 if instance_relative:700 root_path = self.instance_path701 defaults = dict(self.default_config)702 defaults["ENV"] = get_env()703 defaults["DEBUG"] = get_debug_flag()704 return self.config_class(root_path, defaults)705706 def auto_find_instance_path(self):707 """Tries to locate the instance path if it was not provided to the708 constructor of the application class. It will basically calculate709 the path to a folder named ``instance`` next to your main file or710 the package.711712 .. versionadded:: 0.8713 """714 prefix, package_path = find_package(self.import_name)715 if prefix is None:716 return os.path.join(package_path, "instance")717 return os.path.join(prefix, "var", self.name + "-instance")718719 def open_instance_resource(self, resource, mode="rb"):720 """Opens a resource from the application's instance folder721 (:attr:`instance_path`). Otherwise works like722 :meth:`open_resource`. Instance resources can also be opened for723 writing.724725 :param resource: the name of the resource. To access resources within726 subfolders use forward slashes as separator.727 :param mode: resource file opening mode, default is 'rb'.728 """729 return open(os.path.join(self.instance_path, resource), mode)730731 @property732 def templates_auto_reload(self):733 """Reload templates when they are changed. Used by734 :meth:`create_jinja_environment`.735736 This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If737 not set, it will be enabled in debug mode.738739 .. versionadded:: 1.0740 This property was added but the underlying config and behavior741 already existed.742 """743 rv = self.config["TEMPLATES_AUTO_RELOAD"]744 return rv if rv is not None else self.debug745746 @templates_auto_reload.setter747 def templates_auto_reload(self, value):748 self.config["TEMPLATES_AUTO_RELOAD"] = value749750 def create_jinja_environment(self):751 """Create the Jinja environment based on :attr:`jinja_options`752 and the various Jinja-related methods of the app. Changing753 :attr:`jinja_options` after this will have no effect. Also adds754 Flask-related globals and filters to the environment.755756 .. versionchanged:: 0.11757 ``Environment.auto_reload`` set in accordance with758 ``TEMPLATES_AUTO_RELOAD`` configuration option.759760 .. versionadded:: 0.5761 """762 options = dict(self.jinja_options)763764 if "autoescape" not in options:765 options["autoescape"] = self.select_jinja_autoescape766767 if "auto_reload" not in options:768 options["auto_reload"] = self.templates_auto_reload769770 rv = self.jinja_environment(self, **options)771 rv.globals.update(772 url_for=url_for,773 get_flashed_messages=get_flashed_messages,774 config=self.config,775 # request, session and g are normally added with the776 # context processor for efficiency reasons but for imported777 # templates we also want the proxies in there.778 request=request,779 session=session,780 g=g,781 )782 rv.filters["tojson"] = json.tojson_filter783 return rv784785 def create_global_jinja_loader(self):786 """Creates the loader for the Jinja2 environment. Can be used to787 override just the loader and keeping the rest unchanged. It's788 discouraged to override this function. Instead one should override789 the :meth:`jinja_loader` function instead.790791 The global loader dispatches between the loaders of the application792 and the individual blueprints.793794 .. versionadded:: 0.7795 """796 return DispatchingJinjaLoader(self)797798 def select_jinja_autoescape(self, filename):799 """Returns ``True`` if autoescaping should be active for the given800 template name. If no template name is given, returns `True`.801802 .. versionadded:: 0.5803 """804 if filename is None:805 return True806 return filename.endswith((".html", ".htm", ".xml", ".xhtml"))807808 def update_template_context(self, context):809 """Update the template context with some commonly used variables.810 This injects request, session, config and g into the template811 context as well as everything template context processors want812 to inject. Note that the as of Flask 0.6, the original values813 in the context will not be overridden if a context processor814 decides to return a value with the same key.815816 :param context: the context as a dictionary that is updated in place817 to add extra variables.818 """819 funcs = self.template_context_processors[None]820 reqctx = _request_ctx_stack.top821 if reqctx is not None:822 bp = reqctx.request.blueprint823 if bp is not None and bp in self.template_context_processors:824 funcs = chain(funcs, self.template_context_processors[bp])825 orig_ctx = context.copy()826 for func in funcs:827 context.update(func())828 # make sure the original values win. This makes it possible to829 # easier add new variables in context processors without breaking830 # existing views.831 context.update(orig_ctx)832833 def make_shell_context(self):834 """Returns the shell context for an interactive shell for this835 application. This runs all the registered shell context836 processors.837838 .. versionadded:: 0.11839 """840 rv = {"app": self, "g": g}841 for processor in self.shell_context_processors:842 rv.update(processor())843 return rv844845 #: What environment the app is running in. Flask and extensions may846 #: enable behaviors based on the environment, such as enabling debug847 #: mode. This maps to the :data:`ENV` config key. This is set by the848 #: :envvar:`FLASK_ENV` environment variable and may not behave as849 #: expected if set in code.850 #:851 #: **Do not enable development when deploying in production.**852 #:853 #: Default: ``'production'``854 env = ConfigAttribute("ENV")855856 @property857 def debug(self):858 """Whether debug mode is enabled. When using ``flask run`` to start859 the development server, an interactive debugger will be shown for860 unhandled exceptions, and the server will be reloaded when code861 changes. This maps to the :data:`DEBUG` config key. This is862 enabled when :attr:`env` is ``'development'`` and is overridden863 by the ``FLASK_DEBUG`` environment variable. It may not behave as864 expected if set in code.865866 **Do not enable debug mode when deploying in production.**867868 Default: ``True`` if :attr:`env` is ``'development'``, or869 ``False`` otherwise.870 """871 return self.config["DEBUG"]872873 @debug.setter874 def debug(self, value):875 self.config["DEBUG"] = value876 self.jinja_env.auto_reload = self.templates_auto_reload877878 def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):879 """Runs the application on a local development server.880881 Do not use ``run()`` in a production setting. It is not intended to882 meet security and performance requirements for a production server.883 Instead, see :ref:`deployment` for WSGI server recommendations.884885 If the :attr:`debug` flag is set the server will automatically reload886 for code changes and show a debugger in case an exception happened.887888 If you want to run the application in debug mode, but disable the889 code execution on the interactive debugger, you can pass890 ``use_evalex=False`` as parameter. This will keep the debugger's891 traceback screen active, but disable code execution.892893 It is not recommended to use this function for development with894 automatic reloading as this is badly supported. Instead you should895 be using the :command:`flask` command line script's ``run`` support.896897 .. admonition:: Keep in Mind898899 Flask will suppress any server error with a generic error page900 unless it is in debug mode. As such to enable just the901 interactive debugger without the code reloading, you have to902 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.903 Setting ``use_debugger`` to ``True`` without being in debug mode904 won't catch any exceptions because there won't be any to905 catch.906907 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to908 have the server available externally as well. Defaults to909 ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable910 if present.911 :param port: the port of the webserver. Defaults to ``5000`` or the912 port defined in the ``SERVER_NAME`` config variable if present.913 :param debug: if given, enable or disable debug mode. See914 :attr:`debug`.915 :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`916 files to set environment variables. Will also change the working917 directory to the directory containing the first file found.918 :param options: the options to be forwarded to the underlying Werkzeug919 server. See :func:`werkzeug.serving.run_simple` for more920 information.921922 .. versionchanged:: 1.0923 If installed, python-dotenv will be used to load environment924 variables from :file:`.env` and :file:`.flaskenv` files.925926 If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`927 environment variables will override :attr:`env` and928 :attr:`debug`.929930 Threaded mode is enabled by default.931932 .. versionchanged:: 0.10933 The default port is now picked from the ``SERVER_NAME``934 variable.935 """936 # Change this into a no-op if the server is invoked from the937 # command line. Have a look at cli.py for more information.938 if os.environ.get("FLASK_RUN_FROM_CLI") == "true":939 from .debughelpers import explain_ignored_app_run940941 explain_ignored_app_run()942 return943944 if get_load_dotenv(load_dotenv):945 cli.load_dotenv()946947 # if set, let env vars override previous values948 if "FLASK_ENV" in os.environ:949 self.env = get_env()950 self.debug = get_debug_flag()951 elif "FLASK_DEBUG" in os.environ:952 self.debug = get_debug_flag()953954 # debug passed to method overrides all other sources955 if debug is not None:956 self.debug = bool(debug)957958 _host = "127.0.0.1"959 _port = 5000960 server_name = self.config.get("SERVER_NAME")961 sn_host, sn_port = None, None962963 if server_name:964 sn_host, _, sn_port = server_name.partition(":")965966 host = host or sn_host or _host967 # pick the first value that's not None (0 is allowed)968 port = int(next((p for p in (port, sn_port) if p is not None), _port))969970 options.setdefault("use_reloader", self.debug)971 options.setdefault("use_debugger", self.debug)972 options.setdefault("threaded", True)973974 cli.show_server_banner(self.env, self.debug, self.name, False)975976 from werkzeug.serving import run_simple977978 try:979 run_simple(host, port, self, **options)980 finally:981 # reset the first request information if the development server982 # reset normally. This makes it possible to restart the server983 # without reloader and that stuff from an interactive shell.984 self._got_first_request = False985986 def test_client(self, use_cookies=True, **kwargs):987 """Creates a test client for this application. For information988 about unit testing head over to :ref:`testing`.989990 Note that if you are testing for assertions or exceptions in your991 application code, you must set ``app.testing = True`` in order for the992 exceptions to propagate to the test client. Otherwise, the exception993 will be handled by the application (not visible to the test client) and994 the only indication of an AssertionError or other exception will be a995 500 status code response to the test client. See the :attr:`testing`996 attribute. For example::997998 app.testing = True999 client = app.test_client()10001001 The test client can be used in a ``with`` block to defer the closing down1002 of the context until the end of the ``with`` block. This is useful if1003 you want to access the context locals for testing::10041005 with app.test_client() as c:1006 rv = c.get('/?vodka=42')1007 assert request.args['vodka'] == '42'10081009 Additionally, you may pass optional keyword arguments that will then1010 be passed to the application's :attr:`test_client_class` constructor.1011 For example::10121013 from flask.testing import FlaskClient10141015 class CustomClient(FlaskClient):1016 def __init__(self, *args, **kwargs):1017 self._authentication = kwargs.pop("authentication")1018 super(CustomClient,self).__init__( *args, **kwargs)10191020 app.test_client_class = CustomClient1021 client = app.test_client(authentication='Basic ....')10221023 See :class:`~flask.testing.FlaskClient` for more information.10241025 .. versionchanged:: 0.41026 added support for ``with`` block usage for the client.10271028 .. versionadded:: 0.71029 The `use_cookies` parameter was added as well as the ability1030 to override the client to be used by setting the1031 :attr:`test_client_class` attribute.10321033 .. versionchanged:: 0.111034 Added `**kwargs` to support passing additional keyword arguments to1035 the constructor of :attr:`test_client_class`.1036 """1037 cls = self.test_client_class1038 if cls is None:1039 from flask.testing import FlaskClient as cls1040 return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)10411042 def test_cli_runner(self, **kwargs):1043 """Create a CLI runner for testing CLI commands.1044 See :ref:`testing-cli`.10451046 Returns an instance of :attr:`test_cli_runner_class`, by default1047 :class:`~flask.testing.FlaskCliRunner`. The Flask app object is1048 passed as the first argument.10491050 .. versionadded:: 1.01051 """1052 cls = self.test_cli_runner_class10531054 if cls is None:1055 from flask.testing import FlaskCliRunner as cls10561057 return cls(self, **kwargs)10581059 def open_session(self, request):1060 """Creates or opens a new session. Default implementation stores all1061 session data in a signed cookie. This requires that the1062 :attr:`secret_key` is set. Instead of overriding this method1063 we recommend replacing the :class:`session_interface`.10641065 .. deprecated: 1.01066 Will be removed in 1.1. Use ``session_interface.open_session``1067 instead.10681069 :param request: an instance of :attr:`request_class`.1070 """10711072 warnings.warn(1073 DeprecationWarning(1074 '"open_session" is deprecated and will be removed in 1.1. Use'1075 ' "session_interface.open_session" instead.'1076 )1077 )1078 return self.session_interface.open_session(self, request)10791080 def save_session(self, session, response):1081 """Saves the session if it needs updates. For the default1082 implementation, check :meth:`open_session`. Instead of overriding this1083 method we recommend replacing the :class:`session_interface`.10841085 .. deprecated: 1.01086 Will be removed in 1.1. Use ``session_interface.save_session``1087 instead.10881089 :param session: the session to be saved (a1090 :class:`~werkzeug.contrib.securecookie.SecureCookie`1091 object)1092 :param response: an instance of :attr:`response_class`1093 """10941095 warnings.warn(1096 DeprecationWarning(1097 '"save_session" is deprecated and will be removed in 1.1. Use'1098 ' "session_interface.save_session" instead.'1099 )1100 )1101 return self.session_interface.save_session(self, session, response)11021103 def make_null_session(self):1104 """Creates a new instance of a missing session. Instead of overriding1105 this method we recommend replacing the :class:`session_interface`.11061107 .. deprecated: 1.01108 Will be removed in 1.1. Use ``session_interface.make_null_session``1109 instead.11101111 .. versionadded:: 0.71112 """11131114 warnings.warn(1115 DeprecationWarning(1116 '"make_null_session" is deprecated and will be removed in 1.1. Use'1117 ' "session_interface.make_null_session" instead.'1118 )1119 )1120 return self.session_interface.make_null_session(self)11211122 @setupmethod1123 def register_blueprint(self, blueprint, **options):1124 """Register a :class:`~flask.Blueprint` on the application. Keyword1125 arguments passed to this method will override the defaults set on the1126 blueprint.11271128 Calls the blueprint's :meth:`~flask.Blueprint.register` method after1129 recording the blueprint in the application's :attr:`blueprints`.11301131 :param blueprint: The blueprint to register.1132 :param url_prefix: Blueprint routes will be prefixed with this.1133 :param subdomain: Blueprint routes will match on this subdomain.1134 :param url_defaults: Blueprint routes will use these default values for1135 view arguments.1136 :param options: Additional keyword arguments are passed to1137 :class:`~flask.blueprints.BlueprintSetupState`. They can be1138 accessed in :meth:`~flask.Blueprint.record` callbacks.11391140 .. versionadded:: 0.71141 """1142 first_registration = False11431144 if blueprint.name in self.blueprints:1145 assert self.blueprints[blueprint.name] is blueprint, (1146 "A name collision occurred between blueprints %r and %r. Both"1147 ' share the same name "%s". Blueprints that are created on the'1148 " fly need unique names."1149 % (blueprint, self.blueprints[blueprint.name], blueprint.name)1150 )1151 else:1152 self.blueprints[blueprint.name] = blueprint1153 self._blueprint_order.append(blueprint)1154 first_registration = True11551156 blueprint.register(self, options, first_registration)11571158 def iter_blueprints(self):1159 """Iterates over all blueprints by the order they were registered.11601161 .. versionadded:: 0.111162 """1163 return iter(self._blueprint_order)11641165 @setupmethod1166 def add_url_rule(1167 self,1168 rule,1169 endpoint=None,1170 view_func=None,1171 provide_automatic_options=None,1172 **options1173 ):1174 """Connects a URL rule. Works exactly like the :meth:`route`1175 decorator. If a view_func is provided it will be registered with the1176 endpoint.11771178 Basically this example::11791180 @app.route('/')1181 def index():1182 pass11831184 Is equivalent to the following::11851186 def index():1187 pass1188 app.add_url_rule('/', 'index', index)11891190 If the view_func is not provided you will need to connect the endpoint1191 to a view function like so::11921193 app.view_functions['index'] = index11941195 Internally :meth:`route` invokes :meth:`add_url_rule` so if you want1196 to customize the behavior via subclassing you only need to change1197 this method.11981199 For more information refer to :ref:`url-route-registrations`.12001201 .. versionchanged:: 0.21202 `view_func` parameter added.12031204 .. versionchanged:: 0.61205 ``OPTIONS`` is added automatically as method.12061207 :param rule: the URL rule as string1208 :param endpoint: the endpoint for the registered URL rule. Flask1209 itself assumes the name of the view function as1210 endpoint1211 :param view_func: the function to call when serving a request to the1212 provided endpoint1213 :param provide_automatic_options: controls whether the ``OPTIONS``1214 method should be added automatically. This can also be controlled1215 by setting the ``view_func.provide_automatic_options = False``1216 before adding the rule.1217 :param options: the options to be forwarded to the underlying1218 :class:`~werkzeug.routing.Rule` object. A change1219 to Werkzeug is handling of method options. methods1220 is a list of methods this rule should be limited1221 to (``GET``, ``POST`` etc.). By default a rule1222 just listens for ``GET`` (and implicitly ``HEAD``).1223 Starting with Flask 0.6, ``OPTIONS`` is implicitly1224 added and handled by the standard request handling.1225 """1226 if endpoint is None:1227 endpoint = _endpoint_from_view_func(view_func)1228 options["endpoint"] = endpoint1229 methods = options.pop("methods", None)12301231 # if the methods are not given and the view_func object knows its1232 # methods we can use that instead. If neither exists, we go with1233 # a tuple of only ``GET`` as default.1234 if methods is None:1235 methods = getattr(view_func, "methods", None) or ("GET",)1236 if isinstance(methods, string_types):1237 raise TypeError(1238 "Allowed methods have to be iterables of strings, "1239 'for example: @app.route(..., methods=["POST"])'1240 )1241 methods = set(item.upper() for item in methods)12421243 # Methods that should always be added1244 required_methods = set(getattr(view_func, "required_methods", ()))12451246 # starting with Flask 0.8 the view_func object can disable and1247 # force-enable the automatic options handling.1248 if provide_automatic_options is None:1249 provide_automatic_options = getattr(1250 view_func, "provide_automatic_options", None1251 )12521253 if provide_automatic_options is None:1254 if "OPTIONS" not in methods:1255 provide_automatic_options = True1256 required_methods.add("OPTIONS")1257 else:1258 provide_automatic_options = False12591260 # Add the required methods now.1261 methods |= required_methods12621263 rule = self.url_rule_class(rule, methods=methods, **options)1264 rule.provide_automatic_options = provide_automatic_options12651266 self.url_map.add(rule)1267 if view_func is not None:1268 old_func = self.view_functions.get(endpoint)1269 if old_func is not None and old_func != view_func:1270 raise AssertionError(1271 "View function mapping is overwriting an "1272 "existing endpoint function: %s" % endpoint1273 )1274 self.view_functions[endpoint] = view_func12751276 def route(self, rule, **options):1277 """A decorator that is used to register a view function for a1278 given URL rule. This does the same thing as :meth:`add_url_rule`1279 but is intended for decorator usage::12801281 @app.route('/')1282 def index():1283 return 'Hello World'12841285 For more information refer to :ref:`url-route-registrations`.12861287 :param rule: the URL rule as string1288 :param endpoint: the endpoint for the registered URL rule. Flask1289 itself assumes the name of the view function as1290 endpoint1291 :param options: the options to be forwarded to the underlying1292 :class:`~werkzeug.routing.Rule` object. A change1293 to Werkzeug is handling of method options. methods1294 is a list of methods this rule should be limited1295 to (``GET``, ``POST`` etc.). By default a rule1296 just listens for ``GET`` (and implicitly ``HEAD``).1297 Starting with Flask 0.6, ``OPTIONS`` is implicitly1298 added and handled by the standard request handling.1299 """13001301 def decorator(f):1302 endpoint = options.pop("endpoint", None)1303 self.add_url_rule(rule, endpoint, f, **options)1304 return f13051306 return decorator13071308 @setupmethod1309 def endpoint(self, endpoint):1310 """A decorator to register a function as an endpoint.1311 Example::13121313 @app.endpoint('example.endpoint')1314 def example():1315 return "example"13161317 :param endpoint: the name of the endpoint1318 """13191320 def decorator(f):1321 self.view_functions[endpoint] = f1322 return f13231324 return decorator13251326 @staticmethod1327 def _get_exc_class_and_code(exc_class_or_code):1328 """Ensure that we register only exceptions as handler keys"""1329 if isinstance(exc_class_or_code, integer_types):1330 exc_class = default_exceptions[exc_class_or_code]1331 else:1332 exc_class = exc_class_or_code13331334 assert issubclass(exc_class, Exception)13351336 if issubclass(exc_class, HTTPException):1337 return exc_class, exc_class.code1338 else:1339 return exc_class, None13401341 @setupmethod1342 def errorhandler(self, code_or_exception):1343 """Register a function to handle errors by code or exception class.13441345 A decorator that is used to register a function given an1346 error code. Example::13471348 @app.errorhandler(404)1349 def page_not_found(error):1350 return 'This page does not exist', 40413511352 You can also register handlers for arbitrary exceptions::13531354 @app.errorhandler(DatabaseError)1355 def special_exception_handler(error):1356 return 'Database connection failed', 50013571358 .. versionadded:: 0.71359 Use :meth:`register_error_handler` instead of modifying1360 :attr:`error_handler_spec` directly, for application wide error1361 handlers.13621363 .. versionadded:: 0.71364 One can now additionally also register custom exception types1365 that do not necessarily have to be a subclass of the1366 :class:`~werkzeug.exceptions.HTTPException` class.13671368 :param code_or_exception: the code as integer for the handler, or1369 an arbitrary exception1370 """13711372 def decorator(f):1373 self._register_error_handler(None, code_or_exception, f)1374 return f13751376 return decorator13771378 @setupmethod1379 def register_error_handler(self, code_or_exception, f):1380 """Alternative error attach function to the :meth:`errorhandler`1381 decorator that is more straightforward to use for non decorator1382 usage.13831384 .. versionadded:: 0.71385 """1386 self._register_error_handler(None, code_or_exception, f)13871388 @setupmethod1389 def _register_error_handler(self, key, code_or_exception, f):1390 """1391 :type key: None|str1392 :type code_or_exception: int|T<=Exception1393 :type f: callable1394 """1395 if isinstance(code_or_exception, HTTPException): # old broken behavior1396 raise ValueError(1397 "Tried to register a handler for an exception instance {0!r}."1398 " Handlers can only be registered for exception classes or"1399 " HTTP error codes.".format(code_or_exception)1400 )14011402 try:1403 exc_class, code = self._get_exc_class_and_code(code_or_exception)1404 except KeyError:1405 raise KeyError(1406 "'{0}' is not a recognized HTTP error code. Use a subclass of"1407 " HTTPException with that code instead.".format(code_or_exception)1408 )14091410 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1411 handlers[exc_class] = f14121413 @setupmethod1414 def template_filter(self, name=None):1415 """A decorator that is used to register custom template filter.1416 You can specify a name for the filter, otherwise the function1417 name will be used. Example::14181419 @app.template_filter()1420 def reverse(s):1421 return s[::-1]14221423 :param name: the optional name of the filter, otherwise the1424 function name will be used.1425 """14261427 def decorator(f):1428 self.add_template_filter(f, name=name)1429 return f14301431 return decorator14321433 @setupmethod1434 def add_template_filter(self, f, name=None):1435 """Register a custom template filter. Works exactly like the1436 :meth:`template_filter` decorator.14371438 :param name: the optional name of the filter, otherwise the1439 function name will be used.1440 """1441 self.jinja_env.filters[name or f.__name__] = f14421443 @setupmethod1444 def template_test(self, name=None):1445 """A decorator that is used to register custom template test.1446 You can specify a name for the test, otherwise the function1447 name will be used. Example::14481449 @app.template_test()1450 def is_prime(n):1451 if n == 2:1452 return True1453 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):1454 if n % i == 0:1455 return False1456 return True14571458 .. versionadded:: 0.1014591460 :param name: the optional name of the test, otherwise the1461 function name will be used.1462 """14631464 def decorator(f):1465 self.add_template_test(f, name=name)1466 return f14671468 return decorator14691470 @setupmethod1471 def add_template_test(self, f, name=None):1472 """Register a custom template test. Works exactly like the1473 :meth:`template_test` decorator.14741475 .. versionadded:: 0.1014761477 :param name: the optional name of the test, otherwise the1478 function name will be used.1479 """1480 self.jinja_env.tests[name or f.__name__] = f14811482 @setupmethod1483 def template_global(self, name=None):1484 """A decorator that is used to register a custom template global function.1485 You can specify a name for the global function, otherwise the function1486 name will be used. Example::14871488 @app.template_global()1489 def double(n):1490 return 2 * n14911492 .. versionadded:: 0.1014931494 :param name: the optional name of the global function, otherwise the1495 function name will be used.1496 """14971498 def decorator(f):1499 self.add_template_global(f, name=name)1500 return f15011502 return decorator15031504 @setupmethod1505 def add_template_global(self, f, name=None):1506 """Register a custom template global function. Works exactly like the1507 :meth:`template_global` decorator.15081509 .. versionadded:: 0.1015101511 :param name: the optional name of the global function, otherwise the1512 function name will be used.1513 """1514 self.jinja_env.globals[name or f.__name__] = f15151516 @setupmethod1517 def before_request(self, f):1518 """Registers a function to run before each request.15191520 For example, this can be used to open a database connection, or to load1521 the logged in user from the session.15221523 The function will be called without any arguments. If it returns a1524 non-None value, the value is handled as if it was the return value from1525 the view, and further request handling is stopped.1526 """1527 self.before_request_funcs.setdefault(None, []).append(f)1528 return f15291530 @setupmethod1531 def before_first_request(self, f):1532 """Registers a function to be run before the first request to this1533 instance of the application.15341535 The function will be called without any arguments and its return1536 value is ignored.15371538 .. versionadded:: 0.81539 """1540 self.before_first_request_funcs.append(f)1541 return f15421543 @setupmethod1544 def after_request(self, f):1545 """Register a function to be run after each request.15461547 Your function must take one parameter, an instance of1548 :attr:`response_class` and return a new response object or the1549 same (see :meth:`process_response`).15501551 As of Flask 0.7 this function might not be executed at the end of the1552 request in case an unhandled exception occurred.1553 """1554 self.after_request_funcs.setdefault(None, []).append(f)1555 return f15561557 @setupmethod1558 def teardown_request(self, f):1559 """Register a function to be run at the end of each request,1560 regardless of whether there was an exception or not. These functions1561 are executed when the request context is popped, even if not an1562 actual request was performed.15631564 Example::15651566 ctx = app.test_request_context()1567 ctx.push()1568 ...1569 ctx.pop()15701571 When ``ctx.pop()`` is executed in the above example, the teardown1572 functions are called just before the request context moves from the1573 stack of active contexts. This becomes relevant if you are using1574 such constructs in tests.15751576 Generally teardown functions must take every necessary step to avoid1577 that they will fail. If they do execute code that might fail they1578 will have to surround the execution of these code by try/except1579 statements and log occurring errors.15801581 When a teardown function was called because of an exception it will1582 be passed an error object.15831584 The return values of teardown functions are ignored.15851586 .. admonition:: Debug Note15871588 In debug mode Flask will not tear down a request on an exception1589 immediately. Instead it will keep it alive so that the interactive1590 debugger can still access it. This behavior can be controlled1591 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.1592 """1593 self.teardown_request_funcs.setdefault(None, []).append(f)1594 return f15951596 @setupmethod1597 def teardown_appcontext(self, f):1598 """Registers a function to be called when the application context1599 ends. These functions are typically also called when the request1600 context is popped.16011602 Example::16031604 ctx = app.app_context()1605 ctx.push()1606 ...1607 ctx.pop()16081609 When ``ctx.pop()`` is executed in the above example, the teardown1610 functions are called just before the app context moves from the1611 stack of active contexts. This becomes relevant if you are using1612 such constructs in tests.16131614 Since a request context typically also manages an application1615 context it would also be called when you pop a request context.16161617 When a teardown function was called because of an unhandled exception1618 it will be passed an error object. If an :meth:`errorhandler` is1619 registered, it will handle the exception and the teardown will not1620 receive it.16211622 The return values of teardown functions are ignored.16231624 .. versionadded:: 0.91625 """1626 self.teardown_appcontext_funcs.append(f)1627 return f16281629 @setupmethod1630 def context_processor(self, f):1631 """Registers a template context processor function."""1632 self.template_context_processors[None].append(f)1633 return f16341635 @setupmethod1636 def shell_context_processor(self, f):1637 """Registers a shell context processor function.16381639 .. versionadded:: 0.111640 """1641 self.shell_context_processors.append(f)1642 return f16431644 @setupmethod1645 def url_value_preprocessor(self, f):1646 """Register a URL value preprocessor function for all view1647 functions in the application. These functions will be called before the1648 :meth:`before_request` functions.16491650 The function can modify the values captured from the matched url before1651 they are passed to the view. For example, this can be used to pop a1652 common language code value and place it in ``g`` rather than pass it to1653 every view.16541655 The function is passed the endpoint name and values dict. The return1656 value is ignored.1657 """1658 self.url_value_preprocessors.setdefault(None, []).append(f)1659 return f16601661 @setupmethod1662 def url_defaults(self, f):1663 """Callback function for URL defaults for all view functions of the1664 application. It's called with the endpoint and values and should1665 update the values passed in place.1666 """1667 self.url_default_functions.setdefault(None, []).append(f)1668 return f16691670 def _find_error_handler(self, e):1671 """Return a registered error handler for an exception in this order:1672 blueprint handler for a specific code, app handler for a specific code,1673 blueprint handler for an exception class, app handler for an exception1674 class, or ``None`` if a suitable handler is not found.1675 """1676 exc_class, code = self._get_exc_class_and_code(type(e))16771678 for name, c in (1679 (request.blueprint, code),1680 (None, code),1681 (request.blueprint, None),1682 (None, None),1683 ):1684 handler_map = self.error_handler_spec.setdefault(name, {}).get(c)16851686 if not handler_map:1687 continue16881689 for cls in exc_class.__mro__:1690 handler = handler_map.get(cls)16911692 if handler is not None:1693 return handler16941695 def handle_http_exception(self, e):1696 """Handles an HTTP exception. By default this will invoke the1697 registered error handlers and fall back to returning the1698 exception as response.16991700 .. versionchanged:: 1.0.31701 ``RoutingException``, used internally for actions such as1702 slash redirects during routing, is not passed to error1703 handlers.17041705 .. versionchanged:: 1.01706 Exceptions are looked up by code *and* by MRO, so1707 ``HTTPExcpetion`` subclasses can be handled with a catch-all1708 handler for the base ``HTTPException``.17091710 .. versionadded:: 0.31711 """1712 # Proxy exceptions don't have error codes. We want to always return1713 # those unchanged as errors1714 if e.code is None:1715 return e17161717 # RoutingExceptions are used internally to trigger routing1718 # actions, such as slash redirects raising RequestRedirect. They1719 # are not raised or handled in user code.1720 if isinstance(e, RoutingException):1721 return e17221723 handler = self._find_error_handler(e)1724 if handler is None:1725 return e1726 return handler(e)17271728 def trap_http_exception(self, e):1729 """Checks if an HTTP exception should be trapped or not. By default1730 this will return ``False`` for all exceptions except for a bad request1731 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It1732 also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.17331734 This is called for all HTTP exceptions raised by a view function.1735 If it returns ``True`` for any exception the error handler for this1736 exception is not called and it shows up as regular exception in the1737 traceback. This is helpful for debugging implicitly raised HTTP1738 exceptions.17391740 .. versionchanged:: 1.01741 Bad request errors are not trapped by default in debug mode.17421743 .. versionadded:: 0.81744 """1745 if self.config["TRAP_HTTP_EXCEPTIONS"]:1746 return True17471748 trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]17491750 # if unset, trap key errors in debug mode1751 if (1752 trap_bad_request is None1753 and self.debug1754 and isinstance(e, BadRequestKeyError)1755 ):1756 return True17571758 if trap_bad_request:1759 return isinstance(e, BadRequest)17601761 return False17621763 def handle_user_exception(self, e):1764 """This method is called whenever an exception occurs that1765 should be handled. A special case is :class:`~werkzeug1766 .exceptions.HTTPException` which is forwarded to the1767 :meth:`handle_http_exception` method. This function will either1768 return a response value or reraise the exception with the same1769 traceback.17701771 .. versionchanged:: 1.01772 Key errors raised from request data like ``form`` show the1773 bad key in debug mode rather than a generic bad request1774 message.17751776 .. versionadded:: 0.71777 """1778 exc_type, exc_value, tb = sys.exc_info()1779 assert exc_value is e1780 # ensure not to trash sys.exc_info() at that point in case someone1781 # wants the traceback preserved in handle_http_exception. Of course1782 # we cannot prevent users from trashing it themselves in a custom1783 # trap_http_exception method so that's their fault then.17841785 if isinstance(e, BadRequestKeyError):1786 if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]:1787 # Werkzeug < 0.15 doesn't add the KeyError to the 4001788 # message, add it in manually.1789 description = e.get_description()17901791 if e.args[0] not in description:1792 e.description = "KeyError: '{}'".format(*e.args)1793 else:1794 # Werkzeug >= 0.15 does add it, remove it in production1795 e.args = ()17961797 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1798 return self.handle_http_exception(e)17991800 handler = self._find_error_handler(e)18011802 if handler is None:1803 reraise(exc_type, exc_value, tb)1804 return handler(e)18051806 def handle_exception(self, e):1807 """Default exception handling that kicks in when an exception1808 occurs that is not caught. In debug mode the exception will1809 be re-raised immediately, otherwise it is logged and the handler1810 for a 500 internal server error is used. If no such handler1811 exists, a default 500 internal server error message is displayed.18121813 .. versionadded:: 0.31814 """1815 exc_type, exc_value, tb = sys.exc_info()1816 got_request_exception.send(self, exception=e)18171818 if self.propagate_exceptions:1819 # if we want to repropagate the exception, we can attempt to1820 # raise it with the whole traceback in case we can do that1821 # (the function was actually called from the except part)1822 # otherwise, we just raise the error again1823 if exc_value is e:1824 reraise(exc_type, exc_value, tb)1825 else:1826 raise e18271828 self.log_exception((exc_type, exc_value, tb))1829 handler = self._find_error_handler(InternalServerError())1830 if handler is None:1831 return InternalServerError()1832 return self.finalize_request(handler(e), from_error_handler=True)18331834 def log_exception(self, exc_info):1835 """Logs an exception. This is called by :meth:`handle_exception`1836 if debugging is disabled and right before the handler is called.1837 The default implementation logs the exception as error on the1838 :attr:`logger`.18391840 .. versionadded:: 0.81841 """1842 self.logger.error(1843 "Exception on %s [%s]" % (request.path, request.method), exc_info=exc_info1844 )18451846 def raise_routing_exception(self, request):1847 """Exceptions that are recording during routing are reraised with1848 this method. During debug we are not reraising redirect requests1849 for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising1850 a different error instead to help debug situations.18511852 :internal:1853 """1854 if (1855 not self.debug1856 or not isinstance(request.routing_exception, RequestRedirect)1857 or request.method in ("GET", "HEAD", "OPTIONS")1858 ):1859 raise request.routing_exception18601861 from .debughelpers import FormDataRoutingRedirect18621863 raise FormDataRoutingRedirect(request)18641865 def dispatch_request(self):1866 """Does the request dispatching. Matches the URL and returns the1867 return value of the view or error handler. This does not have to1868 be a response object. In order to convert the return value to a1869 proper response object, call :func:`make_response`.18701871 .. versionchanged:: 0.71872 This no longer does the exception handling, this code was1873 moved to the new :meth:`full_dispatch_request`.1874 """1875 req = _request_ctx_stack.top.request1876 if req.routing_exception is not None:1877 self.raise_routing_exception(req)1878 rule = req.url_rule1879 # if we provide automatic options for this URL and the1880 # request came with the OPTIONS method, reply automatically1881 if (1882 getattr(rule, "provide_automatic_options", False)1883 and req.method == "OPTIONS"1884 ):1885 return self.make_default_options_response()1886 # otherwise dispatch to the handler for that endpoint1887 return self.view_functions[rule.endpoint](**req.view_args)18881889 def full_dispatch_request(self):1890 """Dispatches the request and on top of that performs request1891 pre and postprocessing as well as HTTP exception catching and1892 error handling.18931894 .. versionadded:: 0.71895 """1896 self.try_trigger_before_first_request_functions()1897 try:1898 request_started.send(self)1899 rv = self.preprocess_request()1900 if rv is None:1901 rv = self.dispatch_request()1902 except Exception as e:1903 rv = self.handle_user_exception(e)1904 return self.finalize_request(rv)19051906 def finalize_request(self, rv, from_error_handler=False):1907 """Given the return value from a view function this finalizes1908 the request by converting it into a response and invoking the1909 postprocessing functions. This is invoked for both normal1910 request dispatching as well as error handlers.19111912 Because this means that it might be called as a result of a1913 failure a special safe mode is available which can be enabled1914 with the `from_error_handler` flag. If enabled, failures in1915 response processing will be logged and otherwise ignored.19161917 :internal:1918 """1919 response = self.make_response(rv)1920 try:1921 response = self.process_response(response)1922 request_finished.send(self, response=response)1923 except Exception:1924 if not from_error_handler:1925 raise1926 self.logger.exception(1927 "Request finalizing failed with an " "error while handling an error"1928 )1929 return response19301931 def try_trigger_before_first_request_functions(self):1932 """Called before each request and will ensure that it triggers1933 the :attr:`before_first_request_funcs` and only exactly once per1934 application instance (which means process usually).19351936 :internal:1937 """1938 if self._got_first_request:1939 return1940 with self._before_request_lock:1941 if self._got_first_request:1942 return1943 for func in self.before_first_request_funcs:1944 func()1945 self._got_first_request = True19461947 def make_default_options_response(self):1948 """This method is called to create the default ``OPTIONS`` response.1949 This can be changed through subclassing to change the default1950 behavior of ``OPTIONS`` responses.19511952 .. versionadded:: 0.71953 """1954 adapter = _request_ctx_stack.top.url_adapter1955 if hasattr(adapter, "allowed_methods"):1956 methods = adapter.allowed_methods()1957 else:1958 # fallback for Werkzeug < 0.71959 methods = []1960 try:1961 adapter.match(method="--")1962 except MethodNotAllowed as e:1963 methods = e.valid_methods1964 except HTTPException:1965 pass1966 rv = self.response_class()1967 rv.allow.update(methods)1968 return rv19691970 def should_ignore_error(self, error):1971 """This is called to figure out if an error should be ignored1972 or not as far as the teardown system is concerned. If this1973 function returns ``True`` then the teardown handlers will not be1974 passed the error.19751976 .. versionadded:: 0.101977 """1978 return False19791980 def make_response(self, rv):1981 """Convert the return value from a view function to an instance of1982 :attr:`response_class`.19831984 :param rv: the return value from the view function. The view function1985 must return a response. Returning ``None``, or the view ending1986 without returning, is not allowed. The following types are allowed1987 for ``view_rv``:19881989 ``str`` (``unicode`` in Python 2)1990 A response object is created with the string encoded to UTF-81991 as the body.19921993 ``bytes`` (``str`` in Python 2)1994 A response object is created with the bytes as the body.19951996 ``dict``1997 A dictionary that will be jsonify'd before being returned.19981999 ``tuple``2000 Either ``(body, status, headers)``, ``(body, status)``, or2001 ``(body, headers)``, where ``body`` is any of the other types2002 allowed here, ``status`` is a string or an integer, and2003 ``headers`` is a dictionary or a list of ``(key, value)``2004 tuples. If ``body`` is a :attr:`response_class` instance,2005 ``status`` overwrites the exiting value and ``headers`` are2006 extended.20072008 :attr:`response_class`2009 The object is returned unchanged.20102011 other :class:`~werkzeug.wrappers.Response` class2012 The object is coerced to :attr:`response_class`.20132014 :func:`callable`2015 The function is called as a WSGI application. The result is2016 used to create a response object.20172018 .. versionchanged:: 0.92019 Previously a tuple was interpreted as the arguments for the2020 response object.2021 """20222023 status = headers = None20242025 # unpack tuple returns2026 if isinstance(rv, tuple):2027 len_rv = len(rv)20282029 # a 3-tuple is unpacked directly2030 if len_rv == 3:2031 rv, status, headers = rv2032 # decide if a 2-tuple has status or headers2033 elif len_rv == 2:2034 if isinstance(rv[1], (Headers, dict, tuple, list)):2035 rv, headers = rv2036 else:2037 rv, status = rv2038 # other sized tuples are not allowed2039 else:2040 raise TypeError(2041 "The view function did not return a valid response tuple."2042 " The tuple must have the form (body, status, headers),"2043 " (body, status), or (body, headers)."2044 )20452046 # the body must not be None2047 if rv is None:2048 raise TypeError(2049 "The view function did not return a valid response. The"2050 " function either returned None or ended without a return"2051 " statement."2052 )20532054 # make sure the body is an instance of the response class2055 if not isinstance(rv, self.response_class):2056 if isinstance(rv, (text_type, bytes, bytearray)):2057 # let the response class set the status and headers instead of2058 # waiting to do it manually, so that the class can handle any2059 # special logic2060 rv = self.response_class(rv, status=status, headers=headers)2061 status = headers = None2062 elif isinstance(rv, dict):2063 rv = jsonify(rv)2064 elif isinstance(rv, BaseResponse) or callable(rv):2065 # evaluate a WSGI callable, or coerce a different response2066 # class to the correct type2067 try:2068 rv = self.response_class.force_type(rv, request.environ)2069 except TypeError as e:2070 new_error = TypeError(2071 "{e}\nThe view function did not return a valid"2072 " response. The return type must be a string, dict, tuple,"2073 " Response instance, or WSGI callable, but it was a"2074 " {rv.__class__.__name__}.".format(e=e, rv=rv)2075 )2076 reraise(TypeError, new_error, sys.exc_info()[2])2077 else:2078 raise TypeError(2079 "The view function did not return a valid"2080 " response. The return type must be a string, dict, tuple,"2081 " Response instance, or WSGI callable, but it was a"2082 " {rv.__class__.__name__}.".format(rv=rv)2083 )20842085 # prefer the status if it was provided2086 if status is not None:2087 if isinstance(status, (text_type, bytes, bytearray)):2088 rv.status = status2089 else:2090 rv.status_code = status20912092 # extend existing headers with provided headers2093 if headers:2094 rv.headers.extend(headers)20952096 return rv20972098 def create_url_adapter(self, request):2099 """Creates a URL adapter for the given request. The URL adapter2100 is created at a point where the request context is not yet set2101 up so the request is passed explicitly.21022103 .. versionadded:: 0.621042105 .. versionchanged:: 0.92106 This can now also be called without a request object when the2107 URL adapter is created for the application context.21082109 .. versionchanged:: 1.02110 :data:`SERVER_NAME` no longer implicitly enables subdomain2111 matching. Use :attr:`subdomain_matching` instead.2112 """2113 if request is not None:2114 # If subdomain matching is disabled (the default), use the2115 # default subdomain in all cases. This should be the default2116 # in Werkzeug but it currently does not have that feature.2117 subdomain = (2118 (self.url_map.default_subdomain or None)2119 if not self.subdomain_matching2120 else None2121 )2122 return self.url_map.bind_to_environ(2123 request.environ,2124 server_name=self.config["SERVER_NAME"],2125 subdomain=subdomain,2126 )2127 # We need at the very least the server name to be set for this2128 # to work.2129 if self.config["SERVER_NAME"] is not None:2130 return self.url_map.bind(2131 self.config["SERVER_NAME"],2132 script_name=self.config["APPLICATION_ROOT"],2133 url_scheme=self.config["PREFERRED_URL_SCHEME"],2134 )21352136 def inject_url_defaults(self, endpoint, values):2137 """Injects the URL defaults for the given endpoint directly into2138 the values dictionary passed. This is used internally and2139 automatically called on URL building.21402141 .. versionadded:: 0.72142 """2143 funcs = self.url_default_functions.get(None, ())2144 if "." in endpoint:2145 bp = endpoint.rsplit(".", 1)[0]2146 funcs = chain(funcs, self.url_default_functions.get(bp, ()))2147 for func in funcs:2148 func(endpoint, values)21492150 def handle_url_build_error(self, error, endpoint, values):2151 """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.2152 """2153 exc_type, exc_value, tb = sys.exc_info()2154 for handler in self.url_build_error_handlers:2155 try:2156 rv = handler(error, endpoint, values)2157 if rv is not None:2158 return rv2159 except BuildError as e:2160 # make error available outside except block (py3)2161 error = e21622163 # At this point we want to reraise the exception. If the error is2164 # still the same one we can reraise it with the original traceback,2165 # otherwise we raise it from here.2166 if error is exc_value:2167 reraise(exc_type, exc_value, tb)2168 raise error21692170 def preprocess_request(self):2171 """Called before the request is dispatched. Calls2172 :attr:`url_value_preprocessors` registered with the app and the2173 current blueprint (if any). Then calls :attr:`before_request_funcs`2174 registered with the app and the blueprint.21752176 If any :meth:`before_request` handler returns a non-None value, the2177 value is handled as if it was the return value from the view, and2178 further request handling is stopped.2179 """21802181 bp = _request_ctx_stack.top.request.blueprint21822183 funcs = self.url_value_preprocessors.get(None, ())2184 if bp is not None and bp in self.url_value_preprocessors:2185 funcs = chain(funcs, self.url_value_preprocessors[bp])2186 for func in funcs:2187 func(request.endpoint, request.view_args)21882189 funcs = self.before_request_funcs.get(None, ())2190 if bp is not None and bp in self.before_request_funcs:2191 funcs = chain(funcs, self.before_request_funcs[bp])2192 for func in funcs:2193 rv = func()2194 if rv is not None:2195 return rv21962197 def process_response(self, response):2198 """Can be overridden in order to modify the response object2199 before it's sent to the WSGI server. By default this will2200 call all the :meth:`after_request` decorated functions.22012202 .. versionchanged:: 0.52203 As of Flask 0.5 the functions registered for after request2204 execution are called in reverse order of registration.22052206 :param response: a :attr:`response_class` object.2207 :return: a new response object or the same, has to be an2208 instance of :attr:`response_class`.2209 """2210 ctx = _request_ctx_stack.top2211 bp = ctx.request.blueprint2212 funcs = ctx._after_request_functions2213 if bp is not None and bp in self.after_request_funcs:2214 funcs = chain(funcs, reversed(self.after_request_funcs[bp]))2215 if None in self.after_request_funcs:2216 funcs = chain(funcs, reversed(self.after_request_funcs[None]))2217 for handler in funcs:2218 response = handler(response)2219 if not self.session_interface.is_null_session(ctx.session):2220 self.session_interface.save_session(self, ctx.session, response)2221 return response22222223 def do_teardown_request(self, exc=_sentinel):2224 """Called after the request is dispatched and the response is2225 returned, right before the request context is popped.22262227 This calls all functions decorated with2228 :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`2229 if a blueprint handled the request. Finally, the2230 :data:`request_tearing_down` signal is sent.22312232 This is called by2233 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2234 which may be delayed during testing to maintain access to2235 resources.22362237 :param exc: An unhandled exception raised while dispatching the2238 request. Detected from the current exception information if2239 not passed. Passed to each teardown function.22402241 .. versionchanged:: 0.92242 Added the ``exc`` argument.2243 """2244 if exc is _sentinel:2245 exc = sys.exc_info()[1]2246 funcs = reversed(self.teardown_request_funcs.get(None, ()))2247 bp = _request_ctx_stack.top.request.blueprint2248 if bp is not None and bp in self.teardown_request_funcs:2249 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))2250 for func in funcs:2251 func(exc)2252 request_tearing_down.send(self, exc=exc)22532254 def do_teardown_appcontext(self, exc=_sentinel):2255 """Called right before the application context is popped.22562257 When handling a request, the application context is popped2258 after the request context. See :meth:`do_teardown_request`.22592260 This calls all functions decorated with2261 :meth:`teardown_appcontext`. Then the2262 :data:`appcontext_tearing_down` signal is sent.22632264 This is called by2265 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.22662267 .. versionadded:: 0.92268 """2269 if exc is _sentinel:2270 exc = sys.exc_info()[1]2271 for func in reversed(self.teardown_appcontext_funcs):2272 func(exc)2273 appcontext_tearing_down.send(self, exc=exc)22742275 def app_context(self):2276 """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``2277 block to push the context, which will make :data:`current_app`2278 point at this application.22792280 An application context is automatically pushed by2281 :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`2282 when handling a request, and when running a CLI command. Use2283 this to manually create a context outside of these situations.22842285 ::22862287 with app.app_context():2288 init_db()22892290 See :doc:`/appcontext`.22912292 .. versionadded:: 0.92293 """2294 return AppContext(self)22952296 def request_context(self, environ):2297 """Create a :class:`~flask.ctx.RequestContext` representing a2298 WSGI environment. Use a ``with`` block to push the context,2299 which will make :data:`request` point at this request.23002301 See :doc:`/reqcontext`.23022303 Typically you should not call this from your own code. A request2304 context is automatically pushed by the :meth:`wsgi_app` when2305 handling a request. Use :meth:`test_request_context` to create2306 an environment and context instead of this method.23072308 :param environ: a WSGI environment2309 """2310 return RequestContext(self, environ)23112312 def test_request_context(self, *args, **kwargs):2313 """Create a :class:`~flask.ctx.RequestContext` for a WSGI2314 environment created from the given values. This is mostly useful2315 during testing, where you may want to run a function that uses2316 request data without dispatching a full request.23172318 See :doc:`/reqcontext`.23192320 Use a ``with`` block to push the context, which will make2321 :data:`request` point at the request for the created2322 environment. ::23232324 with test_request_context(...):2325 generate_report()23262327 When using the shell, it may be easier to push and pop the2328 context manually to avoid indentation. ::23292330 ctx = app.test_request_context(...)2331 ctx.push()2332 ...2333 ctx.pop()23342335 Takes the same arguments as Werkzeug's2336 :class:`~werkzeug.test.EnvironBuilder`, with some defaults from2337 the application. See the linked Werkzeug docs for most of the2338 available arguments. Flask-specific behavior is listed here.23392340 :param path: URL path being requested.2341 :param base_url: Base URL where the app is being served, which2342 ``path`` is relative to. If not given, built from2343 :data:`PREFERRED_URL_SCHEME`, ``subdomain``,2344 :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.2345 :param subdomain: Subdomain name to append to2346 :data:`SERVER_NAME`.2347 :param url_scheme: Scheme to use instead of2348 :data:`PREFERRED_URL_SCHEME`.2349 :param data: The request body, either as a string or a dict of2350 form keys and values.2351 :param json: If given, this is serialized as JSON and passed as2352 ``data``. Also defaults ``content_type`` to2353 ``application/json``.2354 :param args: other positional arguments passed to2355 :class:`~werkzeug.test.EnvironBuilder`.2356 :param kwargs: other keyword arguments passed to2357 :class:`~werkzeug.test.EnvironBuilder`.2358 """2359 from flask.testing import EnvironBuilder23602361 builder = EnvironBuilder(self, *args, **kwargs)23622363 try:2364 return self.request_context(builder.get_environ())2365 finally:2366 builder.close()23672368 def wsgi_app(self, environ, start_response):2369 """The actual WSGI application. This is not implemented in2370 :meth:`__call__` so that middlewares can be applied without2371 losing a reference to the app object. Instead of doing this::23722373 app = MyMiddleware(app)23742375 It's a better idea to do this instead::23762377 app.wsgi_app = MyMiddleware(app.wsgi_app)23782379 Then you still have the original application object around and2380 can continue to call methods on it.23812382 .. versionchanged:: 0.72383 Teardown events for the request and app contexts are called2384 even if an unhandled error occurs. Other events may not be2385 called depending on when an error occurs during dispatch.2386 See :ref:`callbacks-and-errors`.23872388 :param environ: A WSGI environment.2389 :param start_response: A callable accepting a status code,2390 a list of headers, and an optional exception context to2391 start the response.2392 """2393 ctx = self.request_context(environ)2394 error = None2395 try:2396 try:2397 ctx.push()2398 response = self.full_dispatch_request()2399 except Exception as e:2400 error = e2401 response = self.handle_exception(e)2402 except: # noqa: B0012403 error = sys.exc_info()[1]2404 raise2405 return response(environ, start_response)2406 finally:2407 if self.should_ignore_error(error):2408 error = None2409 ctx.auto_pop(error)24102411 def __call__(self, environ, start_response):2412 """The WSGI server calls the Flask application object as the2413 WSGI application. This calls :meth:`wsgi_app` which can be2414 wrapped to applying middleware."""2415 return self.wsgi_app(environ, start_response)24162417 def __repr__(self):2418 return "<%s %r>" % (self.__class__.__name__, self.name)
added:src/flask/blueprints.py+530 added
1# -*- coding: utf-8 -*-2"""3 flask.blueprints4 ~~~~~~~~~~~~~~~~56 Blueprints are the recommended way to implement larger or more7 pluggable applications in Flask 0.7 and later.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""12from functools import update_wrapper1314from .helpers import _PackageBoundObject, _endpoint_from_view_func1516# a singleton sentinel value for parameter defaults17_sentinel = object()181920class BlueprintSetupState(object):21 """Temporary holder object for registering a blueprint with the22 application. An instance of this class is created by the23 :meth:`~flask.Blueprint.make_setup_state` method and later passed24 to all register callback functions.25 """2627 def __init__(self, blueprint, app, options, first_registration):28 #: a reference to the current application29 self.app = app3031 #: a reference to the blueprint that created this setup state.32 self.blueprint = blueprint3334 #: a dictionary with all options that were passed to the35 #: :meth:`~flask.Flask.register_blueprint` method.36 self.options = options3738 #: as blueprints can be registered multiple times with the39 #: application and not everything wants to be registered40 #: multiple times on it, this attribute can be used to figure41 #: out if the blueprint was registered in the past already.42 self.first_registration = first_registration4344 subdomain = self.options.get("subdomain")45 if subdomain is None:46 subdomain = self.blueprint.subdomain4748 #: The subdomain that the blueprint should be active for, ``None``49 #: otherwise.50 self.subdomain = subdomain5152 url_prefix = self.options.get("url_prefix")53 if url_prefix is None:54 url_prefix = self.blueprint.url_prefix55 #: The prefix that should be used for all URLs defined on the56 #: blueprint.57 self.url_prefix = url_prefix5859 #: A dictionary with URL defaults that is added to each and every60 #: URL that was defined with the blueprint.61 self.url_defaults = dict(self.blueprint.url_values_defaults)62 self.url_defaults.update(self.options.get("url_defaults", ()))6364 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):65 """A helper method to register a rule (and optionally a view function)66 to the application. The endpoint is automatically prefixed with the67 blueprint's name.68 """69 if self.url_prefix is not None:70 if rule:71 rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))72 else:73 rule = self.url_prefix74 options.setdefault("subdomain", self.subdomain)75 if endpoint is None:76 endpoint = _endpoint_from_view_func(view_func)77 defaults = self.url_defaults78 if "defaults" in options:79 defaults = dict(defaults, **options.pop("defaults"))80 self.app.add_url_rule(81 rule,82 "%s.%s" % (self.blueprint.name, endpoint),83 view_func,84 defaults=defaults,85 **options86 )878889class Blueprint(_PackageBoundObject):90 """Represents a blueprint. A blueprint is an object that records91 functions that will be called with the92 :class:`~flask.blueprints.BlueprintSetupState` later to register functions93 or other things on the main application. See :ref:`blueprints` for more94 information.9596 .. versionchanged:: 1.1.097 Blueprints have a ``cli`` group to register nested CLI commands.98 The ``cli_group`` parameter controls the name of the group under99 the ``flask`` command.100101 .. versionadded:: 0.7102 """103104 warn_on_modifications = False105 _got_registered_once = False106107 #: Blueprint local JSON decoder class to use.108 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.109 json_encoder = None110 #: Blueprint local JSON decoder class to use.111 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.112 json_decoder = None113114 # TODO remove the next three attrs when Sphinx :inherited-members: works115 # https://github.com/sphinx-doc/sphinx/issues/741116117 #: The name of the package or module that this app belongs to. Do not118 #: change this once it is set by the constructor.119 import_name = None120121 #: Location of the template files to be added to the template lookup.122 #: ``None`` if templates should not be added.123 template_folder = None124125 #: Absolute path to the package on the filesystem. Used to look up126 #: resources contained in the package.127 root_path = None128129 def __init__(130 self,131 name,132 import_name,133 static_folder=None,134 static_url_path=None,135 template_folder=None,136 url_prefix=None,137 subdomain=None,138 url_defaults=None,139 root_path=None,140 cli_group=_sentinel,141 ):142 _PackageBoundObject.__init__(143 self, import_name, template_folder, root_path=root_path144 )145 self.name = name146 self.url_prefix = url_prefix147 self.subdomain = subdomain148 self.static_folder = static_folder149 self.static_url_path = static_url_path150 self.deferred_functions = []151 if url_defaults is None:152 url_defaults = {}153 self.url_values_defaults = url_defaults154 self.cli_group = cli_group155156 def record(self, func):157 """Registers a function that is called when the blueprint is158 registered on the application. This function is called with the159 state as argument as returned by the :meth:`make_setup_state`160 method.161 """162 if self._got_registered_once and self.warn_on_modifications:163 from warnings import warn164165 warn(166 Warning(167 "The blueprint was already registered once "168 "but is getting modified now. These changes "169 "will not show up."170 )171 )172 self.deferred_functions.append(func)173174 def record_once(self, func):175 """Works like :meth:`record` but wraps the function in another176 function that will ensure the function is only called once. If the177 blueprint is registered a second time on the application, the178 function passed is not called.179 """180181 def wrapper(state):182 if state.first_registration:183 func(state)184185 return self.record(update_wrapper(wrapper, func))186187 def make_setup_state(self, app, options, first_registration=False):188 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`189 object that is later passed to the register callback functions.190 Subclasses can override this to return a subclass of the setup state.191 """192 return BlueprintSetupState(self, app, options, first_registration)193194 def register(self, app, options, first_registration=False):195 """Called by :meth:`Flask.register_blueprint` to register all views196 and callbacks registered on the blueprint with the application. Creates197 a :class:`.BlueprintSetupState` and calls each :meth:`record` callback198 with it.199200 :param app: The application this blueprint is being registered with.201 :param options: Keyword arguments forwarded from202 :meth:`~Flask.register_blueprint`.203 :param first_registration: Whether this is the first time this204 blueprint has been registered on the application.205 """206 self._got_registered_once = True207 state = self.make_setup_state(app, options, first_registration)208209 if self.has_static_folder:210 state.add_url_rule(211 self.static_url_path + "/<path:filename>",212 view_func=self.send_static_file,213 endpoint="static",214 )215216 for deferred in self.deferred_functions:217 deferred(state)218219 cli_resolved_group = options.get("cli_group", self.cli_group)220221 if not self.cli.commands:222 return223224 if cli_resolved_group is None:225 app.cli.commands.update(self.cli.commands)226 elif cli_resolved_group is _sentinel:227 self.cli.name = self.name228 app.cli.add_command(self.cli)229 else:230 self.cli.name = cli_resolved_group231 app.cli.add_command(self.cli)232233 def route(self, rule, **options):234 """Like :meth:`Flask.route` but for a blueprint. The endpoint for the235 :func:`url_for` function is prefixed with the name of the blueprint.236 """237238 def decorator(f):239 endpoint = options.pop("endpoint", f.__name__)240 self.add_url_rule(rule, endpoint, f, **options)241 return f242243 return decorator244245 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):246 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for247 the :func:`url_for` function is prefixed with the name of the blueprint.248 """249 if endpoint:250 assert "." not in endpoint, "Blueprint endpoints should not contain dots"251 if view_func and hasattr(view_func, "__name__"):252 assert (253 "." not in view_func.__name__254 ), "Blueprint view function name should not contain dots"255 self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))256257 def endpoint(self, endpoint):258 """Like :meth:`Flask.endpoint` but for a blueprint. This does not259 prefix the endpoint with the blueprint name, this has to be done260 explicitly by the user of this method. If the endpoint is prefixed261 with a `.` it will be registered to the current blueprint, otherwise262 it's an application independent endpoint.263 """264265 def decorator(f):266 def register_endpoint(state):267 state.app.view_functions[endpoint] = f268269 self.record_once(register_endpoint)270 return f271272 return decorator273274 def app_template_filter(self, name=None):275 """Register a custom template filter, available application wide. Like276 :meth:`Flask.template_filter` but for a blueprint.277278 :param name: the optional name of the filter, otherwise the279 function name will be used.280 """281282 def decorator(f):283 self.add_app_template_filter(f, name=name)284 return f285286 return decorator287288 def add_app_template_filter(self, f, name=None):289 """Register a custom template filter, available application wide. Like290 :meth:`Flask.add_template_filter` but for a blueprint. Works exactly291 like the :meth:`app_template_filter` decorator.292293 :param name: the optional name of the filter, otherwise the294 function name will be used.295 """296297 def register_template(state):298 state.app.jinja_env.filters[name or f.__name__] = f299300 self.record_once(register_template)301302 def app_template_test(self, name=None):303 """Register a custom template test, available application wide. Like304 :meth:`Flask.template_test` but for a blueprint.305306 .. versionadded:: 0.10307308 :param name: the optional name of the test, otherwise the309 function name will be used.310 """311312 def decorator(f):313 self.add_app_template_test(f, name=name)314 return f315316 return decorator317318 def add_app_template_test(self, f, name=None):319 """Register a custom template test, available application wide. Like320 :meth:`Flask.add_template_test` but for a blueprint. Works exactly321 like the :meth:`app_template_test` decorator.322323 .. versionadded:: 0.10324325 :param name: the optional name of the test, otherwise the326 function name will be used.327 """328329 def register_template(state):330 state.app.jinja_env.tests[name or f.__name__] = f331332 self.record_once(register_template)333334 def app_template_global(self, name=None):335 """Register a custom template global, available application wide. Like336 :meth:`Flask.template_global` but for a blueprint.337338 .. versionadded:: 0.10339340 :param name: the optional name of the global, otherwise the341 function name will be used.342 """343344 def decorator(f):345 self.add_app_template_global(f, name=name)346 return f347348 return decorator349350 def add_app_template_global(self, f, name=None):351 """Register a custom template global, available application wide. Like352 :meth:`Flask.add_template_global` but for a blueprint. Works exactly353 like the :meth:`app_template_global` decorator.354355 .. versionadded:: 0.10356357 :param name: the optional name of the global, otherwise the358 function name will be used.359 """360361 def register_template(state):362 state.app.jinja_env.globals[name or f.__name__] = f363364 self.record_once(register_template)365366 def before_request(self, f):367 """Like :meth:`Flask.before_request` but for a blueprint. This function368 is only executed before each request that is handled by a function of369 that blueprint.370 """371 self.record_once(372 lambda s: s.app.before_request_funcs.setdefault(self.name, []).append(f)373 )374 return f375376 def before_app_request(self, f):377 """Like :meth:`Flask.before_request`. Such a function is executed378 before each request, even if outside of a blueprint.379 """380 self.record_once(381 lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)382 )383 return f384385 def before_app_first_request(self, f):386 """Like :meth:`Flask.before_first_request`. Such a function is387 executed before the first request to the application.388 """389 self.record_once(lambda s: s.app.before_first_request_funcs.append(f))390 return f391392 def after_request(self, f):393 """Like :meth:`Flask.after_request` but for a blueprint. This function394 is only executed after each request that is handled by a function of395 that blueprint.396 """397 self.record_once(398 lambda s: s.app.after_request_funcs.setdefault(self.name, []).append(f)399 )400 return f401402 def after_app_request(self, f):403 """Like :meth:`Flask.after_request` but for a blueprint. Such a function404 is executed after each request, even if outside of the blueprint.405 """406 self.record_once(407 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)408 )409 return f410411 def teardown_request(self, f):412 """Like :meth:`Flask.teardown_request` but for a blueprint. This413 function is only executed when tearing down requests handled by a414 function of that blueprint. Teardown request functions are executed415 when the request context is popped, even when no actual request was416 performed.417 """418 self.record_once(419 lambda s: s.app.teardown_request_funcs.setdefault(self.name, []).append(f)420 )421 return f422423 def teardown_app_request(self, f):424 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a425 function is executed when tearing down each request, even if outside of426 the blueprint.427 """428 self.record_once(429 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)430 )431 return f432433 def context_processor(self, f):434 """Like :meth:`Flask.context_processor` but for a blueprint. This435 function is only executed for requests handled by a blueprint.436 """437 self.record_once(438 lambda s: s.app.template_context_processors.setdefault(439 self.name, []440 ).append(f)441 )442 return f443444 def app_context_processor(self, f):445 """Like :meth:`Flask.context_processor` but for a blueprint. Such a446 function is executed each request, even if outside of the blueprint.447 """448 self.record_once(449 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)450 )451 return f452453 def app_errorhandler(self, code):454 """Like :meth:`Flask.errorhandler` but for a blueprint. This455 handler is used for all requests, even if outside of the blueprint.456 """457458 def decorator(f):459 self.record_once(lambda s: s.app.errorhandler(code)(f))460 return f461462 return decorator463464 def url_value_preprocessor(self, f):465 """Registers a function as URL value preprocessor for this466 blueprint. It's called before the view functions are called and467 can modify the url values provided.468 """469 self.record_once(470 lambda s: s.app.url_value_preprocessors.setdefault(self.name, []).append(f)471 )472 return f473474 def url_defaults(self, f):475 """Callback function for URL defaults for this blueprint. It's called476 with the endpoint and values and should update the values passed477 in place.478 """479 self.record_once(480 lambda s: s.app.url_default_functions.setdefault(self.name, []).append(f)481 )482 return f483484 def app_url_value_preprocessor(self, f):485 """Same as :meth:`url_value_preprocessor` but application wide.486 """487 self.record_once(488 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)489 )490 return f491492 def app_url_defaults(self, f):493 """Same as :meth:`url_defaults` but application wide.494 """495 self.record_once(496 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)497 )498 return f499500 def errorhandler(self, code_or_exception):501 """Registers an error handler that becomes active for this blueprint502 only. Please be aware that routing does not happen local to a503 blueprint so an error handler for 404 usually is not handled by504 a blueprint unless it is caused inside a view function. Another505 special case is the 500 internal server error which is always looked506 up from the application.507508 Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator509 of the :class:`~flask.Flask` object.510 """511512 def decorator(f):513 self.record_once(514 lambda s: s.app._register_error_handler(self.name, code_or_exception, f)515 )516 return f517518 return decorator519520 def register_error_handler(self, code_or_exception, f):521 """Non-decorator version of the :meth:`errorhandler` error attach522 function, akin to the :meth:`~flask.Flask.register_error_handler`523 application-wide function of the :class:`~flask.Flask` object but524 for error handlers limited to this blueprint.525526 .. versionadded:: 0.11527 """528 self.record_once(529 lambda s: s.app._register_error_handler(self.name, code_or_exception, f)530 )
added:src/flask/cli.py+963 added
1# -*- coding: utf-8 -*-2"""3 flask.cli4 ~~~~~~~~~56 A simple command line application to run flask apps.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import print_function1314import ast15import inspect16import os17import platform18import re19import sys20import traceback21from functools import update_wrapper22from operator import attrgetter23from threading import Lock, Thread2425import click26from werkzeug.utils import import_string2728from . import __version__29from ._compat import getargspec, itervalues, reraise, text_type30from .globals import current_app31from .helpers import get_debug_flag, get_env, get_load_dotenv3233try:34 import dotenv35except ImportError:36 dotenv = None3738try:39 import ssl40except ImportError:41 ssl = None424344class NoAppException(click.UsageError):45 """Raised if an application cannot be found or loaded."""464748def find_best_app(script_info, module):49 """Given a module instance this tries to find the best possible50 application in the module or raises an exception.51 """52 from . import Flask5354 # Search for the most common names first.55 for attr_name in ("app", "application"):56 app = getattr(module, attr_name, None)5758 if isinstance(app, Flask):59 return app6061 # Otherwise find the only object that is a Flask instance.62 matches = [v for v in itervalues(module.__dict__) if isinstance(v, Flask)]6364 if len(matches) == 1:65 return matches[0]66 elif len(matches) > 1:67 raise NoAppException(68 'Detected multiple Flask applications in module "{module}". Use '69 '"FLASK_APP={module}:name" to specify the correct '70 "one.".format(module=module.__name__)71 )7273 # Search for app factory functions.74 for attr_name in ("create_app", "make_app"):75 app_factory = getattr(module, attr_name, None)7677 if inspect.isfunction(app_factory):78 try:79 app = call_factory(script_info, app_factory)8081 if isinstance(app, Flask):82 return app83 except TypeError:84 if not _called_with_wrong_args(app_factory):85 raise86 raise NoAppException(87 'Detected factory "{factory}" in module "{module}", but '88 "could not call it without arguments. Use "89 "\"FLASK_APP='{module}:{factory}(args)'\" to specify "90 "arguments.".format(factory=attr_name, module=module.__name__)91 )9293 raise NoAppException(94 'Failed to find Flask application or factory in module "{module}". '95 'Use "FLASK_APP={module}:name to specify one.'.format(module=module.__name__)96 )979899def call_factory(script_info, app_factory, arguments=()):100 """Takes an app factory, a ``script_info` object and optionally a tuple101 of arguments. Checks for the existence of a script_info argument and calls102 the app_factory depending on that and the arguments provided.103 """104 args_spec = getargspec(app_factory)105 arg_names = args_spec.args106 arg_defaults = args_spec.defaults107108 if "script_info" in arg_names:109 return app_factory(*arguments, script_info=script_info)110 elif arguments:111 return app_factory(*arguments)112 elif not arguments and len(arg_names) == 1 and arg_defaults is None:113 return app_factory(script_info)114115 return app_factory()116117118def _called_with_wrong_args(factory):119 """Check whether calling a function raised a ``TypeError`` because120 the call failed or because something in the factory raised the121 error.122123 :param factory: the factory function that was called124 :return: true if the call failed125 """126 tb = sys.exc_info()[2]127128 try:129 while tb is not None:130 if tb.tb_frame.f_code is factory.__code__:131 # in the factory, it was called successfully132 return False133134 tb = tb.tb_next135136 # didn't reach the factory137 return True138 finally:139 # explicitly delete tb as it is circular referenced140 # https://docs.python.org/2/library/sys.html#sys.exc_info141 del tb142143144def find_app_by_string(script_info, module, app_name):145 """Checks if the given string is a variable name or a function. If it is a146 function, it checks for specified arguments and whether it takes a147 ``script_info`` argument and calls the function with the appropriate148 arguments.149 """150 from flask import Flask151152 match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name)153154 if not match:155 raise NoAppException(156 '"{name}" is not a valid variable name or function '157 "expression.".format(name=app_name)158 )159160 name, args = match.groups()161162 try:163 attr = getattr(module, name)164 except AttributeError as e:165 raise NoAppException(e.args[0])166167 if inspect.isfunction(attr):168 if args:169 try:170 args = ast.literal_eval("({args},)".format(args=args))171 except (ValueError, SyntaxError) as e:172 raise NoAppException(173 "Could not parse the arguments in "174 '"{app_name}".'.format(e=e, app_name=app_name)175 )176 else:177 args = ()178179 try:180 app = call_factory(script_info, attr, args)181 except TypeError as e:182 if not _called_with_wrong_args(attr):183 raise184185 raise NoAppException(186 '{e}\nThe factory "{app_name}" in module "{module}" could not '187 "be called with the specified arguments.".format(188 e=e, app_name=app_name, module=module.__name__189 )190 )191 else:192 app = attr193194 if isinstance(app, Flask):195 return app196197 raise NoAppException(198 "A valid Flask application was not obtained from "199 '"{module}:{app_name}".'.format(module=module.__name__, app_name=app_name)200 )201202203def prepare_import(path):204 """Given a filename this will try to calculate the python path, add it205 to the search path and return the actual module name that is expected.206 """207 path = os.path.realpath(path)208209 fname, ext = os.path.splitext(path)210 if ext == ".py":211 path = fname212213 if os.path.basename(path) == "__init__":214 path = os.path.dirname(path)215216 module_name = []217218 # move up until outside package structure (no __init__.py)219 while True:220 path, name = os.path.split(path)221 module_name.append(name)222223 if not os.path.exists(os.path.join(path, "__init__.py")):224 break225226 if sys.path[0] != path:227 sys.path.insert(0, path)228229 return ".".join(module_name[::-1])230231232def locate_app(script_info, module_name, app_name, raise_if_not_found=True):233 __traceback_hide__ = True # noqa: F841234235 try:236 __import__(module_name)237 except ImportError:238 # Reraise the ImportError if it occurred within the imported module.239 # Determine this by checking whether the trace has a depth > 1.240 if sys.exc_info()[-1].tb_next:241 raise NoAppException(242 'While importing "{name}", an ImportError was raised:'243 "\n\n{tb}".format(name=module_name, tb=traceback.format_exc())244 )245 elif raise_if_not_found:246 raise NoAppException('Could not import "{name}".'.format(name=module_name))247 else:248 return249250 module = sys.modules[module_name]251252 if app_name is None:253 return find_best_app(script_info, module)254 else:255 return find_app_by_string(script_info, module, app_name)256257258def get_version(ctx, param, value):259 if not value or ctx.resilient_parsing:260 return261 import werkzeug262263 message = "Python %(python)s\n" "Flask %(flask)s\n" "Werkzeug %(werkzeug)s"264 click.echo(265 message266 % {267 "python": platform.python_version(),268 "flask": __version__,269 "werkzeug": werkzeug.__version__,270 },271 color=ctx.color,272 )273 ctx.exit()274275276version_option = click.Option(277 ["--version"],278 help="Show the flask version",279 expose_value=False,280 callback=get_version,281 is_flag=True,282 is_eager=True,283)284285286class DispatchingApp(object):287 """Special application that dispatches to a Flask application which288 is imported by name in a background thread. If an error happens289 it is recorded and shown as part of the WSGI handling which in case290 of the Werkzeug debugger means that it shows up in the browser.291 """292293 def __init__(self, loader, use_eager_loading=False):294 self.loader = loader295 self._app = None296 self._lock = Lock()297 self._bg_loading_exc_info = None298 if use_eager_loading:299 self._load_unlocked()300 else:301 self._load_in_background()302303 def _load_in_background(self):304 def _load_app():305 __traceback_hide__ = True # noqa: F841306 with self._lock:307 try:308 self._load_unlocked()309 except Exception:310 self._bg_loading_exc_info = sys.exc_info()311312 t = Thread(target=_load_app, args=())313 t.start()314315 def _flush_bg_loading_exception(self):316 __traceback_hide__ = True # noqa: F841317 exc_info = self._bg_loading_exc_info318 if exc_info is not None:319 self._bg_loading_exc_info = None320 reraise(*exc_info)321322 def _load_unlocked(self):323 __traceback_hide__ = True # noqa: F841324 self._app = rv = self.loader()325 self._bg_loading_exc_info = None326 return rv327328 def __call__(self, environ, start_response):329 __traceback_hide__ = True # noqa: F841330 if self._app is not None:331 return self._app(environ, start_response)332 self._flush_bg_loading_exception()333 with self._lock:334 if self._app is not None:335 rv = self._app336 else:337 rv = self._load_unlocked()338 return rv(environ, start_response)339340341class ScriptInfo(object):342 """Helper object to deal with Flask applications. This is usually not343 necessary to interface with as it's used internally in the dispatching344 to click. In future versions of Flask this object will most likely play345 a bigger role. Typically it's created automatically by the346 :class:`FlaskGroup` but you can also manually create it and pass it347 onwards as click object.348 """349350 def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):351 #: Optionally the import path for the Flask application.352 self.app_import_path = app_import_path or os.environ.get("FLASK_APP")353 #: Optionally a function that is passed the script info to create354 #: the instance of the application.355 self.create_app = create_app356 #: A dictionary with arbitrary data that can be associated with357 #: this script info.358 self.data = {}359 self.set_debug_flag = set_debug_flag360 self._loaded_app = None361362 def load_app(self):363 """Loads the Flask app (if not yet loaded) and returns it. Calling364 this multiple times will just result in the already loaded app to365 be returned.366 """367 __traceback_hide__ = True # noqa: F841368369 if self._loaded_app is not None:370 return self._loaded_app371372 app = None373374 if self.create_app is not None:375 app = call_factory(self, self.create_app)376 else:377 if self.app_import_path:378 path, name = (379 re.split(r":(?![\\/])", self.app_import_path, 1) + [None]380 )[:2]381 import_name = prepare_import(path)382 app = locate_app(self, import_name, name)383 else:384 for path in ("wsgi.py", "app.py"):385 import_name = prepare_import(path)386 app = locate_app(self, import_name, None, raise_if_not_found=False)387388 if app:389 break390391 if not app:392 raise NoAppException(393 "Could not locate a Flask application. You did not provide "394 'the "FLASK_APP" environment variable, and a "wsgi.py" or '395 '"app.py" module was not found in the current directory.'396 )397398 if self.set_debug_flag:399 # Update the app's debug flag through the descriptor so that400 # other values repopulate as well.401 app.debug = get_debug_flag()402403 self._loaded_app = app404 return app405406407pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)408409410def with_appcontext(f):411 """Wraps a callback so that it's guaranteed to be executed with the412 script's application context. If callbacks are registered directly413 to the ``app.cli`` object then they are wrapped with this function414 by default unless it's disabled.415 """416417 @click.pass_context418 def decorator(__ctx, *args, **kwargs):419 with __ctx.ensure_object(ScriptInfo).load_app().app_context():420 return __ctx.invoke(f, *args, **kwargs)421422 return update_wrapper(decorator, f)423424425class AppGroup(click.Group):426 """This works similar to a regular click :class:`~click.Group` but it427 changes the behavior of the :meth:`command` decorator so that it428 automatically wraps the functions in :func:`with_appcontext`.429430 Not to be confused with :class:`FlaskGroup`.431 """432433 def command(self, *args, **kwargs):434 """This works exactly like the method of the same name on a regular435 :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`436 unless it's disabled by passing ``with_appcontext=False``.437 """438 wrap_for_ctx = kwargs.pop("with_appcontext", True)439440 def decorator(f):441 if wrap_for_ctx:442 f = with_appcontext(f)443 return click.Group.command(self, *args, **kwargs)(f)444445 return decorator446447 def group(self, *args, **kwargs):448 """This works exactly like the method of the same name on a regular449 :class:`click.Group` but it defaults the group class to450 :class:`AppGroup`.451 """452 kwargs.setdefault("cls", AppGroup)453 return click.Group.group(self, *args, **kwargs)454455456class FlaskGroup(AppGroup):457 """Special subclass of the :class:`AppGroup` group that supports458 loading more commands from the configured Flask app. Normally a459 developer does not have to interface with this class but there are460 some very advanced use cases for which it makes sense to create an461 instance of this.462463 For information as of why this is useful see :ref:`custom-scripts`.464465 :param add_default_commands: if this is True then the default run and466 shell commands wil be added.467 :param add_version_option: adds the ``--version`` option.468 :param create_app: an optional callback that is passed the script info and469 returns the loaded app.470 :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`471 files to set environment variables. Will also change the working472 directory to the directory containing the first file found.473 :param set_debug_flag: Set the app's debug flag based on the active474 environment475476 .. versionchanged:: 1.0477 If installed, python-dotenv will be used to load environment variables478 from :file:`.env` and :file:`.flaskenv` files.479 """480481 def __init__(482 self,483 add_default_commands=True,484 create_app=None,485 add_version_option=True,486 load_dotenv=True,487 set_debug_flag=True,488 **extra489 ):490 params = list(extra.pop("params", None) or ())491492 if add_version_option:493 params.append(version_option)494495 AppGroup.__init__(self, params=params, **extra)496 self.create_app = create_app497 self.load_dotenv = load_dotenv498 self.set_debug_flag = set_debug_flag499500 if add_default_commands:501 self.add_command(run_command)502 self.add_command(shell_command)503 self.add_command(routes_command)504505 self._loaded_plugin_commands = False506507 def _load_plugin_commands(self):508 if self._loaded_plugin_commands:509 return510 try:511 import pkg_resources512 except ImportError:513 self._loaded_plugin_commands = True514 return515516 for ep in pkg_resources.iter_entry_points("flask.commands"):517 self.add_command(ep.load(), ep.name)518 self._loaded_plugin_commands = True519520 def get_command(self, ctx, name):521 self._load_plugin_commands()522523 # We load built-in commands first as these should always be the524 # same no matter what the app does. If the app does want to525 # override this it needs to make a custom instance of this group526 # and not attach the default commands.527 #528 # This also means that the script stays functional in case the529 # application completely fails.530 rv = AppGroup.get_command(self, ctx, name)531 if rv is not None:532 return rv533534 info = ctx.ensure_object(ScriptInfo)535 try:536 rv = info.load_app().cli.get_command(ctx, name)537 if rv is not None:538 return rv539 except NoAppException:540 pass541542 def list_commands(self, ctx):543 self._load_plugin_commands()544545 # The commands available is the list of both the application (if546 # available) plus the builtin commands.547 rv = set(click.Group.list_commands(self, ctx))548 info = ctx.ensure_object(ScriptInfo)549 try:550 rv.update(info.load_app().cli.list_commands(ctx))551 except Exception:552 # Here we intentionally swallow all exceptions as we don't553 # want the help page to break if the app does not exist.554 # If someone attempts to use the command we try to create555 # the app again and this will give us the error.556 # However, we will not do so silently because that would confuse557 # users.558 traceback.print_exc()559 return sorted(rv)560561 def main(self, *args, **kwargs):562 # Set a global flag that indicates that we were invoked from the563 # command line interface. This is detected by Flask.run to make the564 # call into a no-op. This is necessary to avoid ugly errors when the565 # script that is loaded here also attempts to start a server.566 os.environ["FLASK_RUN_FROM_CLI"] = "true"567568 if get_load_dotenv(self.load_dotenv):569 load_dotenv()570571 obj = kwargs.get("obj")572573 if obj is None:574 obj = ScriptInfo(575 create_app=self.create_app, set_debug_flag=self.set_debug_flag576 )577578 kwargs["obj"] = obj579 kwargs.setdefault("auto_envvar_prefix", "FLASK")580 return super(FlaskGroup, self).main(*args, **kwargs)581582583def _path_is_ancestor(path, other):584 """Take ``other`` and remove the length of ``path`` from it. Then join it585 to ``path``. If it is the original value, ``path`` is an ancestor of586 ``other``."""587 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other588589590def load_dotenv(path=None):591 """Load "dotenv" files in order of precedence to set environment variables.592593 If an env var is already set it is not overwritten, so earlier files in the594 list are preferred over later files.595596 Changes the current working directory to the location of the first file597 found, with the assumption that it is in the top level project directory598 and will be where the Python path should import local packages from.599600 This is a no-op if `python-dotenv`_ is not installed.601602 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme603604 :param path: Load the file at this location instead of searching.605 :return: ``True`` if a file was loaded.606607 .. versionchanged:: 1.1.0608 Returns ``False`` when python-dotenv is not installed, or when609 the given path isn't a file.610611 .. versionadded:: 1.0612 """613 if dotenv is None:614 if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):615 click.secho(616 " * Tip: There are .env or .flaskenv files present."617 ' Do "pip install python-dotenv" to use them.',618 fg="yellow",619 )620621 return False622623 # if the given path specifies the actual file then return True,624 # else False625 if path is not None:626 if os.path.isfile(path):627 return dotenv.load_dotenv(path)628629 return False630631 new_dir = None632633 for name in (".env", ".flaskenv"):634 path = dotenv.find_dotenv(name, usecwd=True)635636 if not path:637 continue638639 if new_dir is None:640 new_dir = os.path.dirname(path)641642 dotenv.load_dotenv(path)643644 if new_dir and os.getcwd() != new_dir:645 os.chdir(new_dir)646647 return new_dir is not None # at least one file was located and loaded648649650def show_server_banner(env, debug, app_import_path, eager_loading):651 """Show extra startup messages the first time the server is run,652 ignoring the reloader.653 """654 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":655 return656657 if app_import_path is not None:658 message = ' * Serving Flask app "{0}"'.format(app_import_path)659660 if not eager_loading:661 message += " (lazy loading)"662663 click.echo(message)664665 click.echo(" * Environment: {0}".format(env))666667 if env == "production":668 click.secho(669 " WARNING: This is a development server. "670 "Do not use it in a production deployment.",671 fg="red",672 )673 click.secho(" Use a production WSGI server instead.", dim=True)674675 if debug is not None:676 click.echo(" * Debug mode: {0}".format("on" if debug else "off"))677678679class CertParamType(click.ParamType):680 """Click option type for the ``--cert`` option. Allows either an681 existing file, the string ``'adhoc'``, or an import for a682 :class:`~ssl.SSLContext` object.683 """684685 name = "path"686687 def __init__(self):688 self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)689690 def convert(self, value, param, ctx):691 if ssl is None:692 raise click.BadParameter(693 'Using "--cert" requires Python to be compiled with SSL support.',694 ctx,695 param,696 )697698 try:699 return self.path_type(value, param, ctx)700 except click.BadParameter:701 value = click.STRING(value, param, ctx).lower()702703 if value == "adhoc":704 try:705 import OpenSSL # noqa: F401706 except ImportError:707 raise click.BadParameter(708 "Using ad-hoc certificates requires pyOpenSSL.", ctx, param709 )710711 return value712713 obj = import_string(value, silent=True)714715 if sys.version_info < (2, 7, 9):716 if obj:717 return obj718 else:719 if isinstance(obj, ssl.SSLContext):720 return obj721722 raise723724725def _validate_key(ctx, param, value):726 """The ``--key`` option must be specified when ``--cert`` is a file.727 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.728 """729 cert = ctx.params.get("cert")730 is_adhoc = cert == "adhoc"731732 if sys.version_info < (2, 7, 9):733 is_context = cert and not isinstance(cert, (text_type, bytes))734 else:735 is_context = isinstance(cert, ssl.SSLContext)736737 if value is not None:738 if is_adhoc:739 raise click.BadParameter(740 'When "--cert" is "adhoc", "--key" is not used.', ctx, param741 )742743 if is_context:744 raise click.BadParameter(745 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param746 )747748 if not cert:749 raise click.BadParameter('"--cert" must also be specified.', ctx, param)750751 ctx.params["cert"] = cert, value752753 else:754 if cert and not (is_adhoc or is_context):755 raise click.BadParameter('Required when using "--cert".', ctx, param)756757 return value758759760class SeparatedPathType(click.Path):761 """Click option type that accepts a list of values separated by the762 OS's path separator (``:``, ``;`` on Windows). Each value is763 validated as a :class:`click.Path` type.764 """765766 def convert(self, value, param, ctx):767 items = self.split_envvar_value(value)768 super_convert = super(SeparatedPathType, self).convert769 return [super_convert(item, param, ctx) for item in items]770771772@click.command("run", short_help="Run a development server.")773@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")774@click.option("--port", "-p", default=5000, help="The port to bind to.")775@click.option(776 "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS."777)778@click.option(779 "--key",780 type=click.Path(exists=True, dir_okay=False, resolve_path=True),781 callback=_validate_key,782 expose_value=False,783 help="The key file to use when specifying a certificate.",784)785@click.option(786 "--reload/--no-reload",787 default=None,788 help="Enable or disable the reloader. By default the reloader "789 "is active if debug is enabled.",790)791@click.option(792 "--debugger/--no-debugger",793 default=None,794 help="Enable or disable the debugger. By default the debugger "795 "is active if debug is enabled.",796)797@click.option(798 "--eager-loading/--lazy-loader",799 default=None,800 help="Enable or disable eager loading. By default eager "801 "loading is enabled if the reloader is disabled.",802)803@click.option(804 "--with-threads/--without-threads",805 default=True,806 help="Enable or disable multithreading.",807)808@click.option(809 "--extra-files",810 default=None,811 type=SeparatedPathType(),812 help=(813 "Extra files that trigger a reload on change. Multiple paths"814 " are separated by '{}'.".format(os.path.pathsep)815 ),816)817@pass_script_info818def run_command(819 info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files820):821 """Run a local development server.822823 This server is for development purposes only. It does not provide824 the stability, security, or performance of production WSGI servers.825826 The reloader and debugger are enabled by default if827 FLASK_ENV=development or FLASK_DEBUG=1.828 """829 debug = get_debug_flag()830831 if reload is None:832 reload = debug833834 if debugger is None:835 debugger = debug836837 if eager_loading is None:838 eager_loading = not reload839840 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)841 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)842843 from werkzeug.serving import run_simple844845 run_simple(846 host,847 port,848 app,849 use_reloader=reload,850 use_debugger=debugger,851 threaded=with_threads,852 ssl_context=cert,853 extra_files=extra_files,854 )855856857@click.command("shell", short_help="Run a shell in the app context.")858@with_appcontext859def shell_command():860 """Run an interactive Python shell in the context of a given861 Flask application. The application will populate the default862 namespace of this shell according to it's configuration.863864 This is useful for executing small snippets of management code865 without having to manually configure the application.866 """867 import code868 from flask.globals import _app_ctx_stack869870 app = _app_ctx_stack.top.app871 banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % (872 sys.version,873 sys.platform,874 app.import_name,875 app.env,876 app.instance_path,877 )878 ctx = {}879880 # Support the regular Python interpreter startup script if someone881 # is using it.882 startup = os.environ.get("PYTHONSTARTUP")883 if startup and os.path.isfile(startup):884 with open(startup, "r") as f:885 eval(compile(f.read(), startup, "exec"), ctx)886887 ctx.update(app.make_shell_context())888889 code.interact(banner=banner, local=ctx)890891892@click.command("routes", short_help="Show the routes for the app.")893@click.option(894 "--sort",895 "-s",896 type=click.Choice(("endpoint", "methods", "rule", "match")),897 default="endpoint",898 help=(899 'Method to sort routes by. "match" is the order that Flask will match '900 "routes when dispatching a request."901 ),902)903@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")904@with_appcontext905def routes_command(sort, all_methods):906 """Show all registered routes with endpoints and methods."""907908 rules = list(current_app.url_map.iter_rules())909 if not rules:910 click.echo("No routes were registered.")911 return912913 ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))914915 if sort in ("endpoint", "rule"):916 rules = sorted(rules, key=attrgetter(sort))917 elif sort == "methods":918 rules = sorted(rules, key=lambda rule: sorted(rule.methods))919920 rule_methods = [", ".join(sorted(rule.methods - ignored_methods)) for rule in rules]921922 headers = ("Endpoint", "Methods", "Rule")923 widths = (924 max(len(rule.endpoint) for rule in rules),925 max(len(methods) for methods in rule_methods),926 max(len(rule.rule) for rule in rules),927 )928 widths = [max(len(h), w) for h, w in zip(headers, widths)]929 row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)930931 click.echo(row.format(*headers).strip())932 click.echo(row.format(*("-" * width for width in widths)))933934 for rule, methods in zip(rules, rule_methods):935 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())936937938cli = FlaskGroup(939 help="""\940A general utility script for Flask applications.941942Provides commands from Flask, extensions, and the application. Loads the943application defined in the FLASK_APP environment variable, or from a wsgi.py944file. Setting the FLASK_ENV environment variable to 'development' will enable945debug mode.946947\b948 {prefix}{cmd} FLASK_APP=hello.py949 {prefix}{cmd} FLASK_ENV=development950 {prefix}flask run951""".format(952 cmd="export" if os.name == "posix" else "set",953 prefix="$ " if os.name == "posix" else "> ",954 )955)956957958def main(as_module=False):959 cli.main(prog_name="python -m flask" if as_module else None)960961962if __name__ == "__main__":963 main(as_module=True)
added:src/flask/config.py+268 added
1# -*- coding: utf-8 -*-2"""3 flask.config4 ~~~~~~~~~~~~56 Implements the configuration related objects.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import os13import types14import errno1516from werkzeug.utils import import_string17from ._compat import string_types, iteritems18from . import json192021class ConfigAttribute(object):22 """Makes an attribute forward to the config"""2324 def __init__(self, name, get_converter=None):25 self.__name__ = name26 self.get_converter = get_converter2728 def __get__(self, obj, type=None):29 if obj is None:30 return self31 rv = obj.config[self.__name__]32 if self.get_converter is not None:33 rv = self.get_converter(rv)34 return rv3536 def __set__(self, obj, value):37 obj.config[self.__name__] = value383940class Config(dict):41 """Works exactly like a dict but provides ways to fill it from files42 or special dictionaries. There are two common patterns to populate the43 config.4445 Either you can fill the config from a config file::4647 app.config.from_pyfile('yourconfig.cfg')4849 Or alternatively you can define the configuration options in the50 module that calls :meth:`from_object` or provide an import path to51 a module that should be loaded. It is also possible to tell it to52 use the same module and with that provide the configuration values53 just before the call::5455 DEBUG = True56 SECRET_KEY = 'development key'57 app.config.from_object(__name__)5859 In both cases (loading from any Python file or loading from modules),60 only uppercase keys are added to the config. This makes it possible to use61 lowercase values in the config file for temporary values that are not added62 to the config or to define the config keys in the same file that implements63 the application.6465 Probably the most interesting way to load configurations is from an66 environment variable pointing to a file::6768 app.config.from_envvar('YOURAPPLICATION_SETTINGS')6970 In this case before launching the application you have to set this71 environment variable to the file you want to use. On Linux and OS X72 use the export statement::7374 export YOURAPPLICATION_SETTINGS='/path/to/config/file'7576 On windows use `set` instead.7778 :param root_path: path to which files are read relative from. When the79 config object is created by the application, this is80 the application's :attr:`~flask.Flask.root_path`.81 :param defaults: an optional dictionary of default values82 """8384 def __init__(self, root_path, defaults=None):85 dict.__init__(self, defaults or {})86 self.root_path = root_path8788 def from_envvar(self, variable_name, silent=False):89 """Loads a configuration from an environment variable pointing to90 a configuration file. This is basically just a shortcut with nicer91 error messages for this line of code::9293 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])9495 :param variable_name: name of the environment variable96 :param silent: set to ``True`` if you want silent failure for missing97 files.98 :return: bool. ``True`` if able to load config, ``False`` otherwise.99 """100 rv = os.environ.get(variable_name)101 if not rv:102 if silent:103 return False104 raise RuntimeError(105 "The environment variable %r is not set "106 "and as such configuration could not be "107 "loaded. Set this variable and make it "108 "point to a configuration file" % variable_name109 )110 return self.from_pyfile(rv, silent=silent)111112 def from_pyfile(self, filename, silent=False):113 """Updates the values in the config from a Python file. This function114 behaves as if the file was imported as module with the115 :meth:`from_object` function.116117 :param filename: the filename of the config. This can either be an118 absolute filename or a filename relative to the119 root path.120 :param silent: set to ``True`` if you want silent failure for missing121 files.122123 .. versionadded:: 0.7124 `silent` parameter.125 """126 filename = os.path.join(self.root_path, filename)127 d = types.ModuleType("config")128 d.__file__ = filename129 try:130 with open(filename, mode="rb") as config_file:131 exec(compile(config_file.read(), filename, "exec"), d.__dict__)132 except IOError as e:133 if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):134 return False135 e.strerror = "Unable to load configuration file (%s)" % e.strerror136 raise137 self.from_object(d)138 return True139140 def from_object(self, obj):141 """Updates the values from the given object. An object can be of one142 of the following two types:143144 - a string: in this case the object with that name will be imported145 - an actual object reference: that object is used directly146147 Objects are usually either modules or classes. :meth:`from_object`148 loads only the uppercase attributes of the module/class. A ``dict``149 object will not work with :meth:`from_object` because the keys of a150 ``dict`` are not attributes of the ``dict`` class.151152 Example of module-based configuration::153154 app.config.from_object('yourapplication.default_config')155 from yourapplication import default_config156 app.config.from_object(default_config)157158 Nothing is done to the object before loading. If the object is a159 class and has ``@property`` attributes, it needs to be160 instantiated before being passed to this method.161162 You should not use this function to load the actual configuration but163 rather configuration defaults. The actual config should be loaded164 with :meth:`from_pyfile` and ideally from a location not within the165 package because the package might be installed system wide.166167 See :ref:`config-dev-prod` for an example of class-based configuration168 using :meth:`from_object`.169170 :param obj: an import name or object171 """172 if isinstance(obj, string_types):173 obj = import_string(obj)174 for key in dir(obj):175 if key.isupper():176 self[key] = getattr(obj, key)177178 def from_json(self, filename, silent=False):179 """Updates the values in the config from a JSON file. This function180 behaves as if the JSON object was a dictionary and passed to the181 :meth:`from_mapping` function.182183 :param filename: the filename of the JSON file. This can either be an184 absolute filename or a filename relative to the185 root path.186 :param silent: set to ``True`` if you want silent failure for missing187 files.188189 .. versionadded:: 0.11190 """191 filename = os.path.join(self.root_path, filename)192193 try:194 with open(filename) as json_file:195 obj = json.loads(json_file.read())196 except IOError as e:197 if silent and e.errno in (errno.ENOENT, errno.EISDIR):198 return False199 e.strerror = "Unable to load configuration file (%s)" % e.strerror200 raise201 return self.from_mapping(obj)202203 def from_mapping(self, *mapping, **kwargs):204 """Updates the config like :meth:`update` ignoring items with non-upper205 keys.206207 .. versionadded:: 0.11208 """209 mappings = []210 if len(mapping) == 1:211 if hasattr(mapping[0], "items"):212 mappings.append(mapping[0].items())213 else:214 mappings.append(mapping[0])215 elif len(mapping) > 1:216 raise TypeError(217 "expected at most 1 positional argument, got %d" % len(mapping)218 )219 mappings.append(kwargs.items())220 for mapping in mappings:221 for (key, value) in mapping:222 if key.isupper():223 self[key] = value224 return True225226 def get_namespace(self, namespace, lowercase=True, trim_namespace=True):227 """Returns a dictionary containing a subset of configuration options228 that match the specified namespace/prefix. Example usage::229230 app.config['IMAGE_STORE_TYPE'] = 'fs'231 app.config['IMAGE_STORE_PATH'] = '/var/app/images'232 app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'233 image_store_config = app.config.get_namespace('IMAGE_STORE_')234235 The resulting dictionary `image_store_config` would look like::236237 {238 'type': 'fs',239 'path': '/var/app/images',240 'base_url': 'http://img.website.com'241 }242243 This is often useful when configuration options map directly to244 keyword arguments in functions or class constructors.245246 :param namespace: a configuration namespace247 :param lowercase: a flag indicating if the keys of the resulting248 dictionary should be lowercase249 :param trim_namespace: a flag indicating if the keys of the resulting250 dictionary should not include the namespace251252 .. versionadded:: 0.11253 """254 rv = {}255 for k, v in iteritems(self):256 if not k.startswith(namespace):257 continue258 if trim_namespace:259 key = k[len(namespace) :]260 else:261 key = k262 if lowercase:263 key = key.lower()264 rv[key] = v265 return rv266267 def __repr__(self):268 return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))
added:src/flask/ctx.py+472 added
1# -*- coding: utf-8 -*-2"""3 flask.ctx4 ~~~~~~~~~56 Implements the objects required to keep the context.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import sys13from functools import update_wrapper1415from werkzeug.exceptions import HTTPException1617from .globals import _request_ctx_stack, _app_ctx_stack18from .signals import appcontext_pushed, appcontext_popped19from ._compat import BROKEN_PYPY_CTXMGR_EXIT, reraise202122# a singleton sentinel value for parameter defaults23_sentinel = object()242526class _AppCtxGlobals(object):27 """A plain object. Used as a namespace for storing data during an28 application context.2930 Creating an app context automatically creates this object, which is31 made available as the :data:`g` proxy.3233 .. describe:: 'key' in g3435 Check whether an attribute is present.3637 .. versionadded:: 0.103839 .. describe:: iter(g)4041 Return an iterator over the attribute names.4243 .. versionadded:: 0.1044 """4546 def get(self, name, default=None):47 """Get an attribute by name, or a default value. Like48 :meth:`dict.get`.4950 :param name: Name of attribute to get.51 :param default: Value to return if the attribute is not present.5253 .. versionadded:: 0.1054 """55 return self.__dict__.get(name, default)5657 def pop(self, name, default=_sentinel):58 """Get and remove an attribute by name. Like :meth:`dict.pop`.5960 :param name: Name of attribute to pop.61 :param default: Value to return if the attribute is not present,62 instead of raise a ``KeyError``.6364 .. versionadded:: 0.1165 """66 if default is _sentinel:67 return self.__dict__.pop(name)68 else:69 return self.__dict__.pop(name, default)7071 def setdefault(self, name, default=None):72 """Get the value of an attribute if it is present, otherwise73 set and return a default value. Like :meth:`dict.setdefault`.7475 :param name: Name of attribute to get.76 :param: default: Value to set and return if the attribute is not77 present.7879 .. versionadded:: 0.1180 """81 return self.__dict__.setdefault(name, default)8283 def __contains__(self, item):84 return item in self.__dict__8586 def __iter__(self):87 return iter(self.__dict__)8889 def __repr__(self):90 top = _app_ctx_stack.top91 if top is not None:92 return "<flask.g of %r>" % top.app.name93 return object.__repr__(self)949596def after_this_request(f):97 """Executes a function after this request. This is useful to modify98 response objects. The function is passed the response object and has99 to return the same or a new one.100101 Example::102103 @app.route('/')104 def index():105 @after_this_request106 def add_header(response):107 response.headers['X-Foo'] = 'Parachute'108 return response109 return 'Hello World!'110111 This is more useful if a function other than the view function wants to112 modify a response. For instance think of a decorator that wants to add113 some headers without converting the return value into a response object.114115 .. versionadded:: 0.9116 """117 _request_ctx_stack.top._after_request_functions.append(f)118 return f119120121def copy_current_request_context(f):122 """A helper function that decorates a function to retain the current123 request context. This is useful when working with greenlets. The moment124 the function is decorated a copy of the request context is created and125 then pushed when the function is called. The current session is also126 included in the copied request context.127128 Example::129130 import gevent131 from flask import copy_current_request_context132133 @app.route('/')134 def index():135 @copy_current_request_context136 def do_some_work():137 # do some work here, it can access flask.request or138 # flask.session like you would otherwise in the view function.139 ...140 gevent.spawn(do_some_work)141 return 'Regular response'142143 .. versionadded:: 0.10144 """145 top = _request_ctx_stack.top146 if top is None:147 raise RuntimeError(148 "This decorator can only be used at local scopes "149 "when a request context is on the stack. For instance within "150 "view functions."151 )152 reqctx = top.copy()153154 def wrapper(*args, **kwargs):155 with reqctx:156 return f(*args, **kwargs)157158 return update_wrapper(wrapper, f)159160161def has_request_context():162 """If you have code that wants to test if a request context is there or163 not this function can be used. For instance, you may want to take advantage164 of request information if the request object is available, but fail165 silently if it is unavailable.166167 ::168169 class User(db.Model):170171 def __init__(self, username, remote_addr=None):172 self.username = username173 if remote_addr is None and has_request_context():174 remote_addr = request.remote_addr175 self.remote_addr = remote_addr176177 Alternatively you can also just test any of the context bound objects178 (such as :class:`request` or :class:`g`) for truthness::179180 class User(db.Model):181182 def __init__(self, username, remote_addr=None):183 self.username = username184 if remote_addr is None and request:185 remote_addr = request.remote_addr186 self.remote_addr = remote_addr187188 .. versionadded:: 0.7189 """190 return _request_ctx_stack.top is not None191192193def has_app_context():194 """Works like :func:`has_request_context` but for the application195 context. You can also just do a boolean check on the196 :data:`current_app` object instead.197198 .. versionadded:: 0.9199 """200 return _app_ctx_stack.top is not None201202203class AppContext(object):204 """The application context binds an application object implicitly205 to the current thread or greenlet, similar to how the206 :class:`RequestContext` binds request information. The application207 context is also implicitly created if a request context is created208 but the application is not on top of the individual application209 context.210 """211212 def __init__(self, app):213 self.app = app214 self.url_adapter = app.create_url_adapter(None)215 self.g = app.app_ctx_globals_class()216217 # Like request context, app contexts can be pushed multiple times218 # but there a basic "refcount" is enough to track them.219 self._refcnt = 0220221 def push(self):222 """Binds the app context to the current context."""223 self._refcnt += 1224 if hasattr(sys, "exc_clear"):225 sys.exc_clear()226 _app_ctx_stack.push(self)227 appcontext_pushed.send(self.app)228229 def pop(self, exc=_sentinel):230 """Pops the app context."""231 try:232 self._refcnt -= 1233 if self._refcnt <= 0:234 if exc is _sentinel:235 exc = sys.exc_info()[1]236 self.app.do_teardown_appcontext(exc)237 finally:238 rv = _app_ctx_stack.pop()239 assert rv is self, "Popped wrong app context. (%r instead of %r)" % (rv, self)240 appcontext_popped.send(self.app)241242 def __enter__(self):243 self.push()244 return self245246 def __exit__(self, exc_type, exc_value, tb):247 self.pop(exc_value)248249 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:250 reraise(exc_type, exc_value, tb)251252253class RequestContext(object):254 """The request context contains all request relevant information. It is255 created at the beginning of the request and pushed to the256 `_request_ctx_stack` and removed at the end of it. It will create the257 URL adapter and request object for the WSGI environment provided.258259 Do not attempt to use this class directly, instead use260 :meth:`~flask.Flask.test_request_context` and261 :meth:`~flask.Flask.request_context` to create this object.262263 When the request context is popped, it will evaluate all the264 functions registered on the application for teardown execution265 (:meth:`~flask.Flask.teardown_request`).266267 The request context is automatically popped at the end of the request268 for you. In debug mode the request context is kept around if269 exceptions happen so that interactive debuggers have a chance to270 introspect the data. With 0.4 this can also be forced for requests271 that did not fail and outside of ``DEBUG`` mode. By setting272 ``'flask._preserve_context'`` to ``True`` on the WSGI environment the273 context will not pop itself at the end of the request. This is used by274 the :meth:`~flask.Flask.test_client` for example to implement the275 deferred cleanup functionality.276277 You might find this helpful for unittests where you need the278 information from the context local around for a little longer. Make279 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in280 that situation, otherwise your unittests will leak memory.281 """282283 def __init__(self, app, environ, request=None, session=None):284 self.app = app285 if request is None:286 request = app.request_class(environ)287 self.request = request288 self.url_adapter = None289 try:290 self.url_adapter = app.create_url_adapter(self.request)291 except HTTPException as e:292 self.request.routing_exception = e293 self.flashes = None294 self.session = session295296 # Request contexts can be pushed multiple times and interleaved with297 # other request contexts. Now only if the last level is popped we298 # get rid of them. Additionally if an application context is missing299 # one is created implicitly so for each level we add this information300 self._implicit_app_ctx_stack = []301302 # indicator if the context was preserved. Next time another context303 # is pushed the preserved context is popped.304 self.preserved = False305306 # remembers the exception for pop if there is one in case the context307 # preservation kicks in.308 self._preserved_exc = None309310 # Functions that should be executed after the request on the response311 # object. These will be called before the regular "after_request"312 # functions.313 self._after_request_functions = []314315 if self.url_adapter is not None:316 self.match_request()317318 @property319 def g(self):320 return _app_ctx_stack.top.g321322 @g.setter323 def g(self, value):324 _app_ctx_stack.top.g = value325326 def copy(self):327 """Creates a copy of this request context with the same request object.328 This can be used to move a request context to a different greenlet.329 Because the actual request object is the same this cannot be used to330 move a request context to a different thread unless access to the331 request object is locked.332333 .. versionadded:: 0.10334335 .. versionchanged:: 1.1336 The current session object is used instead of reloading the original337 data. This prevents `flask.session` pointing to an out-of-date object.338 """339 return self.__class__(340 self.app,341 environ=self.request.environ,342 request=self.request,343 session=self.session,344 )345346 def match_request(self):347 """Can be overridden by a subclass to hook into the matching348 of the request.349 """350 try:351 url_rule, self.request.view_args = self.url_adapter.match(return_rule=True)352 self.request.url_rule = url_rule353 except HTTPException as e:354 self.request.routing_exception = e355356 def push(self):357 """Binds the request context to the current context."""358 # If an exception occurs in debug mode or if context preservation is359 # activated under exception situations exactly one context stays360 # on the stack. The rationale is that you want to access that361 # information under debug situations. However if someone forgets to362 # pop that context again we want to make sure that on the next push363 # it's invalidated, otherwise we run at risk that something leaks364 # memory. This is usually only a problem in test suite since this365 # functionality is not active in production environments.366 top = _request_ctx_stack.top367 if top is not None and top.preserved:368 top.pop(top._preserved_exc)369370 # Before we push the request context we have to ensure that there371 # is an application context.372 app_ctx = _app_ctx_stack.top373 if app_ctx is None or app_ctx.app != self.app:374 app_ctx = self.app.app_context()375 app_ctx.push()376 self._implicit_app_ctx_stack.append(app_ctx)377 else:378 self._implicit_app_ctx_stack.append(None)379380 if hasattr(sys, "exc_clear"):381 sys.exc_clear()382383 _request_ctx_stack.push(self)384385 # Open the session at the moment that the request context is available.386 # This allows a custom open_session method to use the request context.387 # Only open a new session if this is the first time the request was388 # pushed, otherwise stream_with_context loses the session.389 if self.session is None:390 session_interface = self.app.session_interface391 self.session = session_interface.open_session(self.app, self.request)392393 if self.session is None:394 self.session = session_interface.make_null_session(self.app)395396 def pop(self, exc=_sentinel):397 """Pops the request context and unbinds it by doing that. This will398 also trigger the execution of functions registered by the399 :meth:`~flask.Flask.teardown_request` decorator.400401 .. versionchanged:: 0.9402 Added the `exc` argument.403 """404 app_ctx = self._implicit_app_ctx_stack.pop()405406 try:407 clear_request = False408 if not self._implicit_app_ctx_stack:409 self.preserved = False410 self._preserved_exc = None411 if exc is _sentinel:412 exc = sys.exc_info()[1]413 self.app.do_teardown_request(exc)414415 # If this interpreter supports clearing the exception information416 # we do that now. This will only go into effect on Python 2.x,417 # on 3.x it disappears automatically at the end of the exception418 # stack.419 if hasattr(sys, "exc_clear"):420 sys.exc_clear()421422 request_close = getattr(self.request, "close", None)423 if request_close is not None:424 request_close()425 clear_request = True426 finally:427 rv = _request_ctx_stack.pop()428429 # get rid of circular dependencies at the end of the request430 # so that we don't require the GC to be active.431 if clear_request:432 rv.request.environ["werkzeug.request"] = None433434 # Get rid of the app as well if necessary.435 if app_ctx is not None:436 app_ctx.pop(exc)437438 assert (439 rv is self440 ), "Popped wrong request context. " "(%r instead of %r)" % (rv, self)441442 def auto_pop(self, exc):443 if self.request.environ.get("flask._preserve_context") or (444 exc is not None and self.app.preserve_context_on_exception445 ):446 self.preserved = True447 self._preserved_exc = exc448 else:449 self.pop(exc)450451 def __enter__(self):452 self.push()453 return self454455 def __exit__(self, exc_type, exc_value, tb):456 # do not pop the request stack if we are in debug mode and an457 # exception happened. This will allow the debugger to still458 # access the request object in the interactive shell. Furthermore459 # the context can be force kept alive for the test client.460 # See flask.testing for how this works.461 self.auto_pop(exc_value)462463 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:464 reraise(exc_type, exc_value, tb)465466 def __repr__(self):467 return "<%s '%s' [%s] of %s>" % (468 self.__class__.__name__,469 self.request.url,470 self.request.method,471 self.app.name,472 )
added:src/flask/debughelpers.py+183 added
1# -*- coding: utf-8 -*-2"""3 flask.debughelpers4 ~~~~~~~~~~~~~~~~~~56 Various helpers to make the development experience better.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import os13from warnings import warn1415from ._compat import implements_to_string, text_type16from .app import Flask17from .blueprints import Blueprint18from .globals import _request_ctx_stack192021class UnexpectedUnicodeError(AssertionError, UnicodeError):22 """Raised in places where we want some better error reporting for23 unexpected unicode or binary data.24 """252627@implements_to_string28class DebugFilesKeyError(KeyError, AssertionError):29 """Raised from request.files during debugging. The idea is that it can30 provide a better error message than just a generic KeyError/BadRequest.31 """3233 def __init__(self, request, key):34 form_matches = request.form.getlist(key)35 buf = [36 'You tried to access the file "%s" in the request.files '37 "dictionary but it does not exist. The mimetype for the request "38 'is "%s" instead of "multipart/form-data" which means that no '39 "file contents were transmitted. To fix this error you should "40 'provide enctype="multipart/form-data" in your form.'41 % (key, request.mimetype)42 ]43 if form_matches:44 buf.append(45 "\n\nThe browser instead transmitted some file names. "46 "This was submitted: %s" % ", ".join('"%s"' % x for x in form_matches)47 )48 self.msg = "".join(buf)4950 def __str__(self):51 return self.msg525354class FormDataRoutingRedirect(AssertionError):55 """This exception is raised by Flask in debug mode if it detects a56 redirect caused by the routing system when the request method is not57 GET, HEAD or OPTIONS. Reasoning: form data will be dropped.58 """5960 def __init__(self, request):61 exc = request.routing_exception62 buf = [63 "A request was sent to this URL (%s) but a redirect was "64 'issued automatically by the routing system to "%s".'65 % (request.url, exc.new_url)66 ]6768 # In case just a slash was appended we can be extra helpful69 if request.base_url + "/" == exc.new_url.split("?")[0]:70 buf.append(71 " The URL was defined with a trailing slash so "72 "Flask will automatically redirect to the URL "73 "with the trailing slash if it was accessed "74 "without one."75 )7677 buf.append(78 " Make sure to directly send your %s-request to this URL "79 "since we can't make browsers or HTTP clients redirect "80 "with form data reliably or without user interaction." % request.method81 )82 buf.append("\n\nNote: this exception is only raised in debug mode")83 AssertionError.__init__(self, "".join(buf).encode("utf-8"))848586def attach_enctype_error_multidict(request):87 """Since Flask 0.8 we're monkeypatching the files object in case a88 request is detected that does not use multipart form data but the files89 object is accessed.90 """91 oldcls = request.files.__class__9293 class newcls(oldcls):94 def __getitem__(self, key):95 try:96 return oldcls.__getitem__(self, key)97 except KeyError:98 if key not in request.form:99 raise100 raise DebugFilesKeyError(request, key)101102 newcls.__name__ = oldcls.__name__103 newcls.__module__ = oldcls.__module__104 request.files.__class__ = newcls105106107def _dump_loader_info(loader):108 yield "class: %s.%s" % (type(loader).__module__, type(loader).__name__)109 for key, value in sorted(loader.__dict__.items()):110 if key.startswith("_"):111 continue112 if isinstance(value, (tuple, list)):113 if not all(isinstance(x, (str, text_type)) for x in value):114 continue115 yield "%s:" % key116 for item in value:117 yield " - %s" % item118 continue119 elif not isinstance(value, (str, text_type, int, float, bool)):120 continue121 yield "%s: %r" % (key, value)122123124def explain_template_loading_attempts(app, template, attempts):125 """This should help developers understand what failed"""126 info = ['Locating template "%s":' % template]127 total_found = 0128 blueprint = None129 reqctx = _request_ctx_stack.top130 if reqctx is not None and reqctx.request.blueprint is not None:131 blueprint = reqctx.request.blueprint132133 for idx, (loader, srcobj, triple) in enumerate(attempts):134 if isinstance(srcobj, Flask):135 src_info = 'application "%s"' % srcobj.import_name136 elif isinstance(srcobj, Blueprint):137 src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name)138 else:139 src_info = repr(srcobj)140141 info.append("% 5d: trying loader of %s" % (idx + 1, src_info))142143 for line in _dump_loader_info(loader):144 info.append(" %s" % line)145146 if triple is None:147 detail = "no match"148 else:149 detail = "found (%r)" % (triple[1] or "<string>")150 total_found += 1151 info.append(" -> %s" % detail)152153 seems_fishy = False154 if total_found == 0:155 info.append("Error: the template could not be found.")156 seems_fishy = True157 elif total_found > 1:158 info.append("Warning: multiple loaders returned a match for the template.")159 seems_fishy = True160161 if blueprint is not None and seems_fishy:162 info.append(163 " The template was looked up from an endpoint that "164 'belongs to the blueprint "%s".' % blueprint165 )166 info.append(" Maybe you did not place a template in the right folder?")167 info.append(" See http://flask.pocoo.org/docs/blueprints/#templates")168169 app.logger.info("\n".join(info))170171172def explain_ignored_app_run():173 if os.environ.get("WERKZEUG_RUN_MAIN") != "true":174 warn(175 Warning(176 "Silently ignoring app.run() because the "177 "application is run from the flask command line "178 "executable. Consider putting app.run() behind an "179 'if __name__ == "__main__" guard to silence this '180 "warning."181 ),182 stacklevel=3,183 )
added:src/flask/globals.py+61 added
1# -*- coding: utf-8 -*-2"""3 flask.globals4 ~~~~~~~~~~~~~56 Defines all the global objects that are proxies to the current7 active context.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213from functools import partial14from werkzeug.local import LocalStack, LocalProxy151617_request_ctx_err_msg = """\18Working outside of request context.1920This typically means that you attempted to use functionality that needed21an active HTTP request. Consult the documentation on testing for22information about how to avoid this problem.\23"""24_app_ctx_err_msg = """\25Working outside of application context.2627This typically means that you attempted to use functionality that needed28to interface with the current application object in some way. To solve29this, set up an application context with app.app_context(). See the30documentation for more information.\31"""323334def _lookup_req_object(name):35 top = _request_ctx_stack.top36 if top is None:37 raise RuntimeError(_request_ctx_err_msg)38 return getattr(top, name)394041def _lookup_app_object(name):42 top = _app_ctx_stack.top43 if top is None:44 raise RuntimeError(_app_ctx_err_msg)45 return getattr(top, name)464748def _find_app():49 top = _app_ctx_stack.top50 if top is None:51 raise RuntimeError(_app_ctx_err_msg)52 return top.app535455# context locals56_request_ctx_stack = LocalStack()57_app_ctx_stack = LocalStack()58current_app = LocalProxy(_find_app)59request = LocalProxy(partial(_lookup_req_object, "request"))60session = LocalProxy(partial(_lookup_req_object, "session"))61g = LocalProxy(partial(_lookup_app_object, "g"))
added:src/flask/helpers.py+1115 added
1# -*- coding: utf-8 -*-2"""3 flask.helpers4 ~~~~~~~~~~~~~56 Implements various helpers.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""11import io12import os13import socket14import sys15import pkgutil16import posixpath17import mimetypes18from time import time19from zlib import adler3220from threading import RLock21import unicodedata22from werkzeug.routing import BuildError23from functools import update_wrapper2425from werkzeug.urls import url_quote26from werkzeug.datastructures import Headers27from werkzeug.exceptions import BadRequest, NotFound, RequestedRangeNotSatisfiable2829from werkzeug.wsgi import wrap_file30from jinja2 import FileSystemLoader3132from .signals import message_flashed33from .globals import session, _request_ctx_stack, _app_ctx_stack, current_app, request34from ._compat import string_types, text_type, PY2, fspath3536# sentinel37_missing = object()383940# what separators does this operating system provide that are not a slash?41# this is used by the send_from_directory function to ensure that nobody is42# able to access files from outside the filesystem.43_os_alt_seps = list(44 sep for sep in [os.path.sep, os.path.altsep] if sep not in (None, "/")45)464748def get_env():49 """Get the environment the app is running in, indicated by the50 :envvar:`FLASK_ENV` environment variable. The default is51 ``'production'``.52 """53 return os.environ.get("FLASK_ENV") or "production"545556def get_debug_flag():57 """Get whether debug mode should be enabled for the app, indicated58 by the :envvar:`FLASK_DEBUG` environment variable. The default is59 ``True`` if :func:`.get_env` returns ``'development'``, or ``False``60 otherwise.61 """62 val = os.environ.get("FLASK_DEBUG")6364 if not val:65 return get_env() == "development"6667 return val.lower() not in ("0", "false", "no")686970def get_load_dotenv(default=True):71 """Get whether the user has disabled loading dotenv files by setting72 :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the73 files.7475 :param default: What to return if the env var isn't set.76 """77 val = os.environ.get("FLASK_SKIP_DOTENV")7879 if not val:80 return default8182 return val.lower() in ("0", "false", "no")838485def _endpoint_from_view_func(view_func):86 """Internal helper that returns the default endpoint for a given87 function. This always is the function name.88 """89 assert view_func is not None, "expected view func if endpoint " "is not provided."90 return view_func.__name__919293def stream_with_context(generator_or_function):94 """Request contexts disappear when the response is started on the server.95 This is done for efficiency reasons and to make it less likely to encounter96 memory leaks with badly written WSGI middlewares. The downside is that if97 you are using streamed responses, the generator cannot access request bound98 information any more.99100 This function however can help you keep the context around for longer::101102 from flask import stream_with_context, request, Response103104 @app.route('/stream')105 def streamed_response():106 @stream_with_context107 def generate():108 yield 'Hello '109 yield request.args['name']110 yield '!'111 return Response(generate())112113 Alternatively it can also be used around a specific generator::114115 from flask import stream_with_context, request, Response116117 @app.route('/stream')118 def streamed_response():119 def generate():120 yield 'Hello '121 yield request.args['name']122 yield '!'123 return Response(stream_with_context(generate()))124125 .. versionadded:: 0.9126 """127 try:128 gen = iter(generator_or_function)129 except TypeError:130131 def decorator(*args, **kwargs):132 gen = generator_or_function(*args, **kwargs)133 return stream_with_context(gen)134135 return update_wrapper(decorator, generator_or_function)136137 def generator():138 ctx = _request_ctx_stack.top139 if ctx is None:140 raise RuntimeError(141 "Attempted to stream with context but "142 "there was no context in the first place to keep around."143 )144 with ctx:145 # Dummy sentinel. Has to be inside the context block or we're146 # not actually keeping the context around.147 yield None148149 # The try/finally is here so that if someone passes a WSGI level150 # iterator in we're still running the cleanup logic. Generators151 # don't need that because they are closed on their destruction152 # automatically.153 try:154 for item in gen:155 yield item156 finally:157 if hasattr(gen, "close"):158 gen.close()159160 # The trick is to start the generator. Then the code execution runs until161 # the first dummy None is yielded at which point the context was already162 # pushed. This item is discarded. Then when the iteration continues the163 # real generator is executed.164 wrapped_g = generator()165 next(wrapped_g)166 return wrapped_g167168169def make_response(*args):170 """Sometimes it is necessary to set additional headers in a view. Because171 views do not have to return response objects but can return a value that172 is converted into a response object by Flask itself, it becomes tricky to173 add headers to it. This function can be called instead of using a return174 and you will get a response object which you can use to attach headers.175176 If view looked like this and you want to add a new header::177178 def index():179 return render_template('index.html', foo=42)180181 You can now do something like this::182183 def index():184 response = make_response(render_template('index.html', foo=42))185 response.headers['X-Parachutes'] = 'parachutes are cool'186 return response187188 This function accepts the very same arguments you can return from a189 view function. This for example creates a response with a 404 error190 code::191192 response = make_response(render_template('not_found.html'), 404)193194 The other use case of this function is to force the return value of a195 view function into a response which is helpful with view196 decorators::197198 response = make_response(view_function())199 response.headers['X-Parachutes'] = 'parachutes are cool'200201 Internally this function does the following things:202203 - if no arguments are passed, it creates a new response argument204 - if one argument is passed, :meth:`flask.Flask.make_response`205 is invoked with it.206 - if more than one argument is passed, the arguments are passed207 to the :meth:`flask.Flask.make_response` function as tuple.208209 .. versionadded:: 0.6210 """211 if not args:212 return current_app.response_class()213 if len(args) == 1:214 args = args[0]215 return current_app.make_response(args)216217218def url_for(endpoint, **values):219 """Generates a URL to the given endpoint with the method provided.220221 Variable arguments that are unknown to the target endpoint are appended222 to the generated URL as query arguments. If the value of a query argument223 is ``None``, the whole pair is skipped. In case blueprints are active224 you can shortcut references to the same blueprint by prefixing the225 local endpoint with a dot (``.``).226227 This will reference the index function local to the current blueprint::228229 url_for('.index')230231 For more information, head over to the :ref:`Quickstart <url-building>`.232233 Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when234 generating URLs outside of a request context.235236 To integrate applications, :class:`Flask` has a hook to intercept URL build237 errors through :attr:`Flask.url_build_error_handlers`. The `url_for`238 function results in a :exc:`~werkzeug.routing.BuildError` when the current239 app does not have a URL for the given endpoint and values. When it does, the240 :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if241 it is not ``None``, which can return a string to use as the result of242 `url_for` (instead of `url_for`'s default to raise the243 :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.244 An example::245246 def external_url_handler(error, endpoint, values):247 "Looks up an external URL when `url_for` cannot build a URL."248 # This is an example of hooking the build_error_handler.249 # Here, lookup_url is some utility function you've built250 # which looks up the endpoint in some external URL registry.251 url = lookup_url(endpoint, **values)252 if url is None:253 # External lookup did not have a URL.254 # Re-raise the BuildError, in context of original traceback.255 exc_type, exc_value, tb = sys.exc_info()256 if exc_value is error:257 raise exc_type, exc_value, tb258 else:259 raise error260 # url_for will use this result, instead of raising BuildError.261 return url262263 app.url_build_error_handlers.append(external_url_handler)264265 Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and266 `endpoint` and `values` are the arguments passed into `url_for`. Note267 that this is for building URLs outside the current application, and not for268 handling 404 NotFound errors.269270 .. versionadded:: 0.10271 The `_scheme` parameter was added.272273 .. versionadded:: 0.9274 The `_anchor` and `_method` parameters were added.275276 .. versionadded:: 0.9277 Calls :meth:`Flask.handle_build_error` on278 :exc:`~werkzeug.routing.BuildError`.279280 :param endpoint: the endpoint of the URL (name of the function)281 :param values: the variable arguments of the URL rule282 :param _external: if set to ``True``, an absolute URL is generated. Server283 address can be changed via ``SERVER_NAME`` configuration variable which284 falls back to the `Host` header, then to the IP and port of the request.285 :param _scheme: a string specifying the desired URL scheme. The `_external`286 parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default287 behavior uses the same scheme as the current request, or288 ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no289 request context is available. As of Werkzeug 0.10, this also can be set290 to an empty string to build protocol-relative URLs.291 :param _anchor: if provided this is added as anchor to the URL.292 :param _method: if provided this explicitly specifies an HTTP method.293 """294 appctx = _app_ctx_stack.top295 reqctx = _request_ctx_stack.top296297 if appctx is None:298 raise RuntimeError(299 "Attempted to generate a URL without the application context being"300 " pushed. This has to be executed when application context is"301 " available."302 )303304 # If request specific information is available we have some extra305 # features that support "relative" URLs.306 if reqctx is not None:307 url_adapter = reqctx.url_adapter308 blueprint_name = request.blueprint309310 if endpoint[:1] == ".":311 if blueprint_name is not None:312 endpoint = blueprint_name + endpoint313 else:314 endpoint = endpoint[1:]315316 external = values.pop("_external", False)317318 # Otherwise go with the url adapter from the appctx and make319 # the URLs external by default.320 else:321 url_adapter = appctx.url_adapter322323 if url_adapter is None:324 raise RuntimeError(325 "Application was not able to create a URL adapter for request"326 " independent URL generation. You might be able to fix this by"327 " setting the SERVER_NAME config variable."328 )329330 external = values.pop("_external", True)331332 anchor = values.pop("_anchor", None)333 method = values.pop("_method", None)334 scheme = values.pop("_scheme", None)335 appctx.app.inject_url_defaults(endpoint, values)336337 # This is not the best way to deal with this but currently the338 # underlying Werkzeug router does not support overriding the scheme on339 # a per build call basis.340 old_scheme = None341 if scheme is not None:342 if not external:343 raise ValueError("When specifying _scheme, _external must be True")344 old_scheme = url_adapter.url_scheme345 url_adapter.url_scheme = scheme346347 try:348 try:349 rv = url_adapter.build(350 endpoint, values, method=method, force_external=external351 )352 finally:353 if old_scheme is not None:354 url_adapter.url_scheme = old_scheme355 except BuildError as error:356 # We need to inject the values again so that the app callback can357 # deal with that sort of stuff.358 values["_external"] = external359 values["_anchor"] = anchor360 values["_method"] = method361 values["_scheme"] = scheme362 return appctx.app.handle_url_build_error(error, endpoint, values)363364 if anchor is not None:365 rv += "#" + url_quote(anchor)366 return rv367368369def get_template_attribute(template_name, attribute):370 """Loads a macro (or variable) a template exports. This can be used to371 invoke a macro from within Python code. If you for example have a372 template named :file:`_cider.html` with the following contents:373374 .. sourcecode:: html+jinja375376 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}377378 You can access this from Python code like this::379380 hello = get_template_attribute('_cider.html', 'hello')381 return hello('World')382383 .. versionadded:: 0.2384385 :param template_name: the name of the template386 :param attribute: the name of the variable of macro to access387 """388 return getattr(current_app.jinja_env.get_template(template_name).module, attribute)389390391def flash(message, category="message"):392 """Flashes a message to the next request. In order to remove the393 flashed message from the session and to display it to the user,394 the template has to call :func:`get_flashed_messages`.395396 .. versionchanged:: 0.3397 `category` parameter added.398399 :param message: the message to be flashed.400 :param category: the category for the message. The following values401 are recommended: ``'message'`` for any kind of message,402 ``'error'`` for errors, ``'info'`` for information403 messages and ``'warning'`` for warnings. However any404 kind of string can be used as category.405 """406 # Original implementation:407 #408 # session.setdefault('_flashes', []).append((category, message))409 #410 # This assumed that changes made to mutable structures in the session are411 # always in sync with the session object, which is not true for session412 # implementations that use external storage for keeping their keys/values.413 flashes = session.get("_flashes", [])414 flashes.append((category, message))415 session["_flashes"] = flashes416 message_flashed.send(417 current_app._get_current_object(), message=message, category=category418 )419420421def get_flashed_messages(with_categories=False, category_filter=()):422 """Pulls all flashed messages from the session and returns them.423 Further calls in the same request to the function will return424 the same messages. By default just the messages are returned,425 but when `with_categories` is set to ``True``, the return value will426 be a list of tuples in the form ``(category, message)`` instead.427428 Filter the flashed messages to one or more categories by providing those429 categories in `category_filter`. This allows rendering categories in430 separate html blocks. The `with_categories` and `category_filter`431 arguments are distinct:432433 * `with_categories` controls whether categories are returned with message434 text (``True`` gives a tuple, where ``False`` gives just the message text).435 * `category_filter` filters the messages down to only those matching the436 provided categories.437438 See :ref:`message-flashing-pattern` for examples.439440 .. versionchanged:: 0.3441 `with_categories` parameter added.442443 .. versionchanged:: 0.9444 `category_filter` parameter added.445446 :param with_categories: set to ``True`` to also receive categories.447 :param category_filter: whitelist of categories to limit return values448 """449 flashes = _request_ctx_stack.top.flashes450 if flashes is None:451 _request_ctx_stack.top.flashes = flashes = (452 session.pop("_flashes") if "_flashes" in session else []453 )454 if category_filter:455 flashes = list(filter(lambda f: f[0] in category_filter, flashes))456 if not with_categories:457 return [x[1] for x in flashes]458 return flashes459460461def send_file(462 filename_or_fp,463 mimetype=None,464 as_attachment=False,465 attachment_filename=None,466 add_etags=True,467 cache_timeout=None,468 conditional=False,469 last_modified=None,470):471 """Sends the contents of a file to the client. This will use the472 most efficient method available and configured. By default it will473 try to use the WSGI server's file_wrapper support. Alternatively474 you can set the application's :attr:`~Flask.use_x_sendfile` attribute475 to ``True`` to directly emit an ``X-Sendfile`` header. This however476 requires support of the underlying webserver for ``X-Sendfile``.477478 By default it will try to guess the mimetype for you, but you can479 also explicitly provide one. For extra security you probably want480 to send certain files as attachment (HTML for instance). The mimetype481 guessing requires a `filename` or an `attachment_filename` to be482 provided.483484 ETags will also be attached automatically if a `filename` is provided. You485 can turn this off by setting `add_etags=False`.486487 If `conditional=True` and `filename` is provided, this method will try to488 upgrade the response stream to support range requests. This will allow489 the request to be answered with partial content response.490491 Please never pass filenames to this function from user sources;492 you should use :func:`send_from_directory` instead.493494 .. versionadded:: 0.2495496 .. versionadded:: 0.5497 The `add_etags`, `cache_timeout` and `conditional` parameters were498 added. The default behavior is now to attach etags.499500 .. versionchanged:: 0.7501 mimetype guessing and etag support for file objects was502 deprecated because it was unreliable. Pass a filename if you are503 able to, otherwise attach an etag yourself. This functionality504 will be removed in Flask 1.0505506 .. versionchanged:: 0.9507 cache_timeout pulls its default from application config, when None.508509 .. versionchanged:: 0.12510 The filename is no longer automatically inferred from file objects. If511 you want to use automatic mimetype and etag support, pass a filepath via512 `filename_or_fp` or `attachment_filename`.513514 .. versionchanged:: 0.12515 The `attachment_filename` is preferred over `filename` for MIME-type516 detection.517518 .. versionchanged:: 1.0519 UTF-8 filenames, as specified in `RFC 2231`_, are supported.520521 .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4522523 .. versionchanged:: 1.0.3524 Filenames are encoded with ASCII instead of Latin-1 for broader525 compatibility with WSGI servers.526527 .. versionchanged:: 1.1528 Filename may be a :class:`~os.PathLike` object.529530 .. versionadded:: 1.1531 Partial content supports :class:`~io.BytesIO`.532533 :param filename_or_fp: the filename of the file to send.534 This is relative to the :attr:`~Flask.root_path`535 if a relative path is specified.536 Alternatively a file object might be provided in537 which case ``X-Sendfile`` might not work and fall538 back to the traditional method. Make sure that the539 file pointer is positioned at the start of data to540 send before calling :func:`send_file`.541 :param mimetype: the mimetype of the file if provided. If a file path is542 given, auto detection happens as fallback, otherwise an543 error will be raised.544 :param as_attachment: set to ``True`` if you want to send this file with545 a ``Content-Disposition: attachment`` header.546 :param attachment_filename: the filename for the attachment if it547 differs from the file's filename.548 :param add_etags: set to ``False`` to disable attaching of etags.549 :param conditional: set to ``True`` to enable conditional responses.550551 :param cache_timeout: the timeout in seconds for the headers. When ``None``552 (default), this value is set by553 :meth:`~Flask.get_send_file_max_age` of554 :data:`~flask.current_app`.555 :param last_modified: set the ``Last-Modified`` header to this value,556 a :class:`~datetime.datetime` or timestamp.557 If a file was passed, this overrides its mtime.558 """559 mtime = None560 fsize = None561562 if hasattr(filename_or_fp, "__fspath__"):563 filename_or_fp = fspath(filename_or_fp)564565 if isinstance(filename_or_fp, string_types):566 filename = filename_or_fp567 if not os.path.isabs(filename):568 filename = os.path.join(current_app.root_path, filename)569 file = None570 if attachment_filename is None:571 attachment_filename = os.path.basename(filename)572 else:573 file = filename_or_fp574 filename = None575576 if mimetype is None:577 if attachment_filename is not None:578 mimetype = (579 mimetypes.guess_type(attachment_filename)[0]580 or "application/octet-stream"581 )582583 if mimetype is None:584 raise ValueError(585 "Unable to infer MIME-type because no filename is available. "586 "Please set either `attachment_filename`, pass a filepath to "587 "`filename_or_fp` or set your own MIME-type via `mimetype`."588 )589590 headers = Headers()591 if as_attachment:592 if attachment_filename is None:593 raise TypeError(594 "filename unavailable, required for " "sending as attachment"595 )596597 if not isinstance(attachment_filename, text_type):598 attachment_filename = attachment_filename.decode("utf-8")599600 try:601 attachment_filename = attachment_filename.encode("ascii")602 except UnicodeEncodeError:603 filenames = {604 "filename": unicodedata.normalize("NFKD", attachment_filename).encode(605 "ascii", "ignore"606 ),607 "filename*": "UTF-8''%s" % url_quote(attachment_filename),608 }609 else:610 filenames = {"filename": attachment_filename}611612 headers.add("Content-Disposition", "attachment", **filenames)613614 if current_app.use_x_sendfile and filename:615 if file is not None:616 file.close()617 headers["X-Sendfile"] = filename618 fsize = os.path.getsize(filename)619 headers["Content-Length"] = fsize620 data = None621 else:622 if file is None:623 file = open(filename, "rb")624 mtime = os.path.getmtime(filename)625 fsize = os.path.getsize(filename)626 headers["Content-Length"] = fsize627 elif isinstance(file, io.BytesIO):628 try:629 fsize = file.getbuffer().nbytes630 except AttributeError:631 # Python 2 doesn't have getbuffer632 fsize = len(file.getvalue())633 headers["Content-Length"] = fsize634 data = wrap_file(request.environ, file)635636 rv = current_app.response_class(637 data, mimetype=mimetype, headers=headers, direct_passthrough=True638 )639640 if last_modified is not None:641 rv.last_modified = last_modified642 elif mtime is not None:643 rv.last_modified = mtime644645 rv.cache_control.public = True646 if cache_timeout is None:647 cache_timeout = current_app.get_send_file_max_age(filename)648 if cache_timeout is not None:649 rv.cache_control.max_age = cache_timeout650 rv.expires = int(time() + cache_timeout)651652 if add_etags and filename is not None:653 from warnings import warn654655 try:656 rv.set_etag(657 "%s-%s-%s"658 % (659 os.path.getmtime(filename),660 os.path.getsize(filename),661 adler32(662 filename.encode("utf-8")663 if isinstance(filename, text_type)664 else filename665 )666 & 0xFFFFFFFF,667 )668 )669 except OSError:670 warn(671 "Access %s failed, maybe it does not exist, so ignore etags in "672 "headers" % filename,673 stacklevel=2,674 )675676 if conditional:677 try:678 rv = rv.make_conditional(request, accept_ranges=True, complete_length=fsize)679 except RequestedRangeNotSatisfiable:680 if file is not None:681 file.close()682 raise683 # make sure we don't send x-sendfile for servers that684 # ignore the 304 status code for x-sendfile.685 if rv.status_code == 304:686 rv.headers.pop("x-sendfile", None)687 return rv688689690def safe_join(directory, *pathnames):691 """Safely join `directory` and zero or more untrusted `pathnames`692 components.693694 Example usage::695696 @app.route('/wiki/<path:filename>')697 def wiki_page(filename):698 filename = safe_join(app.config['WIKI_FOLDER'], filename)699 with open(filename, 'rb') as fd:700 content = fd.read() # Read and process the file content...701702 :param directory: the trusted base directory.703 :param pathnames: the untrusted pathnames relative to that directory.704 :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed705 paths fall out of its boundaries.706 """707708 parts = [directory]709710 for filename in pathnames:711 if filename != "":712 filename = posixpath.normpath(filename)713714 if (715 any(sep in filename for sep in _os_alt_seps)716 or os.path.isabs(filename)717 or filename == ".."718 or filename.startswith("../")719 ):720 raise NotFound()721722 parts.append(filename)723724 return posixpath.join(*parts)725726727def send_from_directory(directory, filename, **options):728 """Send a file from a given directory with :func:`send_file`. This729 is a secure way to quickly expose static files from an upload folder730 or something similar.731732 Example usage::733734 @app.route('/uploads/<path:filename>')735 def download_file(filename):736 return send_from_directory(app.config['UPLOAD_FOLDER'],737 filename, as_attachment=True)738739 .. admonition:: Sending files and Performance740741 It is strongly recommended to activate either ``X-Sendfile`` support in742 your webserver or (if no authentication happens) to tell the webserver743 to serve files for the given path on its own without calling into the744 web application for improved performance.745746 .. versionadded:: 0.5747748 :param directory: the directory where all the files are stored.749 :param filename: the filename relative to that directory to750 download.751 :param options: optional keyword arguments that are directly752 forwarded to :func:`send_file`.753 """754 filename = fspath(filename)755 directory = fspath(directory)756 filename = safe_join(directory, filename)757 if not os.path.isabs(filename):758 filename = os.path.join(current_app.root_path, filename)759 try:760 if not os.path.isfile(filename):761 raise NotFound()762 except (TypeError, ValueError):763 raise BadRequest()764 options.setdefault("conditional", True)765 return send_file(filename, **options)766767768def get_root_path(import_name):769 """Returns the path to a package or cwd if that cannot be found. This770 returns the path of a package or the folder that contains a module.771772 Not to be confused with the package path returned by :func:`find_package`.773 """774 # Module already imported and has a file attribute. Use that first.775 mod = sys.modules.get(import_name)776 if mod is not None and hasattr(mod, "__file__"):777 return os.path.dirname(os.path.abspath(mod.__file__))778779 # Next attempt: check the loader.780 loader = pkgutil.get_loader(import_name)781782 # Loader does not exist or we're referring to an unloaded main module783 # or a main module without path (interactive sessions), go with the784 # current working directory.785 if loader is None or import_name == "__main__":786 return os.getcwd()787788 # For .egg, zipimporter does not have get_filename until Python 2.7.789 # Some other loaders might exhibit the same behavior.790 if hasattr(loader, "get_filename"):791 filepath = loader.get_filename(import_name)792 else:793 # Fall back to imports.794 __import__(import_name)795 mod = sys.modules[import_name]796 filepath = getattr(mod, "__file__", None)797798 # If we don't have a filepath it might be because we are a799 # namespace package. In this case we pick the root path from the800 # first module that is contained in our package.801 if filepath is None:802 raise RuntimeError(803 "No root path can be found for the provided "804 'module "%s". This can happen because the '805 "module came from an import hook that does "806 "not provide file name information or because "807 "it's a namespace package. In this case "808 "the root path needs to be explicitly "809 "provided." % import_name810 )811812 # filepath is import_name.py for a module, or __init__.py for a package.813 return os.path.dirname(os.path.abspath(filepath))814815816def _matching_loader_thinks_module_is_package(loader, mod_name):817 """Given the loader that loaded a module and the module this function818 attempts to figure out if the given module is actually a package.819 """820 # If the loader can tell us if something is a package, we can821 # directly ask the loader.822 if hasattr(loader, "is_package"):823 return loader.is_package(mod_name)824 # importlib's namespace loaders do not have this functionality but825 # all the modules it loads are packages, so we can take advantage of826 # this information.827 elif (828 loader.__class__.__module__ == "_frozen_importlib"829 and loader.__class__.__name__ == "NamespaceLoader"830 ):831 return True832 # Otherwise we need to fail with an error that explains what went833 # wrong.834 raise AttributeError(835 (836 "%s.is_package() method is missing but is required by Flask of "837 "PEP 302 import hooks. If you do not use import hooks and "838 "you encounter this error please file a bug against Flask."839 )840 % loader.__class__.__name__841 )842843844def find_package(import_name):845 """Finds a package and returns the prefix (or None if the package is846 not installed) as well as the folder that contains the package or847 module as a tuple. The package path returned is the module that would848 have to be added to the pythonpath in order to make it possible to849 import the module. The prefix is the path below which a UNIX like850 folder structure exists (lib, share etc.).851 """852 root_mod_name = import_name.split(".")[0]853 loader = pkgutil.get_loader(root_mod_name)854 if loader is None or import_name == "__main__":855 # import name is not found, or interactive/main module856 package_path = os.getcwd()857 else:858 # For .egg, zipimporter does not have get_filename until Python 2.7.859 if hasattr(loader, "get_filename"):860 filename = loader.get_filename(root_mod_name)861 elif hasattr(loader, "archive"):862 # zipimporter's loader.archive points to the .egg or .zip863 # archive filename is dropped in call to dirname below.864 filename = loader.archive865 else:866 # At least one loader is missing both get_filename and archive:867 # Google App Engine's HardenedModulesHook868 #869 # Fall back to imports.870 __import__(import_name)871 filename = sys.modules[import_name].__file__872 package_path = os.path.abspath(os.path.dirname(filename))873874 # In case the root module is a package we need to chop of the875 # rightmost part. This needs to go through a helper function876 # because of python 3.3 namespace packages.877 if _matching_loader_thinks_module_is_package(loader, root_mod_name):878 package_path = os.path.dirname(package_path)879880 site_parent, site_folder = os.path.split(package_path)881 py_prefix = os.path.abspath(sys.prefix)882 if package_path.startswith(py_prefix):883 return py_prefix, package_path884 elif site_folder.lower() == "site-packages":885 parent, folder = os.path.split(site_parent)886 # Windows like installations887 if folder.lower() == "lib":888 base_dir = parent889 # UNIX like installations890 elif os.path.basename(parent).lower() == "lib":891 base_dir = os.path.dirname(parent)892 else:893 base_dir = site_parent894 return base_dir, package_path895 return None, package_path896897898class locked_cached_property(object):899 """A decorator that converts a function into a lazy property. The900 function wrapped is called the first time to retrieve the result901 and then that calculated result is used the next time you access902 the value. Works like the one in Werkzeug but has a lock for903 thread safety.904 """905906 def __init__(self, func, name=None, doc=None):907 self.__name__ = name or func.__name__908 self.__module__ = func.__module__909 self.__doc__ = doc or func.__doc__910 self.func = func911 self.lock = RLock()912913 def __get__(self, obj, type=None):914 if obj is None:915 return self916 with self.lock:917 value = obj.__dict__.get(self.__name__, _missing)918 if value is _missing:919 value = self.func(obj)920 obj.__dict__[self.__name__] = value921 return value922923924class _PackageBoundObject(object):925 #: The name of the package or module that this app belongs to. Do not926 #: change this once it is set by the constructor.927 import_name = None928929 #: Location of the template files to be added to the template lookup.930 #: ``None`` if templates should not be added.931 template_folder = None932933 #: Absolute path to the package on the filesystem. Used to look up934 #: resources contained in the package.935 root_path = None936937 def __init__(self, import_name, template_folder=None, root_path=None):938 self.import_name = import_name939 self.template_folder = template_folder940941 if root_path is None:942 root_path = get_root_path(self.import_name)943944 self.root_path = root_path945 self._static_folder = None946 self._static_url_path = None947948 # circular import949 from .cli import AppGroup950951 #: The Click command group for registration of CLI commands952 #: on the application and associated blueprints. These commands953 #: are accessible via the :command:`flask` command once the954 #: application has been discovered and blueprints registered.955 self.cli = AppGroup()956957 @property958 def static_folder(self):959 """The absolute path to the configured static folder."""960 if self._static_folder is not None:961 return os.path.join(self.root_path, self._static_folder)962963 @static_folder.setter964 def static_folder(self, value):965 self._static_folder = value966967 @property968 def static_url_path(self):969 """The URL prefix that the static route will be accessible from.970971 If it was not configured during init, it is derived from972 :attr:`static_folder`.973 """974 if self._static_url_path is not None:975 return self._static_url_path976977 if self.static_folder is not None:978 basename = os.path.basename(self.static_folder)979 return ("/" + basename).rstrip("/")980981 @static_url_path.setter982 def static_url_path(self, value):983 if value is not None:984 value = value.rstrip("/")985986 self._static_url_path = value987988 @property989 def has_static_folder(self):990 """This is ``True`` if the package bound object's container has a991 folder for static files.992993 .. versionadded:: 0.5994 """995 return self.static_folder is not None996997 @locked_cached_property998 def jinja_loader(self):999 """The Jinja loader for this package bound object.10001001 .. versionadded:: 0.51002 """1003 if self.template_folder is not None:1004 return FileSystemLoader(os.path.join(self.root_path, self.template_folder))10051006 def get_send_file_max_age(self, filename):1007 """Provides default cache_timeout for the :func:`send_file` functions.10081009 By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from1010 the configuration of :data:`~flask.current_app`.10111012 Static file functions such as :func:`send_from_directory` use this1013 function, and :func:`send_file` calls this function on1014 :data:`~flask.current_app` when the given cache_timeout is ``None``. If a1015 cache_timeout is given in :func:`send_file`, that timeout is used;1016 otherwise, this method is called.10171018 This allows subclasses to change the behavior when sending files based1019 on the filename. For example, to set the cache timeout for .js files1020 to 60 seconds::10211022 class MyFlask(flask.Flask):1023 def get_send_file_max_age(self, name):1024 if name.lower().endswith('.js'):1025 return 601026 return flask.Flask.get_send_file_max_age(self, name)10271028 .. versionadded:: 0.91029 """1030 return total_seconds(current_app.send_file_max_age_default)10311032 def send_static_file(self, filename):1033 """Function used internally to send static files from the static1034 folder to the browser.10351036 .. versionadded:: 0.51037 """1038 if not self.has_static_folder:1039 raise RuntimeError("No static folder for this object")1040 # Ensure get_send_file_max_age is called in all cases.1041 # Here, we ensure get_send_file_max_age is called for Blueprints.1042 cache_timeout = self.get_send_file_max_age(filename)1043 return send_from_directory(1044 self.static_folder, filename, cache_timeout=cache_timeout1045 )10461047 def open_resource(self, resource, mode="rb"):1048 """Opens a resource from the application's resource folder. To see1049 how this works, consider the following folder structure::10501051 /myapplication.py1052 /schema.sql1053 /static1054 /style.css1055 /templates1056 /layout.html1057 /index.html10581059 If you want to open the :file:`schema.sql` file you would do the1060 following::10611062 with app.open_resource('schema.sql') as f:1063 contents = f.read()1064 do_something_with(contents)10651066 :param resource: the name of the resource. To access resources within1067 subfolders use forward slashes as separator.1068 :param mode: Open file in this mode. Only reading is supported,1069 valid values are "r" (or "rt") and "rb".1070 """1071 if mode not in {"r", "rt", "rb"}:1072 raise ValueError("Resources can only be opened for reading")10731074 return open(os.path.join(self.root_path, resource), mode)107510761077def total_seconds(td):1078 """Returns the total seconds from a timedelta object.10791080 :param timedelta td: the timedelta to be converted in seconds10811082 :returns: number of seconds1083 :rtype: int1084 """1085 return td.days * 60 * 60 * 24 + td.seconds108610871088def is_ip(value):1089 """Determine if the given string is an IP address.10901091 Python 2 on Windows doesn't provide ``inet_pton``, so this only1092 checks IPv4 addresses in that environment.10931094 :param value: value to check1095 :type value: str10961097 :return: True if string is an IP address1098 :rtype: bool1099 """1100 if PY2 and os.name == "nt":1101 try:1102 socket.inet_aton(value)1103 return True1104 except socket.error:1105 return False11061107 for family in (socket.AF_INET, socket.AF_INET6):1108 try:1109 socket.inet_pton(family, value)1110 except socket.error:1111 pass1112 else:1113 return True11141115 return False
added:src/flask/logging.py+78 added
1# -*- coding: utf-8 -*-2"""3flask.logging4~~~~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""910from __future__ import absolute_import1112import logging13import sys1415from werkzeug.local import LocalProxy1617from .globals import request181920@LocalProxy21def wsgi_errors_stream():22 """Find the most appropriate error stream for the application. If a request23 is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.2425 If you configure your own :class:`logging.StreamHandler`, you may want to26 use this for the stream. If you are using file or dict configuration and27 can't import this directly, you can refer to it as28 ``ext://flask.logging.wsgi_errors_stream``.29 """30 return request.environ["wsgi.errors"] if request else sys.stderr313233def has_level_handler(logger):34 """Check if there is a handler in the logging chain that will handle the35 given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.36 """37 level = logger.getEffectiveLevel()38 current = logger3940 while current:41 if any(handler.level <= level for handler in current.handlers):42 return True4344 if not current.propagate:45 break4647 current = current.parent4849 return False505152#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format53#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.54default_handler = logging.StreamHandler(wsgi_errors_stream)55default_handler.setFormatter(56 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")57)585960def create_logger(app):61 """Get the ``'flask.app'`` logger and configure it if needed.6263 When :attr:`~flask.Flask.debug` is enabled, set the logger level to64 :data:`logging.DEBUG` if it is not set.6566 If there is no handler for the logger's effective level, add a67 :class:`~logging.StreamHandler` for68 :func:`~flask.logging.wsgi_errors_stream` with a basic format.69 """70 logger = logging.getLogger("flask.app")7172 if app.debug and logger.level == logging.NOTSET:73 logger.setLevel(logging.DEBUG)7475 if not has_level_handler(logger):76 logger.addHandler(default_handler)7778 return logger
added:src/flask/sessions.py+387 added
1# -*- coding: utf-8 -*-2"""3 flask.sessions4 ~~~~~~~~~~~~~~56 Implements cookie based sessions based on itsdangerous.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import hashlib13import warnings14from datetime import datetime1516from itsdangerous import BadSignature, URLSafeTimedSerializer17from werkzeug.datastructures import CallbackDict1819from flask._compat import collections_abc20from flask.helpers import is_ip, total_seconds21from flask.json.tag import TaggedJSONSerializer222324class SessionMixin(collections_abc.MutableMapping):25 """Expands a basic dictionary with session attributes."""2627 @property28 def permanent(self):29 """This reflects the ``'_permanent'`` key in the dict."""30 return self.get("_permanent", False)3132 @permanent.setter33 def permanent(self, value):34 self["_permanent"] = bool(value)3536 #: Some implementations can detect whether a session is newly37 #: created, but that is not guaranteed. Use with caution. The mixin38 # default is hard-coded ``False``.39 new = False4041 #: Some implementations can detect changes to the session and set42 #: this when that happens. The mixin default is hard coded to43 #: ``True``.44 modified = True4546 #: Some implementations can detect when session data is read or47 #: written and set this when that happens. The mixin default is hard48 #: coded to ``True``.49 accessed = True505152class SecureCookieSession(CallbackDict, SessionMixin):53 """Base class for sessions based on signed cookies.5455 This session backend will set the :attr:`modified` and56 :attr:`accessed` attributes. It cannot reliably track whether a57 session is new (vs. empty), so :attr:`new` remains hard coded to58 ``False``.59 """6061 #: When data is changed, this is set to ``True``. Only the session62 #: dictionary itself is tracked; if the session contains mutable63 #: data (for example a nested dict) then this must be set to64 #: ``True`` manually when modifying that data. The session cookie65 #: will only be written to the response if this is ``True``.66 modified = False6768 #: When data is read or written, this is set to ``True``. Used by69 # :class:`.SecureCookieSessionInterface` to add a ``Vary: Cookie``70 #: header, which allows caching proxies to cache different pages for71 #: different users.72 accessed = False7374 def __init__(self, initial=None):75 def on_update(self):76 self.modified = True77 self.accessed = True7879 super(SecureCookieSession, self).__init__(initial, on_update)8081 def __getitem__(self, key):82 self.accessed = True83 return super(SecureCookieSession, self).__getitem__(key)8485 def get(self, key, default=None):86 self.accessed = True87 return super(SecureCookieSession, self).get(key, default)8889 def setdefault(self, key, default=None):90 self.accessed = True91 return super(SecureCookieSession, self).setdefault(key, default)929394class NullSession(SecureCookieSession):95 """Class used to generate nicer error messages if sessions are not96 available. Will still allow read-only access to the empty session97 but fail on setting.98 """99100 def _fail(self, *args, **kwargs):101 raise RuntimeError(102 "The session is unavailable because no secret "103 "key was set. Set the secret_key on the "104 "application to something unique and secret."105 )106107 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail108 del _fail109110111class SessionInterface(object):112 """The basic interface you have to implement in order to replace the113 default session interface which uses werkzeug's securecookie114 implementation. The only methods you have to implement are115 :meth:`open_session` and :meth:`save_session`, the others have116 useful defaults which you don't need to change.117118 The session object returned by the :meth:`open_session` method has to119 provide a dictionary like interface plus the properties and methods120 from the :class:`SessionMixin`. We recommend just subclassing a dict121 and adding that mixin::122123 class Session(dict, SessionMixin):124 pass125126 If :meth:`open_session` returns ``None`` Flask will call into127 :meth:`make_null_session` to create a session that acts as replacement128 if the session support cannot work because some requirement is not129 fulfilled. The default :class:`NullSession` class that is created130 will complain that the secret key was not set.131132 To replace the session interface on an application all you have to do133 is to assign :attr:`flask.Flask.session_interface`::134135 app = Flask(__name__)136 app.session_interface = MySessionInterface()137138 .. versionadded:: 0.8139 """140141 #: :meth:`make_null_session` will look here for the class that should142 #: be created when a null session is requested. Likewise the143 #: :meth:`is_null_session` method will perform a typecheck against144 #: this type.145 null_session_class = NullSession146147 #: A flag that indicates if the session interface is pickle based.148 #: This can be used by Flask extensions to make a decision in regards149 #: to how to deal with the session object.150 #:151 #: .. versionadded:: 0.10152 pickle_based = False153154 def make_null_session(self, app):155 """Creates a null session which acts as a replacement object if the156 real session support could not be loaded due to a configuration157 error. This mainly aids the user experience because the job of the158 null session is to still support lookup without complaining but159 modifications are answered with a helpful error message of what160 failed.161162 This creates an instance of :attr:`null_session_class` by default.163 """164 return self.null_session_class()165166 def is_null_session(self, obj):167 """Checks if a given object is a null session. Null sessions are168 not asked to be saved.169170 This checks if the object is an instance of :attr:`null_session_class`171 by default.172 """173 return isinstance(obj, self.null_session_class)174175 def get_cookie_domain(self, app):176 """Returns the domain that should be set for the session cookie.177178 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise179 falls back to detecting the domain based on ``SERVER_NAME``.180181 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is182 updated to avoid re-running the logic.183 """184185 rv = app.config["SESSION_COOKIE_DOMAIN"]186187 # set explicitly, or cached from SERVER_NAME detection188 # if False, return None189 if rv is not None:190 return rv if rv else None191192 rv = app.config["SERVER_NAME"]193194 # server name not set, cache False to return none next time195 if not rv:196 app.config["SESSION_COOKIE_DOMAIN"] = False197 return None198199 # chop off the port which is usually not supported by browsers200 # remove any leading '.' since we'll add that later201 rv = rv.rsplit(":", 1)[0].lstrip(".")202203 if "." not in rv:204 # Chrome doesn't allow names without a '.'205 # this should only come up with localhost206 # hack around this by not setting the name, and show a warning207 warnings.warn(208 '"{rv}" is not a valid cookie domain, it must contain a ".".'209 " Add an entry to your hosts file, for example"210 ' "{rv}.localdomain", and use that instead.'.format(rv=rv)211 )212 app.config["SESSION_COOKIE_DOMAIN"] = False213 return None214215 ip = is_ip(rv)216217 if ip:218 warnings.warn(219 "The session cookie domain is an IP address. This may not work"220 " as intended in some browsers. Add an entry to your hosts"221 ' file, for example "localhost.localdomain", and use that'222 " instead."223 )224225 # if this is not an ip and app is mounted at the root, allow subdomain226 # matching by adding a '.' prefix227 if self.get_cookie_path(app) == "/" and not ip:228 rv = "." + rv229230 app.config["SESSION_COOKIE_DOMAIN"] = rv231 return rv232233 def get_cookie_path(self, app):234 """Returns the path for which the cookie should be valid. The235 default implementation uses the value from the ``SESSION_COOKIE_PATH``236 config var if it's set, and falls back to ``APPLICATION_ROOT`` or237 uses ``/`` if it's ``None``.238 """239 return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]240241 def get_cookie_httponly(self, app):242 """Returns True if the session cookie should be httponly. This243 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``244 config var.245 """246 return app.config["SESSION_COOKIE_HTTPONLY"]247248 def get_cookie_secure(self, app):249 """Returns True if the cookie should be secure. This currently250 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.251 """252 return app.config["SESSION_COOKIE_SECURE"]253254 def get_cookie_samesite(self, app):255 """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the256 ``SameSite`` attribute. This currently just returns the value of257 the :data:`SESSION_COOKIE_SAMESITE` setting.258 """259 return app.config["SESSION_COOKIE_SAMESITE"]260261 def get_expiration_time(self, app, session):262 """A helper method that returns an expiration date for the session263 or ``None`` if the session is linked to the browser session. The264 default implementation returns now + the permanent session265 lifetime configured on the application.266 """267 if session.permanent:268 return datetime.utcnow() + app.permanent_session_lifetime269270 def should_set_cookie(self, app, session):271 """Used by session backends to determine if a ``Set-Cookie`` header272 should be set for this session cookie for this response. If the session273 has been modified, the cookie is set. If the session is permanent and274 the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is275 always set.276277 This check is usually skipped if the session was deleted.278279 .. versionadded:: 0.11280 """281282 return session.modified or (283 session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]284 )285286 def open_session(self, app, request):287 """This method has to be implemented and must either return ``None``288 in case the loading failed because of a configuration error or an289 instance of a session object which implements a dictionary like290 interface + the methods and attributes on :class:`SessionMixin`.291 """292 raise NotImplementedError()293294 def save_session(self, app, session, response):295 """This is called for actual sessions returned by :meth:`open_session`296 at the end of the request. This is still called during a request297 context so if you absolutely need access to the request you can do298 that.299 """300 raise NotImplementedError()301302303session_json_serializer = TaggedJSONSerializer()304305306class SecureCookieSessionInterface(SessionInterface):307 """The default session interface that stores sessions in signed cookies308 through the :mod:`itsdangerous` module.309 """310311 #: the salt that should be applied on top of the secret key for the312 #: signing of cookie based sessions.313 salt = "cookie-session"314 #: the hash function to use for the signature. The default is sha1315 digest_method = staticmethod(hashlib.sha1)316 #: the name of the itsdangerous supported key derivation. The default317 #: is hmac.318 key_derivation = "hmac"319 #: A python serializer for the payload. The default is a compact320 #: JSON derived serializer with support for some extra Python types321 #: such as datetime objects or tuples.322 serializer = session_json_serializer323 session_class = SecureCookieSession324325 def get_signing_serializer(self, app):326 if not app.secret_key:327 return None328 signer_kwargs = dict(329 key_derivation=self.key_derivation, digest_method=self.digest_method330 )331 return URLSafeTimedSerializer(332 app.secret_key,333 salt=self.salt,334 serializer=self.serializer,335 signer_kwargs=signer_kwargs,336 )337338 def open_session(self, app, request):339 s = self.get_signing_serializer(app)340 if s is None:341 return None342 val = request.cookies.get(app.session_cookie_name)343 if not val:344 return self.session_class()345 max_age = total_seconds(app.permanent_session_lifetime)346 try:347 data = s.loads(val, max_age=max_age)348 return self.session_class(data)349 except BadSignature:350 return self.session_class()351352 def save_session(self, app, session, response):353 domain = self.get_cookie_domain(app)354 path = self.get_cookie_path(app)355356 # If the session is modified to be empty, remove the cookie.357 # If the session is empty, return without setting the cookie.358 if not session:359 if session.modified:360 response.delete_cookie(361 app.session_cookie_name, domain=domain, path=path362 )363364 return365366 # Add a "Vary: Cookie" header if the session was accessed at all.367 if session.accessed:368 response.vary.add("Cookie")369370 if not self.should_set_cookie(app, session):371 return372373 httponly = self.get_cookie_httponly(app)374 secure = self.get_cookie_secure(app)375 samesite = self.get_cookie_samesite(app)376 expires = self.get_expiration_time(app, session)377 val = self.get_signing_serializer(app).dumps(dict(session))378 response.set_cookie(379 app.session_cookie_name,380 val,381 expires=expires,382 httponly=httponly,383 domain=domain,384 path=path,385 secure=secure,386 samesite=samesite,387 )
added:src/flask/signals.py+66 added
1# -*- coding: utf-8 -*-2"""3 flask.signals4 ~~~~~~~~~~~~~56 Implements signals based on blinker if available, otherwise7 falls silently back to a noop.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213signals_available = False14try:15 from blinker import Namespace1617 signals_available = True18except ImportError:1920 class Namespace(object):21 def signal(self, name, doc=None):22 return _FakeSignal(name, doc)2324 class _FakeSignal(object):25 """If blinker is unavailable, create a fake class with the same26 interface that allows sending of signals but will fail with an27 error on anything else. Instead of doing anything on send, it28 will just ignore the arguments and do nothing instead.29 """3031 def __init__(self, name, doc=None):32 self.name = name33 self.__doc__ = doc3435 def send(self, *args, **kwargs):36 pass3738 def _fail(self, *args, **kwargs):39 raise RuntimeError(40 "Signalling support is unavailable because the blinker"41 " library is not installed."42 )4344 connect = connect_via = connected_to = temporarily_connected_to = _fail45 disconnect = _fail46 has_receivers_for = receivers_for = _fail47 del _fail484950# The namespace for code signals. If you are not Flask code, do51# not put signals in here. Create your own namespace instead.52_signals = Namespace()535455# Core signals. For usage examples grep the source code or consult56# the API documentation in docs/api.rst as well as docs/signals.rst57template_rendered = _signals.signal("template-rendered")58before_render_template = _signals.signal("before-render-template")59request_started = _signals.signal("request-started")60request_finished = _signals.signal("request-finished")61request_tearing_down = _signals.signal("request-tearing-down")62got_request_exception = _signals.signal("got-request-exception")63appcontext_tearing_down = _signals.signal("appcontext-tearing-down")64appcontext_pushed = _signals.signal("appcontext-pushed")65appcontext_popped = _signals.signal("appcontext-popped")66message_flashed = _signals.signal("message-flashed")
added:src/flask/templating.py+152 added
1# -*- coding: utf-8 -*-2"""3 flask.templating4 ~~~~~~~~~~~~~~~~56 Implements the bridge to Jinja2.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from jinja2 import BaseLoader, Environment as BaseEnvironment, TemplateNotFound1314from .globals import _request_ctx_stack, _app_ctx_stack15from .signals import template_rendered, before_render_template161718def _default_template_ctx_processor():19 """Default template context processor. Injects `request`,20 `session` and `g`.21 """22 reqctx = _request_ctx_stack.top23 appctx = _app_ctx_stack.top24 rv = {}25 if appctx is not None:26 rv["g"] = appctx.g27 if reqctx is not None:28 rv["request"] = reqctx.request29 rv["session"] = reqctx.session30 return rv313233class Environment(BaseEnvironment):34 """Works like a regular Jinja2 environment but has some additional35 knowledge of how Flask's blueprint works so that it can prepend the36 name of the blueprint to referenced templates if necessary.37 """3839 def __init__(self, app, **options):40 if "loader" not in options:41 options["loader"] = app.create_global_jinja_loader()42 BaseEnvironment.__init__(self, **options)43 self.app = app444546class DispatchingJinjaLoader(BaseLoader):47 """A loader that looks for templates in the application and all48 the blueprint folders.49 """5051 def __init__(self, app):52 self.app = app5354 def get_source(self, environment, template):55 if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:56 return self._get_source_explained(environment, template)57 return self._get_source_fast(environment, template)5859 def _get_source_explained(self, environment, template):60 attempts = []61 trv = None6263 for srcobj, loader in self._iter_loaders(template):64 try:65 rv = loader.get_source(environment, template)66 if trv is None:67 trv = rv68 except TemplateNotFound:69 rv = None70 attempts.append((loader, srcobj, rv))7172 from .debughelpers import explain_template_loading_attempts7374 explain_template_loading_attempts(self.app, template, attempts)7576 if trv is not None:77 return trv78 raise TemplateNotFound(template)7980 def _get_source_fast(self, environment, template):81 for _srcobj, loader in self._iter_loaders(template):82 try:83 return loader.get_source(environment, template)84 except TemplateNotFound:85 continue86 raise TemplateNotFound(template)8788 def _iter_loaders(self, template):89 loader = self.app.jinja_loader90 if loader is not None:91 yield self.app, loader9293 for blueprint in self.app.iter_blueprints():94 loader = blueprint.jinja_loader95 if loader is not None:96 yield blueprint, loader9798 def list_templates(self):99 result = set()100 loader = self.app.jinja_loader101 if loader is not None:102 result.update(loader.list_templates())103104 for blueprint in self.app.iter_blueprints():105 loader = blueprint.jinja_loader106 if loader is not None:107 for template in loader.list_templates():108 result.add(template)109110 return list(result)111112113def _render(template, context, app):114 """Renders the template and fires the signal"""115116 before_render_template.send(app, template=template, context=context)117 rv = template.render(context)118 template_rendered.send(app, template=template, context=context)119 return rv120121122def render_template(template_name_or_list, **context):123 """Renders a template from the template folder with the given124 context.125126 :param template_name_or_list: the name of the template to be127 rendered, or an iterable with template names128 the first one existing will be rendered129 :param context: the variables that should be available in the130 context of the template.131 """132 ctx = _app_ctx_stack.top133 ctx.app.update_template_context(context)134 return _render(135 ctx.app.jinja_env.get_or_select_template(template_name_or_list),136 context,137 ctx.app,138 )139140141def render_template_string(source, **context):142 """Renders a template from the given template source string143 with the given context. Template variables will be autoescaped.144145 :param source: the source code of the template to be146 rendered147 :param context: the variables that should be available in the148 context of the template.149 """150 ctx = _app_ctx_stack.top151 ctx.app.update_template_context(context)152 return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)
added:src/flask/testing.py+283 added
1# -*- coding: utf-8 -*-2"""3 flask.testing4 ~~~~~~~~~~~~~56 Implements test support helpers. This module is lazily imported7 and usually not used in production environments.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""12import warnings13import werkzeug14import werkzeug.test15from contextlib import contextmanager1617from click.testing import CliRunner18from flask.cli import ScriptInfo19from werkzeug.test import Client20from flask import _request_ctx_stack21from flask.json import dumps as json_dumps22from werkzeug.urls import url_parse232425class EnvironBuilder(werkzeug.test.EnvironBuilder):26 """An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the27 application.2829 :param app: The Flask application to configure the environment from.30 :param path: URL path being requested.31 :param base_url: Base URL where the app is being served, which32 ``path`` is relative to. If not given, built from33 :data:`PREFERRED_URL_SCHEME`, ``subdomain``,34 :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.35 :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.36 :param url_scheme: Scheme to use instead of37 :data:`PREFERRED_URL_SCHEME`.38 :param json: If given, this is serialized as JSON and passed as39 ``data``. Also defaults ``content_type`` to40 ``application/json``.41 :param args: other positional arguments passed to42 :class:`~werkzeug.test.EnvironBuilder`.43 :param kwargs: other keyword arguments passed to44 :class:`~werkzeug.test.EnvironBuilder`.45 """4647 def __init__(48 self,49 app,50 path="/",51 base_url=None,52 subdomain=None,53 url_scheme=None,54 *args,55 **kwargs56 ):57 assert not (base_url or subdomain or url_scheme) or (58 base_url is not None59 ) != bool(60 subdomain or url_scheme61 ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'6263 if base_url is None:64 http_host = app.config.get("SERVER_NAME") or "localhost"65 app_root = app.config["APPLICATION_ROOT"]6667 if subdomain:68 http_host = "{0}.{1}".format(subdomain, http_host)6970 if url_scheme is None:71 url_scheme = app.config["PREFERRED_URL_SCHEME"]7273 url = url_parse(path)74 base_url = "{scheme}://{netloc}/{path}".format(75 scheme=url.scheme or url_scheme,76 netloc=url.netloc or http_host,77 path=app_root.lstrip("/"),78 )79 path = url.path8081 if url.query:82 sep = b"?" if isinstance(url.query, bytes) else "?"83 path += sep + url.query8485 self.app = app86 super(EnvironBuilder, self).__init__(path, base_url, *args, **kwargs)8788 def json_dumps(self, obj, **kwargs):89 """Serialize ``obj`` to a JSON-formatted string.9091 The serialization will be configured according to the config associated92 with this EnvironBuilder's ``app``.93 """94 kwargs.setdefault("app", self.app)95 return json_dumps(obj, **kwargs)969798def make_test_environ_builder(*args, **kwargs):99 """Create a :class:`flask.testing.EnvironBuilder`.100101 .. deprecated: 1.1102 Will be removed in 1.2. Construct ``flask.testing.EnvironBuilder``103 directly instead.104 """105 warnings.warn(106 DeprecationWarning(107 '"make_test_environ_builder()" is deprecated and will be removed '108 'in 1.2. Construct "flask.testing.EnvironBuilder" directly '109 "instead."110 )111 )112 return EnvironBuilder(*args, **kwargs)113114115class FlaskClient(Client):116 """Works like a regular Werkzeug test client but has some knowledge about117 how Flask works to defer the cleanup of the request context stack to the118 end of a ``with`` body when used in a ``with`` statement. For general119 information about how to use this class refer to120 :class:`werkzeug.test.Client`.121122 .. versionchanged:: 0.12123 `app.test_client()` includes preset default environment, which can be124 set after instantiation of the `app.test_client()` object in125 `client.environ_base`.126127 Basic usage is outlined in the :ref:`testing` chapter.128 """129130 preserve_context = False131132 def __init__(self, *args, **kwargs):133 super(FlaskClient, self).__init__(*args, **kwargs)134 self.environ_base = {135 "REMOTE_ADDR": "127.0.0.1",136 "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,137 }138139 @contextmanager140 def session_transaction(self, *args, **kwargs):141 """When used in combination with a ``with`` statement this opens a142 session transaction. This can be used to modify the session that143 the test client uses. Once the ``with`` block is left the session is144 stored back.145146 ::147148 with client.session_transaction() as session:149 session['value'] = 42150151 Internally this is implemented by going through a temporary test152 request context and since session handling could depend on153 request variables this function accepts the same arguments as154 :meth:`~flask.Flask.test_request_context` which are directly155 passed through.156 """157 if self.cookie_jar is None:158 raise RuntimeError(159 "Session transactions only make sense " "with cookies enabled."160 )161 app = self.application162 environ_overrides = kwargs.setdefault("environ_overrides", {})163 self.cookie_jar.inject_wsgi(environ_overrides)164 outer_reqctx = _request_ctx_stack.top165 with app.test_request_context(*args, **kwargs) as c:166 session_interface = app.session_interface167 sess = session_interface.open_session(app, c.request)168 if sess is None:169 raise RuntimeError(170 "Session backend did not open a session. " "Check the configuration"171 )172173 # Since we have to open a new request context for the session174 # handling we want to make sure that we hide out own context175 # from the caller. By pushing the original request context176 # (or None) on top of this and popping it we get exactly that177 # behavior. It's important to not use the push and pop178 # methods of the actual request context object since that would179 # mean that cleanup handlers are called180 _request_ctx_stack.push(outer_reqctx)181 try:182 yield sess183 finally:184 _request_ctx_stack.pop()185186 resp = app.response_class()187 if not session_interface.is_null_session(sess):188 session_interface.save_session(app, sess, resp)189 headers = resp.get_wsgi_headers(c.request.environ)190 self.cookie_jar.extract_wsgi(c.request.environ, headers)191192 def open(self, *args, **kwargs):193 as_tuple = kwargs.pop("as_tuple", False)194 buffered = kwargs.pop("buffered", False)195 follow_redirects = kwargs.pop("follow_redirects", False)196197 if (198 not kwargs199 and len(args) == 1200 and isinstance(args[0], (werkzeug.test.EnvironBuilder, dict))201 ):202 environ = self.environ_base.copy()203204 if isinstance(args[0], werkzeug.test.EnvironBuilder):205 environ.update(args[0].get_environ())206 else:207 environ.update(args[0])208209 environ["flask._preserve_context"] = self.preserve_context210 else:211 kwargs.setdefault("environ_overrides", {})[212 "flask._preserve_context"213 ] = self.preserve_context214 kwargs.setdefault("environ_base", self.environ_base)215 builder = EnvironBuilder(self.application, *args, **kwargs)216217 try:218 environ = builder.get_environ()219 finally:220 builder.close()221222 return Client.open(223 self,224 environ,225 as_tuple=as_tuple,226 buffered=buffered,227 follow_redirects=follow_redirects,228 )229230 def __enter__(self):231 if self.preserve_context:232 raise RuntimeError("Cannot nest client invocations")233 self.preserve_context = True234 return self235236 def __exit__(self, exc_type, exc_value, tb):237 self.preserve_context = False238239 # Normally the request context is preserved until the next240 # request in the same thread comes. When the client exits we241 # want to clean up earlier. Pop request contexts until the stack242 # is empty or a non-preserved one is found.243 while True:244 top = _request_ctx_stack.top245246 if top is not None and top.preserved:247 top.pop()248 else:249 break250251252class FlaskCliRunner(CliRunner):253 """A :class:`~click.testing.CliRunner` for testing a Flask app's254 CLI commands. Typically created using255 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.256 """257258 def __init__(self, app, **kwargs):259 self.app = app260 super(FlaskCliRunner, self).__init__(**kwargs)261262 def invoke(self, cli=None, args=None, **kwargs):263 """Invokes a CLI command in an isolated environment. See264 :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for265 full method documentation. See :ref:`testing-cli` for examples.266267 If the ``obj`` argument is not given, passes an instance of268 :class:`~flask.cli.ScriptInfo` that knows how to load the Flask269 app being tested.270271 :param cli: Command object to invoke. Default is the app's272 :attr:`~flask.app.Flask.cli` group.273 :param args: List of strings to invoke the command with.274275 :return: a :class:`~click.testing.Result` object.276 """277 if cli is None:278 cli = self.app.cli279280 if "obj" not in kwargs:281 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)282283 return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)
added:src/flask/views.py+164 added
1# -*- coding: utf-8 -*-2"""3 flask.views4 ~~~~~~~~~~~56 This module provides class-based views inspired by the ones in Django.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from .globals import request13from ._compat import with_metaclass141516http_method_funcs = frozenset(17 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]18)192021class View(object):22 """Alternative way to use view functions. A subclass has to implement23 :meth:`dispatch_request` which is called with the view arguments from24 the URL routing system. If :attr:`methods` is provided the methods25 do not have to be passed to the :meth:`~flask.Flask.add_url_rule`26 method explicitly::2728 class MyView(View):29 methods = ['GET']3031 def dispatch_request(self, name):32 return 'Hello %s!' % name3334 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))3536 When you want to decorate a pluggable view you will have to either do that37 when the view function is created (by wrapping the return value of38 :meth:`as_view`) or you can use the :attr:`decorators` attribute::3940 class SecretView(View):41 methods = ['GET']42 decorators = [superuser_required]4344 def dispatch_request(self):45 ...4647 The decorators stored in the decorators list are applied one after another48 when the view function is created. Note that you can *not* use the class49 based decorators since those would decorate the view class and not the50 generated view function!51 """5253 #: A list of methods this view can handle.54 methods = None5556 #: Setting this disables or force-enables the automatic options handling.57 provide_automatic_options = None5859 #: The canonical way to decorate class-based views is to decorate the60 #: return value of as_view(). However since this moves parts of the61 #: logic from the class declaration to the place where it's hooked62 #: into the routing system.63 #:64 #: You can place one or more decorators in this list and whenever the65 #: view function is created the result is automatically decorated.66 #:67 #: .. versionadded:: 0.868 decorators = ()6970 def dispatch_request(self):71 """Subclasses have to override this method to implement the72 actual view function code. This method is called with all73 the arguments from the URL rule.74 """75 raise NotImplementedError()7677 @classmethod78 def as_view(cls, name, *class_args, **class_kwargs):79 """Converts the class into an actual view function that can be used80 with the routing system. Internally this generates a function on the81 fly which will instantiate the :class:`View` on each request and call82 the :meth:`dispatch_request` method on it.8384 The arguments passed to :meth:`as_view` are forwarded to the85 constructor of the class.86 """8788 def view(*args, **kwargs):89 self = view.view_class(*class_args, **class_kwargs)90 return self.dispatch_request(*args, **kwargs)9192 if cls.decorators:93 view.__name__ = name94 view.__module__ = cls.__module__95 for decorator in cls.decorators:96 view = decorator(view)9798 # We attach the view class to the view function for two reasons:99 # first of all it allows us to easily figure out what class-based100 # view this thing came from, secondly it's also used for instantiating101 # the view class so you can actually replace it with something else102 # for testing purposes and debugging.103 view.view_class = cls104 view.__name__ = name105 view.__doc__ = cls.__doc__106 view.__module__ = cls.__module__107 view.methods = cls.methods108 view.provide_automatic_options = cls.provide_automatic_options109 return view110111112class MethodViewType(type):113 """Metaclass for :class:`MethodView` that determines what methods the view114 defines.115 """116117 def __init__(cls, name, bases, d):118 super(MethodViewType, cls).__init__(name, bases, d)119120 if "methods" not in d:121 methods = set()122123 for base in bases:124 if getattr(base, "methods", None):125 methods.update(base.methods)126127 for key in http_method_funcs:128 if hasattr(cls, key):129 methods.add(key.upper())130131 # If we have no method at all in there we don't want to add a132 # method list. This is for instance the case for the base class133 # or another subclass of a base method view that does not introduce134 # new methods.135 if methods:136 cls.methods = methods137138139class MethodView(with_metaclass(MethodViewType, View)):140 """A class-based view that dispatches request methods to the corresponding141 class methods. For example, if you implement a ``get`` method, it will be142 used to handle ``GET`` requests. ::143144 class CounterAPI(MethodView):145 def get(self):146 return session.get('counter', 0)147148 def post(self):149 session['counter'] = session.get('counter', 0) + 1150 return 'OK'151152 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))153 """154155 def dispatch_request(self, *args, **kwargs):156 meth = getattr(self, request.method.lower(), None)157158 # If the request method is HEAD and we don't have a handler for it159 # retry with GET.160 if meth is None and request.method == "HEAD":161 meth = getattr(self, "get", None)162163 assert meth is not None, "Unimplemented method %r" % request.method164 return meth(*args, **kwargs)
added:src/flask/wrappers.py+137 added
1# -*- coding: utf-8 -*-2"""3 flask.wrappers4 ~~~~~~~~~~~~~~56 Implements the WSGI wrappers (request and response).78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from werkzeug.exceptions import BadRequest13from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase14from werkzeug.wrappers.json import JSONMixin as _JSONMixin1516from flask import json17from flask.globals import current_app181920class JSONMixin(_JSONMixin):21 json_module = json2223 def on_json_loading_failed(self, e):24 if current_app and current_app.debug:25 raise BadRequest("Failed to decode JSON object: {0}".format(e))2627 raise BadRequest()282930class Request(RequestBase, JSONMixin):31 """The request object used by default in Flask. Remembers the32 matched endpoint and view arguments.3334 It is what ends up as :class:`~flask.request`. If you want to replace35 the request object used you can subclass this and set36 :attr:`~flask.Flask.request_class` to your subclass.3738 The request object is a :class:`~werkzeug.wrappers.Request` subclass and39 provides all of the attributes Werkzeug defines plus a few Flask40 specific ones.41 """4243 #: The internal URL rule that matched the request. This can be44 #: useful to inspect which methods are allowed for the URL from45 #: a before/after handler (``request.url_rule.methods``) etc.46 #: Though if the request's method was invalid for the URL rule,47 #: the valid list is available in ``routing_exception.valid_methods``48 #: instead (an attribute of the Werkzeug exception49 #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)50 #: because the request was never internally bound.51 #:52 #: .. versionadded:: 0.653 url_rule = None5455 #: A dict of view arguments that matched the request. If an exception56 #: happened when matching, this will be ``None``.57 view_args = None5859 #: If matching the URL failed, this is the exception that will be60 #: raised / was raised as part of the request handling. This is61 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or62 #: something similar.63 routing_exception = None6465 @property66 def max_content_length(self):67 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""68 if current_app:69 return current_app.config["MAX_CONTENT_LENGTH"]7071 @property72 def endpoint(self):73 """The endpoint that matched the request. This in combination with74 :attr:`view_args` can be used to reconstruct the same or a75 modified URL. If an exception happened when matching, this will76 be ``None``.77 """78 if self.url_rule is not None:79 return self.url_rule.endpoint8081 @property82 def blueprint(self):83 """The name of the current blueprint"""84 if self.url_rule and "." in self.url_rule.endpoint:85 return self.url_rule.endpoint.rsplit(".", 1)[0]8687 def _load_form_data(self):88 RequestBase._load_form_data(self)8990 # In debug mode we're replacing the files multidict with an ad-hoc91 # subclass that raises a different error for key errors.92 if (93 current_app94 and current_app.debug95 and self.mimetype != "multipart/form-data"96 and not self.files97 ):98 from .debughelpers import attach_enctype_error_multidict99100 attach_enctype_error_multidict(self)101102103class Response(ResponseBase, JSONMixin):104 """The response object that is used by default in Flask. Works like the105 response object from Werkzeug but is set to have an HTML mimetype by106 default. Quite often you don't have to create this object yourself because107 :meth:`~flask.Flask.make_response` will take care of that for you.108109 If you want to replace the response object used you can subclass this and110 set :attr:`~flask.Flask.response_class` to your subclass.111112 .. versionchanged:: 1.0113 JSON support is added to the response, like the request. This is useful114 when testing to get the test client response data as JSON.115116 .. versionchanged:: 1.0117118 Added :attr:`max_cookie_size`.119 """120121 default_mimetype = "text/html"122123 def _get_data_for_json(self, cache):124 return self.get_data()125126 @property127 def max_cookie_size(self):128 """Read-only view of the :data:`MAX_COOKIE_SIZE` config key.129130 See :attr:`~werkzeug.wrappers.BaseResponse.max_cookie_size` in131 Werkzeug's docs.132 """133 if current_app:134 return current_app.config["MAX_COOKIE_SIZE"]135136 # return Werkzeug's default when not in an app context137 return super(Response, self).max_cookie_size
modified:setup.cfg+2 added-2 removed
17 unmodified lines
18 tests1920[coverage:paths]21source =22 flask22 src/flask23 .tox/*/lib/python*/site-packages/flask24 .tox/pypy/site-packages/flask2526[flake8]
18 unmodified lines
45max-line-length = 8046per-file-ignores =47 # __init__ modules export names48 **/__init__.py: F40149 **/_compat.py: E731, B301, F40149 src/flask/_compat.py: E731, B301, F401
modified:setup.py+4 added-2 removed
2 unmodified lines
3import io4import re5from collections import OrderedDict67from setuptools import find_packages8from setuptools import setup910with io.open("README.rst", "rt", encoding="utf8") as f:11 readme = f.read()1212with io.open("flask/__init__.py", "rt", encoding="utf8") as f:13with io.open("src/flask/__init__.py", "rt", encoding="utf8") as f:14 version = re.search(r"__version__ = \"(.*?)\"", f.read()).group(1)1516setup(17 name="Flask",
12 unmodified lines
30 maintainer="Pallets team",31 maintainer_email="contact@palletsprojects.com",32 description="A simple framework for building complex web applications.",33 long_description=readme,33 packages=["flask", "flask.json"],34 packages=find_packages("src"),35 package_dir={"": "src"},36 include_package_data=True,37 zip_safe=False,38 platforms="any",39 python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",
41 unmodified lines