Skip to content
Myr

Merged in changes from justquick

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

authored by Armin Ronacher · committed by Armin Ronacher · parents 10fff18, 1a69c7d · Browse files · 11 files+1608 added−1602 removed
This commit

State

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

Diff stats

11 files+1608 added−1602 removed

  • tests:+3 added−3 removed
  • other:+1605 added−1599 removed

11 files+1608 added−1602 removed

added:flask/__init__.py+23 added
1# -*- coding: utf-8 -*-2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213# utilities we import from Werkzeug and Jinja2 that are unused14# in the module but are exported as public interface.15from werkzeug import abort, redirect16from jinja2 import Markup, escape1718from flask.app import Flask19from flask.helpers import url_for, jsonify, json_available, flash, send_file, \20 get_flashed_messages, render_template, render_template, render_template_string, \21 get_template_attribute22from flask.globals import current_app, g, request, session, _request_ctx_stack23from flask.module import Module
added:flask/app.py+798 added
1from threading import Lock2from datetime import timedelta, datetime3from itertools import chain45from jinja2 import Environment, PackageLoader, FileSystemLoader6from werkzeug import ImmutableDict, SharedDataMiddleware, create_environ7from werkzeug.routing import Map, Rule8from werkzeug.exceptions import HTTPException, InternalServerError910from flask.helpers import _PackageBoundObject, url_for, get_flashed_messages, \11 _tojson_filter, get_pkg_resources12from flask.wrappers import Request, Response13from flask.conf import ConfigAttribute, Config14from flask.ctx import _default_template_ctx_processor, _RequestContext15from flask.globals import _request_ctx_stack, request16from flask.session import Session, _NullSession17from flask.module import _ModuleSetupState1819# a lock used for logger initialization20_logger_lock = Lock()212223class Flask(_PackageBoundObject):24 """The flask object implements a WSGI application and acts as the central25 object. It is passed the name of the module or package of the26 application. Once it is created it will act as a central registry for27 the view functions, the URL rules, template configuration and much more.2829 The name of the package is used to resolve resources from inside the30 package or the folder the module is contained in depending on if the31 package parameter resolves to an actual python package (a folder with32 an `__init__.py` file inside) or a standard module (just a `.py` file).3334 For more information about resource loading, see :func:`open_resource`.3536 Usually you create a :class:`Flask` instance in your main module or37 in the `__init__.py` file of your package like this::3839 from flask import Flask40 app = Flask(__name__)4142 .. admonition:: About the First Parameter4344 The idea of the first parameter is to give Flask an idea what45 belongs to your application. This name is used to find resources46 on the file system, can be used by extensions to improve debugging47 information and a lot more.4849 So it's important what you provide there. If you are using a single50 module, `__name__` is always the correct value. If you however are51 using a package, it's usually recommended to hardcode the name of52 your package there.5354 For example if your application is defined in `yourapplication/app.py`55 you should create it with one of the two versions below::5657 app = Flask('yourapplication')58 app = Flask(__name__.split('.')[0])5960 Why is that? The application will work even with `__name__`, thanks61 to how resources are looked up. However it will make debugging more62 painful. Certain extensions can make assumptions based on the63 import name of your application. For example the Flask-SQLAlchemy64 extension will look for the code in your application that triggered65 an SQL query in debug mode. If the import name is not properly set66 up, that debugging information is lost. (For example it would only67 pick up SQL queries in `yourapplicaiton.app` and not68 `yourapplication.views.frontend`)69 """7071 #: The class that is used for request objects. See :class:`~flask.Request`72 #: for more information.73 request_class = Request7475 #: The class that is used for response objects. See76 #: :class:`~flask.Response` for more information.77 response_class = Response7879 #: Path for the static files. If you don't want to use static files80 #: you can set this value to `None` in which case no URL rule is added81 #: and the development server will no longer serve any static files.82 static_path = '/static'8384 #: The debug flag. Set this to `True` to enable debugging of the85 #: application. In debug mode the debugger will kick in when an unhandled86 #: exception ocurrs and the integrated server will automatically reload87 #: the application if changes in the code are detected.88 #:89 #: This attribute can also be configured from the config with the `DEBUG`90 #: configuration key. Defaults to `False`.91 debug = ConfigAttribute('DEBUG')9293 #: The testing flask. Set this to `True` to enable the test mode of94 #: Flask extensions (and in the future probably also Flask itself).95 #: For example this might activate unittest helpers that have an96 #: additional runtime cost which should not be enabled by default.97 #:98 #: This attribute can also be configured from the config with the99 #: `TESTING` configuration key. Defaults to `False`.100 testing = ConfigAttribute('TESTING')101102 #: If a secret key is set, cryptographic components can use this to103 #: sign cookies and other things. Set this to a complex random value104 #: when you want to use the secure cookie for instance.105 #:106 #: This attribute can also be configured from the config with the107 #: `SECRET_KEY` configuration key. Defaults to `None`.108 secret_key = ConfigAttribute('SECRET_KEY')109110 #: The secure cookie uses this for the name of the session cookie.111 #:112 #: This attribute can also be configured from the config with the113 #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``114 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')115116 #: A :class:`~datetime.timedelta` which is used to set the expiration117 #: date of a permanent session. The default is 31 days which makes a118 #: permanent session survive for roughly one month.119 #:120 #: This attribute can also be configured from the config with the121 #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to122 #: ``timedelta(days=31)``123 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME')124125 #: Enable this if you want to use the X-Sendfile feature. Keep in126 #: mind that the server has to support this. This only affects files127 #: sent with the :func:`send_file` method.128 #:129 #: .. versionadded:: 0.2130 #:131 #: This attribute can also be configured from the config with the132 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.133 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')134135 #: The name of the logger to use. By default the logger name is the136 #: package name passed to the constructor.137 #:138 #: .. versionadded:: 0.4139 logger_name = ConfigAttribute('LOGGER_NAME')140141 #: The logging format used for the debug logger. This is only used when142 #: the application is in debug mode, otherwise the attached logging143 #: handler does the formatting.144 #:145 #: .. versionadded:: 0.3146 debug_log_format = (147 '-' * 80 + '\n' +148 '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +149 '%(message)s\n' +150 '-' * 80151 )152153 #: Options that are passed directly to the Jinja2 environment.154 jinja_options = ImmutableDict(155 autoescape=True,156 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']157 )158159 #: Default configuration parameters.160 default_config = ImmutableDict({161 'DEBUG': False,162 'TESTING': False,163 'SECRET_KEY': None,164 'SESSION_COOKIE_NAME': 'session',165 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),166 'USE_X_SENDFILE': False,167 'LOGGER_NAME': None,168 'SERVER_NAME': None169 })170171 def __init__(self, import_name):172 _PackageBoundObject.__init__(self, import_name)173174 #: The configuration dictionary as :class:`Config`. This behaves175 #: exactly like a regular dictionary but supports additional methods176 #: to load a config from files.177 self.config = Config(self.root_path, self.default_config)178179 #: Prepare the deferred setup of the logger.180 self._logger = None181 self.logger_name = self.import_name182183 #: A dictionary of all view functions registered. The keys will184 #: be function names which are also used to generate URLs and185 #: the values are the function objects themselves.186 #: to register a view function, use the :meth:`route` decorator.187 self.view_functions = {}188189 #: A dictionary of all registered error handlers. The key is190 #: be the error code as integer, the value the function that191 #: should handle that error.192 #: To register a error handler, use the :meth:`errorhandler`193 #: decorator.194 self.error_handlers = {}195196 #: A dictionary with lists of functions that should be called at the197 #: beginning of the request. The key of the dictionary is the name of198 #: the module this function is active for, `None` for all requests.199 #: This can for example be used to open database connections or200 #: getting hold of the currently logged in user. To register a201 #: function here, use the :meth:`before_request` decorator.202 self.before_request_funcs = {}203204 #: A dictionary with lists of functions that should be called after205 #: each request. The key of the dictionary is the name of the module206 #: this function is active for, `None` for all requests. This can for207 #: example be used to open database connections or getting hold of the208 #: currently logged in user. To register a function here, use the209 #: :meth:`before_request` decorator.210 self.after_request_funcs = {}211212 #: A dictionary with list of functions that are called without argument213 #: to populate the template context. They key of the dictionary is the214 #: name of the module this function is active for, `None` for all215 #: requests. Each returns a dictionary that the template context is216 #: updated with. To register a function here, use the217 #: :meth:`context_processor` decorator.218 self.template_context_processors = {219 None: [_default_template_ctx_processor]220 }221222 #: The :class:`~werkzeug.routing.Map` for this instance. You can use223 #: this to change the routing converters after the class was created224 #: but before any routes are connected. Example::225 #:226 #: from werkzeug import BaseConverter227 #:228 #: class ListConverter(BaseConverter):229 #: def to_python(self, value):230 #: return value.split(',')231 #: def to_url(self, values):232 #: return ','.join(BaseConverter.to_url(value)233 #: for value in values)234 #:235 #: app = Flask(__name__)236 #: app.url_map.converters['list'] = ListConverter237 self.url_map = Map()238239 if self.static_path is not None:240 self.add_url_rule(self.static_path + '/<filename>',241 build_only=True, endpoint='static')242 if get_pkg_resources() is not None:243 target = (self.import_name, 'static')244 else:245 target = os.path.join(self.root_path, 'static')246 self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {247 self.static_path: target248 })249250 #: The Jinja2 environment. It is created from the251 #: :attr:`jinja_options` and the loader that is returned252 #: by the :meth:`create_jinja_loader` function.253 self.jinja_env = Environment(loader=self.create_jinja_loader(),254 **self.jinja_options)255 self.jinja_env.globals.update(256 url_for=url_for,257 get_flashed_messages=get_flashed_messages258 )259 self.jinja_env.filters['tojson'] = _tojson_filter260261 @property262 def logger(self):263 """A :class:`logging.Logger` object for this application. The264 default configuration is to log to stderr if the application is265 in debug mode. This logger can be used to (surprise) log messages.266 Here some examples::267268 app.logger.debug('A value for debugging')269 app.logger.warning('A warning ocurred (%d apples)', 42)270 app.logger.error('An error occoured')271272 .. versionadded:: 0.3273 """274 if self._logger and self._logger.name == self.logger_name:275 return self._logger276 with _logger_lock:277 if self._logger and self._logger.name == self.logger_name:278 return self._logger279 from logging import getLogger, StreamHandler, Formatter, \280 Logger, DEBUG281 class DebugLogger(Logger):282 def getEffectiveLevel(x):283 return DEBUG if self.debug else Logger.getEffectiveLevel(x)284 class DebugHandler(StreamHandler):285 def emit(x, record):286 StreamHandler.emit(x, record) if self.debug else None287 handler = DebugHandler()288 handler.setLevel(DEBUG)289 handler.setFormatter(Formatter(self.debug_log_format))290 logger = getLogger(self.logger_name)291 logger.__class__ = DebugLogger292 logger.addHandler(handler)293 self._logger = logger294 return logger295296 def create_jinja_loader(self):297 """Creates the Jinja loader. By default just a package loader for298 the configured package is returned that looks up templates in the299 `templates` folder. To add other loaders it's possible to300 override this method.301 """302 if get_pkg_resources() is None:303 return FileSystemLoader(os.path.join(self.root_path, 'templates'))304 return PackageLoader(self.import_name)305306 def update_template_context(self, context):307 """Update the template context with some commonly used variables.308 This injects request, session and g into the template context.309310 :param context: the context as a dictionary that is updated in place311 to add extra variables.312 """313 funcs = self.template_context_processors[None]314 mod = _request_ctx_stack.top.request.module315 if mod is not None and mod in self.template_context_processors:316 funcs = chain(funcs, self.template_context_processors[mod])317 for func in funcs:318 context.update(func())319320 def run(self, host='127.0.0.1', port=5000, **options):321 """Runs the application on a local development server. If the322 :attr:`debug` flag is set the server will automatically reload323 for code changes and show a debugger in case an exception happened.324325 .. admonition:: Keep in Mind326327 Flask will supress any server error with a generic error page328 unless it is in debug mode. As such to enable just the329 interactive debugger without the code reloading, you ahve to330 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.331 Setting ``use_debugger`` to `True` without being in debug mode332 won't catch any exceptions because there won't be any to333 catch.334335 :param host: the hostname to listen on. set this to ``'0.0.0.0'``336 to have the server available externally as well.337 :param port: the port of the webserver338 :param options: the options to be forwarded to the underlying339 Werkzeug server. See :func:`werkzeug.run_simple`340 for more information.341 """342 from werkzeug import run_simple343 if 'debug' in options:344 self.debug = options.pop('debug')345 options.setdefault('use_reloader', self.debug)346 options.setdefault('use_debugger', self.debug)347 return run_simple(host, port, self, **options)348349 def test_client(self):350 """Creates a test client for this application. For information351 about unit testing head over to :ref:`testing`.352353 The test client can be used in a `with` block to defer the closing down354 of the context until the end of the `with` block. This is useful if355 you want to access the context locals for testing::356357 with app.test_client() as c:358 rv = c.get('/?vodka=42')359 assert request.args['vodka'] == '42'360361 .. versionchanged:: 0.4362 added support for `with` block usage for the client.363 """364 from werkzeug import Client365 class FlaskClient(Client):366 preserve_context = context_preserved = False367 def open(self, *args, **kwargs):368 if self.context_preserved:369 _request_ctx_stack.pop()370 self.context_preserved = False371 kwargs.setdefault('environ_overrides', {}) \372 ['flask._preserve_context'] = self.preserve_context373 old = _request_ctx_stack.top374 try:375 return Client.open(self, *args, **kwargs)376 finally:377 self.context_preserved = _request_ctx_stack.top is not old378 def __enter__(self):379 self.preserve_context = True380 return self381 def __exit__(self, exc_type, exc_value, tb):382 self.preserve_context = False383 if self.context_preserved:384 _request_ctx_stack.pop()385 return FlaskClient(self, self.response_class, use_cookies=True)386387 def open_session(self, request):388 """Creates or opens a new session. Default implementation stores all389 session data in a signed cookie. This requires that the390 :attr:`secret_key` is set.391392 :param request: an instance of :attr:`request_class`.393 """394 key = self.secret_key395 if key is not None:396 return Session.load_cookie(request, self.session_cookie_name,397 secret_key=key)398399 def save_session(self, session, response):400 """Saves the session if it needs updates. For the default401 implementation, check :meth:`open_session`.402403 :param session: the session to be saved (a404 :class:`~werkzeug.contrib.securecookie.SecureCookie`405 object)406 :param response: an instance of :attr:`response_class`407 """408 expires = None409 if session.permanent:410 expires = datetime.utcnow() + self.permanent_session_lifetime411 session.save_cookie(response, self.session_cookie_name,412 expires=expires, httponly=True)413414 def register_module(self, module, **options):415 """Registers a module with this application. The keyword argument416 of this function are the same as the ones for the constructor of the417 :class:`Module` class and will override the values of the module if418 provided.419 """420 options.setdefault('url_prefix', module.url_prefix)421 state = _ModuleSetupState(self, **options)422 for func in module._register_events:423 func(state)424425 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):426 """Connects a URL rule. Works exactly like the :meth:`route`427 decorator. If a view_func is provided it will be registered with the428 endpoint.429430 Basically this example::431432 @app.route('/')433 def index():434 pass435436 Is equivalent to the following::437438 def index():439 pass440 app.add_url_rule('/', 'index', index)441442 If the view_func is not provided you will need to connect the endpoint443 to a view function like so::444445 app.view_functions['index'] = index446447 .. versionchanged:: 0.2448 `view_func` parameter added.449450 :param rule: the URL rule as string451 :param endpoint: the endpoint for the registered URL rule. Flask452 itself assumes the name of the view function as453 endpoint454 :param view_func: the function to call when serving a request to the455 provided endpoint456 :param options: the options to be forwarded to the underlying457 :class:`~werkzeug.routing.Rule` object458 """459 if endpoint is None:460 assert view_func is not None, 'expected view func if endpoint ' \461 'is not provided.'462 endpoint = view_func.__name__463 options['endpoint'] = endpoint464 options.setdefault('methods', ('GET',))465 self.url_map.add(Rule(rule, **options))466 if view_func is not None:467 self.view_functions[endpoint] = view_func468469 def route(self, rule, **options):470 """A decorator that is used to register a view function for a471 given URL rule. Example::472473 @app.route('/')474 def index():475 return 'Hello World'476477 Variables parts in the route can be specified with angular478 brackets (``/user/<username>``). By default a variable part479 in the URL accepts any string without a slash however a different480 converter can be specified as well by using ``<converter:name>``.481482 Variable parts are passed to the view function as keyword483 arguments.484485 The following converters are possible:486487 =========== ===========================================488 `int` accepts integers489 `float` like `int` but for floating point values490 `path` like the default but also accepts slashes491 =========== ===========================================492493 Here some examples::494495 @app.route('/')496 def index():497 pass498499 @app.route('/<username>')500 def show_user(username):501 pass502503 @app.route('/post/<int:post_id>')504 def show_post(post_id):505 pass506507 An important detail to keep in mind is how Flask deals with trailing508 slashes. The idea is to keep each URL unique so the following rules509 apply:510511 1. If a rule ends with a slash and is requested without a slash512 by the user, the user is automatically redirected to the same513 page with a trailing slash attached.514 2. If a rule does not end with a trailing slash and the user request515 the page with a trailing slash, a 404 not found is raised.516517 This is consistent with how web servers deal with static files. This518 also makes it possible to use relative link targets safely.519520 The :meth:`route` decorator accepts a couple of other arguments521 as well:522523 :param rule: the URL rule as string524 :param methods: a list of methods this rule should be limited525 to (``GET``, ``POST`` etc.). By default a rule526 just listens for ``GET`` (and implicitly ``HEAD``).527 :param subdomain: specifies the rule for the subdoain in case528 subdomain matching is in use.529 :param strict_slashes: can be used to disable the strict slashes530 setting for this rule. See above.531 :param options: other options to be forwarded to the underlying532 :class:`~werkzeug.routing.Rule` object.533 """534 def decorator(f):535 self.add_url_rule(rule, None, f, **options)536 return f537 return decorator538539 def errorhandler(self, code):540 """A decorator that is used to register a function give a given541 error code. Example::542543 @app.errorhandler(404)544 def page_not_found(error):545 return 'This page does not exist', 404546547 You can also register a function as error handler without using548 the :meth:`errorhandler` decorator. The following example is549 equivalent to the one above::550551 def page_not_found(error):552 return 'This page does not exist', 404553 app.error_handlers[404] = page_not_found554555 :param code: the code as integer for the handler556 """557 def decorator(f):558 self.error_handlers[code] = f559 return f560 return decorator561562 def template_filter(self, name=None):563 """A decorator that is used to register custom template filter.564 You can specify a name for the filter, otherwise the function565 name will be used. Example::566567 @app.template_filter()568 def reverse(s):569 return s[::-1]570571 :param name: the optional name of the filter, otherwise the572 function name will be used.573 """574 def decorator(f):575 self.jinja_env.filters[name or f.__name__] = f576 return f577 return decorator578579 def before_request(self, f):580 """Registers a function to run before each request."""581 self.before_request_funcs.setdefault(None, []).append(f)582 return f583584 def after_request(self, f):585 """Register a function to be run after each request."""586 self.after_request_funcs.setdefault(None, []).append(f)587 return f588589 def context_processor(self, f):590 """Registers a template context processor function."""591 self.template_context_processors[None].append(f)592 return f593594 def handle_http_exception(self, e):595 """Handles an HTTP exception. By default this will invoke the596 registered error handlers and fall back to returning the597 exception as response.598599 .. versionadded: 0.3600 """601 handler = self.error_handlers.get(e.code)602 if handler is None:603 return e604 return handler(e)605606 def handle_exception(self, e):607 """Default exception handling that kicks in when an exception608 occours that is not catched. In debug mode the exception will609 be re-raised immediately, otherwise it is logged and the handler610 for a 500 internal server error is used. If no such handler611 exists, a default 500 internal server error message is displayed.612613 .. versionadded: 0.3614 """615 handler = self.error_handlers.get(500)616 if self.debug:617 raise618 self.logger.exception('Exception on %s [%s]' % (619 request.path,620 request.method621 ))622 if handler is None:623 return InternalServerError()624 return handler(e)625626 def dispatch_request(self):627 """Does the request dispatching. Matches the URL and returns the628 return value of the view or error handler. This does not have to629 be a response object. In order to convert the return value to a630 proper response object, call :func:`make_response`.631 """632 req = _request_ctx_stack.top.request633 try:634 if req.routing_exception is not None:635 raise req.routing_exception636 return self.view_functions[req.endpoint](**req.view_args)637 except HTTPException, e:638 return self.handle_http_exception(e)639640 def make_response(self, rv):641 """Converts the return value from a view function to a real642 response object that is an instance of :attr:`response_class`.643644 The following types are allowed for `rv`:645646 .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|647648 ======================= ===========================================649 :attr:`response_class` the object is returned unchanged650 :class:`str` a response object is created with the651 string as body652 :class:`unicode` a response object is created with the653 string encoded to utf-8 as body654 :class:`tuple` the response object is created with the655 contents of the tuple as arguments656 a WSGI function the function is called as WSGI application657 and buffered as response object658 ======================= ===========================================659660 :param rv: the return value from the view function661 """662 if rv is None:663 raise ValueError('View function did not return a response')664 if isinstance(rv, self.response_class):665 return rv666 if isinstance(rv, basestring):667 return self.response_class(rv)668 if isinstance(rv, tuple):669 return self.response_class(*rv)670 return self.response_class.force_type(rv, request.environ)671672 def preprocess_request(self):673 """Called before the actual request dispatching and will674 call every as :meth:`before_request` decorated function.675 If any of these function returns a value it's handled as676 if it was the return value from the view and further677 request handling is stopped.678 """679 funcs = self.before_request_funcs.get(None, ())680 mod = request.module681 if mod and mod in self.before_request_funcs:682 funcs = chain(funcs, self.before_request_funcs[mod])683 for func in funcs:684 rv = func()685 if rv is not None:686 return rv687688 def process_response(self, response):689 """Can be overridden in order to modify the response object690 before it's sent to the WSGI server. By default this will691 call all the :meth:`after_request` decorated functions.692693 :param response: a :attr:`response_class` object.694 :return: a new response object or the same, has to be an695 instance of :attr:`response_class`.696 """697 ctx = _request_ctx_stack.top698 mod = ctx.request.module699 if not isinstance(ctx.session, _NullSession):700 self.save_session(ctx.session, response)701 funcs = ()702 if mod and mod in self.after_request_funcs:703 funcs = chain(funcs, self.after_request_funcs[mod])704 if None in self.after_request_funcs:705 funcs = chain(funcs, self.after_request_funcs[None])706 for handler in funcs:707 response = handler(response)708 return response709710 def wsgi_app(self, environ, start_response):711 """The actual WSGI application. This is not implemented in712 `__call__` so that middlewares can be applied without losing a713 reference to the class. So instead of doing this::714715 app = MyMiddleware(app)716717 It's a better idea to do this instead::718719 app.wsgi_app = MyMiddleware(app.wsgi_app)720721 Then you still have the original application object around and722 can continue to call methods on it.723724 .. versionchanged:: 0.4725 The :meth:`after_request` functions are now called even if an726 error handler took over request processing. This ensures that727 even if an exception happens database have the chance to728 properly close the connection.729730 :param environ: a WSGI environment731 :param start_response: a callable accepting a status code,732 a list of headers and an optional733 exception context to start the response734 """735 with self.request_context(environ):736 try:737 rv = self.preprocess_request()738 if rv is None:739 rv = self.dispatch_request()740 response = self.make_response(rv)741 except Exception, e:742 response = self.make_response(self.handle_exception(e))743 try:744 response = self.process_response(response)745 except Exception, e:746 response = self.make_response(self.handle_exception(e))747 return response(environ, start_response)748749 def request_context(self, environ):750 """Creates a request context from the given environment and binds751 it to the current context. This must be used in combination with752 the `with` statement because the request is only bound to the753 current context for the duration of the `with` block.754755 Example usage::756757 with app.request_context(environ):758 do_something_with(request)759760 The object returned can also be used without the `with` statement761 which is useful for working in the shell. The example above is762 doing exactly the same as this code::763764 ctx = app.request_context(environ)765 ctx.push()766 try:767 do_something_with(request)768 finally:769 ctx.pop()770771 The big advantage of this approach is that you can use it without772 the try/finally statement in a shell for interactive testing:773774 >>> ctx = app.test_request_context()775 >>> ctx.bind()776 >>> request.path777 u'/'778 >>> ctx.unbind()779780 .. versionchanged:: 0.3781 Added support for non-with statement usage and `with` statement782 is now passed the ctx object.783784 :param environ: a WSGI environment785 """786 return _RequestContext(self, environ)787788 def test_request_context(self, *args, **kwargs):789 """Creates a WSGI environment from the given values (see790 :func:`werkzeug.create_environ` for more information, this791 function accepts the same arguments).792 """793 return self.request_context(create_environ(*args, **kwargs))794795 def __call__(self, environ, start_response):796 """Shortcut for :attr:`wsgi_app`."""797 return self.wsgi_app(environ, start_response)798
added:flask/conf.py+139 added
1import os2import sys34from werkzeug import import_string567class ConfigAttribute(object):8 """Makes an attribute forward to the config"""910 def __init__(self, name):11 self.__name__ = name1213 def __get__(self, obj, type=None):14 if obj is None:15 return self16 return obj.config[self.__name__]1718 def __set__(self, obj, value):19 obj.config[self.__name__] = value202122class Config(dict):23 """Works exactly like a dict but provides ways to fill it from files24 or special dictionaries. There are two common patterns to populate the25 config.2627 Either you can fill the config from a config file::2829 app.config.from_pyfile('yourconfig.cfg')3031 Or alternatively you can define the configuration options in the32 module that calls :meth:`from_object` or provide an import path to33 a module that should be loaded. It is also possible to tell it to34 use the same module and with that provide the configuration values35 just before the call::3637 DEBUG = True38 SECRET_KEY = 'development key'39 app.config.from_object(__name__)4041 In both cases (loading from any Python file or loading from modules),42 only uppercase keys are added to the config. This makes it possible to use43 lowercase values in the config file for temporary values that are not added44 to the config or to define the config keys in the same file that implements45 the application.4647 Probably the most interesting way to load configurations is from an48 environment variable pointing to a file::4950 app.config.from_envvar('YOURAPPLICATION_SETTINGS')5152 In this case before launching the application you have to set this53 environment variable to the file you want to use. On Linux and OS X54 use the export statement::5556 export YOURAPPLICATION_SETTINGS='/path/to/config/file'5758 On windows use `set` instead.5960 :param root_path: path to which files are read relative from. When the61 config object is created by the application, this is62 the application's :attr:`~flask.Flask.root_path`.63 :param defaults: an optional dictionary of default values64 """6566 def __init__(self, root_path, defaults=None):67 dict.__init__(self, defaults or {})68 self.root_path = root_path6970 def from_envvar(self, variable_name, silent=False):71 """Loads a configuration from an environment variable pointing to72 a configuration file. This basically is just a shortcut with nicer73 error messages for this line of code::7475 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])7677 :param variable_name: name of the environment variable78 :param silent: set to `True` if you want silent failing for missing79 files.80 :return: bool. `True` if able to load config, `False` otherwise.81 """82 rv = os.environ.get(variable_name)83 if not rv:84 if silent:85 return False86 raise RuntimeError('The environment variable %r is not set '87 'and as such configuration could not be '88 'loaded. Set this variable and make it '89 'point to a configuration file' %90 variable_name)91 self.from_pyfile(rv)92 return True9394 def from_pyfile(self, filename):95 """Updates the values in the config from a Python file. This function96 behaves as if the file was imported as module with the97 :meth:`from_object` function.9899 :param filename: the filename of the config. This can either be an100 absolute filename or a filename relative to the101 root path.102 """103 filename = os.path.join(self.root_path, filename)104 d = type(sys)('config')105 d.__file__ = filename106 execfile(filename, d.__dict__)107 self.from_object(d)108109 def from_object(self, obj):110 """Updates the values from the given object. An object can be of one111 of the following two types:112113 - a string: in this case the object with that name will be imported114 - an actual object reference: that object is used directly115116 Objects are usually either modules or classes.117118 Just the uppercase variables in that object are stored in the config119 after lowercasing. Example usage::120121 app.config.from_object('yourapplication.default_config')122 from yourapplication import default_config123 app.config.from_object(default_config)124125 You should not use this function to load the actual configuration but126 rather configuration defaults. The actual config should be loaded127 with :meth:`from_pyfile` and ideally from a location not within the128 package because the package might be installed system wide.129130 :param obj: an import name or object131 """132 if isinstance(obj, basestring):133 obj = import_string(obj)134 for key in dir(obj):135 if key.isupper():136 self[key] = getattr(obj, key)137138 def __repr__(self):139 return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
added:flask/ctx.py+62 added
1from werkzeug.exceptions import HTTPException23from flask.wrappers import _RequestGlobals4from flask.globals import _request_ctx_stack5from flask.session import _NullSession678class _RequestContext(object):9 """The request context contains all request relevant information. It is10 created at the beginning of the request and pushed to the11 `_request_ctx_stack` and removed at the end of it. It will create the12 URL adapter and request object for the WSGI environment provided.13 """1415 def __init__(self, app, environ):16 self.app = app17 self.url_adapter = app.url_map.bind_to_environ(environ,18 server_name=app.config['SERVER_NAME'])19 self.request = app.request_class(environ)20 self.session = app.open_session(self.request)21 if self.session is None:22 self.session = _NullSession()23 self.g = _RequestGlobals()24 self.flashes = None2526 try:27 self.request.endpoint, self.request.view_args = \28 self.url_adapter.match()29 except HTTPException, e:30 self.request.routing_exception = e3132 def push(self):33 """Binds the request context."""34 _request_ctx_stack.push(self)3536 def pop(self):37 """Pops the request context."""38 _request_ctx_stack.pop()3940 def __enter__(self):41 self.push()42 return self4344 def __exit__(self, exc_type, exc_value, tb):45 # do not pop the request stack if we are in debug mode and an46 # exception happened. This will allow the debugger to still47 # access the request object in the interactive shell. Furthermore48 # the context can be force kept alive for the test client.49 if not self.request.environ.get('flask._preserve_context') and \50 (tb is None or not self.app.debug):51 self.pop()52 53def _default_template_ctx_processor():54 """Default template context processor. Injects `request`,55 `session` and `g`.56 """57 reqctx = _request_ctx_stack.top58 return dict(59 request=reqctx.request,60 session=reqctx.session,61 g=reqctx.g62 )
added:flask/globals.py+8 added
1from werkzeug import LocalStack, LocalProxy23# context locals4_request_ctx_stack = LocalStack()5current_app = LocalProxy(lambda: _request_ctx_stack.top.app)6request = LocalProxy(lambda: _request_ctx_stack.top.request)7session = LocalProxy(lambda: _request_ctx_stack.top.session)8g = LocalProxy(lambda: _request_ctx_stack.top.g)
added:flask/helpers.py+328 added
1import os2import sys3import mimetypes45# try to load the best simplejson implementation available. If JSON6# is not installed, we add a failing class.7json_available = True8try:9 import simplejson as json10except ImportError:11 try:12 import json13 except ImportError:14 json_available = False15 16from werkzeug import Headers, wrap_file1718from flask.globals import session, _request_ctx_stack, current_app, request19from flask.wrappers import Response2021 22def _assert_have_json():23 """Helper function that fails if JSON is unavailable."""24 if not json_available:25 raise RuntimeError('simplejson not installed')2627# figure out if simplejson escapes slashes. This behaviour was changed28# from one version to another without reason.29if not json_available or '\\/' not in json.dumps('/'):3031 def _tojson_filter(*args, **kwargs):32 if __debug__:33 _assert_have_json()34 return json.dumps(*args, **kwargs).replace('/', '\\/')35else:36 _tojson_filter = json.dumps3738def jsonify(*args, **kwargs):39 """Creates a :class:`~flask.Response` with the JSON representation of40 the given arguments with an `application/json` mimetype. The arguments41 to this function are the same as to the :class:`dict` constructor.4243 Example usage::4445 @app.route('/_get_current_user')46 def get_current_user():47 return jsonify(username=g.user.username,48 email=g.user.email,49 id=g.user.id)5051 This will send a JSON response like this to the browser::5253 {54 "username": "admin",55 "email": "admin@localhost",56 "id": 4257 }5859 This requires Python 2.6 or an installed version of simplejson. For60 security reasons only objects are supported toplevel. For more61 information about this, have a look at :ref:`json-security`.6263 .. versionadded:: 0.264 """65 if __debug__:66 _assert_have_json()67 return current_app.response_class(json.dumps(dict(*args, **kwargs),68 indent=None if request.is_xhr else 2), mimetype='application/json')69 70def get_pkg_resources():71 """Use pkg_resource if that works, otherwise fall back to cwd. The72 current working directory is generally not reliable with the notable73 exception of google appengine.74 """75 try:76 import pkg_resources77 pkg_resources.resource_stream78 except (ImportError, AttributeError):79 return80 return pkg_resources818283def url_for(endpoint, **values):84 """Generates a URL to the given endpoint with the method provided.85 The endpoint is relative to the active module if modules are in use.8687 Here some examples:8889 ==================== ======================= =============================90 Active Module Target Endpoint Target Function91 ==================== ======================= =============================92 `None` ``'index'`` `index` of the application93 `None` ``'.index'`` `index` of the application94 ``'admin'`` ``'index'`` `index` of the `admin` module95 any ``'.index'`` `index` of the application96 any ``'admin.index'`` `index` of the `admin` module97 ==================== ======================= =============================9899 Variable arguments that are unknown to the target endpoint are appended100 to the generated URL as query arguments.101102 For more information, head over to the :ref:`Quickstart <url-building>`.103104 :param endpoint: the endpoint of the URL (name of the function)105 :param values: the variable arguments of the URL rule106 :param _external: if set to `True`, an absolute URL is generated.107 """108 ctx = _request_ctx_stack.top109 if '.' not in endpoint:110 mod = ctx.request.module111 if mod is not None:112 endpoint = mod + '.' + endpoint113 elif endpoint.startswith('.'):114 endpoint = endpoint[1:]115 external = values.pop('_external', False)116 return ctx.url_adapter.build(endpoint, values, force_external=external)117118119def get_template_attribute(template_name, attribute):120 """Loads a macro (or variable) a template exports. This can be used to121 invoke a macro from within Python code. If you for example have a122 template named `_cider.html` with the following contents:123124 .. sourcecode:: html+jinja125126 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}127128 You can access this from Python code like this::129130 hello = get_template_attribute('_cider.html', 'hello')131 return hello('World')132133 .. versionadded:: 0.2134135 :param template_name: the name of the template136 :param attribute: the name of the variable of macro to acccess137 """138 return getattr(current_app.jinja_env.get_template(template_name).module,139 attribute)140141142def flash(message, category='message'):143 """Flashes a message to the next request. In order to remove the144 flashed message from the session and to display it to the user,145 the template has to call :func:`get_flashed_messages`.146147 .. versionchanged: 0.3148 `category` parameter added.149150 :param message: the message to be flashed.151 :param category: the category for the message. The following values152 are recommended: ``'message'`` for any kind of message,153 ``'error'`` for errors, ``'info'`` for information154 messages and ``'warning'`` for warnings. However any155 kind of string can be used as category.156 """157 session.setdefault('_flashes', []).append((category, message))158159160def get_flashed_messages(with_categories=False):161 """Pulls all flashed messages from the session and returns them.162 Further calls in the same request to the function will return163 the same messages. By default just the messages are returned,164 but when `with_categories` is set to `True`, the return value will165 be a list of tuples in the form ``(category, message)`` instead.166167 Example usage:168169 .. sourcecode:: html+jinja170171 {% for category, msg in get_flashed_messages(with_categories=true) %}172 <p class=flash-{{ category }}>{{ msg }}173 {% endfor %}174175 .. versionchanged:: 0.3176 `with_categories` parameter added.177178 :param with_categories: set to `True` to also receive categories.179 """180 flashes = _request_ctx_stack.top.flashes181 if flashes is None:182 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])183 if not with_categories:184 return [x[1] for x in flashes]185 return flashes186187188def send_file(filename_or_fp, mimetype=None, as_attachment=False,189 attachment_filename=None):190 """Sends the contents of a file to the client. This will use the191 most efficient method available and configured. By default it will192 try to use the WSGI server's file_wrapper support. Alternatively193 you can set the application's :attr:`~Flask.use_x_sendfile` attribute194 to ``True`` to directly emit an `X-Sendfile` header. This however195 requires support of the underlying webserver for `X-Sendfile`.196197 By default it will try to guess the mimetype for you, but you can198 also explicitly provide one. For extra security you probably want199 to sent certain files as attachment (HTML for instance).200201 Please never pass filenames to this function from user sources without202 checking them first. Something like this is usually sufficient to203 avoid security problems::204205 if '..' in filename or filename.startswith('/'):206 abort(404)207208 .. versionadded:: 0.2209210 :param filename_or_fp: the filename of the file to send. This is211 relative to the :attr:`~Flask.root_path` if a212 relative path is specified.213 Alternatively a file object might be provided214 in which case `X-Sendfile` might not work and215 fall back to the traditional method.216 :param mimetype: the mimetype of the file if provided, otherwise217 auto detection happens.218 :param as_attachment: set to `True` if you want to send this file with219 a ``Content-Disposition: attachment`` header.220 :param attachment_filename: the filename for the attachment if it221 differs from the file's filename.222 """223 if isinstance(filename_or_fp, basestring):224 filename = filename_or_fp225 file = None226 else:227 file = filename_or_fp228 filename = getattr(file, 'name', None)229 if filename is not None:230 filename = os.path.join(current_app.root_path, filename)231 if mimetype is None and (filename or attachment_filename):232 mimetype = mimetypes.guess_type(filename or attachment_filename)[0]233 if mimetype is None:234 mimetype = 'application/octet-stream'235236 headers = Headers()237 if as_attachment:238 if attachment_filename is None:239 if filename is None:240 raise TypeError('filename unavailable, required for '241 'sending as attachment')242 attachment_filename = os.path.basename(filename)243 headers.add('Content-Disposition', 'attachment',244 filename=attachment_filename)245246 if current_app.use_x_sendfile and filename:247 if file is not None:248 file.close()249 headers['X-Sendfile'] = filename250 data = None251 else:252 if file is None:253 file = open(filename, 'rb')254 data = wrap_file(request.environ, file)255256 return Response(data, mimetype=mimetype, headers=headers,257 direct_passthrough=True)258259260def render_template(template_name, **context):261 """Renders a template from the template folder with the given262 context.263264 :param template_name: the name of the template to be rendered265 :param context: the variables that should be available in the266 context of the template.267 """268 current_app.update_template_context(context)269 return current_app.jinja_env.get_template(template_name).render(context)270271272def render_template_string(source, **context):273 """Renders a template from the given template source string274 with the given context.275276 :param template_name: the sourcecode of the template to be277 rendered278 :param context: the variables that should be available in the279 context of the template.280 """281 current_app.update_template_context(context)282 return current_app.jinja_env.from_string(source).render(context)283284285def _get_package_path(name):286 """Returns the path to a package or cwd if that cannot be found."""287 try:288 return os.path.abspath(os.path.dirname(sys.modules[name].__file__))289 except (KeyError, AttributeError):290 return os.getcwd()291292293class _PackageBoundObject(object):294295 def __init__(self, import_name):296 #: The name of the package or module. Do not change this once297 #: it was set by the constructor.298 self.import_name = import_name299300 #: Where is the app root located?301 self.root_path = _get_package_path(self.import_name)302303 def open_resource(self, resource):304 """Opens a resource from the application's resource folder. To see305 how this works, consider the following folder structure::306307 /myapplication.py308 /schemal.sql309 /static310 /style.css311 /templates312 /layout.html313 /index.html314315 If you want to open the `schema.sql` file you would do the316 following::317318 with app.open_resource('schema.sql') as f:319 contents = f.read()320 do_something_with(contents)321322 :param resource: the name of the resource. To access resources within323 subfolders use forward slashes as separator.324 """325 pkg_resources = get_pkg_resources()326 if pkg_resources is None:327 return open(os.path.join(self.root_path, resource), 'rb')328 return pkg_resources.resource_stream(self.import_name, resource)
added:flask/module.py+152 added
1from flask.helpers import _PackageBoundObject234class _ModuleSetupState(object):56 def __init__(self, app, url_prefix=None):7 self.app = app8 self.url_prefix = url_prefix91011class Module(_PackageBoundObject):12 """Container object that enables pluggable applications. A module can13 be used to organize larger applications. They represent blueprints that,14 in combination with a :class:`Flask` object are used to create a large15 application.1617 A module is like an application bound to an `import_name`. Multiple18 modules can share the same import names, but in that case a `name` has19 to be provided to keep them apart. If different import names are used,20 the rightmost part of the import name is used as name.2122 Here an example structure for a larger appliation::2324 /myapplication25 /__init__.py26 /views27 /__init__.py28 /admin.py29 /frontend.py3031 The `myapplication/__init__.py` can look like this::3233 from flask import Flask34 from myapplication.views.admin import admin35 from myapplication.views.frontend import frontend3637 app = Flask(__name__)38 app.register_module(admin, url_prefix='/admin')39 app.register_module(frontend)4041 And here an example view module (`myapplication/views/admin.py`)::4243 from flask import Module4445 admin = Module(__name__)4647 @admin.route('/')48 def index():49 pass5051 @admin.route('/login')52 def login():53 pass5455 For a gentle introduction into modules, checkout the56 :ref:`working-with-modules` section.57 """5859 def __init__(self, import_name, name=None, url_prefix=None):60 if name is None:61 assert '.' in import_name, 'name required if package name ' \62 'does not point to a submodule'63 name = import_name.rsplit('.', 1)[1]64 _PackageBoundObject.__init__(self, import_name)65 self.name = name66 self.url_prefix = url_prefix67 self._register_events = []6869 def route(self, rule, **options):70 """Like :meth:`Flask.route` but for a module. The endpoint for the71 :func:`url_for` function is prefixed with the name of the module.72 """73 def decorator(f):74 self.add_url_rule(rule, f.__name__, f, **options)75 return f76 return decorator7778 def add_url_rule(self, rule, endpoint, view_func=None, **options):79 """Like :meth:`Flask.add_url_rule` but for a module. The endpoint for80 the :func:`url_for` function is prefixed with the name of the module.81 """82 def register_rule(state):83 the_rule = rule84 if state.url_prefix:85 the_rule = state.url_prefix + rule86 state.app.add_url_rule(the_rule, '%s.%s' % (self.name, endpoint),87 view_func, **options)88 self._record(register_rule)8990 def before_request(self, f):91 """Like :meth:`Flask.before_request` but for a module. This function92 is only executed before each request that is handled by a function of93 that module.94 """95 self._record(lambda s: s.app.before_request_funcs96 .setdefault(self.name, []).append(f))97 return f9899 def before_app_request(self, f):100 """Like :meth:`Flask.before_request`. Such a function is executed101 before each request, even if outside of a module.102 """103 self._record(lambda s: s.app.before_request_funcs104 .setdefault(None, []).append(f))105 return f106107 def after_request(self, f):108 """Like :meth:`Flask.after_request` but for a module. This function109 is only executed after each request that is handled by a function of110 that module.111 """112 self._record(lambda s: s.app.after_request_funcs113 .setdefault(self.name, []).append(f))114 return f115116 def after_app_request(self, f):117 """Like :meth:`Flask.after_request` but for a module. Such a function118 is executed after each request, even if outside of the module.119 """120 self._record(lambda s: s.app.after_request_funcs121 .setdefault(None, []).append(f))122 return f123124 def context_processor(self, f):125 """Like :meth:`Flask.context_processor` but for a module. This126 function is only executed for requests handled by a module.127 """128 self._record(lambda s: s.app.template_context_processors129 .setdefault(self.name, []).append(f))130 return f131132 def app_context_processor(self, f):133 """Like :meth:`Flask.context_processor` but for a module. Such a134 function is executed each request, even if outside of the module.135 """136 self._record(lambda s: s.app.template_context_processors137 .setdefault(None, []).append(f))138 return f139140 def app_errorhandler(self, code):141 """Like :meth:`Flask.errorhandler` but for a module. This142 handler is used for all requests, even if outside of the module.143144 .. versionadded:: 0.4145 """146 def decorator(f):147 self._record(lambda s: s.app.errorhandler(code)(f))148 return f149 return decorator150151 def _record(self, func):152 self._register_events.append(func)
added:flask/session.py+31 added
1from werkzeug.contrib.securecookie import SecureCookie234class Session(SecureCookie):5 """Expands the session with support for switching between permanent6 and non-permanent sessions.7 """89 def _get_permanent(self):10 return self.get('_permanent', False)1112 def _set_permanent(self, value):13 self['_permanent'] = bool(value)1415 permanent = property(_get_permanent, _set_permanent)16 del _get_permanent, _set_permanent171819class _NullSession(Session):20 """Class used to generate nicer error messages if sessions are not21 available. Will still allow read-only access to the empty session22 but fail on setting.23 """2425 def _fail(self, *args, **kwargs):26 raise RuntimeError('the session is unavailable because no secret '27 'key was set. Set the secret_key on the '28 'application to something unique and secret')29 __setitem__ = __delitem__ = clear = pop = popitem = \30 update = setdefault = _fail31 del _fail
added:flask/wrappers.py+64 added
1from werkzeug import Request as RequestBase, Response as ResponseBase, \2 cached_property34from helpers import json567class Request(RequestBase):8 """The request object used by default in flask. Remembers the9 matched endpoint and view arguments.1011 It is what ends up as :class:`~flask.request`. If you want to replace12 the request object used you can subclass this and set13 :attr:`~flask.Flask.request_class` to your subclass.14 """1516 #: the endpoint that matched the request. This in combination with17 #: :attr:`view_args` can be used to reconstruct the same or a18 #: modified URL. If an exception happened when matching, this will19 #: be `None`.20 endpoint = None2122 #: a dict of view arguments that matched the request. If an exception23 #: happened when matching, this will be `None`.24 view_args = None2526 #: if matching the URL failed, this is the exception that will be27 #: raised / was raised as part of the request handling. This is28 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or29 #: something similar.30 routing_exception = None3132 @property33 def module(self):34 """The name of the current module"""35 if self.endpoint and '.' in self.endpoint:36 return self.endpoint.rsplit('.', 1)[0]3738 @cached_property39 def json(self):40 """If the mimetype is `application/json` this will contain the41 parsed JSON data.42 """43 if __debug__:44 from flask.helpers import _assert_have_json45 _assert_have_json()46 if self.mimetype == 'application/json':47 return json.loads(self.data)484950class Response(ResponseBase):51 """The response object that is used by default in flask. Works like the52 response object from Werkzeug but is set to have a HTML mimetype by53 default. Quite often you don't have to create this object yourself because54 :meth:`~flask.Flask.make_response` will take care of that for you.5556 If you want to replace the response object used you can subclass this and57 set :attr:`~flask.Flask.response_class` to your subclass.58 """59 default_mimetype = 'text/html'606162class _RequestGlobals(object):63 pass64
modified:tests/flask_tests.py+3 added-3 removed
19 unmodified lines
20from contextlib import contextmanager21from datetime import datetime22from werkzeug import parse_date, parse_options_header23from cStringIO import StringIO24from flask.helpers import json252526example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')27sys.path.append(os.path.join(example_path, 'flaskr'))28sys.path.append(os.path.join(example_path, 'minitwit'))29
378 unmodified lines
408 c = app.test_client()409 for url in '/kw', '/dict':410 rv = c.get(url)411 assert rv.mimetype == 'application/json'412 assert flask.json.loads(rv.data) == d412 assert json.loads(rv.data) == d413414 def test_json_attr(self):415 app = flask.Flask(__name__)416 @app.route('/add', methods=['POST'])417 def add():418 return unicode(flask.request.json['a'] + flask.request.json['b'])419 c = app.test_client()420 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),420 rv = c.post('/add', data=json.dumps({'a': 1, 'b': 2}),421 content_type='application/json')422 assert rv.data == '3'423424 def test_template_escaping(self):
474 unmodified lines
deleted:flask.py-1599 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))789790791def _select_autoescape(filename):792 """Returns `True` if autoescaping should be active for the given793 template name.794 """795 if filename is None:796 return False797 return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))798799800class Flask(_PackageBoundObject):801 """The flask object implements a WSGI application and acts as the central802 object. It is passed the name of the module or package of the803 application. Once it is created it will act as a central registry for804 the view functions, the URL rules, template configuration and much more.805806 The name of the package is used to resolve resources from inside the807 package or the folder the module is contained in depending on if the808 package parameter resolves to an actual python package (a folder with809 an `__init__.py` file inside) or a standard module (just a `.py` file).810811 For more information about resource loading, see :func:`open_resource`.812813 Usually you create a :class:`Flask` instance in your main module or814 in the `__init__.py` file of your package like this::815816 from flask import Flask817 app = Flask(__name__)818819 .. admonition:: About the First Parameter820821 The idea of the first parameter is to give Flask an idea what822 belongs to your application. This name is used to find resources823 on the file system, can be used by extensions to improve debugging824 information and a lot more.825826 So it's important what you provide there. If you are using a single827 module, `__name__` is always the correct value. If you however are828 using a package, it's usually recommended to hardcode the name of829 your package there.830831 For example if your application is defined in `yourapplication/app.py`832 you should create it with one of the two versions below::833834 app = Flask('yourapplication')835 app = Flask(__name__.split('.')[0])836837 Why is that? The application will work even with `__name__`, thanks838 to how resources are looked up. However it will make debugging more839 painful. Certain extensions can make assumptions based on the840 import name of your application. For example the Flask-SQLAlchemy841 extension will look for the code in your application that triggered842 an SQL query in debug mode. If the import name is not properly set843 up, that debugging information is lost. (For example it would only844 pick up SQL queries in `yourapplicaiton.app` and not845 `yourapplication.views.frontend`)846 """847848 #: The class that is used for request objects. See :class:`~flask.Request`849 #: for more information.850 request_class = Request851852 #: The class that is used for response objects. See853 #: :class:`~flask.Response` for more information.854 response_class = Response855856 #: Path for the static files. If you don't want to use static files857 #: you can set this value to `None` in which case no URL rule is added858 #: and the development server will no longer serve any static files.859 static_path = '/static'860861 #: The debug flag. Set this to `True` to enable debugging of the862 #: application. In debug mode the debugger will kick in when an unhandled863 #: exception ocurrs and the integrated server will automatically reload864 #: the application if changes in the code are detected.865 #:866 #: This attribute can also be configured from the config with the `DEBUG`867 #: configuration key. Defaults to `False`.868 debug = ConfigAttribute('DEBUG')869870 #: The testing flask. Set this to `True` to enable the test mode of871 #: Flask extensions (and in the future probably also Flask itself).872 #: For example this might activate unittest helpers that have an873 #: additional runtime cost which should not be enabled by default.874 #:875 #: This attribute can also be configured from the config with the876 #: `TESTING` configuration key. Defaults to `False`.877 testing = ConfigAttribute('TESTING')878879 #: If a secret key is set, cryptographic components can use this to880 #: sign cookies and other things. Set this to a complex random value881 #: when you want to use the secure cookie for instance.882 #:883 #: This attribute can also be configured from the config with the884 #: `SECRET_KEY` configuration key. Defaults to `None`.885 secret_key = ConfigAttribute('SECRET_KEY')886887 #: The secure cookie uses this for the name of the session cookie.888 #:889 #: This attribute can also be configured from the config with the890 #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``891 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')892893 #: A :class:`~datetime.timedelta` which is used to set the expiration894 #: date of a permanent session. The default is 31 days which makes a895 #: permanent session survive for roughly one month.896 #:897 #: This attribute can also be configured from the config with the898 #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to899 #: ``timedelta(days=31)``900 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME')901902 #: Enable this if you want to use the X-Sendfile feature. Keep in903 #: mind that the server has to support this. This only affects files904 #: sent with the :func:`send_file` method.905 #:906 #: .. versionadded:: 0.2907 #:908 #: This attribute can also be configured from the config with the909 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.910 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')911912 #: The name of the logger to use. By default the logger name is the913 #: package name passed to the constructor.914 #:915 #: .. versionadded:: 0.4916 logger_name = ConfigAttribute('LOGGER_NAME')917918 #: The logging format used for the debug logger. This is only used when919 #: the application is in debug mode, otherwise the attached logging920 #: handler does the formatting.921 #:922 #: .. versionadded:: 0.3923 debug_log_format = (924 '-' * 80 + '\n' +925 '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +926 '%(message)s\n' +927 '-' * 80928 )929930 #: Options that are passed directly to the Jinja2 environment.931 jinja_options = ImmutableDict(932 autoescape=_select_autoescape,933 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']934 )935936 #: Default configuration parameters.937 default_config = ImmutableDict({938 'DEBUG': False,939 'TESTING': False,940 'SECRET_KEY': None,941 'SESSION_COOKIE_NAME': 'session',942 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),943 'USE_X_SENDFILE': False,944 'LOGGER_NAME': None,945 'SERVER_NAME': None946 })947948 def __init__(self, import_name):949 _PackageBoundObject.__init__(self, import_name)950951 #: The configuration dictionary as :class:`Config`. This behaves952 #: exactly like a regular dictionary but supports additional methods953 #: to load a config from files.954 self.config = Config(self.root_path, self.default_config)955956 #: Prepare the deferred setup of the logger.957 self._logger = None958 self.logger_name = self.import_name959960 #: A dictionary of all view functions registered. The keys will961 #: be function names which are also used to generate URLs and962 #: the values are the function objects themselves.963 #: to register a view function, use the :meth:`route` decorator.964 self.view_functions = {}965966 #: A dictionary of all registered error handlers. The key is967 #: be the error code as integer, the value the function that968 #: should handle that error.969 #: To register a error handler, use the :meth:`errorhandler`970 #: decorator.971 self.error_handlers = {}972973 #: A dictionary with lists of functions that should be called at the974 #: beginning of the request. The key of the dictionary is the name of975 #: the module this function is active for, `None` for all requests.976 #: This can for example be used to open database connections or977 #: getting hold of the currently logged in user. To register a978 #: function here, use the :meth:`before_request` decorator.979 self.before_request_funcs = {}980981 #: A dictionary with lists of functions that should be called after982 #: each request. The key of the dictionary is the name of the module983 #: this function is active for, `None` for all requests. This can for984 #: example be used to open database connections or getting hold of the985 #: currently logged in user. To register a function here, use the986 #: :meth:`before_request` decorator.987 self.after_request_funcs = {}988989 #: A dictionary with list of functions that are called without argument990 #: to populate the template context. They key of the dictionary is the991 #: name of the module this function is active for, `None` for all992 #: requests. Each returns a dictionary that the template context is993 #: updated with. To register a function here, use the994 #: :meth:`context_processor` decorator.995 self.template_context_processors = {996 None: [_default_template_ctx_processor]997 }998999 #: The :class:`~werkzeug.routing.Map` for this instance. You can use1000 #: this to change the routing converters after the class was created1001 #: but before any routes are connected. Example::1002 #:1003 #: from werkzeug import BaseConverter1004 #:1005 #: class ListConverter(BaseConverter):1006 #: def to_python(self, value):1007 #: return value.split(',')1008 #: def to_url(self, values):1009 #: return ','.join(BaseConverter.to_url(value)1010 #: for value in values)1011 #:1012 #: app = Flask(__name__)1013 #: app.url_map.converters['list'] = ListConverter1014 self.url_map = Map()10151016 if self.static_path is not None:1017 self.add_url_rule(self.static_path + '/<filename>',1018 build_only=True, endpoint='static')1019 if pkg_resources is not None:1020 target = (self.import_name, 'static')1021 else:1022 target = os.path.join(self.root_path, 'static')1023 self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {1024 self.static_path: target1025 })10261027 #: The Jinja2 environment. It is created from the1028 #: :attr:`jinja_options` and the loader that is returned1029 #: by the :meth:`create_jinja_loader` function.1030 self.jinja_env = self.create_jinja_environment()1031 self.init_jinja_globals()10321033 @property1034 def logger(self):1035 """A :class:`logging.Logger` object for this application. The1036 default configuration is to log to stderr if the application is1037 in debug mode. This logger can be used to (surprise) log messages.1038 Here some examples::10391040 app.logger.debug('A value for debugging')1041 app.logger.warning('A warning ocurred (%d apples)', 42)1042 app.logger.error('An error occoured')10431044 .. versionadded:: 0.31045 """1046 if self._logger and self._logger.name == self.logger_name:1047 return self._logger1048 with _logger_lock:1049 if self._logger and self._logger.name == self.logger_name:1050 return self._logger1051 from logging import getLogger, StreamHandler, Formatter, \1052 Logger, DEBUG1053 class DebugLogger(Logger):1054 def getEffectiveLevel(x):1055 return DEBUG if self.debug else Logger.getEffectiveLevel(x)1056 class DebugHandler(StreamHandler):1057 def emit(x, record):1058 StreamHandler.emit(x, record) if self.debug else None1059 handler = DebugHandler()1060 handler.setLevel(DEBUG)1061 handler.setFormatter(Formatter(self.debug_log_format))1062 logger = getLogger(self.logger_name)1063 logger.__class__ = DebugLogger1064 logger.addHandler(handler)1065 self._logger = logger1066 return logger10671068 def create_jinja_environment(self):1069 """Creates the Jinja2 environment based on :attr:`jinja_options`1070 and :meth:`create_jinja_loader`.10711072 .. versionadded:: 0.51073 """1074 return Environment(loader=self.create_jinja_loader(),1075 **self.jinja_options)10761077 def create_jinja_loader(self):1078 """Creates the Jinja loader. By default just a package loader for1079 the configured package is returned that looks up templates in the1080 `templates` folder. To add other loaders it's possible to1081 override this method.1082 """1083 if pkg_resources is None:1084 return FileSystemLoader(os.path.join(self.root_path, 'templates'))1085 return PackageLoader(self.import_name)10861087 def init_jinja_globals(self):1088 """Callde directly after the environment was created to inject1089 some defaults (like `url_for`, `get_flashed_messages` and the1090 `tojson` filter.10911092 .. versionadded:: 0.51093 """1094 self.jinja_env.globals.update(1095 url_for=url_for,1096 get_flashed_messages=get_flashed_messages1097 )1098 self.jinja_env.filters['tojson'] = _tojson_filter10991100 def update_template_context(self, context):1101 """Update the template context with some commonly used variables.1102 This injects request, session and g into the template context.11031104 :param context: the context as a dictionary that is updated in place1105 to add extra variables.1106 """1107 funcs = self.template_context_processors[None]1108 mod = _request_ctx_stack.top.request.module1109 if mod is not None and mod in self.template_context_processors:1110 funcs = chain(funcs, self.template_context_processors[mod])1111 for func in funcs:1112 context.update(func())11131114 def run(self, host='127.0.0.1', port=5000, **options):1115 """Runs the application on a local development server. If the1116 :attr:`debug` flag is set the server will automatically reload1117 for code changes and show a debugger in case an exception happened.11181119 .. admonition:: Keep in Mind11201121 Flask will supress any server error with a generic error page1122 unless it is in debug mode. As such to enable just the1123 interactive debugger without the code reloading, you ahve to1124 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.1125 Setting ``use_debugger`` to `True` without being in debug mode1126 won't catch any exceptions because there won't be any to1127 catch.11281129 :param host: the hostname to listen on. set this to ``'0.0.0.0'``1130 to have the server available externally as well.1131 :param port: the port of the webserver1132 :param options: the options to be forwarded to the underlying1133 Werkzeug server. See :func:`werkzeug.run_simple`1134 for more information.1135 """1136 from werkzeug import run_simple1137 if 'debug' in options:1138 self.debug = options.pop('debug')1139 options.setdefault('use_reloader', self.debug)1140 options.setdefault('use_debugger', self.debug)1141 return run_simple(host, port, self, **options)11421143 def test_client(self):1144 """Creates a test client for this application. For information1145 about unit testing head over to :ref:`testing`.11461147 The test client can be used in a `with` block to defer the closing down1148 of the context until the end of the `with` block. This is useful if1149 you want to access the context locals for testing::11501151 with app.test_client() as c:1152 rv = c.get('/?vodka=42')1153 assert request.args['vodka'] == '42'11541155 .. versionchanged:: 0.41156 added support for `with` block usage for the client.1157 """1158 from werkzeug import Client1159 class FlaskClient(Client):1160 preserve_context = context_preserved = False1161 def open(self, *args, **kwargs):1162 if self.context_preserved:1163 _request_ctx_stack.pop()1164 self.context_preserved = False1165 kwargs.setdefault('environ_overrides', {}) \1166 ['flask._preserve_context'] = self.preserve_context1167 old = _request_ctx_stack.top1168 try:1169 return Client.open(self, *args, **kwargs)1170 finally:1171 self.context_preserved = _request_ctx_stack.top is not old1172 def __enter__(self):1173 self.preserve_context = True1174 return self1175 def __exit__(self, exc_type, exc_value, tb):1176 self.preserve_context = False1177 if self.context_preserved:1178 _request_ctx_stack.pop()1179 return FlaskClient(self, self.response_class, use_cookies=True)11801181 def open_session(self, request):1182 """Creates or opens a new session. Default implementation stores all1183 session data in a signed cookie. This requires that the1184 :attr:`secret_key` is set.11851186 :param request: an instance of :attr:`request_class`.1187 """1188 key = self.secret_key1189 if key is not None:1190 return Session.load_cookie(request, self.session_cookie_name,1191 secret_key=key)11921193 def save_session(self, session, response):1194 """Saves the session if it needs updates. For the default1195 implementation, check :meth:`open_session`.11961197 :param session: the session to be saved (a1198 :class:`~werkzeug.contrib.securecookie.SecureCookie`1199 object)1200 :param response: an instance of :attr:`response_class`1201 """1202 expires = None1203 if session.permanent:1204 expires = datetime.utcnow() + self.permanent_session_lifetime1205 session.save_cookie(response, self.session_cookie_name,1206 expires=expires, httponly=True)12071208 def register_module(self, module, **options):1209 """Registers a module with this application. The keyword argument1210 of this function are the same as the ones for the constructor of the1211 :class:`Module` class and will override the values of the module if1212 provided.1213 """1214 options.setdefault('url_prefix', module.url_prefix)1215 state = _ModuleSetupState(self, **options)1216 for func in module._register_events:1217 func(state)12181219 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):1220 """Connects a URL rule. Works exactly like the :meth:`route`1221 decorator. If a view_func is provided it will be registered with the1222 endpoint.12231224 Basically this example::12251226 @app.route('/')1227 def index():1228 pass12291230 Is equivalent to the following::12311232 def index():1233 pass1234 app.add_url_rule('/', 'index', index)12351236 If the view_func is not provided you will need to connect the endpoint1237 to a view function like so::12381239 app.view_functions['index'] = index12401241 .. versionchanged:: 0.21242 `view_func` parameter added.12431244 :param rule: the URL rule as string1245 :param endpoint: the endpoint for the registered URL rule. Flask1246 itself assumes the name of the view function as1247 endpoint1248 :param view_func: the function to call when serving a request to the1249 provided endpoint1250 :param options: the options to be forwarded to the underlying1251 :class:`~werkzeug.routing.Rule` object1252 """1253 if endpoint is None:1254 assert view_func is not None, 'expected view func if endpoint ' \1255 'is not provided.'1256 endpoint = view_func.__name__1257 options['endpoint'] = endpoint1258 options.setdefault('methods', ('GET',))1259 self.url_map.add(Rule(rule, **options))1260 if view_func is not None:1261 self.view_functions[endpoint] = view_func12621263 def route(self, rule, **options):1264 """A decorator that is used to register a view function for a1265 given URL rule. Example::12661267 @app.route('/')1268 def index():1269 return 'Hello World'12701271 Variables parts in the route can be specified with angular1272 brackets (``/user/<username>``). By default a variable part1273 in the URL accepts any string without a slash however a different1274 converter can be specified as well by using ``<converter:name>``.12751276 Variable parts are passed to the view function as keyword1277 arguments.12781279 The following converters are possible:12801281 =========== ===========================================1282 `int` accepts integers1283 `float` like `int` but for floating point values1284 `path` like the default but also accepts slashes1285 =========== ===========================================12861287 Here some examples::12881289 @app.route('/')1290 def index():1291 pass12921293 @app.route('/<username>')1294 def show_user(username):1295 pass12961297 @app.route('/post/<int:post_id>')1298 def show_post(post_id):1299 pass13001301 An important detail to keep in mind is how Flask deals with trailing1302 slashes. The idea is to keep each URL unique so the following rules1303 apply:13041305 1. If a rule ends with a slash and is requested without a slash1306 by the user, the user is automatically redirected to the same1307 page with a trailing slash attached.1308 2. If a rule does not end with a trailing slash and the user request1309 the page with a trailing slash, a 404 not found is raised.13101311 This is consistent with how web servers deal with static files. This1312 also makes it possible to use relative link targets safely.13131314 The :meth:`route` decorator accepts a couple of other arguments1315 as well:13161317 :param rule: the URL rule as string1318 :param methods: a list of methods this rule should be limited1319 to (``GET``, ``POST`` etc.). By default a rule1320 just listens for ``GET`` (and implicitly ``HEAD``).1321 :param subdomain: specifies the rule for the subdomain in case1322 subdomain matching is in use.1323 :param strict_slashes: can be used to disable the strict slashes1324 setting for this rule. See above.1325 :param options: other options to be forwarded to the underlying1326 :class:`~werkzeug.routing.Rule` object.1327 """1328 def decorator(f):1329 self.add_url_rule(rule, None, f, **options)1330 return f1331 return decorator13321333 def errorhandler(self, code):1334 """A decorator that is used to register a function give a given1335 error code. Example::13361337 @app.errorhandler(404)1338 def page_not_found(error):1339 return 'This page does not exist', 40413401341 You can also register a function as error handler without using1342 the :meth:`errorhandler` decorator. The following example is1343 equivalent to the one above::13441345 def page_not_found(error):1346 return 'This page does not exist', 4041347 app.error_handlers[404] = page_not_found13481349 :param code: the code as integer for the handler1350 """1351 def decorator(f):1352 self.error_handlers[code] = f1353 return f1354 return decorator13551356 def template_filter(self, name=None):1357 """A decorator that is used to register custom template filter.1358 You can specify a name for the filter, otherwise the function1359 name will be used. Example::13601361 @app.template_filter()1362 def reverse(s):1363 return s[::-1]13641365 :param name: the optional name of the filter, otherwise the1366 function name will be used.1367 """1368 def decorator(f):1369 self.jinja_env.filters[name or f.__name__] = f1370 return f1371 return decorator13721373 def before_request(self, f):1374 """Registers a function to run before each request."""1375 self.before_request_funcs.setdefault(None, []).append(f)1376 return f13771378 def after_request(self, f):1379 """Register a function to be run after each request."""1380 self.after_request_funcs.setdefault(None, []).append(f)1381 return f13821383 def context_processor(self, f):1384 """Registers a template context processor function."""1385 self.template_context_processors[None].append(f)1386 return f13871388 def handle_http_exception(self, e):1389 """Handles an HTTP exception. By default this will invoke the1390 registered error handlers and fall back to returning the1391 exception as response.13921393 .. versionadded: 0.31394 """1395 handler = self.error_handlers.get(e.code)1396 if handler is None:1397 return e1398 return handler(e)13991400 def handle_exception(self, e):1401 """Default exception handling that kicks in when an exception1402 occours that is not catched. In debug mode the exception will1403 be re-raised immediately, otherwise it is logged and the handler1404 for a 500 internal server error is used. If no such handler1405 exists, a default 500 internal server error message is displayed.14061407 .. versionadded: 0.31408 """1409 handler = self.error_handlers.get(500)1410 if self.debug:1411 raise1412 self.logger.exception('Exception on %s [%s]' % (1413 request.path,1414 request.method1415 ))1416 if handler is None:1417 return InternalServerError()1418 return handler(e)14191420 def dispatch_request(self):1421 """Does the request dispatching. Matches the URL and returns the1422 return value of the view or error handler. This does not have to1423 be a response object. In order to convert the return value to a1424 proper response object, call :func:`make_response`.1425 """1426 req = _request_ctx_stack.top.request1427 try:1428 if req.routing_exception is not None:1429 raise req.routing_exception1430 return self.view_functions[req.endpoint](**req.view_args)1431 except HTTPException, e:1432 return self.handle_http_exception(e)14331434 def make_response(self, rv):1435 """Converts the return value from a view function to a real1436 response object that is an instance of :attr:`response_class`.14371438 The following types are allowed for `rv`:14391440 .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|14411442 ======================= ===========================================1443 :attr:`response_class` the object is returned unchanged1444 :class:`str` a response object is created with the1445 string as body1446 :class:`unicode` a response object is created with the1447 string encoded to utf-8 as body1448 :class:`tuple` the response object is created with the1449 contents of the tuple as arguments1450 a WSGI function the function is called as WSGI application1451 and buffered as response object1452 ======================= ===========================================14531454 :param rv: the return value from the view function1455 """1456 if rv is None:1457 raise ValueError('View function did not return a response')1458 if isinstance(rv, self.response_class):1459 return rv1460 if isinstance(rv, basestring):1461 return self.response_class(rv)1462 if isinstance(rv, tuple):1463 return self.response_class(*rv)1464 return self.response_class.force_type(rv, request.environ)14651466 def preprocess_request(self):1467 """Called before the actual request dispatching and will1468 call every as :meth:`before_request` decorated function.1469 If any of these function returns a value it's handled as1470 if it was the return value from the view and further1471 request handling is stopped.1472 """1473 funcs = self.before_request_funcs.get(None, ())1474 mod = request.module1475 if mod and mod in self.before_request_funcs:1476 funcs = chain(funcs, self.before_request_funcs[mod])1477 for func in funcs:1478 rv = func()1479 if rv is not None:1480 return rv14811482 def process_response(self, response):1483 """Can be overridden in order to modify the response object1484 before it's sent to the WSGI server. By default this will1485 call all the :meth:`after_request` decorated functions.14861487 :param response: a :attr:`response_class` object.1488 :return: a new response object or the same, has to be an1489 instance of :attr:`response_class`.1490 """1491 ctx = _request_ctx_stack.top1492 mod = ctx.request.module1493 if not isinstance(ctx.session, _NullSession):1494 self.save_session(ctx.session, response)1495 funcs = ()1496 if mod and mod in self.after_request_funcs:1497 funcs = chain(funcs, self.after_request_funcs[mod])1498 if None in self.after_request_funcs:1499 funcs = chain(funcs, self.after_request_funcs[None])1500 for handler in funcs:1501 response = handler(response)1502 return response15031504 def wsgi_app(self, environ, start_response):1505 """The actual WSGI application. This is not implemented in1506 `__call__` so that middlewares can be applied without losing a1507 reference to the class. So instead of doing this::15081509 app = MyMiddleware(app)15101511 It's a better idea to do this instead::15121513 app.wsgi_app = MyMiddleware(app.wsgi_app)15141515 Then you still have the original application object around and1516 can continue to call methods on it.15171518 .. versionchanged:: 0.41519 The :meth:`after_request` functions are now called even if an1520 error handler took over request processing. This ensures that1521 even if an exception happens database have the chance to1522 properly close the connection.15231524 :param environ: a WSGI environment1525 :param start_response: a callable accepting a status code,1526 a list of headers and an optional1527 exception context to start the response1528 """1529 with self.request_context(environ):1530 try:1531 rv = self.preprocess_request()1532 if rv is None:1533 rv = self.dispatch_request()1534 response = self.make_response(rv)1535 except Exception, e:1536 response = self.make_response(self.handle_exception(e))1537 try:1538 response = self.process_response(response)1539 except Exception, e:1540 response = self.make_response(self.handle_exception(e))1541 return response(environ, start_response)15421543 def request_context(self, environ):1544 """Creates a request context from the given environment and binds1545 it to the current context. This must be used in combination with1546 the `with` statement because the request is only bound to the1547 current context for the duration of the `with` block.15481549 Example usage::15501551 with app.request_context(environ):1552 do_something_with(request)15531554 The object returned can also be used without the `with` statement1555 which is useful for working in the shell. The example above is1556 doing exactly the same as this code::15571558 ctx = app.request_context(environ)1559 ctx.push()1560 try:1561 do_something_with(request)1562 finally:1563 ctx.pop()15641565 The big advantage of this approach is that you can use it without1566 the try/finally statement in a shell for interactive testing:15671568 >>> ctx = app.test_request_context()1569 >>> ctx.bind()1570 >>> request.path1571 u'/'1572 >>> ctx.unbind()15731574 .. versionchanged:: 0.31575 Added support for non-with statement usage and `with` statement1576 is now passed the ctx object.15771578 :param environ: a WSGI environment1579 """1580 return _RequestContext(self, environ)15811582 def test_request_context(self, *args, **kwargs):1583 """Creates a WSGI environment from the given values (see1584 :func:`werkzeug.create_environ` for more information, this1585 function accepts the same arguments).1586 """1587 return self.request_context(create_environ(*args, **kwargs))15881589 def __call__(self, environ, start_response):1590 """Shortcut for :attr:`wsgi_app`."""1591 return self.wsgi_app(environ, start_response)159215931594# context locals1595_request_ctx_stack = LocalStack()1596current_app = LocalProxy(lambda: _request_ctx_stack.top.app)1597request = LocalProxy(lambda: _request_ctx_stack.top.request)1598session = LocalProxy(lambda: _request_ctx_stack.top.session)1599g = LocalProxy(lambda: _request_ctx_stack.top.g)