Skip to content
Myr

in with the new. i have the bits in places where i think they should be, now i just need to work on the import scheme layout

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

authored by Justin Quick · committed by Justin Quick · parent ee16a68 · Browse files · 8 files+1574 added−0 removed
This commit

State

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

Diff stats

8 files+1574 added−0 removed

  • other:+1574 added−0 removed

8 files+1574 added−0 removed

added:flask/__init__.py+58 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"""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 SecureCookie31323334# utilities we import from Werkzeug and Jinja2 that are unused35# in the module but are exported as public interface.36from werkzeug import abort, redirect37from jinja2 import Markup, escape3839# use pkg_resource if that works, otherwise fall back to cwd. The40# current working directory is generally not reliable with the notable41# exception of google appengine.42try:43 import pkg_resources44 pkg_resources.resource_stream45except (ImportError, AttributeError):46 pkg_resources = None4748# a lock used for logger initialization49_logger_lock = Lock()50515253# context locals54_request_ctx_stack = LocalStack()55current_app = LocalProxy(lambda: _request_ctx_stack.top.app)56request = LocalProxy(lambda: _request_ctx_stack.top.request)57session = LocalProxy(lambda: _request_ctx_stack.top.session)58g = LocalProxy(lambda: _request_ctx_stack.top.g)
added:flask/app.py+778 added
123class Flask(_PackageBoundObject):4 """The flask object implements a WSGI application and acts as the central5 object. It is passed the name of the module or package of the6 application. Once it is created it will act as a central registry for7 the view functions, the URL rules, template configuration and much more.89 The name of the package is used to resolve resources from inside the10 package or the folder the module is contained in depending on if the11 package parameter resolves to an actual python package (a folder with12 an `__init__.py` file inside) or a standard module (just a `.py` file).1314 For more information about resource loading, see :func:`open_resource`.1516 Usually you create a :class:`Flask` instance in your main module or17 in the `__init__.py` file of your package like this::1819 from flask import Flask20 app = Flask(__name__)2122 .. admonition:: About the First Parameter2324 The idea of the first parameter is to give Flask an idea what25 belongs to your application. This name is used to find resources26 on the file system, can be used by extensions to improve debugging27 information and a lot more.2829 So it's important what you provide there. If you are using a single30 module, `__name__` is always the correct value. If you however are31 using a package, it's usually recommended to hardcode the name of32 your package there.3334 For example if your application is defined in `yourapplication/app.py`35 you should create it with one of the two versions below::3637 app = Flask('yourapplication')38 app = Flask(__name__.split('.')[0])3940 Why is that? The application will work even with `__name__`, thanks41 to how resources are looked up. However it will make debugging more42 painful. Certain extensions can make assumptions based on the43 import name of your application. For example the Flask-SQLAlchemy44 extension will look for the code in your application that triggered45 an SQL query in debug mode. If the import name is not properly set46 up, that debugging information is lost. (For example it would only47 pick up SQL queries in `yourapplicaiton.app` and not48 `yourapplication.views.frontend`)49 """5051 #: The class that is used for request objects. See :class:`~flask.Request`52 #: for more information.53 request_class = Request5455 #: The class that is used for response objects. See56 #: :class:`~flask.Response` for more information.57 response_class = Response5859 #: Path for the static files. If you don't want to use static files60 #: you can set this value to `None` in which case no URL rule is added61 #: and the development server will no longer serve any static files.62 static_path = '/static'6364 #: The debug flag. Set this to `True` to enable debugging of the65 #: application. In debug mode the debugger will kick in when an unhandled66 #: exception ocurrs and the integrated server will automatically reload67 #: the application if changes in the code are detected.68 #:69 #: This attribute can also be configured from the config with the `DEBUG`70 #: configuration key. Defaults to `False`.71 debug = ConfigAttribute('DEBUG')7273 #: The testing flask. Set this to `True` to enable the test mode of74 #: Flask extensions (and in the future probably also Flask itself).75 #: For example this might activate unittest helpers that have an76 #: additional runtime cost which should not be enabled by default.77 #:78 #: This attribute can also be configured from the config with the79 #: `TESTING` configuration key. Defaults to `False`.80 testing = ConfigAttribute('TESTING')8182 #: If a secret key is set, cryptographic components can use this to83 #: sign cookies and other things. Set this to a complex random value84 #: when you want to use the secure cookie for instance.85 #:86 #: This attribute can also be configured from the config with the87 #: `SECRET_KEY` configuration key. Defaults to `None`.88 secret_key = ConfigAttribute('SECRET_KEY')8990 #: The secure cookie uses this for the name of the session cookie.91 #:92 #: This attribute can also be configured from the config with the93 #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``94 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')9596 #: A :class:`~datetime.timedelta` which is used to set the expiration97 #: date of a permanent session. The default is 31 days which makes a98 #: permanent session survive for roughly one month.99 #:100 #: This attribute can also be configured from the config with the101 #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to102 #: ``timedelta(days=31)``103 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME')104105 #: Enable this if you want to use the X-Sendfile feature. Keep in106 #: mind that the server has to support this. This only affects files107 #: sent with the :func:`send_file` method.108 #:109 #: .. versionadded:: 0.2110 #:111 #: This attribute can also be configured from the config with the112 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.113 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')114115 #: The name of the logger to use. By default the logger name is the116 #: package name passed to the constructor.117 #:118 #: .. versionadded:: 0.4119 logger_name = ConfigAttribute('LOGGER_NAME')120121 #: The logging format used for the debug logger. This is only used when122 #: the application is in debug mode, otherwise the attached logging123 #: handler does the formatting.124 #:125 #: .. versionadded:: 0.3126 debug_log_format = (127 '-' * 80 + '\n' +128 '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +129 '%(message)s\n' +130 '-' * 80131 )132133 #: Options that are passed directly to the Jinja2 environment.134 jinja_options = ImmutableDict(135 autoescape=True,136 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']137 )138139 #: Default configuration parameters.140 default_config = ImmutableDict({141 'DEBUG': False,142 'TESTING': False,143 'SECRET_KEY': None,144 'SESSION_COOKIE_NAME': 'session',145 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),146 'USE_X_SENDFILE': False,147 'LOGGER_NAME': None,148 'SERVER_NAME': None149 })150151 def __init__(self, import_name):152 _PackageBoundObject.__init__(self, import_name)153154 #: The configuration dictionary as :class:`Config`. This behaves155 #: exactly like a regular dictionary but supports additional methods156 #: to load a config from files.157 self.config = Config(self.root_path, self.default_config)158159 #: Prepare the deferred setup of the logger.160 self._logger = None161 self.logger_name = self.import_name162163 #: A dictionary of all view functions registered. The keys will164 #: be function names which are also used to generate URLs and165 #: the values are the function objects themselves.166 #: to register a view function, use the :meth:`route` decorator.167 self.view_functions = {}168169 #: A dictionary of all registered error handlers. The key is170 #: be the error code as integer, the value the function that171 #: should handle that error.172 #: To register a error handler, use the :meth:`errorhandler`173 #: decorator.174 self.error_handlers = {}175176 #: A dictionary with lists of functions that should be called at the177 #: beginning of the request. The key of the dictionary is the name of178 #: the module this function is active for, `None` for all requests.179 #: This can for example be used to open database connections or180 #: getting hold of the currently logged in user. To register a181 #: function here, use the :meth:`before_request` decorator.182 self.before_request_funcs = {}183184 #: A dictionary with lists of functions that should be called after185 #: each request. The key of the dictionary is the name of the module186 #: this function is active for, `None` for all requests. This can for187 #: example be used to open database connections or getting hold of the188 #: currently logged in user. To register a function here, use the189 #: :meth:`before_request` decorator.190 self.after_request_funcs = {}191192 #: A dictionary with list of functions that are called without argument193 #: to populate the template context. They key of the dictionary is the194 #: name of the module this function is active for, `None` for all195 #: requests. Each returns a dictionary that the template context is196 #: updated with. To register a function here, use the197 #: :meth:`context_processor` decorator.198 self.template_context_processors = {199 None: [_default_template_ctx_processor]200 }201202 #: The :class:`~werkzeug.routing.Map` for this instance. You can use203 #: this to change the routing converters after the class was created204 #: but before any routes are connected. Example::205 #:206 #: from werkzeug import BaseConverter207 #:208 #: class ListConverter(BaseConverter):209 #: def to_python(self, value):210 #: return value.split(',')211 #: def to_url(self, values):212 #: return ','.join(BaseConverter.to_url(value)213 #: for value in values)214 #:215 #: app = Flask(__name__)216 #: app.url_map.converters['list'] = ListConverter217 self.url_map = Map()218219 if self.static_path is not None:220 self.add_url_rule(self.static_path + '/<filename>',221 build_only=True, endpoint='static')222 if pkg_resources is not None:223 target = (self.import_name, 'static')224 else:225 target = os.path.join(self.root_path, 'static')226 self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {227 self.static_path: target228 })229230 #: The Jinja2 environment. It is created from the231 #: :attr:`jinja_options` and the loader that is returned232 #: by the :meth:`create_jinja_loader` function.233 self.jinja_env = Environment(loader=self.create_jinja_loader(),234 **self.jinja_options)235 self.jinja_env.globals.update(236 url_for=url_for,237 get_flashed_messages=get_flashed_messages238 )239 self.jinja_env.filters['tojson'] = _tojson_filter240241 @property242 def logger(self):243 """A :class:`logging.Logger` object for this application. The244 default configuration is to log to stderr if the application is245 in debug mode. This logger can be used to (surprise) log messages.246 Here some examples::247248 app.logger.debug('A value for debugging')249 app.logger.warning('A warning ocurred (%d apples)', 42)250 app.logger.error('An error occoured')251252 .. versionadded:: 0.3253 """254 if self._logger and self._logger.name == self.logger_name:255 return self._logger256 with _logger_lock:257 if self._logger and self._logger.name == self.logger_name:258 return self._logger259 from logging import getLogger, StreamHandler, Formatter, \260 Logger, DEBUG261 class DebugLogger(Logger):262 def getEffectiveLevel(x):263 return DEBUG if self.debug else Logger.getEffectiveLevel(x)264 class DebugHandler(StreamHandler):265 def emit(x, record):266 StreamHandler.emit(x, record) if self.debug else None267 handler = DebugHandler()268 handler.setLevel(DEBUG)269 handler.setFormatter(Formatter(self.debug_log_format))270 logger = getLogger(self.logger_name)271 logger.__class__ = DebugLogger272 logger.addHandler(handler)273 self._logger = logger274 return logger275276 def create_jinja_loader(self):277 """Creates the Jinja loader. By default just a package loader for278 the configured package is returned that looks up templates in the279 `templates` folder. To add other loaders it's possible to280 override this method.281 """282 if pkg_resources is None:283 return FileSystemLoader(os.path.join(self.root_path, 'templates'))284 return PackageLoader(self.import_name)285286 def update_template_context(self, context):287 """Update the template context with some commonly used variables.288 This injects request, session and g into the template context.289290 :param context: the context as a dictionary that is updated in place291 to add extra variables.292 """293 funcs = self.template_context_processors[None]294 mod = _request_ctx_stack.top.request.module295 if mod is not None and mod in self.template_context_processors:296 funcs = chain(funcs, self.template_context_processors[mod])297 for func in funcs:298 context.update(func())299300 def run(self, host='127.0.0.1', port=5000, **options):301 """Runs the application on a local development server. If the302 :attr:`debug` flag is set the server will automatically reload303 for code changes and show a debugger in case an exception happened.304305 .. admonition:: Keep in Mind306307 Flask will supress any server error with a generic error page308 unless it is in debug mode. As such to enable just the309 interactive debugger without the code reloading, you ahve to310 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.311 Setting ``use_debugger`` to `True` without being in debug mode312 won't catch any exceptions because there won't be any to313 catch.314315 :param host: the hostname to listen on. set this to ``'0.0.0.0'``316 to have the server available externally as well.317 :param port: the port of the webserver318 :param options: the options to be forwarded to the underlying319 Werkzeug server. See :func:`werkzeug.run_simple`320 for more information.321 """322 from werkzeug import run_simple323 if 'debug' in options:324 self.debug = options.pop('debug')325 options.setdefault('use_reloader', self.debug)326 options.setdefault('use_debugger', self.debug)327 return run_simple(host, port, self, **options)328329 def test_client(self):330 """Creates a test client for this application. For information331 about unit testing head over to :ref:`testing`.332333 The test client can be used in a `with` block to defer the closing down334 of the context until the end of the `with` block. This is useful if335 you want to access the context locals for testing::336337 with app.test_client() as c:338 rv = c.get('/?vodka=42')339 assert request.args['vodka'] == '42'340341 .. versionchanged:: 0.4342 added support for `with` block usage for the client.343 """344 from werkzeug import Client345 class FlaskClient(Client):346 preserve_context = context_preserved = False347 def open(self, *args, **kwargs):348 if self.context_preserved:349 _request_ctx_stack.pop()350 self.context_preserved = False351 kwargs.setdefault('environ_overrides', {}) \352 ['flask._preserve_context'] = self.preserve_context353 old = _request_ctx_stack.top354 try:355 return Client.open(self, *args, **kwargs)356 finally:357 self.context_preserved = _request_ctx_stack.top is not old358 def __enter__(self):359 self.preserve_context = True360 return self361 def __exit__(self, exc_type, exc_value, tb):362 self.preserve_context = False363 if self.context_preserved:364 _request_ctx_stack.pop()365 return FlaskClient(self, self.response_class, use_cookies=True)366367 def open_session(self, request):368 """Creates or opens a new session. Default implementation stores all369 session data in a signed cookie. This requires that the370 :attr:`secret_key` is set.371372 :param request: an instance of :attr:`request_class`.373 """374 key = self.secret_key375 if key is not None:376 return Session.load_cookie(request, self.session_cookie_name,377 secret_key=key)378379 def save_session(self, session, response):380 """Saves the session if it needs updates. For the default381 implementation, check :meth:`open_session`.382383 :param session: the session to be saved (a384 :class:`~werkzeug.contrib.securecookie.SecureCookie`385 object)386 :param response: an instance of :attr:`response_class`387 """388 expires = None389 if session.permanent:390 expires = datetime.utcnow() + self.permanent_session_lifetime391 session.save_cookie(response, self.session_cookie_name,392 expires=expires, httponly=True)393394 def register_module(self, module, **options):395 """Registers a module with this application. The keyword argument396 of this function are the same as the ones for the constructor of the397 :class:`Module` class and will override the values of the module if398 provided.399 """400 options.setdefault('url_prefix', module.url_prefix)401 state = _ModuleSetupState(self, **options)402 for func in module._register_events:403 func(state)404405 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):406 """Connects a URL rule. Works exactly like the :meth:`route`407 decorator. If a view_func is provided it will be registered with the408 endpoint.409410 Basically this example::411412 @app.route('/')413 def index():414 pass415416 Is equivalent to the following::417418 def index():419 pass420 app.add_url_rule('/', 'index', index)421422 If the view_func is not provided you will need to connect the endpoint423 to a view function like so::424425 app.view_functions['index'] = index426427 .. versionchanged:: 0.2428 `view_func` parameter added.429430 :param rule: the URL rule as string431 :param endpoint: the endpoint for the registered URL rule. Flask432 itself assumes the name of the view function as433 endpoint434 :param view_func: the function to call when serving a request to the435 provided endpoint436 :param options: the options to be forwarded to the underlying437 :class:`~werkzeug.routing.Rule` object438 """439 if endpoint is None:440 assert view_func is not None, 'expected view func if endpoint ' \441 'is not provided.'442 endpoint = view_func.__name__443 options['endpoint'] = endpoint444 options.setdefault('methods', ('GET',))445 self.url_map.add(Rule(rule, **options))446 if view_func is not None:447 self.view_functions[endpoint] = view_func448449 def route(self, rule, **options):450 """A decorator that is used to register a view function for a451 given URL rule. Example::452453 @app.route('/')454 def index():455 return 'Hello World'456457 Variables parts in the route can be specified with angular458 brackets (``/user/<username>``). By default a variable part459 in the URL accepts any string without a slash however a different460 converter can be specified as well by using ``<converter:name>``.461462 Variable parts are passed to the view function as keyword463 arguments.464465 The following converters are possible:466467 =========== ===========================================468 `int` accepts integers469 `float` like `int` but for floating point values470 `path` like the default but also accepts slashes471 =========== ===========================================472473 Here some examples::474475 @app.route('/')476 def index():477 pass478479 @app.route('/<username>')480 def show_user(username):481 pass482483 @app.route('/post/<int:post_id>')484 def show_post(post_id):485 pass486487 An important detail to keep in mind is how Flask deals with trailing488 slashes. The idea is to keep each URL unique so the following rules489 apply:490491 1. If a rule ends with a slash and is requested without a slash492 by the user, the user is automatically redirected to the same493 page with a trailing slash attached.494 2. If a rule does not end with a trailing slash and the user request495 the page with a trailing slash, a 404 not found is raised.496497 This is consistent with how web servers deal with static files. This498 also makes it possible to use relative link targets safely.499500 The :meth:`route` decorator accepts a couple of other arguments501 as well:502503 :param rule: the URL rule as string504 :param methods: a list of methods this rule should be limited505 to (``GET``, ``POST`` etc.). By default a rule506 just listens for ``GET`` (and implicitly ``HEAD``).507 :param subdomain: specifies the rule for the subdoain in case508 subdomain matching is in use.509 :param strict_slashes: can be used to disable the strict slashes510 setting for this rule. See above.511 :param options: other options to be forwarded to the underlying512 :class:`~werkzeug.routing.Rule` object.513 """514 def decorator(f):515 self.add_url_rule(rule, None, f, **options)516 return f517 return decorator518519 def errorhandler(self, code):520 """A decorator that is used to register a function give a given521 error code. Example::522523 @app.errorhandler(404)524 def page_not_found(error):525 return 'This page does not exist', 404526527 You can also register a function as error handler without using528 the :meth:`errorhandler` decorator. The following example is529 equivalent to the one above::530531 def page_not_found(error):532 return 'This page does not exist', 404533 app.error_handlers[404] = page_not_found534535 :param code: the code as integer for the handler536 """537 def decorator(f):538 self.error_handlers[code] = f539 return f540 return decorator541542 def template_filter(self, name=None):543 """A decorator that is used to register custom template filter.544 You can specify a name for the filter, otherwise the function545 name will be used. Example::546547 @app.template_filter()548 def reverse(s):549 return s[::-1]550551 :param name: the optional name of the filter, otherwise the552 function name will be used.553 """554 def decorator(f):555 self.jinja_env.filters[name or f.__name__] = f556 return f557 return decorator558559 def before_request(self, f):560 """Registers a function to run before each request."""561 self.before_request_funcs.setdefault(None, []).append(f)562 return f563564 def after_request(self, f):565 """Register a function to be run after each request."""566 self.after_request_funcs.setdefault(None, []).append(f)567 return f568569 def context_processor(self, f):570 """Registers a template context processor function."""571 self.template_context_processors[None].append(f)572 return f573574 def handle_http_exception(self, e):575 """Handles an HTTP exception. By default this will invoke the576 registered error handlers and fall back to returning the577 exception as response.578579 .. versionadded: 0.3580 """581 handler = self.error_handlers.get(e.code)582 if handler is None:583 return e584 return handler(e)585586 def handle_exception(self, e):587 """Default exception handling that kicks in when an exception588 occours that is not catched. In debug mode the exception will589 be re-raised immediately, otherwise it is logged and the handler590 for a 500 internal server error is used. If no such handler591 exists, a default 500 internal server error message is displayed.592593 .. versionadded: 0.3594 """595 handler = self.error_handlers.get(500)596 if self.debug:597 raise598 self.logger.exception('Exception on %s [%s]' % (599 request.path,600 request.method601 ))602 if handler is None:603 return InternalServerError()604 return handler(e)605606 def dispatch_request(self):607 """Does the request dispatching. Matches the URL and returns the608 return value of the view or error handler. This does not have to609 be a response object. In order to convert the return value to a610 proper response object, call :func:`make_response`.611 """612 req = _request_ctx_stack.top.request613 try:614 if req.routing_exception is not None:615 raise req.routing_exception616 return self.view_functions[req.endpoint](**req.view_args)617 except HTTPException, e:618 return self.handle_http_exception(e)619620 def make_response(self, rv):621 """Converts the return value from a view function to a real622 response object that is an instance of :attr:`response_class`.623624 The following types are allowed for `rv`:625626 .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|627628 ======================= ===========================================629 :attr:`response_class` the object is returned unchanged630 :class:`str` a response object is created with the631 string as body632 :class:`unicode` a response object is created with the633 string encoded to utf-8 as body634 :class:`tuple` the response object is created with the635 contents of the tuple as arguments636 a WSGI function the function is called as WSGI application637 and buffered as response object638 ======================= ===========================================639640 :param rv: the return value from the view function641 """642 if rv is None:643 raise ValueError('View function did not return a response')644 if isinstance(rv, self.response_class):645 return rv646 if isinstance(rv, basestring):647 return self.response_class(rv)648 if isinstance(rv, tuple):649 return self.response_class(*rv)650 return self.response_class.force_type(rv, request.environ)651652 def preprocess_request(self):653 """Called before the actual request dispatching and will654 call every as :meth:`before_request` decorated function.655 If any of these function returns a value it's handled as656 if it was the return value from the view and further657 request handling is stopped.658 """659 funcs = self.before_request_funcs.get(None, ())660 mod = request.module661 if mod and mod in self.before_request_funcs:662 funcs = chain(funcs, self.before_request_funcs[mod])663 for func in funcs:664 rv = func()665 if rv is not None:666 return rv667668 def process_response(self, response):669 """Can be overridden in order to modify the response object670 before it's sent to the WSGI server. By default this will671 call all the :meth:`after_request` decorated functions.672673 :param response: a :attr:`response_class` object.674 :return: a new response object or the same, has to be an675 instance of :attr:`response_class`.676 """677 ctx = _request_ctx_stack.top678 mod = ctx.request.module679 if not isinstance(ctx.session, _NullSession):680 self.save_session(ctx.session, response)681 funcs = ()682 if mod and mod in self.after_request_funcs:683 funcs = chain(funcs, self.after_request_funcs[mod])684 if None in self.after_request_funcs:685 funcs = chain(funcs, self.after_request_funcs[None])686 for handler in funcs:687 response = handler(response)688 return response689690 def wsgi_app(self, environ, start_response):691 """The actual WSGI application. This is not implemented in692 `__call__` so that middlewares can be applied without losing a693 reference to the class. So instead of doing this::694695 app = MyMiddleware(app)696697 It's a better idea to do this instead::698699 app.wsgi_app = MyMiddleware(app.wsgi_app)700701 Then you still have the original application object around and702 can continue to call methods on it.703704 .. versionchanged:: 0.4705 The :meth:`after_request` functions are now called even if an706 error handler took over request processing. This ensures that707 even if an exception happens database have the chance to708 properly close the connection.709710 :param environ: a WSGI environment711 :param start_response: a callable accepting a status code,712 a list of headers and an optional713 exception context to start the response714 """715 with self.request_context(environ):716 try:717 rv = self.preprocess_request()718 if rv is None:719 rv = self.dispatch_request()720 response = self.make_response(rv)721 except Exception, e:722 response = self.make_response(self.handle_exception(e))723 try:724 response = self.process_response(response)725 except Exception, e:726 response = self.make_response(self.handle_exception(e))727 return response(environ, start_response)728729 def request_context(self, environ):730 """Creates a request context from the given environment and binds731 it to the current context. This must be used in combination with732 the `with` statement because the request is only bound to the733 current context for the duration of the `with` block.734735 Example usage::736737 with app.request_context(environ):738 do_something_with(request)739740 The object returned can also be used without the `with` statement741 which is useful for working in the shell. The example above is742 doing exactly the same as this code::743744 ctx = app.request_context(environ)745 ctx.push()746 try:747 do_something_with(request)748 finally:749 ctx.pop()750751 The big advantage of this approach is that you can use it without752 the try/finally statement in a shell for interactive testing:753754 >>> ctx = app.test_request_context()755 >>> ctx.bind()756 >>> request.path757 u'/'758 >>> ctx.unbind()759760 .. versionchanged:: 0.3761 Added support for non-with statement usage and `with` statement762 is now passed the ctx object.763764 :param environ: a WSGI environment765 """766 return _RequestContext(self, environ)767768 def test_request_context(self, *args, **kwargs):769 """Creates a WSGI environment from the given values (see770 :func:`werkzeug.create_environ` for more information, this771 function accepts the same arguments).772 """773 return self.request_context(create_environ(*args, **kwargs))774775 def __call__(self, environ, start_response):776 """Shortcut for :attr:`wsgi_app`."""777 return self.wsgi_app(environ, start_response)778
added:flask/conf.py+135 added
123class ConfigAttribute(object):4 """Makes an attribute forward to the config"""56 def __init__(self, name):7 self.__name__ = name89 def __get__(self, obj, type=None):10 if obj is None:11 return self12 return obj.config[self.__name__]1314 def __set__(self, obj, value):15 obj.config[self.__name__] = value161718class Config(dict):19 """Works exactly like a dict but provides ways to fill it from files20 or special dictionaries. There are two common patterns to populate the21 config.2223 Either you can fill the config from a config file::2425 app.config.from_pyfile('yourconfig.cfg')2627 Or alternatively you can define the configuration options in the28 module that calls :meth:`from_object` or provide an import path to29 a module that should be loaded. It is also possible to tell it to30 use the same module and with that provide the configuration values31 just before the call::3233 DEBUG = True34 SECRET_KEY = 'development key'35 app.config.from_object(__name__)3637 In both cases (loading from any Python file or loading from modules),38 only uppercase keys are added to the config. This makes it possible to use39 lowercase values in the config file for temporary values that are not added40 to the config or to define the config keys in the same file that implements41 the application.4243 Probably the most interesting way to load configurations is from an44 environment variable pointing to a file::4546 app.config.from_envvar('YOURAPPLICATION_SETTINGS')4748 In this case before launching the application you have to set this49 environment variable to the file you want to use. On Linux and OS X50 use the export statement::5152 export YOURAPPLICATION_SETTINGS='/path/to/config/file'5354 On windows use `set` instead.5556 :param root_path: path to which files are read relative from. When the57 config object is created by the application, this is58 the application's :attr:`~flask.Flask.root_path`.59 :param defaults: an optional dictionary of default values60 """6162 def __init__(self, root_path, defaults=None):63 dict.__init__(self, defaults or {})64 self.root_path = root_path6566 def from_envvar(self, variable_name, silent=False):67 """Loads a configuration from an environment variable pointing to68 a configuration file. This basically is just a shortcut with nicer69 error messages for this line of code::7071 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])7273 :param variable_name: name of the environment variable74 :param silent: set to `True` if you want silent failing for missing75 files.76 :return: bool. `True` if able to load config, `False` otherwise.77 """78 rv = os.environ.get(variable_name)79 if not rv:80 if silent:81 return False82 raise RuntimeError('The environment variable %r is not set '83 'and as such configuration could not be '84 'loaded. Set this variable and make it '85 'point to a configuration file' %86 variable_name)87 self.from_pyfile(rv)88 return True8990 def from_pyfile(self, filename):91 """Updates the values in the config from a Python file. This function92 behaves as if the file was imported as module with the93 :meth:`from_object` function.9495 :param filename: the filename of the config. This can either be an96 absolute filename or a filename relative to the97 root path.98 """99 filename = os.path.join(self.root_path, filename)100 d = type(sys)('config')101 d.__file__ = filename102 execfile(filename, d.__dict__)103 self.from_object(d)104105 def from_object(self, obj):106 """Updates the values from the given object. An object can be of one107 of the following two types:108109 - a string: in this case the object with that name will be imported110 - an actual object reference: that object is used directly111112 Objects are usually either modules or classes.113114 Just the uppercase variables in that object are stored in the config115 after lowercasing. Example usage::116117 app.config.from_object('yourapplication.default_config')118 from yourapplication import default_config119 app.config.from_object(default_config)120121 You should not use this function to load the actual configuration but122 rather configuration defaults. The actual config should be loaded123 with :meth:`from_pyfile` and ideally from a location not within the124 package because the package might be installed system wide.125126 :param obj: an import name or object127 """128 if isinstance(obj, basestring):129 obj = import_string(obj)130 for key in dir(obj):131 if key.isupper():132 self[key] = getattr(obj, key)133134 def __repr__(self):135 return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
added:flask/ctx.py+57 added
123class _RequestContext(object):4 """The request context contains all request relevant information. It is5 created at the beginning of the request and pushed to the6 `_request_ctx_stack` and removed at the end of it. It will create the7 URL adapter and request object for the WSGI environment provided.8 """910 def __init__(self, app, environ):11 self.app = app12 self.url_adapter = app.url_map.bind_to_environ(environ,13 server_name=app.config['SERVER_NAME'])14 self.request = app.request_class(environ)15 self.session = app.open_session(self.request)16 if self.session is None:17 self.session = _NullSession()18 self.g = _RequestGlobals()19 self.flashes = None2021 try:22 self.request.endpoint, self.request.view_args = \23 self.url_adapter.match()24 except HTTPException, e:25 self.request.routing_exception = e2627 def push(self):28 """Binds the request context."""29 _request_ctx_stack.push(self)3031 def pop(self):32 """Pops the request context."""33 _request_ctx_stack.pop()3435 def __enter__(self):36 self.push()37 return self3839 def __exit__(self, exc_type, exc_value, tb):40 # do not pop the request stack if we are in debug mode and an41 # exception happened. This will allow the debugger to still42 # access the request object in the interactive shell. Furthermore43 # the context can be force kept alive for the test client.44 if not self.request.environ.get('flask._preserve_context') and \45 (tb is None or not self.app.debug):46 self.pop()47 48def _default_template_ctx_processor():49 """Default template context processor. Injects `request`,50 `session` and `g`.51 """52 reqctx = _request_ctx_stack.top53 return dict(54 request=reqctx.request,55 session=reqctx.session,56 g=reqctx.g57 )
added:flask/helpers.py+310 added
1# try to load the best simplejson implementation available. If JSON2# is not installed, we add a failing class.3json_available = True4try:5 import simplejson as json6except ImportError:7 try:8 import json9 except ImportError:10 json_available = False11 12def _assert_have_json():13 """Helper function that fails if JSON is unavailable."""14 if not json_available:15 raise RuntimeError('simplejson not installed')1617# figure out if simplejson escapes slashes. This behaviour was changed18# from one version to another without reason.19if not json_available or '\\/' not in json.dumps('/'):2021 def _tojson_filter(*args, **kwargs):22 if __debug__:23 _assert_have_json()24 return json.dumps(*args, **kwargs).replace('/', '\\/')25else:26 _tojson_filter = json.dumps2728def jsonify(*args, **kwargs):29 """Creates a :class:`~flask.Response` with the JSON representation of30 the given arguments with an `application/json` mimetype. The arguments31 to this function are the same as to the :class:`dict` constructor.3233 Example usage::3435 @app.route('/_get_current_user')36 def get_current_user():37 return jsonify(username=g.user.username,38 email=g.user.email,39 id=g.user.id)4041 This will send a JSON response like this to the browser::4243 {44 "username": "admin",45 "email": "admin@localhost",46 "id": 4247 }4849 This requires Python 2.6 or an installed version of simplejson. For50 security reasons only objects are supported toplevel. For more51 information about this, have a look at :ref:`json-security`.5253 .. versionadded:: 0.254 """55 if __debug__:56 _assert_have_json()57 return current_app.response_class(json.dumps(dict(*args, **kwargs),58 indent=None if request.is_xhr else 2), mimetype='application/json')59 606162def url_for(endpoint, **values):63 """Generates a URL to the given endpoint with the method provided.64 The endpoint is relative to the active module if modules are in use.6566 Here some examples:6768 ==================== ======================= =============================69 Active Module Target Endpoint Target Function70 ==================== ======================= =============================71 `None` ``'index'`` `index` of the application72 `None` ``'.index'`` `index` of the application73 ``'admin'`` ``'index'`` `index` of the `admin` module74 any ``'.index'`` `index` of the application75 any ``'admin.index'`` `index` of the `admin` module76 ==================== ======================= =============================7778 Variable arguments that are unknown to the target endpoint are appended79 to the generated URL as query arguments.8081 For more information, head over to the :ref:`Quickstart <url-building>`.8283 :param endpoint: the endpoint of the URL (name of the function)84 :param values: the variable arguments of the URL rule85 :param _external: if set to `True`, an absolute URL is generated.86 """87 ctx = _request_ctx_stack.top88 if '.' not in endpoint:89 mod = ctx.request.module90 if mod is not None:91 endpoint = mod + '.' + endpoint92 elif endpoint.startswith('.'):93 endpoint = endpoint[1:]94 external = values.pop('_external', False)95 return ctx.url_adapter.build(endpoint, values, force_external=external)969798def get_template_attribute(template_name, attribute):99 """Loads a macro (or variable) a template exports. This can be used to100 invoke a macro from within Python code. If you for example have a101 template named `_cider.html` with the following contents:102103 .. sourcecode:: html+jinja104105 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}106107 You can access this from Python code like this::108109 hello = get_template_attribute('_cider.html', 'hello')110 return hello('World')111112 .. versionadded:: 0.2113114 :param template_name: the name of the template115 :param attribute: the name of the variable of macro to acccess116 """117 return getattr(current_app.jinja_env.get_template(template_name).module,118 attribute)119120121def flash(message, category='message'):122 """Flashes a message to the next request. In order to remove the123 flashed message from the session and to display it to the user,124 the template has to call :func:`get_flashed_messages`.125126 .. versionchanged: 0.3127 `category` parameter added.128129 :param message: the message to be flashed.130 :param category: the category for the message. The following values131 are recommended: ``'message'`` for any kind of message,132 ``'error'`` for errors, ``'info'`` for information133 messages and ``'warning'`` for warnings. However any134 kind of string can be used as category.135 """136 session.setdefault('_flashes', []).append((category, message))137138139def get_flashed_messages(with_categories=False):140 """Pulls all flashed messages from the session and returns them.141 Further calls in the same request to the function will return142 the same messages. By default just the messages are returned,143 but when `with_categories` is set to `True`, the return value will144 be a list of tuples in the form ``(category, message)`` instead.145146 Example usage:147148 .. sourcecode:: html+jinja149150 {% for category, msg in get_flashed_messages(with_categories=true) %}151 <p class=flash-{{ category }}>{{ msg }}152 {% endfor %}153154 .. versionchanged:: 0.3155 `with_categories` parameter added.156157 :param with_categories: set to `True` to also receive categories.158 """159 flashes = _request_ctx_stack.top.flashes160 if flashes is None:161 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])162 if not with_categories:163 return [x[1] for x in flashes]164 return flashes165166167168def send_file(filename_or_fp, mimetype=None, as_attachment=False,169 attachment_filename=None):170 """Sends the contents of a file to the client. This will use the171 most efficient method available and configured. By default it will172 try to use the WSGI server's file_wrapper support. Alternatively173 you can set the application's :attr:`~Flask.use_x_sendfile` attribute174 to ``True`` to directly emit an `X-Sendfile` header. This however175 requires support of the underlying webserver for `X-Sendfile`.176177 By default it will try to guess the mimetype for you, but you can178 also explicitly provide one. For extra security you probably want179 to sent certain files as attachment (HTML for instance).180181 Please never pass filenames to this function from user sources without182 checking them first. Something like this is usually sufficient to183 avoid security problems::184185 if '..' in filename or filename.startswith('/'):186 abort(404)187188 .. versionadded:: 0.2189190 :param filename_or_fp: the filename of the file to send. This is191 relative to the :attr:`~Flask.root_path` if a192 relative path is specified.193 Alternatively a file object might be provided194 in which case `X-Sendfile` might not work and195 fall back to the traditional method.196 :param mimetype: the mimetype of the file if provided, otherwise197 auto detection happens.198 :param as_attachment: set to `True` if you want to send this file with199 a ``Content-Disposition: attachment`` header.200 :param attachment_filename: the filename for the attachment if it201 differs from the file's filename.202 """203 if isinstance(filename_or_fp, basestring):204 filename = filename_or_fp205 file = None206 else:207 file = filename_or_fp208 filename = getattr(file, 'name', None)209 if filename is not None:210 filename = os.path.join(current_app.root_path, filename)211 if mimetype is None and (filename or attachment_filename):212 mimetype = mimetypes.guess_type(filename or attachment_filename)[0]213 if mimetype is None:214 mimetype = 'application/octet-stream'215216 headers = Headers()217 if as_attachment:218 if attachment_filename is None:219 if filename is None:220 raise TypeError('filename unavailable, required for '221 'sending as attachment')222 attachment_filename = os.path.basename(filename)223 headers.add('Content-Disposition', 'attachment',224 filename=attachment_filename)225226 if current_app.use_x_sendfile and filename:227 if file is not None:228 file.close()229 headers['X-Sendfile'] = filename230 data = None231 else:232 if file is None:233 file = open(filename, 'rb')234 data = wrap_file(request.environ, file)235236 return Response(data, mimetype=mimetype, headers=headers,237 direct_passthrough=True)238239240def render_template(template_name, **context):241 """Renders a template from the template folder with the given242 context.243244 :param template_name: the name of the template to be rendered245 :param context: the variables that should be available in the246 context of the template.247 """248 current_app.update_template_context(context)249 return current_app.jinja_env.get_template(template_name).render(context)250251252def render_template_string(source, **context):253 """Renders a template from the given template source string254 with the given context.255256 :param template_name: the sourcecode of the template to be257 rendered258 :param context: the variables that should be available in the259 context of the template.260 """261 current_app.update_template_context(context)262 return current_app.jinja_env.from_string(source).render(context)263264265266def _get_package_path(name):267 """Returns the path to a package or cwd if that cannot be found."""268 try:269 return os.path.abspath(os.path.dirname(sys.modules[name].__file__))270 except (KeyError, AttributeError):271 return os.getcwd()272273274275class _PackageBoundObject(object):276277 def __init__(self, import_name):278 #: The name of the package or module. Do not change this once279 #: it was set by the constructor.280 self.import_name = import_name281282 #: Where is the app root located?283 self.root_path = _get_package_path(self.import_name)284285 def open_resource(self, resource):286 """Opens a resource from the application's resource folder. To see287 how this works, consider the following folder structure::288289 /myapplication.py290 /schemal.sql291 /static292 /style.css293 /templates294 /layout.html295 /index.html296297 If you want to open the `schema.sql` file you would do the298 following::299300 with app.open_resource('schema.sql') as f:301 contents = f.read()302 do_something_with(contents)303304 :param resource: the name of the resource. To access resources within305 subfolders use forward slashes as separator.306 """307 if pkg_resources is None:308 return open(os.path.join(self.root_path, resource), 'rb')309 return pkg_resources.resource_stream(self.import_name, resource)310
added:flask/module.py+151 added
123class _ModuleSetupState(object):45 def __init__(self, app, url_prefix=None):6 self.app = app7 self.url_prefix = url_prefix8910class Module(_PackageBoundObject):11 """Container object that enables pluggable applications. A module can12 be used to organize larger applications. They represent blueprints that,13 in combination with a :class:`Flask` object are used to create a large14 application.1516 A module is like an application bound to an `import_name`. Multiple17 modules can share the same import names, but in that case a `name` has18 to be provided to keep them apart. If different import names are used,19 the rightmost part of the import name is used as name.2021 Here an example structure for a larger appliation::2223 /myapplication24 /__init__.py25 /views26 /__init__.py27 /admin.py28 /frontend.py2930 The `myapplication/__init__.py` can look like this::3132 from flask import Flask33 from myapplication.views.admin import admin34 from myapplication.views.frontend import frontend3536 app = Flask(__name__)37 app.register_module(admin, url_prefix='/admin')38 app.register_module(frontend)3940 And here an example view module (`myapplication/views/admin.py`)::4142 from flask import Module4344 admin = Module(__name__)4546 @admin.route('/')47 def index():48 pass4950 @admin.route('/login')51 def login():52 pass5354 For a gentle introduction into modules, checkout the55 :ref:`working-with-modules` section.56 """5758 def __init__(self, import_name, name=None, url_prefix=None):59 if name is None:60 assert '.' in import_name, 'name required if package name ' \61 'does not point to a submodule'62 name = import_name.rsplit('.', 1)[1]63 _PackageBoundObject.__init__(self, import_name)64 self.name = name65 self.url_prefix = url_prefix66 self._register_events = []6768 def route(self, rule, **options):69 """Like :meth:`Flask.route` but for a module. The endpoint for the70 :func:`url_for` function is prefixed with the name of the module.71 """72 def decorator(f):73 self.add_url_rule(rule, f.__name__, f, **options)74 return f75 return decorator7677 def add_url_rule(self, rule, endpoint, view_func=None, **options):78 """Like :meth:`Flask.add_url_rule` but for a module. The endpoint for79 the :func:`url_for` function is prefixed with the name of the module.80 """81 def register_rule(state):82 the_rule = rule83 if state.url_prefix:84 the_rule = state.url_prefix + rule85 state.app.add_url_rule(the_rule, '%s.%s' % (self.name, endpoint),86 view_func, **options)87 self._record(register_rule)8889 def before_request(self, f):90 """Like :meth:`Flask.before_request` but for a module. This function91 is only executed before each request that is handled by a function of92 that module.93 """94 self._record(lambda s: s.app.before_request_funcs95 .setdefault(self.name, []).append(f))96 return f9798 def before_app_request(self, f):99 """Like :meth:`Flask.before_request`. Such a function is executed100 before each request, even if outside of a module.101 """102 self._record(lambda s: s.app.before_request_funcs103 .setdefault(None, []).append(f))104 return f105106 def after_request(self, f):107 """Like :meth:`Flask.after_request` but for a module. This function108 is only executed after each request that is handled by a function of109 that module.110 """111 self._record(lambda s: s.app.after_request_funcs112 .setdefault(self.name, []).append(f))113 return f114115 def after_app_request(self, f):116 """Like :meth:`Flask.after_request` but for a module. Such a function117 is executed after each request, even if outside of the module.118 """119 self._record(lambda s: s.app.after_request_funcs120 .setdefault(None, []).append(f))121 return f122123 def context_processor(self, f):124 """Like :meth:`Flask.context_processor` but for a module. This125 function is only executed for requests handled by a module.126 """127 self._record(lambda s: s.app.template_context_processors128 .setdefault(self.name, []).append(f))129 return f130131 def app_context_processor(self, f):132 """Like :meth:`Flask.context_processor` but for a module. Such a133 function is executed each request, even if outside of the module.134 """135 self._record(lambda s: s.app.template_context_processors136 .setdefault(None, []).append(f))137 return f138139 def app_errorhandler(self, code):140 """Like :meth:`Flask.errorhandler` but for a module. This141 handler is used for all requests, even if outside of the module.142143 .. versionadded:: 0.4144 """145 def decorator(f):146 self._record(lambda s: s.app.errorhandler(code)(f))147 return f148 return decorator149150 def _record(self, func):151 self._register_events.append(func)
added:flask/session.py+28 added
1class Session(SecureCookie):2 """Expands the session with support for switching between permanent3 and non-permanent sessions.4 """56 def _get_permanent(self):7 return self.get('_permanent', False)89 def _set_permanent(self, value):10 self['_permanent'] = bool(value)1112 permanent = property(_get_permanent, _set_permanent)13 del _get_permanent, _set_permanent141516class _NullSession(Session):17 """Class used to generate nicer error messages if sessions are not18 available. Will still allow read-only access to the empty session19 but fail on setting.20 """2122 def _fail(self, *args, **kwargs):23 raise RuntimeError('the session is unavailable because no secret '24 'key was set. Set the secret_key on the '25 'application to something unique and secret')26 __setitem__ = __delitem__ = clear = pop = popitem = \27 update = setdefault = _fail28 del _fail
added:flask/wrappers.py+57 added
1class Request(RequestBase):2 """The request object used by default in flask. Remembers the3 matched endpoint and view arguments.45 It is what ends up as :class:`~flask.request`. If you want to replace6 the request object used you can subclass this and set7 :attr:`~flask.Flask.request_class` to your subclass.8 """910 #: the endpoint that matched the request. This in combination with11 #: :attr:`view_args` can be used to reconstruct the same or a12 #: modified URL. If an exception happened when matching, this will13 #: be `None`.14 endpoint = None1516 #: a dict of view arguments that matched the request. If an exception17 #: happened when matching, this will be `None`.18 view_args = None1920 #: if matching the URL failed, this is the exception that will be21 #: raised / was raised as part of the request handling. This is22 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or23 #: something similar.24 routing_exception = None2526 @property27 def module(self):28 """The name of the current module"""29 if self.endpoint and '.' in self.endpoint:30 return self.endpoint.rsplit('.', 1)[0]3132 @cached_property33 def json(self):34 """If the mimetype is `application/json` this will contain the35 parsed JSON data.36 """37 if __debug__:38 _assert_have_json()39 if self.mimetype == 'application/json':40 return json.loads(self.data)414243class Response(ResponseBase):44 """The response object that is used by default in flask. Works like the45 response object from Werkzeug but is set to have a HTML mimetype by46 default. Quite often you don't have to create this object yourself because47 :meth:`~flask.Flask.make_response` will take care of that for you.4849 If you want to replace the response object used you can subclass this and50 set :attr:`~flask.Flask.response_class` to your subclass.51 """52 default_mimetype = 'text/html'535455class _RequestGlobals(object):56 pass57