Skip to content
Myr

out with the old

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

authored by Justin Quick · committed by Justin Quick · parent a154c87 · Browse files · 1 file+0 added−1573 removed
This commit

State

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

Diff stats

1 file+0 added−1573 removed

  • other:+0 added−1573 removed

1 file+0 added−1573 removed

deleted:flask.py-1573 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: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12from __future__ import with_statement13import os14import sys15import mimetypes16from datetime import datetime, timedelta1718# this is a workaround for appengine. Do not remove this import19import werkzeug2021from itertools import chain22from threading import Lock23from jinja2 import Environment, PackageLoader, FileSystemLoader24from werkzeug import Request as RequestBase, Response as ResponseBase, \25 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \26 ImmutableDict, cached_property, wrap_file, Headers, \27 import_string28from werkzeug.routing import Map, Rule29from werkzeug.exceptions import HTTPException, InternalServerError30from werkzeug.contrib.securecookie import SecureCookie3132# try to load the best simplejson implementation available. If JSON33# is not installed, we add a failing class.34json_available = True35try:36 import simplejson as json37except ImportError:38 try:39 import json40 except ImportError:41 json_available = False4243# utilities we import from Werkzeug and Jinja2 that are unused44# in the module but are exported as public interface.45from werkzeug import abort, redirect46from jinja2 import Markup, escape4748# use pkg_resource if that works, otherwise fall back to cwd. The49# current working directory is generally not reliable with the notable50# exception of google appengine.51try:52 import pkg_resources53 pkg_resources.resource_stream54except (ImportError, AttributeError):55 pkg_resources = None5657# a lock used for logger initialization58_logger_lock = Lock()596061class Request(RequestBase):62 """The request object used by default in flask. Remembers the63 matched endpoint and view arguments.6465 It is what ends up as :class:`~flask.request`. If you want to replace66 the request object used you can subclass this and set67 :attr:`~flask.Flask.request_class` to your subclass.68 """6970 #: the endpoint that matched the request. This in combination with71 #: :attr:`view_args` can be used to reconstruct the same or a72 #: modified URL. If an exception happened when matching, this will73 #: be `None`.74 endpoint = None7576 #: a dict of view arguments that matched the request. If an exception77 #: happened when matching, this will be `None`.78 view_args = None7980 #: if matching the URL failed, this is the exception that will be81 #: raised / was raised as part of the request handling. This is82 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or83 #: something similar.84 routing_exception = None8586 @property87 def module(self):88 """The name of the current module"""89 if self.endpoint and '.' in self.endpoint:90 return self.endpoint.rsplit('.', 1)[0]9192 @cached_property93 def json(self):94 """If the mimetype is `application/json` this will contain the95 parsed JSON data.96 """97 if __debug__:98 _assert_have_json()99 if self.mimetype == 'application/json':100 return json.loads(self.data)101102103class Response(ResponseBase):104 """The response object that is used by default in flask. Works like the105 response object from Werkzeug but is set to have a 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.111 """112 default_mimetype = 'text/html'113114115class _RequestGlobals(object):116 pass117118119class Session(SecureCookie):120 """Expands the session with support for switching between permanent121 and non-permanent sessions.122 """123124 def _get_permanent(self):125 return self.get('_permanent', False)126127 def _set_permanent(self, value):128 self['_permanent'] = bool(value)129130 permanent = property(_get_permanent, _set_permanent)131 del _get_permanent, _set_permanent132133134class _NullSession(Session):135 """Class used to generate nicer error messages if sessions are not136 available. Will still allow read-only access to the empty session137 but fail on setting.138 """139140 def _fail(self, *args, **kwargs):141 raise RuntimeError('the session is unavailable because no secret '142 'key was set. Set the secret_key on the '143 'application to something unique and secret')144 __setitem__ = __delitem__ = clear = pop = popitem = \145 update = setdefault = _fail146 del _fail147148149class _RequestContext(object):150 """The request context contains all request relevant information. It is151 created at the beginning of the request and pushed to the152 `_request_ctx_stack` and removed at the end of it. It will create the153 URL adapter and request object for the WSGI environment provided.154 """155156 def __init__(self, app, environ):157 self.app = app158 self.url_adapter = app.url_map.bind_to_environ(environ,159 server_name=app.config['SERVER_NAME'])160 self.request = app.request_class(environ)161 self.session = app.open_session(self.request)162 if self.session is None:163 self.session = _NullSession()164 self.g = _RequestGlobals()165 self.flashes = None166167 try:168 self.request.endpoint, self.request.view_args = \169 self.url_adapter.match()170 except HTTPException, e:171 self.request.routing_exception = e172173 def push(self):174 """Binds the request context."""175 _request_ctx_stack.push(self)176177 def pop(self):178 """Pops the request context."""179 _request_ctx_stack.pop()180181 def __enter__(self):182 self.push()183 return self184185 def __exit__(self, exc_type, exc_value, tb):186 # do not pop the request stack if we are in debug mode and an187 # exception happened. This will allow the debugger to still188 # access the request object in the interactive shell. Furthermore189 # the context can be force kept alive for the test client.190 if not self.request.environ.get('flask._preserve_context') and \191 (tb is None or not self.app.debug):192 self.pop()193194195def url_for(endpoint, **values):196 """Generates a URL to the given endpoint with the method provided.197 The endpoint is relative to the active module if modules are in use.198199 Here some examples:200201 ==================== ======================= =============================202 Active Module Target Endpoint Target Function203 ==================== ======================= =============================204 `None` ``'index'`` `index` of the application205 `None` ``'.index'`` `index` of the application206 ``'admin'`` ``'index'`` `index` of the `admin` module207 any ``'.index'`` `index` of the application208 any ``'admin.index'`` `index` of the `admin` module209 ==================== ======================= =============================210211 Variable arguments that are unknown to the target endpoint are appended212 to the generated URL as query arguments.213214 For more information, head over to the :ref:`Quickstart <url-building>`.215216 :param endpoint: the endpoint of the URL (name of the function)217 :param values: the variable arguments of the URL rule218 :param _external: if set to `True`, an absolute URL is generated.219 """220 ctx = _request_ctx_stack.top221 if '.' not in endpoint:222 mod = ctx.request.module223 if mod is not None:224 endpoint = mod + '.' + endpoint225 elif endpoint.startswith('.'):226 endpoint = endpoint[1:]227 external = values.pop('_external', False)228 return ctx.url_adapter.build(endpoint, values, force_external=external)229230231def get_template_attribute(template_name, attribute):232 """Loads a macro (or variable) a template exports. This can be used to233 invoke a macro from within Python code. If you for example have a234 template named `_cider.html` with the following contents:235236 .. sourcecode:: html+jinja237238 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}239240 You can access this from Python code like this::241242 hello = get_template_attribute('_cider.html', 'hello')243 return hello('World')244245 .. versionadded:: 0.2246247 :param template_name: the name of the template248 :param attribute: the name of the variable of macro to acccess249 """250 return getattr(current_app.jinja_env.get_template(template_name).module,251 attribute)252253254def flash(message, category='message'):255 """Flashes a message to the next request. In order to remove the256 flashed message from the session and to display it to the user,257 the template has to call :func:`get_flashed_messages`.258259 .. versionchanged: 0.3260 `category` parameter added.261262 :param message: the message to be flashed.263 :param category: the category for the message. The following values264 are recommended: ``'message'`` for any kind of message,265 ``'error'`` for errors, ``'info'`` for information266 messages and ``'warning'`` for warnings. However any267 kind of string can be used as category.268 """269 session.setdefault('_flashes', []).append((category, message))270271272def get_flashed_messages(with_categories=False):273 """Pulls all flashed messages from the session and returns them.274 Further calls in the same request to the function will return275 the same messages. By default just the messages are returned,276 but when `with_categories` is set to `True`, the return value will277 be a list of tuples in the form ``(category, message)`` instead.278279 Example usage:280281 .. sourcecode:: html+jinja282283 {% for category, msg in get_flashed_messages(with_categories=true) %}284 <p class=flash-{{ category }}>{{ msg }}285 {% endfor %}286287 .. versionchanged:: 0.3288 `with_categories` parameter added.289290 :param with_categories: set to `True` to also receive categories.291 """292 flashes = _request_ctx_stack.top.flashes293 if flashes is None:294 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])295 if not with_categories:296 return [x[1] for x in flashes]297 return flashes298299300def jsonify(*args, **kwargs):301 """Creates a :class:`~flask.Response` with the JSON representation of302 the given arguments with an `application/json` mimetype. The arguments303 to this function are the same as to the :class:`dict` constructor.304305 Example usage::306307 @app.route('/_get_current_user')308 def get_current_user():309 return jsonify(username=g.user.username,310 email=g.user.email,311 id=g.user.id)312313 This will send a JSON response like this to the browser::314315 {316 "username": "admin",317 "email": "admin@localhost",318 "id": 42319 }320321 This requires Python 2.6 or an installed version of simplejson. For322 security reasons only objects are supported toplevel. For more323 information about this, have a look at :ref:`json-security`.324325 .. versionadded:: 0.2326 """327 if __debug__:328 _assert_have_json()329 return current_app.response_class(json.dumps(dict(*args, **kwargs),330 indent=None if request.is_xhr else 2), mimetype='application/json')331332333def send_file(filename_or_fp, mimetype=None, as_attachment=False,334 attachment_filename=None):335 """Sends the contents of a file to the client. This will use the336 most efficient method available and configured. By default it will337 try to use the WSGI server's file_wrapper support. Alternatively338 you can set the application's :attr:`~Flask.use_x_sendfile` attribute339 to ``True`` to directly emit an `X-Sendfile` header. This however340 requires support of the underlying webserver for `X-Sendfile`.341342 By default it will try to guess the mimetype for you, but you can343 also explicitly provide one. For extra security you probably want344 to sent certain files as attachment (HTML for instance).345346 Please never pass filenames to this function from user sources without347 checking them first. Something like this is usually sufficient to348 avoid security problems::349350 if '..' in filename or filename.startswith('/'):351 abort(404)352353 .. versionadded:: 0.2354355 :param filename_or_fp: the filename of the file to send. This is356 relative to the :attr:`~Flask.root_path` if a357 relative path is specified.358 Alternatively a file object might be provided359 in which case `X-Sendfile` might not work and360 fall back to the traditional method.361 :param mimetype: the mimetype of the file if provided, otherwise362 auto detection happens.363 :param as_attachment: set to `True` if you want to send this file with364 a ``Content-Disposition: attachment`` header.365 :param attachment_filename: the filename for the attachment if it366 differs from the file's filename.367 """368 if isinstance(filename_or_fp, basestring):369 filename = filename_or_fp370 file = None371 else:372 file = filename_or_fp373 filename = getattr(file, 'name', None)374 if filename is not None:375 filename = os.path.join(current_app.root_path, filename)376 if mimetype is None and (filename or attachment_filename):377 mimetype = mimetypes.guess_type(filename or attachment_filename)[0]378 if mimetype is None:379 mimetype = 'application/octet-stream'380381 headers = Headers()382 if as_attachment:383 if attachment_filename is None:384 if filename is None:385 raise TypeError('filename unavailable, required for '386 'sending as attachment')387 attachment_filename = os.path.basename(filename)388 headers.add('Content-Disposition', 'attachment',389 filename=attachment_filename)390391 if current_app.use_x_sendfile and filename:392 if file is not None:393 file.close()394 headers['X-Sendfile'] = filename395 data = None396 else:397 if file is None:398 file = open(filename, 'rb')399 data = wrap_file(request.environ, file)400401 return Response(data, mimetype=mimetype, headers=headers,402 direct_passthrough=True)403404405def render_template(template_name, **context):406 """Renders a template from the template folder with the given407 context.408409 :param template_name: the name of the template to be rendered410 :param context: the variables that should be available in the411 context of the template.412 """413 current_app.update_template_context(context)414 return current_app.jinja_env.get_template(template_name).render(context)415416417def render_template_string(source, **context):418 """Renders a template from the given template source string419 with the given context.420421 :param template_name: the sourcecode of the template to be422 rendered423 :param context: the variables that should be available in the424 context of the template.425 """426 current_app.update_template_context(context)427 return current_app.jinja_env.from_string(source).render(context)428429430def _default_template_ctx_processor():431 """Default template context processor. Injects `request`,432 `session` and `g`.433 """434 reqctx = _request_ctx_stack.top435 return dict(436 request=reqctx.request,437 session=reqctx.session,438 g=reqctx.g439 )440441442def _assert_have_json():443 """Helper function that fails if JSON is unavailable."""444 if not json_available:445 raise RuntimeError('simplejson not installed')446447448def _get_package_path(name):449 """Returns the path to a package or cwd if that cannot be found."""450 try:451 return os.path.abspath(os.path.dirname(sys.modules[name].__file__))452 except (KeyError, AttributeError):453 return os.getcwd()454455456# figure out if simplejson escapes slashes. This behaviour was changed457# from one version to another without reason.458if not json_available or '\\/' not in json.dumps('/'):459460 def _tojson_filter(*args, **kwargs):461 if __debug__:462 _assert_have_json()463 return json.dumps(*args, **kwargs).replace('/', '\\/')464else:465 _tojson_filter = json.dumps466467468class _PackageBoundObject(object):469470 def __init__(self, import_name):471 #: The name of the package or module. Do not change this once472 #: it was set by the constructor.473 self.import_name = import_name474475 #: Where is the app root located?476 self.root_path = _get_package_path(self.import_name)477478 def open_resource(self, resource):479 """Opens a resource from the application's resource folder. To see480 how this works, consider the following folder structure::481482 /myapplication.py483 /schemal.sql484 /static485 /style.css486 /templates487 /layout.html488 /index.html489490 If you want to open the `schema.sql` file you would do the491 following::492493 with app.open_resource('schema.sql') as f:494 contents = f.read()495 do_something_with(contents)496497 :param resource: the name of the resource. To access resources within498 subfolders use forward slashes as separator.499 """500 if pkg_resources is None:501 return open(os.path.join(self.root_path, resource), 'rb')502 return pkg_resources.resource_stream(self.import_name, resource)503504505class _ModuleSetupState(object):506507 def __init__(self, app, url_prefix=None):508 self.app = app509 self.url_prefix = url_prefix510511512class Module(_PackageBoundObject):513 """Container object that enables pluggable applications. A module can514 be used to organize larger applications. They represent blueprints that,515 in combination with a :class:`Flask` object are used to create a large516 application.517518 A module is like an application bound to an `import_name`. Multiple519 modules can share the same import names, but in that case a `name` has520 to be provided to keep them apart. If different import names are used,521 the rightmost part of the import name is used as name.522523 Here an example structure for a larger appliation::524525 /myapplication526 /__init__.py527 /views528 /__init__.py529 /admin.py530 /frontend.py531532 The `myapplication/__init__.py` can look like this::533534 from flask import Flask535 from myapplication.views.admin import admin536 from myapplication.views.frontend import frontend537538 app = Flask(__name__)539 app.register_module(admin, url_prefix='/admin')540 app.register_module(frontend)541542 And here an example view module (`myapplication/views/admin.py`)::543544 from flask import Module545546 admin = Module(__name__)547548 @admin.route('/')549 def index():550 pass551552 @admin.route('/login')553 def login():554 pass555556 For a gentle introduction into modules, checkout the557 :ref:`working-with-modules` section.558 """559560 def __init__(self, import_name, name=None, url_prefix=None):561 if name is None:562 assert '.' in import_name, 'name required if package name ' \563 'does not point to a submodule'564 name = import_name.rsplit('.', 1)[1]565 _PackageBoundObject.__init__(self, import_name)566 self.name = name567 self.url_prefix = url_prefix568 self._register_events = []569570 def route(self, rule, **options):571 """Like :meth:`Flask.route` but for a module. The endpoint for the572 :func:`url_for` function is prefixed with the name of the module.573 """574 def decorator(f):575 self.add_url_rule(rule, f.__name__, f, **options)576 return f577 return decorator578579 def add_url_rule(self, rule, endpoint, view_func=None, **options):580 """Like :meth:`Flask.add_url_rule` but for a module. The endpoint for581 the :func:`url_for` function is prefixed with the name of the module.582 """583 def register_rule(state):584 the_rule = rule585 if state.url_prefix:586 the_rule = state.url_prefix + rule587 state.app.add_url_rule(the_rule, '%s.%s' % (self.name, endpoint),588 view_func, **options)589 self._record(register_rule)590591 def before_request(self, f):592 """Like :meth:`Flask.before_request` but for a module. This function593 is only executed before each request that is handled by a function of594 that module.595 """596 self._record(lambda s: s.app.before_request_funcs597 .setdefault(self.name, []).append(f))598 return f599600 def before_app_request(self, f):601 """Like :meth:`Flask.before_request`. Such a function is executed602 before each request, even if outside of a module.603 """604 self._record(lambda s: s.app.before_request_funcs605 .setdefault(None, []).append(f))606 return f607608 def after_request(self, f):609 """Like :meth:`Flask.after_request` but for a module. This function610 is only executed after each request that is handled by a function of611 that module.612 """613 self._record(lambda s: s.app.after_request_funcs614 .setdefault(self.name, []).append(f))615 return f616617 def after_app_request(self, f):618 """Like :meth:`Flask.after_request` but for a module. Such a function619 is executed after each request, even if outside of the module.620 """621 self._record(lambda s: s.app.after_request_funcs622 .setdefault(None, []).append(f))623 return f624625 def context_processor(self, f):626 """Like :meth:`Flask.context_processor` but for a module. This627 function is only executed for requests handled by a module.628 """629 self._record(lambda s: s.app.template_context_processors630 .setdefault(self.name, []).append(f))631 return f632633 def app_context_processor(self, f):634 """Like :meth:`Flask.context_processor` but for a module. Such a635 function is executed each request, even if outside of the module.636 """637 self._record(lambda s: s.app.template_context_processors638 .setdefault(None, []).append(f))639 return f640641 def app_errorhandler(self, code):642 """Like :meth:`Flask.errorhandler` but for a module. This643 handler is used for all requests, even if outside of the module.644645 .. versionadded:: 0.4646 """647 def decorator(f):648 self._record(lambda s: s.app.errorhandler(code)(f))649 return f650 return decorator651652 def _record(self, func):653 self._register_events.append(func)654655656class ConfigAttribute(object):657 """Makes an attribute forward to the config"""658659 def __init__(self, name):660 self.__name__ = name661662 def __get__(self, obj, type=None):663 if obj is None:664 return self665 return obj.config[self.__name__]666667 def __set__(self, obj, value):668 obj.config[self.__name__] = value669670671class Config(dict):672 """Works exactly like a dict but provides ways to fill it from files673 or special dictionaries. There are two common patterns to populate the674 config.675676 Either you can fill the config from a config file::677678 app.config.from_pyfile('yourconfig.cfg')679680 Or alternatively you can define the configuration options in the681 module that calls :meth:`from_object` or provide an import path to682 a module that should be loaded. It is also possible to tell it to683 use the same module and with that provide the configuration values684 just before the call::685686 DEBUG = True687 SECRET_KEY = 'development key'688 app.config.from_object(__name__)689690 In both cases (loading from any Python file or loading from modules),691 only uppercase keys are added to the config. This makes it possible to use692 lowercase values in the config file for temporary values that are not added693 to the config or to define the config keys in the same file that implements694 the application.695696 Probably the most interesting way to load configurations is from an697 environment variable pointing to a file::698699 app.config.from_envvar('YOURAPPLICATION_SETTINGS')700701 In this case before launching the application you have to set this702 environment variable to the file you want to use. On Linux and OS X703 use the export statement::704705 export YOURAPPLICATION_SETTINGS='/path/to/config/file'706707 On windows use `set` instead.708709 :param root_path: path to which files are read relative from. When the710 config object is created by the application, this is711 the application's :attr:`~flask.Flask.root_path`.712 :param defaults: an optional dictionary of default values713 """714715 def __init__(self, root_path, defaults=None):716 dict.__init__(self, defaults or {})717 self.root_path = root_path718719 def from_envvar(self, variable_name, silent=False):720 """Loads a configuration from an environment variable pointing to721 a configuration file. This basically is just a shortcut with nicer722 error messages for this line of code::723724 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])725726 :param variable_name: name of the environment variable727 :param silent: set to `True` if you want silent failing for missing728 files.729 :return: bool. `True` if able to load config, `False` otherwise.730 """731 rv = os.environ.get(variable_name)732 if not rv:733 if silent:734 return False735 raise RuntimeError('The environment variable %r is not set '736 'and as such configuration could not be '737 'loaded. Set this variable and make it '738 'point to a configuration file' %739 variable_name)740 self.from_pyfile(rv)741 return True742743 def from_pyfile(self, filename):744 """Updates the values in the config from a Python file. This function745 behaves as if the file was imported as module with the746 :meth:`from_object` function.747748 :param filename: the filename of the config. This can either be an749 absolute filename or a filename relative to the750 root path.751 """752 filename = os.path.join(self.root_path, filename)753 d = type(sys)('config')754 d.__file__ = filename755 execfile(filename, d.__dict__)756 self.from_object(d)757758 def from_object(self, obj):759 """Updates the values from the given object. An object can be of one760 of the following two types:761762 - a string: in this case the object with that name will be imported763 - an actual object reference: that object is used directly764765 Objects are usually either modules or classes.766767 Just the uppercase variables in that object are stored in the config768 after lowercasing. Example usage::769770 app.config.from_object('yourapplication.default_config')771 from yourapplication import default_config772 app.config.from_object(default_config)773774 You should not use this function to load the actual configuration but775 rather configuration defaults. The actual config should be loaded776 with :meth:`from_pyfile` and ideally from a location not within the777 package because the package might be installed system wide.778779 :param obj: an import name or object780 """781 if isinstance(obj, basestring):782 obj = import_string(obj)783 for key in dir(obj):784 if key.isupper():785 self[key] = getattr(obj, key)786787 def __repr__(self):788 return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))789790791class Flask(_PackageBoundObject):792 """The flask object implements a WSGI application and acts as the central793 object. It is passed the name of the module or package of the794 application. Once it is created it will act as a central registry for795 the view functions, the URL rules, template configuration and much more.796797 The name of the package is used to resolve resources from inside the798 package or the folder the module is contained in depending on if the799 package parameter resolves to an actual python package (a folder with800 an `__init__.py` file inside) or a standard module (just a `.py` file).801802 For more information about resource loading, see :func:`open_resource`.803804 Usually you create a :class:`Flask` instance in your main module or805 in the `__init__.py` file of your package like this::806807 from flask import Flask808 app = Flask(__name__)809810 .. admonition:: About the First Parameter811812 The idea of the first parameter is to give Flask an idea what813 belongs to your application. This name is used to find resources814 on the file system, can be used by extensions to improve debugging815 information and a lot more.816817 So it's important what you provide there. If you are using a single818 module, `__name__` is always the correct value. If you however are819 using a package, it's usually recommended to hardcode the name of820 your package there.821822 For example if your application is defined in `yourapplication/app.py`823 you should create it with one of the two versions below::824825 app = Flask('yourapplication')826 app = Flask(__name__.split('.')[0])827828 Why is that? The application will work even with `__name__`, thanks829 to how resources are looked up. However it will make debugging more830 painful. Certain extensions can make assumptions based on the831 import name of your application. For example the Flask-SQLAlchemy832 extension will look for the code in your application that triggered833 an SQL query in debug mode. If the import name is not properly set834 up, that debugging information is lost. (For example it would only835 pick up SQL queries in `yourapplicaiton.app` and not836 `yourapplication.views.frontend`)837 """838839 #: The class that is used for request objects. See :class:`~flask.Request`840 #: for more information.841 request_class = Request842843 #: The class that is used for response objects. See844 #: :class:`~flask.Response` for more information.845 response_class = Response846847 #: Path for the static files. If you don't want to use static files848 #: you can set this value to `None` in which case no URL rule is added849 #: and the development server will no longer serve any static files.850 static_path = '/static'851852 #: The debug flag. Set this to `True` to enable debugging of the853 #: application. In debug mode the debugger will kick in when an unhandled854 #: exception ocurrs and the integrated server will automatically reload855 #: the application if changes in the code are detected.856 #:857 #: This attribute can also be configured from the config with the `DEBUG`858 #: configuration key. Defaults to `False`.859 debug = ConfigAttribute('DEBUG')860861 #: The testing flask. Set this to `True` to enable the test mode of862 #: Flask extensions (and in the future probably also Flask itself).863 #: For example this might activate unittest helpers that have an864 #: additional runtime cost which should not be enabled by default.865 #:866 #: This attribute can also be configured from the config with the867 #: `TESTING` configuration key. Defaults to `False`.868 testing = ConfigAttribute('TESTING')869870 #: If a secret key is set, cryptographic components can use this to871 #: sign cookies and other things. Set this to a complex random value872 #: when you want to use the secure cookie for instance.873 #:874 #: This attribute can also be configured from the config with the875 #: `SECRET_KEY` configuration key. Defaults to `None`.876 secret_key = ConfigAttribute('SECRET_KEY')877878 #: The secure cookie uses this for the name of the session cookie.879 #:880 #: This attribute can also be configured from the config with the881 #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``882 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')883884 #: A :class:`~datetime.timedelta` which is used to set the expiration885 #: date of a permanent session. The default is 31 days which makes a886 #: permanent session survive for roughly one month.887 #:888 #: This attribute can also be configured from the config with the889 #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to890 #: ``timedelta(days=31)``891 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME')892893 #: Enable this if you want to use the X-Sendfile feature. Keep in894 #: mind that the server has to support this. This only affects files895 #: sent with the :func:`send_file` method.896 #:897 #: .. versionadded:: 0.2898 #:899 #: This attribute can also be configured from the config with the900 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.901 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')902903 #: The name of the logger to use. By default the logger name is the904 #: package name passed to the constructor.905 #:906 #: .. versionadded:: 0.4907 logger_name = ConfigAttribute('LOGGER_NAME')908909 #: The logging format used for the debug logger. This is only used when910 #: the application is in debug mode, otherwise the attached logging911 #: handler does the formatting.912 #:913 #: .. versionadded:: 0.3914 debug_log_format = (915 '-' * 80 + '\n' +916 '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +917 '%(message)s\n' +918 '-' * 80919 )920921 #: Options that are passed directly to the Jinja2 environment.922 jinja_options = ImmutableDict(923 autoescape=True,924 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']925 )926927 #: Default configuration parameters.928 default_config = ImmutableDict({929 'DEBUG': False,930 'TESTING': False,931 'SECRET_KEY': None,932 'SESSION_COOKIE_NAME': 'session',933 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),934 'USE_X_SENDFILE': False,935 'LOGGER_NAME': None,936 'SERVER_NAME': None937 })938939 def __init__(self, import_name):940 _PackageBoundObject.__init__(self, import_name)941942 #: The configuration dictionary as :class:`Config`. This behaves943 #: exactly like a regular dictionary but supports additional methods944 #: to load a config from files.945 self.config = Config(self.root_path, self.default_config)946947 #: Prepare the deferred setup of the logger.948 self._logger = None949 self.logger_name = self.import_name950951 #: A dictionary of all view functions registered. The keys will952 #: be function names which are also used to generate URLs and953 #: the values are the function objects themselves.954 #: to register a view function, use the :meth:`route` decorator.955 self.view_functions = {}956957 #: A dictionary of all registered error handlers. The key is958 #: be the error code as integer, the value the function that959 #: should handle that error.960 #: To register a error handler, use the :meth:`errorhandler`961 #: decorator.962 self.error_handlers = {}963964 #: A dictionary with lists of functions that should be called at the965 #: beginning of the request. The key of the dictionary is the name of966 #: the module this function is active for, `None` for all requests.967 #: This can for example be used to open database connections or968 #: getting hold of the currently logged in user. To register a969 #: function here, use the :meth:`before_request` decorator.970 self.before_request_funcs = {}971972 #: A dictionary with lists of functions that should be called after973 #: each request. The key of the dictionary is the name of the module974 #: this function is active for, `None` for all requests. This can for975 #: example be used to open database connections or getting hold of the976 #: currently logged in user. To register a function here, use the977 #: :meth:`before_request` decorator.978 self.after_request_funcs = {}979980 #: A dictionary with list of functions that are called without argument981 #: to populate the template context. They key of the dictionary is the982 #: name of the module this function is active for, `None` for all983 #: requests. Each returns a dictionary that the template context is984 #: updated with. To register a function here, use the985 #: :meth:`context_processor` decorator.986 self.template_context_processors = {987 None: [_default_template_ctx_processor]988 }989990 #: The :class:`~werkzeug.routing.Map` for this instance. You can use991 #: this to change the routing converters after the class was created992 #: but before any routes are connected. Example::993 #:994 #: from werkzeug import BaseConverter995 #:996 #: class ListConverter(BaseConverter):997 #: def to_python(self, value):998 #: return value.split(',')999 #: def to_url(self, values):1000 #: return ','.join(BaseConverter.to_url(value)1001 #: for value in values)1002 #:1003 #: app = Flask(__name__)1004 #: app.url_map.converters['list'] = ListConverter1005 self.url_map = Map()10061007 if self.static_path is not None:1008 self.add_url_rule(self.static_path + '/<filename>',1009 build_only=True, endpoint='static')1010 if pkg_resources is not None:1011 target = (self.import_name, 'static')1012 else:1013 target = os.path.join(self.root_path, 'static')1014 self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {1015 self.static_path: target1016 })10171018 #: The Jinja2 environment. It is created from the1019 #: :attr:`jinja_options` and the loader that is returned1020 #: by the :meth:`create_jinja_loader` function.1021 self.jinja_env = Environment(loader=self.create_jinja_loader(),1022 **self.jinja_options)1023 self.jinja_env.globals.update(1024 url_for=url_for,1025 get_flashed_messages=get_flashed_messages1026 )1027 self.jinja_env.filters['tojson'] = _tojson_filter10281029 @property1030 def logger(self):1031 """A :class:`logging.Logger` object for this application. The1032 default configuration is to log to stderr if the application is1033 in debug mode. This logger can be used to (surprise) log messages.1034 Here some examples::10351036 app.logger.debug('A value for debugging')1037 app.logger.warning('A warning ocurred (%d apples)', 42)1038 app.logger.error('An error occoured')10391040 .. versionadded:: 0.31041 """1042 if self._logger and self._logger.name == self.logger_name:1043 return self._logger1044 with _logger_lock:1045 if self._logger and self._logger.name == self.logger_name:1046 return self._logger1047 from logging import getLogger, StreamHandler, Formatter, \1048 Logger, DEBUG1049 class DebugLogger(Logger):1050 def getEffectiveLevel(x):1051 return DEBUG if self.debug else Logger.getEffectiveLevel(x)1052 class DebugHandler(StreamHandler):1053 def emit(x, record):1054 StreamHandler.emit(x, record) if self.debug else None1055 handler = DebugHandler()1056 handler.setLevel(DEBUG)1057 handler.setFormatter(Formatter(self.debug_log_format))1058 logger = getLogger(self.logger_name)1059 logger.__class__ = DebugLogger1060 logger.addHandler(handler)1061 self._logger = logger1062 return logger10631064 def create_jinja_loader(self):1065 """Creates the Jinja loader. By default just a package loader for1066 the configured package is returned that looks up templates in the1067 `templates` folder. To add other loaders it's possible to1068 override this method.1069 """1070 if pkg_resources is None:1071 return FileSystemLoader(os.path.join(self.root_path, 'templates'))1072 return PackageLoader(self.import_name)10731074 def update_template_context(self, context):1075 """Update the template context with some commonly used variables.1076 This injects request, session and g into the template context.10771078 :param context: the context as a dictionary that is updated in place1079 to add extra variables.1080 """1081 funcs = self.template_context_processors[None]1082 mod = _request_ctx_stack.top.request.module1083 if mod is not None and mod in self.template_context_processors:1084 funcs = chain(funcs, self.template_context_processors[mod])1085 for func in funcs:1086 context.update(func())10871088 def run(self, host='127.0.0.1', port=5000, **options):1089 """Runs the application on a local development server. If the1090 :attr:`debug` flag is set the server will automatically reload1091 for code changes and show a debugger in case an exception happened.10921093 .. admonition:: Keep in Mind10941095 Flask will supress any server error with a generic error page1096 unless it is in debug mode. As such to enable just the1097 interactive debugger without the code reloading, you ahve to1098 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.1099 Setting ``use_debugger`` to `True` without being in debug mode1100 won't catch any exceptions because there won't be any to1101 catch.11021103 :param host: the hostname to listen on. set this to ``'0.0.0.0'``1104 to have the server available externally as well.1105 :param port: the port of the webserver1106 :param options: the options to be forwarded to the underlying1107 Werkzeug server. See :func:`werkzeug.run_simple`1108 for more information.1109 """1110 from werkzeug import run_simple1111 if 'debug' in options:1112 self.debug = options.pop('debug')1113 options.setdefault('use_reloader', self.debug)1114 options.setdefault('use_debugger', self.debug)1115 return run_simple(host, port, self, **options)11161117 def test_client(self):1118 """Creates a test client for this application. For information1119 about unit testing head over to :ref:`testing`.11201121 The test client can be used in a `with` block to defer the closing down1122 of the context until the end of the `with` block. This is useful if1123 you want to access the context locals for testing::11241125 with app.test_client() as c:1126 rv = c.get('/?vodka=42')1127 assert request.args['vodka'] == '42'11281129 .. versionchanged:: 0.41130 added support for `with` block usage for the client.1131 """1132 from werkzeug import Client1133 class FlaskClient(Client):1134 preserve_context = context_preserved = False1135 def open(self, *args, **kwargs):1136 if self.context_preserved:1137 _request_ctx_stack.pop()1138 self.context_preserved = False1139 kwargs.setdefault('environ_overrides', {}) \1140 ['flask._preserve_context'] = self.preserve_context1141 old = _request_ctx_stack.top1142 try:1143 return Client.open(self, *args, **kwargs)1144 finally:1145 self.context_preserved = _request_ctx_stack.top is not old1146 def __enter__(self):1147 self.preserve_context = True1148 return self1149 def __exit__(self, exc_type, exc_value, tb):1150 self.preserve_context = False1151 if self.context_preserved:1152 _request_ctx_stack.pop()1153 return FlaskClient(self, self.response_class, use_cookies=True)11541155 def open_session(self, request):1156 """Creates or opens a new session. Default implementation stores all1157 session data in a signed cookie. This requires that the1158 :attr:`secret_key` is set.11591160 :param request: an instance of :attr:`request_class`.1161 """1162 key = self.secret_key1163 if key is not None:1164 return Session.load_cookie(request, self.session_cookie_name,1165 secret_key=key)11661167 def save_session(self, session, response):1168 """Saves the session if it needs updates. For the default1169 implementation, check :meth:`open_session`.11701171 :param session: the session to be saved (a1172 :class:`~werkzeug.contrib.securecookie.SecureCookie`1173 object)1174 :param response: an instance of :attr:`response_class`1175 """1176 expires = None1177 if session.permanent:1178 expires = datetime.utcnow() + self.permanent_session_lifetime1179 session.save_cookie(response, self.session_cookie_name,1180 expires=expires, httponly=True)11811182 def register_module(self, module, **options):1183 """Registers a module with this application. The keyword argument1184 of this function are the same as the ones for the constructor of the1185 :class:`Module` class and will override the values of the module if1186 provided.1187 """1188 options.setdefault('url_prefix', module.url_prefix)1189 state = _ModuleSetupState(self, **options)1190 for func in module._register_events:1191 func(state)11921193 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):1194 """Connects a URL rule. Works exactly like the :meth:`route`1195 decorator. If a view_func is provided it will be registered with the1196 endpoint.11971198 Basically this example::11991200 @app.route('/')1201 def index():1202 pass12031204 Is equivalent to the following::12051206 def index():1207 pass1208 app.add_url_rule('/', 'index', index)12091210 If the view_func is not provided you will need to connect the endpoint1211 to a view function like so::12121213 app.view_functions['index'] = index12141215 .. versionchanged:: 0.21216 `view_func` parameter added.12171218 :param rule: the URL rule as string1219 :param endpoint: the endpoint for the registered URL rule. Flask1220 itself assumes the name of the view function as1221 endpoint1222 :param view_func: the function to call when serving a request to the1223 provided endpoint1224 :param options: the options to be forwarded to the underlying1225 :class:`~werkzeug.routing.Rule` object1226 """1227 if endpoint is None:1228 assert view_func is not None, 'expected view func if endpoint ' \1229 'is not provided.'1230 endpoint = view_func.__name__1231 options['endpoint'] = endpoint1232 options.setdefault('methods', ('GET',))1233 self.url_map.add(Rule(rule, **options))1234 if view_func is not None:1235 self.view_functions[endpoint] = view_func12361237 def route(self, rule, **options):1238 """A decorator that is used to register a view function for a1239 given URL rule. Example::12401241 @app.route('/')1242 def index():1243 return 'Hello World'12441245 Variables parts in the route can be specified with angular1246 brackets (``/user/<username>``). By default a variable part1247 in the URL accepts any string without a slash however a different1248 converter can be specified as well by using ``<converter:name>``.12491250 Variable parts are passed to the view function as keyword1251 arguments.12521253 The following converters are possible:12541255 =========== ===========================================1256 `int` accepts integers1257 `float` like `int` but for floating point values1258 `path` like the default but also accepts slashes1259 =========== ===========================================12601261 Here some examples::12621263 @app.route('/')1264 def index():1265 pass12661267 @app.route('/<username>')1268 def show_user(username):1269 pass12701271 @app.route('/post/<int:post_id>')1272 def show_post(post_id):1273 pass12741275 An important detail to keep in mind is how Flask deals with trailing1276 slashes. The idea is to keep each URL unique so the following rules1277 apply:12781279 1. If a rule ends with a slash and is requested without a slash1280 by the user, the user is automatically redirected to the same1281 page with a trailing slash attached.1282 2. If a rule does not end with a trailing slash and the user request1283 the page with a trailing slash, a 404 not found is raised.12841285 This is consistent with how web servers deal with static files. This1286 also makes it possible to use relative link targets safely.12871288 The :meth:`route` decorator accepts a couple of other arguments1289 as well:12901291 :param rule: the URL rule as string1292 :param methods: a list of methods this rule should be limited1293 to (``GET``, ``POST`` etc.). By default a rule1294 just listens for ``GET`` (and implicitly ``HEAD``).1295 :param subdomain: specifies the rule for the subdoain in case1296 subdomain matching is in use.1297 :param strict_slashes: can be used to disable the strict slashes1298 setting for this rule. See above.1299 :param options: other options to be forwarded to the underlying1300 :class:`~werkzeug.routing.Rule` object.1301 """1302 def decorator(f):1303 self.add_url_rule(rule, None, f, **options)1304 return f1305 return decorator13061307 def errorhandler(self, code):1308 """A decorator that is used to register a function give a given1309 error code. Example::13101311 @app.errorhandler(404)1312 def page_not_found(error):1313 return 'This page does not exist', 40413141315 You can also register a function as error handler without using1316 the :meth:`errorhandler` decorator. The following example is1317 equivalent to the one above::13181319 def page_not_found(error):1320 return 'This page does not exist', 4041321 app.error_handlers[404] = page_not_found13221323 :param code: the code as integer for the handler1324 """1325 def decorator(f):1326 self.error_handlers[code] = f1327 return f1328 return decorator13291330 def template_filter(self, name=None):1331 """A decorator that is used to register custom template filter.1332 You can specify a name for the filter, otherwise the function1333 name will be used. Example::13341335 @app.template_filter()1336 def reverse(s):1337 return s[::-1]13381339 :param name: the optional name of the filter, otherwise the1340 function name will be used.1341 """1342 def decorator(f):1343 self.jinja_env.filters[name or f.__name__] = f1344 return f1345 return decorator13461347 def before_request(self, f):1348 """Registers a function to run before each request."""1349 self.before_request_funcs.setdefault(None, []).append(f)1350 return f13511352 def after_request(self, f):1353 """Register a function to be run after each request."""1354 self.after_request_funcs.setdefault(None, []).append(f)1355 return f13561357 def context_processor(self, f):1358 """Registers a template context processor function."""1359 self.template_context_processors[None].append(f)1360 return f13611362 def handle_http_exception(self, e):1363 """Handles an HTTP exception. By default this will invoke the1364 registered error handlers and fall back to returning the1365 exception as response.13661367 .. versionadded: 0.31368 """1369 handler = self.error_handlers.get(e.code)1370 if handler is None:1371 return e1372 return handler(e)13731374 def handle_exception(self, e):1375 """Default exception handling that kicks in when an exception1376 occours that is not catched. In debug mode the exception will1377 be re-raised immediately, otherwise it is logged and the handler1378 for a 500 internal server error is used. If no such handler1379 exists, a default 500 internal server error message is displayed.13801381 .. versionadded: 0.31382 """1383 handler = self.error_handlers.get(500)1384 if self.debug:1385 raise1386 self.logger.exception('Exception on %s [%s]' % (1387 request.path,1388 request.method1389 ))1390 if handler is None:1391 return InternalServerError()1392 return handler(e)13931394 def dispatch_request(self):1395 """Does the request dispatching. Matches the URL and returns the1396 return value of the view or error handler. This does not have to1397 be a response object. In order to convert the return value to a1398 proper response object, call :func:`make_response`.1399 """1400 req = _request_ctx_stack.top.request1401 try:1402 if req.routing_exception is not None:1403 raise req.routing_exception1404 return self.view_functions[req.endpoint](**req.view_args)1405 except HTTPException, e:1406 return self.handle_http_exception(e)14071408 def make_response(self, rv):1409 """Converts the return value from a view function to a real1410 response object that is an instance of :attr:`response_class`.14111412 The following types are allowed for `rv`:14131414 .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|14151416 ======================= ===========================================1417 :attr:`response_class` the object is returned unchanged1418 :class:`str` a response object is created with the1419 string as body1420 :class:`unicode` a response object is created with the1421 string encoded to utf-8 as body1422 :class:`tuple` the response object is created with the1423 contents of the tuple as arguments1424 a WSGI function the function is called as WSGI application1425 and buffered as response object1426 ======================= ===========================================14271428 :param rv: the return value from the view function1429 """1430 if rv is None:1431 raise ValueError('View function did not return a response')1432 if isinstance(rv, self.response_class):1433 return rv1434 if isinstance(rv, basestring):1435 return self.response_class(rv)1436 if isinstance(rv, tuple):1437 return self.response_class(*rv)1438 return self.response_class.force_type(rv, request.environ)14391440 def preprocess_request(self):1441 """Called before the actual request dispatching and will1442 call every as :meth:`before_request` decorated function.1443 If any of these function returns a value it's handled as1444 if it was the return value from the view and further1445 request handling is stopped.1446 """1447 funcs = self.before_request_funcs.get(None, ())1448 mod = request.module1449 if mod and mod in self.before_request_funcs:1450 funcs = chain(funcs, self.before_request_funcs[mod])1451 for func in funcs:1452 rv = func()1453 if rv is not None:1454 return rv14551456 def process_response(self, response):1457 """Can be overridden in order to modify the response object1458 before it's sent to the WSGI server. By default this will1459 call all the :meth:`after_request` decorated functions.14601461 :param response: a :attr:`response_class` object.1462 :return: a new response object or the same, has to be an1463 instance of :attr:`response_class`.1464 """1465 ctx = _request_ctx_stack.top1466 mod = ctx.request.module1467 if not isinstance(ctx.session, _NullSession):1468 self.save_session(ctx.session, response)1469 funcs = ()1470 if mod and mod in self.after_request_funcs:1471 funcs = chain(funcs, self.after_request_funcs[mod])1472 if None in self.after_request_funcs:1473 funcs = chain(funcs, self.after_request_funcs[None])1474 for handler in funcs:1475 response = handler(response)1476 return response14771478 def wsgi_app(self, environ, start_response):1479 """The actual WSGI application. This is not implemented in1480 `__call__` so that middlewares can be applied without losing a1481 reference to the class. So instead of doing this::14821483 app = MyMiddleware(app)14841485 It's a better idea to do this instead::14861487 app.wsgi_app = MyMiddleware(app.wsgi_app)14881489 Then you still have the original application object around and1490 can continue to call methods on it.14911492 .. versionchanged:: 0.41493 The :meth:`after_request` functions are now called even if an1494 error handler took over request processing. This ensures that1495 even if an exception happens database have the chance to1496 properly close the connection.14971498 :param environ: a WSGI environment1499 :param start_response: a callable accepting a status code,1500 a list of headers and an optional1501 exception context to start the response1502 """1503 with self.request_context(environ):1504 try:1505 rv = self.preprocess_request()1506 if rv is None:1507 rv = self.dispatch_request()1508 response = self.make_response(rv)1509 except Exception, e:1510 response = self.make_response(self.handle_exception(e))1511 try:1512 response = self.process_response(response)1513 except Exception, e:1514 response = self.make_response(self.handle_exception(e))1515 return response(environ, start_response)15161517 def request_context(self, environ):1518 """Creates a request context from the given environment and binds1519 it to the current context. This must be used in combination with1520 the `with` statement because the request is only bound to the1521 current context for the duration of the `with` block.15221523 Example usage::15241525 with app.request_context(environ):1526 do_something_with(request)15271528 The object returned can also be used without the `with` statement1529 which is useful for working in the shell. The example above is1530 doing exactly the same as this code::15311532 ctx = app.request_context(environ)1533 ctx.push()1534 try:1535 do_something_with(request)1536 finally:1537 ctx.pop()15381539 The big advantage of this approach is that you can use it without1540 the try/finally statement in a shell for interactive testing:15411542 >>> ctx = app.test_request_context()1543 >>> ctx.bind()1544 >>> request.path1545 u'/'1546 >>> ctx.unbind()15471548 .. versionchanged:: 0.31549 Added support for non-with statement usage and `with` statement1550 is now passed the ctx object.15511552 :param environ: a WSGI environment1553 """1554 return _RequestContext(self, environ)15551556 def test_request_context(self, *args, **kwargs):1557 """Creates a WSGI environment from the given values (see1558 :func:`werkzeug.create_environ` for more information, this1559 function accepts the same arguments).1560 """1561 return self.request_context(create_environ(*args, **kwargs))15621563 def __call__(self, environ, start_response):1564 """Shortcut for :attr:`wsgi_app`."""1565 return self.wsgi_app(environ, start_response)156615671568# context locals1569_request_ctx_stack = LocalStack()1570current_app = LocalProxy(lambda: _request_ctx_stack.top.app)1571request = LocalProxy(lambda: _request_ctx_stack.top.request)1572session = LocalProxy(lambda: _request_ctx_stack.top.session)1573g = LocalProxy(lambda: _request_ctx_stack.top.g)