· 9 years ago · Oct 05, 2016, 11:24 PM
1# -*- coding: utf-8 -*-
2"""
3 flask.app
4 ~~~~~~~~~
5
6 This module implements the central WSGI application object.
7
8 :copyright: (c) 2015 by Armin Ronacher.
9 :license: BSD, see LICENSE for more details.
10"""
11import os
12import sys
13from threading import Lock
14from datetime import timedelta
15from itertools import chain
16from functools import update_wrapper
17from collections import deque
18
19from werkzeug.datastructures import ImmutableDict
20from werkzeug.routing import Map, Rule, RequestRedirect, BuildError
21from werkzeug.exceptions import HTTPException, InternalServerError, \
22 MethodNotAllowed, BadRequest, default_exceptions
23
24from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \
25 locked_cached_property, _endpoint_from_view_func, find_package, \
26 get_debug_flag
27from . import json, cli
28from .wrappers import Request, Response
29from .config import ConfigAttribute, Config
30from .ctx import RequestContext, AppContext, _AppCtxGlobals
31from .globals import _request_ctx_stack, request, session, g
32from .sessions import SecureCookieSessionInterface
33from .templating import DispatchingJinjaLoader, Environment, \
34 _default_template_ctx_processor
35from .signals import request_started, request_finished, got_request_exception, \
36 request_tearing_down, appcontext_tearing_down
37from ._compat import reraise, string_types, text_type, integer_types
38
39# a lock used for logger initialization
40_logger_lock = Lock()
41
42# a singleton sentinel value for parameter defaults
43_sentinel = object()
44
45
46def _make_timedelta(value):
47 if not isinstance(value, timedelta):
48 return timedelta(seconds=value)
49 return value
50
51
52def setupmethod(f):
53 """Wraps a method so that it performs a check in debug mode if the
54 first request was already handled.
55 """
56 def wrapper_func(self, *args, **kwargs):
57 if self.debug and self._got_first_request:
58 raise AssertionError('A setup function was called after the '
59 'first request was handled. This usually indicates a bug '
60 'in the application where a module was not imported '
61 'and decorators or other functionality was called too late.\n'
62 'To fix this make sure to import all your view modules, '
63 'database models and everything related at a central place '
64 'before the application starts serving requests.')
65 return f(self, *args, **kwargs)
66 return update_wrapper(wrapper_func, f)
67
68
69class Flask(_PackageBoundObject):
70 """The flask object implements a WSGI application and acts as the central
71 object. It is passed the name of the module or package of the
72 application. Once it is created it will act as a central registry for
73 the view functions, the URL rules, template configuration and much more.
74
75 The name of the package is used to resolve resources from inside the
76 package or the folder the module is contained in depending on if the
77 package parameter resolves to an actual python package (a folder with
78 an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
79
80 For more information about resource loading, see :func:`open_resource`.
81
82 Usually you create a :class:`Flask` instance in your main module or
83 in the :file:`__init__.py` file of your package like this::
84
85 from flask import Flask
86 app = Flask(__name__)
87
88 .. admonition:: About the First Parameter
89
90 The idea of the first parameter is to give Flask an idea of what
91 belongs to your application. This name is used to find resources
92 on the filesystem, can be used by extensions to improve debugging
93 information and a lot more.
94
95 So it's important what you provide there. If you are using a single
96 module, `__name__` is always the correct value. If you however are
97 using a package, it's usually recommended to hardcode the name of
98 your package there.
99
100 For example if your application is defined in :file:`yourapplication/app.py`
101 you should create it with one of the two versions below::
102
103 app = Flask('yourapplication')
104 app = Flask(__name__.split('.')[0])
105
106 Why is that? The application will work even with `__name__`, thanks
107 to how resources are looked up. However it will make debugging more
108 painful. Certain extensions can make assumptions based on the
109 import name of your application. For example the Flask-SQLAlchemy
110 extension will look for the code in your application that triggered
111 an SQL query in debug mode. If the import name is not properly set
112 up, that debugging information is lost. (For example it would only
113 pick up SQL queries in `yourapplication.app` and not
114 `yourapplication.views.frontend`)
115
116 .. versionadded:: 0.7
117 The `static_url_path`, `static_folder`, and `template_folder`
118 parameters were added.
119
120 .. versionadded:: 0.8
121 The `instance_path` and `instance_relative_config` parameters were
122 added.
123
124 .. versionadded:: 0.11
125 The `root_path` parameter was added.
126
127 :param import_name: the name of the application package
128 :param static_url_path: can be used to specify a different path for the
129 static files on the web. Defaults to the name
130 of the `static_folder` folder.
131 :param static_folder: the folder with static files that should be served
132 at `static_url_path`. Defaults to the ``'static'``
133 folder in the root path of the application.
134 :param template_folder: the folder that contains the templates that should
135 be used by the application. Defaults to
136 ``'templates'`` folder in the root path of the
137 application.
138 :param instance_path: An alternative instance path for the application.
139 By default the folder ``'instance'`` next to the
140 package or module is assumed to be the instance
141 path.
142 :param instance_relative_config: if set to ``True`` relative filenames
143 for loading the config are assumed to
144 be relative to the instance path instead
145 of the application root.
146 :param root_path: Flask by default will automatically calculate the path
147 to the root of the application. In certain situations
148 this cannot be achieved (for instance if the package
149 is a Python 3 namespace package) and needs to be
150 manually defined.
151 """
152
153 #: The class that is used for request objects. See :class:`~flask.Request`
154 #: for more information.
155 request_class = Request
156
157 #: The class that is used for response objects. See
158 #: :class:`~flask.Response` for more information.
159 response_class = Response
160
161 #: The class that is used for the Jinja environment.
162 #:
163 #: .. versionadded:: 0.11
164 jinja_environment = Environment
165
166 #: The class that is used for the :data:`~flask.g` instance.
167 #:
168 #: Example use cases for a custom class:
169 #:
170 #: 1. Store arbitrary attributes on flask.g.
171 #: 2. Add a property for lazy per-request database connectors.
172 #: 3. Return None instead of AttributeError on unexpected attributes.
173 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
174 #:
175 #: In Flask 0.9 this property was called `request_globals_class` but it
176 #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
177 #: flask.g object is now application context scoped.
178 #:
179 #: .. versionadded:: 0.10
180 app_ctx_globals_class = _AppCtxGlobals
181
182 # Backwards compatibility support
183 def _get_request_globals_class(self):
184 return self.app_ctx_globals_class
185 def _set_request_globals_class(self, value):
186 from warnings import warn
187 warn(DeprecationWarning('request_globals_class attribute is now '
188 'called app_ctx_globals_class'))
189 self.app_ctx_globals_class = value
190 request_globals_class = property(_get_request_globals_class,
191 _set_request_globals_class)
192 del _get_request_globals_class, _set_request_globals_class
193
194 #: The class that is used for the ``config`` attribute of this app.
195 #: Defaults to :class:`~flask.Config`.
196 #:
197 #: Example use cases for a custom class:
198 #:
199 #: 1. Default values for certain config options.
200 #: 2. Access to config values through attributes in addition to keys.
201 #:
202 #: .. versionadded:: 0.11
203 config_class = Config
204
205 #: The debug flag. Set this to ``True`` to enable debugging of the
206 #: application. In debug mode the debugger will kick in when an unhandled
207 #: exception occurs and the integrated server will automatically reload
208 #: the application if changes in the code are detected.
209 #:
210 #: This attribute can also be configured from the config with the ``DEBUG``
211 #: configuration key. Defaults to ``False``.
212 debug = ConfigAttribute('DEBUG')
213
214 #: The testing flag. Set this to ``True`` to enable the test mode of
215 #: Flask extensions (and in the future probably also Flask itself).
216 #: For example this might activate unittest helpers that have an
217 #: additional runtime cost which should not be enabled by default.
218 #:
219 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
220 #: default it's implicitly enabled.
221 #:
222 #: This attribute can also be configured from the config with the
223 #: ``TESTING`` configuration key. Defaults to ``False``.
224 testing = ConfigAttribute('TESTING')
225
226 #: If a secret key is set, cryptographic components can use this to
227 #: sign cookies and other things. Set this to a complex random value
228 #: when you want to use the secure cookie for instance.
229 #:
230 #: This attribute can also be configured from the config with the
231 #: ``SECRET_KEY`` configuration key. Defaults to ``None``.
232 secret_key = ConfigAttribute('SECRET_KEY')
233
234 #: The secure cookie uses this for the name of the session cookie.
235 #:
236 #: This attribute can also be configured from the config with the
237 #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``
238 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')
239
240 #: A :class:`~datetime.timedelta` which is used to set the expiration
241 #: date of a permanent session. The default is 31 days which makes a
242 #: permanent session survive for roughly one month.
243 #:
244 #: This attribute can also be configured from the config with the
245 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
246 #: ``timedelta(days=31)``
247 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',
248 get_converter=_make_timedelta)
249
250 #: A :class:`~datetime.timedelta` which is used as default cache_timeout
251 #: for the :func:`send_file` functions. The default is 12 hours.
252 #:
253 #: This attribute can also be configured from the config with the
254 #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration
255 #: variable can also be set with an integer value used as seconds.
256 #: Defaults to ``timedelta(hours=12)``
257 send_file_max_age_default = ConfigAttribute('SEND_FILE_MAX_AGE_DEFAULT',
258 get_converter=_make_timedelta)
259
260 #: Enable this if you want to use the X-Sendfile feature. Keep in
261 #: mind that the server has to support this. This only affects files
262 #: sent with the :func:`send_file` method.
263 #:
264 #: .. versionadded:: 0.2
265 #:
266 #: This attribute can also be configured from the config with the
267 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.
268 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')
269
270 #: The name of the logger to use. By default the logger name is the
271 #: package name passed to the constructor.
272 #:
273 #: .. versionadded:: 0.4
274 logger_name = ConfigAttribute('LOGGER_NAME')
275
276 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.
277 #:
278 #: .. versionadded:: 0.10
279 json_encoder = json.JSONEncoder
280
281 #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.
282 #:
283 #: .. versionadded:: 0.10
284 json_decoder = json.JSONDecoder
285
286 #: Options that are passed directly to the Jinja2 environment.
287 jinja_options = ImmutableDict(
288 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']
289 )
290
291 #: Default configuration parameters.
292 default_config = ImmutableDict({
293 'DEBUG': get_debug_flag(default=False),
294 'TESTING': False,
295 'PROPAGATE_EXCEPTIONS': None,
296 'PRESERVE_CONTEXT_ON_EXCEPTION': None,
297 'SECRET_KEY': None,
298 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
299 'USE_X_SENDFILE': False,
300 'LOGGER_NAME': None,
301 'LOGGER_HANDLER_POLICY': 'always',
302 'SERVER_NAME': None,
303 'APPLICATION_ROOT': None,
304 'SESSION_COOKIE_NAME': 'session',
305 'SESSION_COOKIE_DOMAIN': None,
306 'SESSION_COOKIE_PATH': None,
307 'SESSION_COOKIE_HTTPONLY': True,
308 'SESSION_COOKIE_SECURE': False,
309 'SESSION_REFRESH_EACH_REQUEST': True,
310 'MAX_CONTENT_LENGTH': None,
311 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
312 'TRAP_BAD_REQUEST_ERRORS': False,
313 'TRAP_HTTP_EXCEPTIONS': False,
314 'EXPLAIN_TEMPLATE_LOADING': False,
315 'PREFERRED_URL_SCHEME': 'http',
316 'JSON_AS_ASCII': True,
317 'JSON_SORT_KEYS': True,
318 'JSONIFY_PRETTYPRINT_REGULAR': True,
319 'JSONIFY_MIMETYPE': 'application/json',
320 'TEMPLATES_AUTO_RELOAD': None,
321 })
322
323 #: The rule object to use for URL rules created. This is used by
324 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
325 #:
326 #: .. versionadded:: 0.7
327 url_rule_class = Rule
328
329 #: the test client that is used with when `test_client` is used.
330 #:
331 #: .. versionadded:: 0.7
332 test_client_class = None
333
334 #: the session interface to use. By default an instance of
335 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
336 #:
337 #: .. versionadded:: 0.8
338 session_interface = SecureCookieSessionInterface()
339
340 def __init__(self, import_name, static_path=None, static_url_path=None,
341 static_folder='static', template_folder='templates',
342 instance_path=None, instance_relative_config=False,
343 root_path=None):
344 _PackageBoundObject.__init__(self, import_name,
345 template_folder=template_folder,
346 root_path=root_path)
347 if static_path is not None:
348 from warnings import warn
349 warn(DeprecationWarning('static_path is now called '
350 'static_url_path'), stacklevel=2)
351 static_url_path = static_path
352
353 if static_url_path is not None:
354 self.static_url_path = static_url_path
355 if static_folder is not None:
356 self.static_folder = static_folder
357 if instance_path is None:
358 instance_path = self.auto_find_instance_path()
359 elif not os.path.isabs(instance_path):
360 raise ValueError('If an instance path is provided it must be '
361 'absolute. A relative path was given instead.')
362
363 #: Holds the path to the instance folder.
364 #:
365 #: .. versionadded:: 0.8
366 self.instance_path = instance_path
367
368 #: The configuration dictionary as :class:`Config`. This behaves
369 #: exactly like a regular dictionary but supports additional methods
370 #: to load a config from files.
371 self.config = self.make_config(instance_relative_config)
372
373 # Prepare the deferred setup of the logger.
374 self._logger = None
375 self.logger_name = self.import_name
376
377 #: A dictionary of all view functions registered. The keys will
378 #: be function names which are also used to generate URLs and
379 #: the values are the function objects themselves.
380 #: To register a view function, use the :meth:`route` decorator.
381 self.view_functions = {}
382
383 # support for the now deprecated `error_handlers` attribute. The
384 # :attr:`error_handler_spec` shall be used now.
385 self._error_handlers = {}
386
387 #: A dictionary of all registered error handlers. The key is ``None``
388 #: for error handlers active on the application, otherwise the key is
389 #: the name of the blueprint. Each key points to another dictionary
390 #: where the key is the status code of the http exception. The
391 #: special key ``None`` points to a list of tuples where the first item
392 #: is the class for the instance check and the second the error handler
393 #: function.
394 #:
395 #: To register a error handler, use the :meth:`errorhandler`
396 #: decorator.
397 self.error_handler_spec = {None: self._error_handlers}
398
399 #: A list of functions that are called when :meth:`url_for` raises a
400 #: :exc:`~werkzeug.routing.BuildError`. Each function registered here
401 #: is called with `error`, `endpoint` and `values`. If a function
402 #: returns ``None`` or raises a :exc:`BuildError` the next function is
403 #: tried.
404 #:
405 #: .. versionadded:: 0.9
406 self.url_build_error_handlers = []
407
408 #: A dictionary with lists of functions that should be called at the
409 #: beginning of the request. The key of the dictionary is the name of
410 #: the blueprint this function is active for, ``None`` for all requests.
411 #: This can for example be used to open database connections or
412 #: getting hold of the currently logged in user. To register a
413 #: function here, use the :meth:`before_request` decorator.
414 self.before_request_funcs = {}
415
416 #: A lists of functions that should be called at the beginning of the
417 #: first request to this instance. To register a function here, use
418 #: the :meth:`before_first_request` decorator.
419 #:
420 #: .. versionadded:: 0.8
421 self.before_first_request_funcs = []
422
423 #: A dictionary with lists of functions that should be called after
424 #: each request. The key of the dictionary is the name of the blueprint
425 #: this function is active for, ``None`` for all requests. This can for
426 #: example be used to close database connections. To register a function
427 #: here, use the :meth:`after_request` decorator.
428 self.after_request_funcs = {}
429
430 #: A dictionary with lists of functions that are called after
431 #: each request, even if an exception has occurred. The key of the
432 #: dictionary is the name of the blueprint this function is active for,
433 #: ``None`` for all requests. These functions are not allowed to modify
434 #: the request, and their return values are ignored. If an exception
435 #: occurred while processing the request, it gets passed to each
436 #: teardown_request function. To register a function here, use the
437 #: :meth:`teardown_request` decorator.
438 #:
439 #: .. versionadded:: 0.7
440 self.teardown_request_funcs = {}
441
442 #: A list of functions that are called when the application context
443 #: is destroyed. Since the application context is also torn down
444 #: if the request ends this is the place to store code that disconnects
445 #: from databases.
446 #:
447 #: .. versionadded:: 0.9
448 self.teardown_appcontext_funcs = []
449
450 #: A dictionary with lists of functions that can be used as URL
451 #: value processor functions. Whenever a URL is built these functions
452 #: are called to modify the dictionary of values in place. The key
453 #: ``None`` here is used for application wide
454 #: callbacks, otherwise the key is the name of the blueprint.
455 #: Each of these functions has the chance to modify the dictionary
456 #:
457 #: .. versionadded:: 0.7
458 self.url_value_preprocessors = {}
459
460 #: A dictionary with lists of functions that can be used as URL value
461 #: preprocessors. The key ``None`` here is used for application wide
462 #: callbacks, otherwise the key is the name of the blueprint.
463 #: Each of these functions has the chance to modify the dictionary
464 #: of URL values before they are used as the keyword arguments of the
465 #: view function. For each function registered this one should also
466 #: provide a :meth:`url_defaults` function that adds the parameters
467 #: automatically again that were removed that way.
468 #:
469 #: .. versionadded:: 0.7
470 self.url_default_functions = {}
471
472 #: A dictionary with list of functions that are called without argument
473 #: to populate the template context. The key of the dictionary is the
474 #: name of the blueprint this function is active for, ``None`` for all
475 #: requests. Each returns a dictionary that the template context is
476 #: updated with. To register a function here, use the
477 #: :meth:`context_processor` decorator.
478 self.template_context_processors = {
479 None: [_default_template_ctx_processor]
480 }
481
482 #: A list of shell context processor functions that should be run
483 #: when a shell context is created.
484 #:
485 #: .. versionadded:: 0.11
486 self.shell_context_processors = []
487
488 #: all the attached blueprints in a dictionary by name. Blueprints
489 #: can be attached multiple times so this dictionary does not tell
490 #: you how often they got attached.
491 #:
492 #: .. versionadded:: 0.7
493 self.blueprints = {}
494 self._blueprint_order = []
495
496 #: a place where extensions can store application specific state. For
497 #: example this is where an extension could store database engines and
498 #: similar things. For backwards compatibility extensions should register
499 #: themselves like this::
500 #:
501 #: if not hasattr(app, 'extensions'):
502 #: app.extensions = {}
503 #: app.extensions['extensionname'] = SomeObject()
504 #:
505 #: The key must match the name of the extension module. For example in
506 #: case of a "Flask-Foo" extension in `flask_foo`, the key would be
507 #: ``'foo'``.
508 #:
509 #: .. versionadded:: 0.7
510 self.extensions = {}
511
512 #: The :class:`~werkzeug.routing.Map` for this instance. You can use
513 #: this to change the routing converters after the class was created
514 #: but before any routes are connected. Example::
515 #:
516 #: from werkzeug.routing import BaseConverter
517 #:
518 #: class ListConverter(BaseConverter):
519 #: def to_python(self, value):
520 #: return value.split(',')
521 #: def to_url(self, values):
522 #: return ','.join(BaseConverter.to_url(value)
523 #: for value in values)
524 #:
525 #: app = Flask(__name__)
526 #: app.url_map.converters['list'] = ListConverter
527 self.url_map = Map()
528
529 # tracks internally if the application already handled at least one
530 # request.
531 self._got_first_request = False
532 self._before_request_lock = Lock()
533
534 # register the static folder for the application. Do that even
535 # if the folder does not exist. First of all it might be created
536 # while the server is running (usually happens during development)
537 # but also because google appengine stores static files somewhere
538 # else when mapped with the .yml file.
539 if self.has_static_folder:
540 self.add_url_rule(self.static_url_path + '/<path:filename>',
541 endpoint='static',
542 view_func=self.send_static_file)
543
544 #: The click command line context for this application. Commands
545 #: registered here show up in the :command:`flask` command once the
546 #: application has been discovered. The default commands are
547 #: provided by Flask itself and can be overridden.
548 #:
549 #: This is an instance of a :class:`click.Group` object.
550 self.cli = cli.AppGroup(self.name)
551
552 def _get_error_handlers(self):
553 from warnings import warn
554 warn(DeprecationWarning('error_handlers is deprecated, use the '
555 'new error_handler_spec attribute instead.'), stacklevel=1)
556 return self._error_handlers
557 def _set_error_handlers(self, value):
558 self._error_handlers = value
559 self.error_handler_spec[None] = value
560 error_handlers = property(_get_error_handlers, _set_error_handlers)
561 del _get_error_handlers, _set_error_handlers
562
563 @locked_cached_property
564 def name(self):
565 """The name of the application. This is usually the import name
566 with the difference that it's guessed from the run file if the
567 import name is main. This name is used as a display name when
568 Flask needs the name of the application. It can be set and overridden
569 to change the value.
570
571 .. versionadded:: 0.8
572 """
573 if self.import_name == '__main__':
574 fn = getattr(sys.modules['__main__'], '__file__', None)
575 if fn is None:
576 return '__main__'
577 return os.path.splitext(os.path.basename(fn))[0]
578 return self.import_name
579
580 @property
581 def propagate_exceptions(self):
582 """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration
583 value in case it's set, otherwise a sensible default is returned.
584
585 .. versionadded:: 0.7
586 """
587 rv = self.config['PROPAGATE_EXCEPTIONS']
588 if rv is not None:
589 return rv
590 return self.testing or self.debug
591
592 @property
593 def preserve_context_on_exception(self):
594 """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``
595 configuration value in case it's set, otherwise a sensible default
596 is returned.
597
598 .. versionadded:: 0.7
599 """
600 rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']
601 if rv is not None:
602 return rv
603 return self.debug
604
605 @property
606 def logger(self):
607 """A :class:`logging.Logger` object for this application. The
608 default configuration is to log to stderr if the application is
609 in debug mode. This logger can be used to (surprise) log messages.
610 Here some examples::
611
612 app.logger.debug('A value for debugging')
613 app.logger.warning('A warning occurred (%d apples)', 42)
614 app.logger.error('An error occurred')
615
616 .. versionadded:: 0.3
617 """
618 if self._logger and self._logger.name == self.logger_name:
619 return self._logger
620 with _logger_lock:
621 if self._logger and self._logger.name == self.logger_name:
622 return self._logger
623 from flask.logging import create_logger
624 self._logger = rv = create_logger(self)
625 return rv
626
627 @locked_cached_property
628 def jinja_env(self):
629 """The Jinja2 environment used to load templates."""
630 return self.create_jinja_environment()
631
632 @property
633 def got_first_request(self):
634 """This attribute is set to ``True`` if the application started
635 handling the first request.
636
637 .. versionadded:: 0.8
638 """
639 return self._got_first_request
640
641 def make_config(self, instance_relative=False):
642 """Used to create the config attribute by the Flask constructor.
643 The `instance_relative` parameter is passed in from the constructor
644 of Flask (there named `instance_relative_config`) and indicates if
645 the config should be relative to the instance path or the root path
646 of the application.
647
648 .. versionadded:: 0.8
649 """
650 root_path = self.root_path
651 if instance_relative:
652 root_path = self.instance_path
653 return self.config_class(root_path, self.default_config)
654
655 def auto_find_instance_path(self):
656 """Tries to locate the instance path if it was not provided to the
657 constructor of the application class. It will basically calculate
658 the path to a folder named ``instance`` next to your main file or
659 the package.
660
661 .. versionadded:: 0.8
662 """
663 prefix, package_path = find_package(self.import_name)
664 if prefix is None:
665 return os.path.join(package_path, 'instance')
666 return os.path.join(prefix, 'var', self.name + '-instance')
667
668 def open_instance_resource(self, resource, mode='rb'):
669 """Opens a resource from the application's instance folder
670 (:attr:`instance_path`). Otherwise works like
671 :meth:`open_resource`. Instance resources can also be opened for
672 writing.
673
674 :param resource: the name of the resource. To access resources within
675 subfolders use forward slashes as separator.
676 :param mode: resource file opening mode, default is 'rb'.
677 """
678 return open(os.path.join(self.instance_path, resource), mode)
679
680 def create_jinja_environment(self):
681 """Creates the Jinja2 environment based on :attr:`jinja_options`
682 and :meth:`select_jinja_autoescape`. Since 0.7 this also adds
683 the Jinja2 globals and filters after initialization. Override
684 this function to customize the behavior.
685
686 .. versionadded:: 0.5
687 .. versionchanged:: 0.11
688 ``Environment.auto_reload`` set in accordance with
689 ``TEMPLATES_AUTO_RELOAD`` configuration option.
690 """
691 options = dict(self.jinja_options)
692 if 'autoescape' not in options:
693 options['autoescape'] = self.select_jinja_autoescape
694 if 'auto_reload' not in options:
695 if self.config['TEMPLATES_AUTO_RELOAD'] is not None:
696 options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD']
697 else:
698 options['auto_reload'] = self.debug
699 rv = self.jinja_environment(self, **options)
700 rv.globals.update(
701 url_for=url_for,
702 get_flashed_messages=get_flashed_messages,
703 config=self.config,
704 # request, session and g are normally added with the
705 # context processor for efficiency reasons but for imported
706 # templates we also want the proxies in there.
707 request=request,
708 session=session,
709 g=g
710 )
711 rv.filters['tojson'] = json.tojson_filter
712 return rv
713
714 def create_global_jinja_loader(self):
715 """Creates the loader for the Jinja2 environment. Can be used to
716 override just the loader and keeping the rest unchanged. It's
717 discouraged to override this function. Instead one should override
718 the :meth:`jinja_loader` function instead.
719
720 The global loader dispatches between the loaders of the application
721 and the individual blueprints.
722
723 .. versionadded:: 0.7
724 """
725 return DispatchingJinjaLoader(self)
726
727 def init_jinja_globals(self):
728 """Deprecated. Used to initialize the Jinja2 globals.
729
730 .. versionadded:: 0.5
731 .. versionchanged:: 0.7
732 This method is deprecated with 0.7. Override
733 :meth:`create_jinja_environment` instead.
734 """
735
736 def select_jinja_autoescape(self, filename):
737 """Returns ``True`` if autoescaping should be active for the given
738 template name. If no template name is given, returns `True`.
739
740 .. versionadded:: 0.5
741 """
742 if filename is None:
743 return True
744 return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))
745
746 def update_template_context(self, context):
747 """Update the template context with some commonly used variables.
748 This injects request, session, config and g into the template
749 context as well as everything template context processors want
750 to inject. Note that the as of Flask 0.6, the original values
751 in the context will not be overridden if a context processor
752 decides to return a value with the same key.
753
754 :param context: the context as a dictionary that is updated in place
755 to add extra variables.
756 """
757 funcs = self.template_context_processors[None]
758 reqctx = _request_ctx_stack.top
759 if reqctx is not None:
760 bp = reqctx.request.blueprint
761 if bp is not None and bp in self.template_context_processors:
762 funcs = chain(funcs, self.template_context_processors[bp])
763 orig_ctx = context.copy()
764 for func in funcs:
765 context.update(func())
766 # make sure the original values win. This makes it possible to
767 # easier add new variables in context processors without breaking
768 # existing views.
769 context.update(orig_ctx)
770
771 def make_shell_context(self):
772 """Returns the shell context for an interactive shell for this
773 application. This runs all the registered shell context
774 processors.
775
776 .. versionadded:: 0.11
777 """
778 rv = {'app': self, 'g': g}
779 for processor in self.shell_context_processors:
780 rv.update(processor())
781 return rv
782
783 def run(self, host=None, port=None, debug=None, **options):
784 """Runs the application on a local development server.
785
786 Do not use ``run()`` in a production setting. It is not intended to
787 meet security and performance requirements for a production server.
788 Instead, see :ref:`deployment` for WSGI server recommendations.
789
790 If the :attr:`debug` flag is set the server will automatically reload
791 for code changes and show a debugger in case an exception happened.
792
793 If you want to run the application in debug mode, but disable the
794 code execution on the interactive debugger, you can pass
795 ``use_evalex=False`` as parameter. This will keep the debugger's
796 traceback screen active, but disable code execution.
797
798 It is not recommended to use this function for development with
799 automatic reloading as this is badly supported. Instead you should
800 be using the :command:`flask` command line script's ``run`` support.
801
802 .. admonition:: Keep in Mind
803
804 Flask will suppress any server error with a generic error page
805 unless it is in debug mode. As such to enable just the
806 interactive debugger without the code reloading, you have to
807 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
808 Setting ``use_debugger`` to ``True`` without being in debug mode
809 won't catch any exceptions because there won't be any to
810 catch.
811
812 .. versionchanged:: 0.10
813 The default port is now picked from the ``SERVER_NAME`` variable.
814
815 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
816 have the server available externally as well. Defaults to
817 ``'127.0.0.1'``.
818 :param port: the port of the webserver. Defaults to ``5000`` or the
819 port defined in the ``SERVER_NAME`` config variable if
820 present.
821 :param debug: if given, enable or disable debug mode.
822 See :attr:`debug`.
823 :param options: the options to be forwarded to the underlying
824 Werkzeug server. See
825 :func:`werkzeug.serving.run_simple` for more
826 information.
827 """
828 from werkzeug.serving import run_simple
829 if host is None:
830 host = '127.0.0.1'
831 if port is None:
832 server_name = self.config['SERVER_NAME']
833 if server_name and ':' in server_name:
834 port = int(server_name.rsplit(':', 1)[1])
835 else:
836 port = 5000
837 if debug is not None:
838 self.debug = bool(debug)
839 options.setdefault('use_reloader', self.debug)
840 options.setdefault('use_debugger', self.debug)
841 options.setdefault('passthrough_errors', True)
842 try:
843 run_simple(host, port, self, **options)
844 finally:
845 # reset the first request information if the development server
846 # resetted normally. This makes it possible to restart the server
847 # without reloader and that stuff from an interactive shell.
848 self._got_first_request = False
849
850 def test_client(self, use_cookies=True, **kwargs):
851 """Creates a test client for this application. For information
852 about unit testing head over to :ref:`testing`.
853
854 Note that if you are testing for assertions or exceptions in your
855 application code, you must set ``app.testing = True`` in order for the
856 exceptions to propagate to the test client. Otherwise, the exception
857 will be handled by the application (not visible to the test client) and
858 the only indication of an AssertionError or other exception will be a
859 500 status code response to the test client. See the :attr:`testing`
860 attribute. For example::
861
862 app.testing = True
863 client = app.test_client()
864
865 The test client can be used in a ``with`` block to defer the closing down
866 of the context until the end of the ``with`` block. This is useful if
867 you want to access the context locals for testing::
868
869 with app.test_client() as c:
870 rv = c.get('/?vodka=42')
871 assert request.args['vodka'] == '42'
872
873 Additionally, you may pass optional keyword arguments that will then
874 be passed to the application's :attr:`test_client_class` constructor.
875 For example::
876
877 from flask.testing import FlaskClient
878
879 class CustomClient(FlaskClient):
880 def __init__(self, authentication=None, *args, **kwargs):
881 FlaskClient.__init__(*args, **kwargs)
882 self._authentication = authentication
883
884 app.test_client_class = CustomClient
885 client = app.test_client(authentication='Basic ....')
886
887 See :class:`~flask.testing.FlaskClient` for more information.
888
889 .. versionchanged:: 0.4
890 added support for ``with`` block usage for the client.
891
892 .. versionadded:: 0.7
893 The `use_cookies` parameter was added as well as the ability
894 to override the client to be used by setting the
895 :attr:`test_client_class` attribute.
896
897 .. versionchanged:: 0.11
898 Added `**kwargs` to support passing additional keyword arguments to
899 the constructor of :attr:`test_client_class`.
900 """
901 cls = self.test_client_class
902 if cls is None:
903 from flask.testing import FlaskClient as cls
904 return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)
905
906 def open_session(self, request):
907 """Creates or opens a new session. Default implementation stores all
908 session data in a signed cookie. This requires that the
909 :attr:`secret_key` is set. Instead of overriding this method
910 we recommend replacing the :class:`session_interface`.
911
912 :param request: an instance of :attr:`request_class`.
913 """
914 return self.session_interface.open_session(self, request)
915
916 def save_session(self, session, response):
917 """Saves the session if it needs updates. For the default
918 implementation, check :meth:`open_session`. Instead of overriding this
919 method we recommend replacing the :class:`session_interface`.
920
921 :param session: the session to be saved (a
922 :class:`~werkzeug.contrib.securecookie.SecureCookie`
923 object)
924 :param response: an instance of :attr:`response_class`
925 """
926 return self.session_interface.save_session(self, session, response)
927
928 def make_null_session(self):
929 """Creates a new instance of a missing session. Instead of overriding
930 this method we recommend replacing the :class:`session_interface`.
931
932 .. versionadded:: 0.7
933 """
934 return self.session_interface.make_null_session(self)
935
936 @setupmethod
937 def register_blueprint(self, blueprint, **options):
938 """Register a blueprint on the application. For information about
939 blueprints head over to :ref:`blueprints`.
940
941 The blueprint name is passed in as the first argument.
942 Options are passed as additional keyword arguments and forwarded to
943 `blueprints` in an "options" dictionary.
944
945 :param subdomain: set a subdomain for the blueprint
946 :param url_prefix: set the prefix for all URLs defined on the blueprint.
947 ``(url_prefix='/<lang code>')``
948 :param url_defaults: a dictionary with URL defaults that is added to
949 each and every URL defined with this blueprint
950 :param static_folder: add a static folder to urls in this blueprint
951 :param static_url_path: add a static url path to urls in this blueprint
952 :param template_folder: set an alternate template folder
953 :param root_path: set an alternate root path for this blueprint
954
955 .. versionadded:: 0.7
956 """
957 first_registration = False
958 if blueprint.name in self.blueprints:
959 assert self.blueprints[blueprint.name] is blueprint, \
960 'A blueprint\'s name collision occurred between %r and ' \
961 '%r. Both share the same name "%s". Blueprints that ' \
962 'are created on the fly need unique names.' % \
963 (blueprint, self.blueprints[blueprint.name], blueprint.name)
964 else:
965 self.blueprints[blueprint.name] = blueprint
966 self._blueprint_order.append(blueprint)
967 first_registration = True
968 blueprint.register(self, options, first_registration)
969
970 def iter_blueprints(self):
971 """Iterates over all blueprints by the order they were registered.
972
973 .. versionadded:: 0.11
974 """
975 return iter(self._blueprint_order)
976
977 @setupmethod
978 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
979 """Connects a URL rule. Works exactly like the :meth:`route`
980 decorator. If a view_func is provided it will be registered with the
981 endpoint.
982
983 Basically this example::
984
985 @app.route('/')
986 def index():
987 pass
988
989 Is equivalent to the following::
990
991 def index():
992 pass
993 app.add_url_rule('/', 'index', index)
994
995 If the view_func is not provided you will need to connect the endpoint
996 to a view function like so::
997
998 app.view_functions['index'] = index
999
1000 Internally :meth:`route` invokes :meth:`add_url_rule` so if you want
1001 to customize the behavior via subclassing you only need to change
1002 this method.
1003
1004 For more information refer to :ref:`url-route-registrations`.
1005
1006 .. versionchanged:: 0.2
1007 `view_func` parameter added.
1008
1009 .. versionchanged:: 0.6
1010 ``OPTIONS`` is added automatically as method.
1011
1012 :param rule: the URL rule as string
1013 :param endpoint: the endpoint for the registered URL rule. Flask
1014 itself assumes the name of the view function as
1015 endpoint
1016 :param view_func: the function to call when serving a request to the
1017 provided endpoint
1018 :param options: the options to be forwarded to the underlying
1019 :class:`~werkzeug.routing.Rule` object. A change
1020 to Werkzeug is handling of method options. methods
1021 is a list of methods this rule should be limited
1022 to (``GET``, ``POST`` etc.). By default a rule
1023 just listens for ``GET`` (and implicitly ``HEAD``).
1024 Starting with Flask 0.6, ``OPTIONS`` is implicitly
1025 added and handled by the standard request handling.
1026 """
1027 if endpoint is None:
1028 endpoint = _endpoint_from_view_func(view_func)
1029 options['endpoint'] = endpoint
1030 methods = options.pop('methods', None)
1031
1032 # if the methods are not given and the view_func object knows its
1033 # methods we can use that instead. If neither exists, we go with
1034 # a tuple of only ``GET`` as default.
1035 if methods is None:
1036 methods = getattr(view_func, 'methods', None) or ('GET',)
1037 if isinstance(methods, string_types):
1038 raise TypeError('Allowed methods have to be iterables of strings, '
1039 'for example: @app.route(..., methods=["POST"])')
1040 methods = set(item.upper() for item in methods)
1041
1042 # Methods that should always be added
1043 required_methods = set(getattr(view_func, 'required_methods', ()))
1044
1045 # starting with Flask 0.8 the view_func object can disable and
1046 # force-enable the automatic options handling.
1047 provide_automatic_options = getattr(view_func,
1048 'provide_automatic_options', None)
1049
1050 if provide_automatic_options is None:
1051 if 'OPTIONS' not in methods:
1052 provide_automatic_options = True
1053 required_methods.add('OPTIONS')
1054 else:
1055 provide_automatic_options = False
1056
1057 # Add the required methods now.
1058 methods |= required_methods
1059
1060 rule = self.url_rule_class(rule, methods=methods, **options)
1061 rule.provide_automatic_options = provide_automatic_options
1062
1063 self.url_map.add(rule)
1064 if view_func is not None:
1065 old_func = self.view_functions.get(endpoint)
1066 if old_func is not None and old_func != view_func:
1067 raise AssertionError('View function mapping is overwriting an '
1068 'existing endpoint function: %s' % endpoint)
1069 self.view_functions[endpoint] = view_func
1070
1071 def route(self, rule, **options):
1072 """A decorator that is used to register a view function for a
1073 given URL rule. This does the same thing as :meth:`add_url_rule`
1074 but is intended for decorator usage::
1075
1076 @app.route('/')
1077 def index():
1078 return 'Hello World'
1079
1080 For more information refer to :ref:`url-route-registrations`.
1081
1082 :param rule: the URL rule as string
1083 :param endpoint: the endpoint for the registered URL rule. Flask
1084 itself assumes the name of the view function as
1085 endpoint
1086 :param options: the options to be forwarded to the underlying
1087 :class:`~werkzeug.routing.Rule` object. A change
1088 to Werkzeug is handling of method options. methods
1089 is a list of methods this rule should be limited
1090 to (``GET``, ``POST`` etc.). By default a rule
1091 just listens for ``GET`` (and implicitly ``HEAD``).
1092 Starting with Flask 0.6, ``OPTIONS`` is implicitly
1093 added and handled by the standard request handling.
1094 """
1095 def decorator(f):
1096 endpoint = options.pop('endpoint', None)
1097 self.add_url_rule(rule, endpoint, f, **options)
1098 return f
1099 return decorator
1100
1101 @setupmethod
1102 def endpoint(self, endpoint):
1103 """A decorator to register a function as an endpoint.
1104 Example::
1105
1106 @app.endpoint('example.endpoint')
1107 def example():
1108 return "example"
1109
1110 :param endpoint: the name of the endpoint
1111 """
1112 def decorator(f):
1113 self.view_functions[endpoint] = f
1114 return f
1115 return decorator
1116
1117 @staticmethod
1118 def _get_exc_class_and_code(exc_class_or_code):
1119 """Ensure that we register only exceptions as handler keys"""
1120 if isinstance(exc_class_or_code, integer_types):
1121 exc_class = default_exceptions[exc_class_or_code]
1122 else:
1123 exc_class = exc_class_or_code
1124
1125 assert issubclass(exc_class, Exception)
1126
1127 if issubclass(exc_class, HTTPException):
1128 return exc_class, exc_class.code
1129 else:
1130 return exc_class, None
1131
1132 @setupmethod
1133 def errorhandler(self, code_or_exception):
1134 """A decorator that is used to register a function give a given
1135 error code. Example::
1136
1137 @app.errorhandler(404)
1138 def page_not_found(error):
1139 return 'This page does not exist', 404
1140
1141 You can also register handlers for arbitrary exceptions::
1142
1143 @app.errorhandler(DatabaseError)
1144 def special_exception_handler(error):
1145 return 'Database connection failed', 500
1146
1147 You can also register a function as error handler without using
1148 the :meth:`errorhandler` decorator. The following example is
1149 equivalent to the one above::
1150
1151 def page_not_found(error):
1152 return 'This page does not exist', 404
1153 app.error_handler_spec[None][404] = page_not_found
1154
1155 Setting error handlers via assignments to :attr:`error_handler_spec`
1156 however is discouraged as it requires fiddling with nested dictionaries
1157 and the special case for arbitrary exception types.
1158
1159 The first ``None`` refers to the active blueprint. If the error
1160 handler should be application wide ``None`` shall be used.
1161
1162 .. versionadded:: 0.7
1163 Use :meth:`register_error_handler` instead of modifying
1164 :attr:`error_handler_spec` directly, for application wide error
1165 handlers.
1166
1167 .. versionadded:: 0.7
1168 One can now additionally also register custom exception types
1169 that do not necessarily have to be a subclass of the
1170 :class:`~werkzeug.exceptions.HTTPException` class.
1171
1172 :param code: the code as integer for the handler
1173 """
1174 def decorator(f):
1175 self._register_error_handler(None, code_or_exception, f)
1176 return f
1177 return decorator
1178
1179 def register_error_handler(self, code_or_exception, f):
1180 """Alternative error attach function to the :meth:`errorhandler`
1181 decorator that is more straightforward to use for non decorator
1182 usage.
1183
1184 .. versionadded:: 0.7
1185 """
1186 self._register_error_handler(None, code_or_exception, f)
1187
1188 @setupmethod
1189 def _register_error_handler(self, key, code_or_exception, f):
1190 """
1191 :type key: None|str
1192 :type code_or_exception: int|T<=Exception
1193 :type f: callable
1194 """
1195 if isinstance(code_or_exception, HTTPException): # old broken behavior
1196 raise ValueError(
1197 'Tried to register a handler for an exception instance {0!r}. '
1198 'Handlers can only be registered for exception classes or HTTP error codes.'
1199 .format(code_or_exception))
1200
1201 exc_class, code = self._get_exc_class_and_code(code_or_exception)
1202
1203 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})
1204 handlers[exc_class] = f
1205
1206 @setupmethod
1207 def template_filter(self, name=None):
1208 """A decorator that is used to register custom template filter.
1209 You can specify a name for the filter, otherwise the function
1210 name will be used. Example::
1211
1212 @app.template_filter()
1213 def reverse(s):
1214 return s[::-1]
1215
1216 :param name: the optional name of the filter, otherwise the
1217 function name will be used.
1218 """
1219 def decorator(f):
1220 self.add_template_filter(f, name=name)
1221 return f
1222 return decorator
1223
1224 @setupmethod
1225 def add_template_filter(self, f, name=None):
1226 """Register a custom template filter. Works exactly like the
1227 :meth:`template_filter` decorator.
1228
1229 :param name: the optional name of the filter, otherwise the
1230 function name will be used.
1231 """
1232 self.jinja_env.filters[name or f.__name__] = f
1233
1234 @setupmethod
1235 def template_test(self, name=None):
1236 """A decorator that is used to register custom template test.
1237 You can specify a name for the test, otherwise the function
1238 name will be used. Example::
1239
1240 @app.template_test()
1241 def is_prime(n):
1242 if n == 2:
1243 return True
1244 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
1245 if n % i == 0:
1246 return False
1247 return True
1248
1249 .. versionadded:: 0.10
1250
1251 :param name: the optional name of the test, otherwise the
1252 function name will be used.
1253 """
1254 def decorator(f):
1255 self.add_template_test(f, name=name)
1256 return f
1257 return decorator
1258
1259 @setupmethod
1260 def add_template_test(self, f, name=None):
1261 """Register a custom template test. Works exactly like the
1262 :meth:`template_test` decorator.
1263
1264 .. versionadded:: 0.10
1265
1266 :param name: the optional name of the test, otherwise the
1267 function name will be used.
1268 """
1269 self.jinja_env.tests[name or f.__name__] = f
1270
1271 @setupmethod
1272 def template_global(self, name=None):
1273 """A decorator that is used to register a custom template global function.
1274 You can specify a name for the global function, otherwise the function
1275 name will be used. Example::
1276
1277 @app.template_global()
1278 def double(n):
1279 return 2 * n
1280
1281 .. versionadded:: 0.10
1282
1283 :param name: the optional name of the global function, otherwise the
1284 function name will be used.
1285 """
1286 def decorator(f):
1287 self.add_template_global(f, name=name)
1288 return f
1289 return decorator
1290
1291 @setupmethod
1292 def add_template_global(self, f, name=None):
1293 """Register a custom template global function. Works exactly like the
1294 :meth:`template_global` decorator.
1295
1296 .. versionadded:: 0.10
1297
1298 :param name: the optional name of the global function, otherwise the
1299 function name will be used.
1300 """
1301 self.jinja_env.globals[name or f.__name__] = f
1302
1303 @setupmethod
1304 def before_request(self, f):
1305 """Registers a function to run before each request.
1306
1307 The function will be called without any arguments.
1308 If the function returns a non-None value, it's handled as
1309 if it was the return value from the view and further
1310 request handling is stopped.
1311 """
1312 self.before_request_funcs.setdefault(None, []).append(f)
1313 return f
1314
1315 @setupmethod
1316 def before_first_request(self, f):
1317 """Registers a function to be run before the first request to this
1318 instance of the application.
1319
1320 The function will be called without any arguments and its return
1321 value is ignored.
1322
1323 .. versionadded:: 0.8
1324 """
1325 self.before_first_request_funcs.append(f)
1326 return f
1327
1328 @setupmethod
1329 def after_request(self, f):
1330 """Register a function to be run after each request.
1331
1332 Your function must take one parameter, an instance of
1333 :attr:`response_class` and return a new response object or the
1334 same (see :meth:`process_response`).
1335
1336 As of Flask 0.7 this function might not be executed at the end of the
1337 request in case an unhandled exception occurred.
1338 """
1339 self.after_request_funcs.setdefault(None, []).append(f)
1340 return f
1341
1342 @setupmethod
1343 def teardown_request(self, f):
1344 """Register a function to be run at the end of each request,
1345 regardless of whether there was an exception or not. These functions
1346 are executed when the request context is popped, even if not an
1347 actual request was performed.
1348
1349 Example::
1350
1351 ctx = app.test_request_context()
1352 ctx.push()
1353 ...
1354 ctx.pop()
1355
1356 When ``ctx.pop()`` is executed in the above example, the teardown
1357 functions are called just before the request context moves from the
1358 stack of active contexts. This becomes relevant if you are using
1359 such constructs in tests.
1360
1361 Generally teardown functions must take every necessary step to avoid
1362 that they will fail. If they do execute code that might fail they
1363 will have to surround the execution of these code by try/except
1364 statements and log occurring errors.
1365
1366 When a teardown function was called because of a exception it will
1367 be passed an error object.
1368
1369 The return values of teardown functions are ignored.
1370
1371 .. admonition:: Debug Note
1372
1373 In debug mode Flask will not tear down a request on an exception
1374 immediately. Instead it will keep it alive so that the interactive
1375 debugger can still access it. This behavior can be controlled
1376 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
1377 """
1378 self.teardown_request_funcs.setdefault(None, []).append(f)
1379 return f
1380
1381 @setupmethod
1382 def teardown_appcontext(self, f):
1383 """Registers a function to be called when the application context
1384 ends. These functions are typically also called when the request
1385 context is popped.
1386
1387 Example::
1388
1389 ctx = app.app_context()
1390 ctx.push()
1391 ...
1392 ctx.pop()
1393
1394 When ``ctx.pop()`` is executed in the above example, the teardown
1395 functions are called just before the app context moves from the
1396 stack of active contexts. This becomes relevant if you are using
1397 such constructs in tests.
1398
1399 Since a request context typically also manages an application
1400 context it would also be called when you pop a request context.
1401
1402 When a teardown function was called because of an exception it will
1403 be passed an error object.
1404
1405 The return values of teardown functions are ignored.
1406
1407 .. versionadded:: 0.9
1408 """
1409 self.teardown_appcontext_funcs.append(f)
1410 return f
1411
1412 @setupmethod
1413 def context_processor(self, f):
1414 """Registers a template context processor function."""
1415 self.template_context_processors[None].append(f)
1416 return f
1417
1418 @setupmethod
1419 def shell_context_processor(self, f):
1420 """Registers a shell context processor function.
1421
1422 .. versionadded:: 0.11
1423 """
1424 self.shell_context_processors.append(f)
1425 return f
1426
1427 @setupmethod
1428 def url_value_preprocessor(self, f):
1429 """Registers a function as URL value preprocessor for all view
1430 functions of the application. It's called before the view functions
1431 are called and can modify the url values provided.
1432 """
1433 self.url_value_preprocessors.setdefault(None, []).append(f)
1434 return f
1435
1436 @setupmethod
1437 def url_defaults(self, f):
1438 """Callback function for URL defaults for all view functions of the
1439 application. It's called with the endpoint and values and should
1440 update the values passed in place.
1441 """
1442 self.url_default_functions.setdefault(None, []).append(f)
1443 return f
1444
1445 def _find_error_handler(self, e):
1446 """Finds a registered error handler for the request’s blueprint.
1447 Otherwise falls back to the app, returns None if not a suitable
1448 handler is found.
1449 """
1450 exc_class, code = self._get_exc_class_and_code(type(e))
1451
1452 def find_handler(handler_map):
1453 if not handler_map:
1454 return
1455 queue = deque(exc_class.__mro__)
1456 # Protect from geniuses who might create circular references in
1457 # __mro__
1458 done = set()
1459
1460 while queue:
1461 cls = queue.popleft()
1462 if cls in done:
1463 continue
1464 done.add(cls)
1465 handler = handler_map.get(cls)
1466 if handler is not None:
1467 # cache for next time exc_class is raised
1468 handler_map[exc_class] = handler
1469 return handler
1470
1471 queue.extend(cls.__mro__)
1472
1473 # try blueprint handlers
1474 handler = find_handler(self.error_handler_spec
1475 .get(request.blueprint, {})
1476 .get(code))
1477 if handler is not None:
1478 return handler
1479
1480 # fall back to app handlers
1481 return find_handler(self.error_handler_spec[None].get(code))
1482
1483 def handle_http_exception(self, e):
1484 """Handles an HTTP exception. By default this will invoke the
1485 registered error handlers and fall back to returning the
1486 exception as response.
1487
1488 .. versionadded:: 0.3
1489 """
1490 # Proxy exceptions don't have error codes. We want to always return
1491 # those unchanged as errors
1492 if e.code is None:
1493 return e
1494
1495 handler = self._find_error_handler(e)
1496 if handler is None:
1497 return e
1498 return handler(e)
1499
1500 def trap_http_exception(self, e):
1501 """Checks if an HTTP exception should be trapped or not. By default
1502 this will return ``False`` for all exceptions except for a bad request
1503 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
1504 also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
1505
1506 This is called for all HTTP exceptions raised by a view function.
1507 If it returns ``True`` for any exception the error handler for this
1508 exception is not called and it shows up as regular exception in the
1509 traceback. This is helpful for debugging implicitly raised HTTP
1510 exceptions.
1511
1512 .. versionadded:: 0.8
1513 """
1514 if self.config['TRAP_HTTP_EXCEPTIONS']:
1515 return True
1516 if self.config['TRAP_BAD_REQUEST_ERRORS']:
1517 return isinstance(e, BadRequest)
1518 return False
1519
1520 def handle_user_exception(self, e):
1521 """This method is called whenever an exception occurs that should be
1522 handled. A special case are
1523 :class:`~werkzeug.exception.HTTPException`\s which are forwarded by
1524 this function to the :meth:`handle_http_exception` method. This
1525 function will either return a response value or reraise the
1526 exception with the same traceback.
1527
1528 .. versionadded:: 0.7
1529 """
1530 exc_type, exc_value, tb = sys.exc_info()
1531 assert exc_value is e
1532
1533 # ensure not to trash sys.exc_info() at that point in case someone
1534 # wants the traceback preserved in handle_http_exception. Of course
1535 # we cannot prevent users from trashing it themselves in a custom
1536 # trap_http_exception method so that's their fault then.
1537
1538 if isinstance(e, HTTPException) and not self.trap_http_exception(e):
1539 return self.handle_http_exception(e)
1540
1541 handler = self._find_error_handler(e)
1542
1543 if handler is None:
1544 reraise(exc_type, exc_value, tb)
1545 return handler(e)
1546
1547 def handle_exception(self, e):
1548 """Default exception handling that kicks in when an exception
1549 occurs that is not caught. In debug mode the exception will
1550 be re-raised immediately, otherwise it is logged and the handler
1551 for a 500 internal server error is used. If no such handler
1552 exists, a default 500 internal server error message is displayed.
1553
1554 .. versionadded:: 0.3
1555 """
1556 exc_type, exc_value, tb = sys.exc_info()
1557
1558 got_request_exception.send(self, exception=e)
1559 handler = self._find_error_handler(InternalServerError())
1560
1561 if self.propagate_exceptions:
1562 # if we want to repropagate the exception, we can attempt to
1563 # raise it with the whole traceback in case we can do that
1564 # (the function was actually called from the except part)
1565 # otherwise, we just raise the error again
1566 if exc_value is e:
1567 reraise(exc_type, exc_value, tb)
1568 else:
1569 raise e
1570
1571 self.log_exception((exc_type, exc_value, tb))
1572 if handler is None:
1573 return InternalServerError()
1574 return handler(e)
1575
1576 def log_exception(self, exc_info):
1577 """Logs an exception. This is called by :meth:`handle_exception`
1578 if debugging is disabled and right before the handler is called.
1579 The default implementation logs the exception as error on the
1580 :attr:`logger`.
1581
1582 .. versionadded:: 0.8
1583 """
1584 self.logger.error('Exception on %s [%s]' % (
1585 request.path,
1586 request.method
1587 ), exc_info=exc_info)
1588
1589 def raise_routing_exception(self, request):
1590 """Exceptions that are recording during routing are reraised with
1591 this method. During debug we are not reraising redirect requests
1592 for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
1593 a different error instead to help debug situations.
1594
1595 :internal:
1596 """
1597 if not self.debug \
1598 or not isinstance(request.routing_exception, RequestRedirect) \
1599 or request.method in ('GET', 'HEAD', 'OPTIONS'):
1600 raise request.routing_exception
1601
1602 from .debughelpers import FormDataRoutingRedirect
1603 raise FormDataRoutingRedirect(request)
1604
1605 def dispatch_request(self):
1606 """Does the request dispatching. Matches the URL and returns the
1607 return value of the view or error handler. This does not have to
1608 be a response object. In order to convert the return value to a
1609 proper response object, call :func:`make_response`.
1610
1611 .. versionchanged:: 0.7
1612 This no longer does the exception handling, this code was
1613 moved to the new :meth:`full_dispatch_request`.
1614 """
1615 req = _request_ctx_stack.top.request
1616 if req.routing_exception is not None:
1617 self.raise_routing_exception(req)
1618 rule = req.url_rule
1619 # if we provide automatic options for this URL and the
1620 # request came with the OPTIONS method, reply automatically
1621 if getattr(rule, 'provide_automatic_options', False) \
1622 and req.method == 'OPTIONS':
1623 return self.make_default_options_response()
1624 # otherwise dispatch to the handler for that endpoint
1625 return self.view_functions[rule.endpoint](**req.view_args)
1626
1627 def full_dispatch_request(self):
1628 """Dispatches the request and on top of that performs request
1629 pre and postprocessing as well as HTTP exception catching and
1630 error handling.
1631
1632 .. versionadded:: 0.7
1633 """
1634 self.try_trigger_before_first_request_functions()
1635 try:
1636 request_started.send(self)
1637 rv = self.preprocess_request()
1638 if rv is None:
1639 rv = self.dispatch_request()
1640 except Exception as e:
1641 rv = self.handle_user_exception(e)
1642 response = self.make_response(rv)
1643 response = self.process_response(response)
1644 request_finished.send(self, response=response)
1645 return response
1646
1647 def try_trigger_before_first_request_functions(self):
1648 """Called before each request and will ensure that it triggers
1649 the :attr:`before_first_request_funcs` and only exactly once per
1650 application instance (which means process usually).
1651
1652 :internal:
1653 """
1654 if self._got_first_request:
1655 return
1656 with self._before_request_lock:
1657 if self._got_first_request:
1658 return
1659 for func in self.before_first_request_funcs:
1660 func()
1661 self._got_first_request = True
1662
1663 def make_default_options_response(self):
1664 """This method is called to create the default ``OPTIONS`` response.
1665 This can be changed through subclassing to change the default
1666 behavior of ``OPTIONS`` responses.
1667
1668 .. versionadded:: 0.7
1669 """
1670 adapter = _request_ctx_stack.top.url_adapter
1671 if hasattr(adapter, 'allowed_methods'):
1672 methods = adapter.allowed_methods()
1673 else:
1674 # fallback for Werkzeug < 0.7
1675 methods = []
1676 try:
1677 adapter.match(method='--')
1678 except MethodNotAllowed as e:
1679 methods = e.valid_methods
1680 except HTTPException as e:
1681 pass
1682 rv = self.response_class()
1683 rv.allow.update(methods)
1684 return rv
1685
1686 def should_ignore_error(self, error):
1687 """This is called to figure out if an error should be ignored
1688 or not as far as the teardown system is concerned. If this
1689 function returns ``True`` then the teardown handlers will not be
1690 passed the error.
1691
1692 .. versionadded:: 0.10
1693 """
1694 return False
1695
1696 def make_response(self, rv):
1697 """Converts the return value from a view function to a real
1698 response object that is an instance of :attr:`response_class`.
1699
1700 The following types are allowed for `rv`:
1701
1702 .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|
1703
1704 ======================= ===========================================
1705 :attr:`response_class` the object is returned unchanged
1706 :class:`str` a response object is created with the
1707 string as body
1708 :class:`unicode` a response object is created with the
1709 string encoded to utf-8 as body
1710 a WSGI function the function is called as WSGI application
1711 and buffered as response object
1712 :class:`tuple` A tuple in the form ``(response, status,
1713 headers)`` or ``(response, headers)``
1714 where `response` is any of the
1715 types defined here, `status` is a string
1716 or an integer and `headers` is a list or
1717 a dictionary with header values.
1718 ======================= ===========================================
1719
1720 :param rv: the return value from the view function
1721
1722 .. versionchanged:: 0.9
1723 Previously a tuple was interpreted as the arguments for the
1724 response object.
1725 """
1726 status_or_headers = headers = None
1727 if isinstance(rv, tuple):
1728 rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))
1729
1730 if rv is None:
1731 raise ValueError('View function did not return a response')
1732
1733 if isinstance(status_or_headers, (dict, list)):
1734 headers, status_or_headers = status_or_headers, None
1735
1736 if not isinstance(rv, self.response_class):
1737 # When we create a response object directly, we let the constructor
1738 # set the headers and status. We do this because there can be
1739 # some extra logic involved when creating these objects with
1740 # specific values (like default content type selection).
1741 if isinstance(rv, (text_type, bytes, bytearray)):
1742 rv = self.response_class(rv, headers=headers,
1743 status=status_or_headers)
1744 headers = status_or_headers = None
1745 else:
1746 rv = self.response_class.force_type(rv, request.environ)
1747
1748 if status_or_headers is not None:
1749 if isinstance(status_or_headers, string_types):
1750 rv.status = status_or_headers
1751 else:
1752 rv.status_code = status_or_headers
1753 if headers:
1754 rv.headers.extend(headers)
1755
1756 return rv
1757
1758 def create_url_adapter(self, request):
1759 """Creates a URL adapter for the given request. The URL adapter
1760 is created at a point where the request context is not yet set up
1761 so the request is passed explicitly.
1762
1763 .. versionadded:: 0.6
1764
1765 .. versionchanged:: 0.9
1766 This can now also be called without a request object when the
1767 URL adapter is created for the application context.
1768 """
1769 if request is not None:
1770 return self.url_map.bind_to_environ(request.environ,
1771 server_name=self.config['SERVER_NAME'])
1772 # We need at the very least the server name to be set for this
1773 # to work.
1774 if self.config['SERVER_NAME'] is not None:
1775 return self.url_map.bind(
1776 self.config['SERVER_NAME'],
1777 script_name=self.config['APPLICATION_ROOT'] or '/',
1778 url_scheme=self.config['PREFERRED_URL_SCHEME'])
1779
1780 def inject_url_defaults(self, endpoint, values):
1781 """Injects the URL defaults for the given endpoint directly into
1782 the values dictionary passed. This is used internally and
1783 automatically called on URL building.
1784
1785 .. versionadded:: 0.7
1786 """
1787 funcs = self.url_default_functions.get(None, ())
1788 if '.' in endpoint:
1789 bp = endpoint.rsplit('.', 1)[0]
1790 funcs = chain(funcs, self.url_default_functions.get(bp, ()))
1791 for func in funcs:
1792 func(endpoint, values)
1793
1794 def handle_url_build_error(self, error, endpoint, values):
1795 """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.
1796 """
1797 exc_type, exc_value, tb = sys.exc_info()
1798 for handler in self.url_build_error_handlers:
1799 try:
1800 rv = handler(error, endpoint, values)
1801 if rv is not None:
1802 return rv
1803 except BuildError as e:
1804 # make error available outside except block (py3)
1805 error = e
1806
1807 # At this point we want to reraise the exception. If the error is
1808 # still the same one we can reraise it with the original traceback,
1809 # otherwise we raise it from here.
1810 if error is exc_value:
1811 reraise(exc_type, exc_value, tb)
1812 raise error
1813
1814 def preprocess_request(self):
1815 """Called before the actual request dispatching and will
1816 call each :meth:`before_request` decorated function, passing no
1817 arguments.
1818 If any of these functions returns a value, it's handled as
1819 if it was the return value from the view and further
1820 request handling is stopped.
1821
1822 This also triggers the :meth:`url_value_processor` functions before
1823 the actual :meth:`before_request` functions are called.
1824 """
1825 bp = _request_ctx_stack.top.request.blueprint
1826
1827 funcs = self.url_value_preprocessors.get(None, ())
1828 if bp is not None and bp in self.url_value_preprocessors:
1829 funcs = chain(funcs, self.url_value_preprocessors[bp])
1830 for func in funcs:
1831 func(request.endpoint, request.view_args)
1832
1833 funcs = self.before_request_funcs.get(None, ())
1834 if bp is not None and bp in self.before_request_funcs:
1835 funcs = chain(funcs, self.before_request_funcs[bp])
1836 for func in funcs:
1837 rv = func()
1838 if rv is not None:
1839 return rv
1840
1841 def process_response(self, response):
1842 """Can be overridden in order to modify the response object
1843 before it's sent to the WSGI server. By default this will
1844 call all the :meth:`after_request` decorated functions.
1845
1846 .. versionchanged:: 0.5
1847 As of Flask 0.5 the functions registered for after request
1848 execution are called in reverse order of registration.
1849
1850 :param response: a :attr:`response_class` object.
1851 :return: a new response object or the same, has to be an
1852 instance of :attr:`response_class`.
1853 """
1854 ctx = _request_ctx_stack.top
1855 bp = ctx.request.blueprint
1856 funcs = ctx._after_request_functions
1857 if bp is not None and bp in self.after_request_funcs:
1858 funcs = chain(funcs, reversed(self.after_request_funcs[bp]))
1859 if None in self.after_request_funcs:
1860 funcs = chain(funcs, reversed(self.after_request_funcs[None]))
1861 for handler in funcs:
1862 response = handler(response)
1863 if not self.session_interface.is_null_session(ctx.session):
1864 self.save_session(ctx.session, response)
1865 return response
1866
1867 def do_teardown_request(self, exc=_sentinel):
1868 """Called after the actual request dispatching and will
1869 call every as :meth:`teardown_request` decorated function. This is
1870 not actually called by the :class:`Flask` object itself but is always
1871 triggered when the request context is popped. That way we have a
1872 tighter control over certain resources under testing environments.
1873
1874 .. versionchanged:: 0.9
1875 Added the `exc` argument. Previously this was always using the
1876 current exception information.
1877 """
1878 if exc is _sentinel:
1879 exc = sys.exc_info()[1]
1880 funcs = reversed(self.teardown_request_funcs.get(None, ()))
1881 bp = _request_ctx_stack.top.request.blueprint
1882 if bp is not None and bp in self.teardown_request_funcs:
1883 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))
1884 for func in funcs:
1885 func(exc)
1886 request_tearing_down.send(self, exc=exc)
1887
1888 def do_teardown_appcontext(self, exc=_sentinel):
1889 """Called when an application context is popped. This works pretty
1890 much the same as :meth:`do_teardown_request` but for the application
1891 context.
1892
1893 .. versionadded:: 0.9
1894 """
1895 if exc is _sentinel:
1896 exc = sys.exc_info()[1]
1897 for func in reversed(self.teardown_appcontext_funcs):
1898 func(exc)
1899 appcontext_tearing_down.send(self, exc=exc)
1900
1901 def app_context(self):
1902 """Binds the application only. For as long as the application is bound
1903 to the current context the :data:`flask.current_app` points to that
1904 application. An application context is automatically created when a
1905 request context is pushed if necessary.
1906
1907 Example usage::
1908
1909 with app.app_context():
1910 ...
1911
1912 .. versionadded:: 0.9
1913 """
1914 return AppContext(self)
1915
1916 def request_context(self, environ):
1917 """Creates a :class:`~flask.ctx.RequestContext` from the given
1918 environment and binds it to the current context. This must be used in
1919 combination with the ``with`` statement because the request is only bound
1920 to the current context for the duration of the ``with`` block.
1921
1922 Example usage::
1923
1924 with app.request_context(environ):
1925 do_something_with(request)
1926
1927 The object returned can also be used without the ``with`` statement
1928 which is useful for working in the shell. The example above is
1929 doing exactly the same as this code::
1930
1931 ctx = app.request_context(environ)
1932 ctx.push()
1933 try:
1934 do_something_with(request)
1935 finally:
1936 ctx.pop()
1937
1938 .. versionchanged:: 0.3
1939 Added support for non-with statement usage and ``with`` statement
1940 is now passed the ctx object.
1941
1942 :param environ: a WSGI environment
1943 """
1944 return RequestContext(self, environ)
1945
1946 def test_request_context(self, *args, **kwargs):
1947 """Creates a WSGI environment from the given values (see
1948 :class:`werkzeug.test.EnvironBuilder` for more information, this
1949 function accepts the same arguments).
1950 """
1951 from flask.testing import make_test_environ_builder
1952 builder = make_test_environ_builder(self, *args, **kwargs)
1953 try:
1954 return self.request_context(builder.get_environ())
1955 finally:
1956 builder.close()
1957
1958 def wsgi_app(self, environ, start_response):
1959 """The actual WSGI application. This is not implemented in
1960 `__call__` so that middlewares can be applied without losing a
1961 reference to the class. So instead of doing this::
1962
1963 app = MyMiddleware(app)
1964
1965 It's a better idea to do this instead::
1966
1967 app.wsgi_app = MyMiddleware(app.wsgi_app)
1968
1969 Then you still have the original application object around and
1970 can continue to call methods on it.
1971
1972 .. versionchanged:: 0.7
1973 The behavior of the before and after request callbacks was changed
1974 under error conditions and a new callback was added that will
1975 always execute at the end of the request, independent on if an
1976 error occurred or not. See :ref:`callbacks-and-errors`.
1977
1978 :param environ: a WSGI environment
1979 :param start_response: a callable accepting a status code,
1980 a list of headers and an optional
1981 exception context to start the response
1982 """
1983 ctx = self.request_context(environ)
1984 ctx.push()
1985 error = None
1986 try:
1987 try:
1988 response = self.full_dispatch_request()
1989 except Exception as e:
1990 error = e
1991 response = self.make_response(self.handle_exception(e))
1992 return response(environ, start_response)
1993 finally:
1994 if self.should_ignore_error(error):
1995 error = None
1996 ctx.auto_pop(error)
1997
1998 def __call__(self, environ, start_response):
1999 """Shortcut for :attr:`wsgi_app`."""
2000 return self.wsgi_app(environ, start_response)
2001
2002 def __repr__(self):
2003 return '<%s %r>' % (
2004 self.__class__.__name__,
2005 self.name,
2006 )