Flask-0.12.2/0000755000175000001440000000000013106517244014024 5ustar untitakerusers00000000000000Flask-0.12.2/README0000644000175000001440000000253613106517205014707 0ustar untitakerusers00000000000000 // Flask // web development, one drop at a time ~ What is Flask? Flask is a microframework for Python based on Werkzeug and Jinja2. It's intended for getting started very quickly and was developed with best intentions in mind. ~ Is it ready? It's still not 1.0 but it's shaping up nicely and is already widely used. Consider the API to slightly improve over time but we don't plan on breaking it. ~ What do I need? All dependencies are installed by using `pip install Flask`. We encourage you to use a virtualenv. Check the docs for complete installation and usage instructions. ~ Where are the docs? Go to http://flask.pocoo.org/docs/ for a prebuilt version of the current documentation. Otherwise build them yourself from the sphinx sources in the docs folder. ~ Where are the tests? Good that you're asking. The tests are in the tests/ folder. To run the tests use the `py.test` testing tool: $ py.test Details on contributing can be found in CONTRIBUTING.rst ~ Where can I get help? Either use the #pocoo IRC channel on irc.freenode.net or ask on the mailinglist: http://flask.pocoo.org/mailinglist/ See http://flask.pocoo.org/community/ for more resources. Flask-0.12.2/CHANGES0000644000175000001440000007073713106517222015031 0ustar untitakerusers00000000000000Flask Changelog =============== Here you can see the full list of changes between each Flask release. Version 0.13 ------------ Major release, unreleased - Make `app.run()` into a noop if a Flask application is run from the development server on the command line. This avoids some behavior that was confusing to debug for newcomers. - Change default configuration `JSONIFY_PRETTYPRINT_REGULAR=False`. jsonify() method returns compressed response by default, and pretty response in debug mode. Version 0.12.2 -------------- Released on May 16 2017 - Fix a bug in `safe_join` on Windows. Version 0.12.1 -------------- Bugfix release, released on March 31st 2017 - Prevent `flask run` from showing a NoAppException when an ImportError occurs within the imported application module. - Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix ``#2118``. - Call `ctx.auto_pop` with the exception object instead of `None`, in the event that a `BaseException` such as `KeyboardInterrupt` is raised in a request handler. Version 0.12 ------------ Released on December 21st 2016, codename Punsch. - the cli command now responds to `--version`. - Mimetype guessing and ETag generation for file-like objects in ``send_file`` has been removed, as per issue ``#104``. See pull request ``#1849``. - Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to ``application/octet-stream``. See pull request ``#1988``. - Make ``flask.safe_join`` able to join multiple paths like ``os.path.join`` (pull request ``#1730``). - Revert a behavior change that made the dev server crash instead of returning a Internal Server Error (pull request ``#2006``). - Correctly invoke response handlers for both regular request dispatching as well as error handlers. - Disable logger propagation by default for the app logger. - Add support for range requests in ``send_file``. - ``app.test_client`` includes preset default environment, which can now be directly set, instead of per ``client.get``. Version 0.11.2 -------------- Bugfix release, unreleased - Fix crash when running under PyPy3, see pull request ``#1814``. Version 0.11.1 -------------- Bugfix release, released on June 7th 2016. - Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. See pull request ``#1872``. Version 0.11 ------------ Released on May 29th 2016, codename Absinthe. - Added support to serializing top-level arrays to :func:`flask.jsonify`. This introduces a security risk in ancient browsers. See :ref:`json-security` for details. - Added before_render_template signal. - Added `**kwargs` to :meth:`flask.Test.test_client` to support passing additional keyword arguments to the constructor of :attr:`flask.Flask.test_client_class`. - Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the set-cookie behavior. If set to ``True`` a permanent session will be refreshed each request and get their lifetime extended, if set to ``False`` it will only be modified if the session actually modifies. Non permanent sessions are not affected by this and will always expire if the browser window closes. - Made Flask support custom JSON mimetypes for incoming data. - Added support for returning tuples in the form ``(response, headers)`` from a view function. - Added :meth:`flask.Config.from_json`. - Added :attr:`flask.Flask.config_class`. - Added :meth:`flask.Config.get_namespace`. - Templates are no longer automatically reloaded outside of debug mode. This can be configured with the new ``TEMPLATES_AUTO_RELOAD`` config key. - Added a workaround for a limitation in Python 3.3's namespace loader. - Added support for explicit root paths when using Python 3.3's namespace packages. - Added :command:`flask` and the ``flask.cli`` module to start the local debug server through the click CLI system. This is recommended over the old ``flask.run()`` method as it works faster and more reliable due to a different design and also replaces ``Flask-Script``. - Error handlers that match specific classes are now checked first, thereby allowing catching exceptions that are subclasses of HTTP exceptions (in ``werkzeug.exceptions``). This makes it possible for an extension author to create exceptions that will by default result in the HTTP error of their choosing, but may be caught with a custom error handler if desired. - Added :meth:`flask.Config.from_mapping`. - Flask will now log by default even if debug is disabled. The log format is now hardcoded but the default log handling can be disabled through the ``LOGGER_HANDLER_POLICY`` configuration key. - Removed deprecated module functionality. - Added the ``EXPLAIN_TEMPLATE_LOADING`` config flag which when enabled will instruct Flask to explain how it locates templates. This should help users debug when the wrong templates are loaded. - Enforce blueprint handling in the order they were registered for template loading. - Ported test suite to py.test. - Deprecated ``request.json`` in favour of ``request.get_json()``. - Add "pretty" and "compressed" separators definitions in jsonify() method. Reduces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing unnecessary white space included by default after separators. - JSON responses are now terminated with a newline character, because it is a convention that UNIX text files end with a newline and some clients don't deal well when this newline is missing. See https://github.com/pallets/flask/pull/1262 -- this came up originally as a part of https://github.com/kennethreitz/httpbin/issues/168 - The automatically provided ``OPTIONS`` method is now correctly disabled if the user registered an overriding rule with the lowercase-version ``options`` (issue ``#1288``). - ``flask.json.jsonify`` now supports the ``datetime.date`` type (pull request ``#1326``). - Don't leak exception info of already catched exceptions to context teardown handlers (pull request ``#1393``). - Allow custom Jinja environment subclasses (pull request ``#1422``). - ``flask.g`` now has ``pop()`` and ``setdefault`` methods. - Turn on autoescape for ``flask.templating.render_template_string`` by default (pull request ``#1515``). - ``flask.ext`` is now deprecated (pull request ``#1484``). - ``send_from_directory`` now raises BadRequest if the filename is invalid on the server OS (pull request ``#1763``). - Added the ``JSONIFY_MIMETYPE`` configuration variable (pull request ``#1728``). - Exceptions during teardown handling will no longer leave bad application contexts lingering around. Version 0.10.2 -------------- (bugfix release, release date to be announced) - Fixed broken `test_appcontext_signals()` test case. - Raise an :exc:`AttributeError` in :func:`flask.helpers.find_package` with a useful message explaining why it is raised when a PEP 302 import hook is used without an `is_package()` method. - Fixed an issue causing exceptions raised before entering a request or app context to be passed to teardown handlers. - Fixed an issue with query parameters getting removed from requests in the test client when absolute URLs were requested. - Made `@before_first_request` into a decorator as intended. - Fixed an etags bug when sending a file streams with a name. - Fixed `send_from_directory` not expanding to the application root path correctly. - Changed logic of before first request handlers to flip the flag after invoking. This will allow some uses that are potentially dangerous but should probably be permitted. - Fixed Python 3 bug when a handler from `app.url_build_error_handlers` reraises the `BuildError`. Version 0.10.1 -------------- (bugfix release, released on June 14th 2013) - Fixed an issue where ``|tojson`` was not quoting single quotes which made the filter not work properly in HTML attributes. Now it's possible to use that filter in single quoted attributes. This should make using that filter with angular.js easier. - Added support for byte strings back to the session system. This broke compatibility with the common case of people putting binary data for token verification into the session. - Fixed an issue where registering the same method twice for the same endpoint would trigger an exception incorrectly. Version 0.10 ------------ Released on June 13th 2013, codename Limoncello. - Changed default cookie serialization format from pickle to JSON to limit the impact an attacker can do if the secret key leaks. See :ref:`upgrading-to-010` for more information. - Added ``template_test`` methods in addition to the already existing ``template_filter`` method family. - Added ``template_global`` methods in addition to the already existing ``template_filter`` method family. - Set the content-length header for x-sendfile. - ``tojson`` filter now does not escape script blocks in HTML5 parsers. - ``tojson`` used in templates is now safe by default due. This was allowed due to the different escaping behavior. - Flask will now raise an error if you attempt to register a new function on an already used endpoint. - Added wrapper module around simplejson and added default serialization of datetime objects. This allows much easier customization of how JSON is handled by Flask or any Flask extension. - Removed deprecated internal ``flask.session`` module alias. Use ``flask.sessions`` instead to get the session module. This is not to be confused with ``flask.session`` the session proxy. - Templates can now be rendered without request context. The behavior is slightly different as the ``request``, ``session`` and ``g`` objects will not be available and blueprint's context processors are not called. - The config object is now available to the template as a real global and not through a context processor which makes it available even in imported templates by default. - Added an option to generate non-ascii encoded JSON which should result in less bytes being transmitted over the network. It's disabled by default to not cause confusion with existing libraries that might expect ``flask.json.dumps`` to return bytestrings by default. - ``flask.g`` is now stored on the app context instead of the request context. - ``flask.g`` now gained a ``get()`` method for not erroring out on non existing items. - ``flask.g`` now can be used with the ``in`` operator to see what's defined and it now is iterable and will yield all attributes stored. - ``flask.Flask.request_globals_class`` got renamed to ``flask.Flask.app_ctx_globals_class`` which is a better name to what it does since 0.10. - `request`, `session` and `g` are now also added as proxies to the template context which makes them available in imported templates. One has to be very careful with those though because usage outside of macros might cause caching. - Flask will no longer invoke the wrong error handlers if a proxy exception is passed through. - Added a workaround for chrome's cookies in localhost not working as intended with domain names. - Changed logic for picking defaults for cookie values from sessions to work better with Google Chrome. - Added `message_flashed` signal that simplifies flashing testing. - Added support for copying of request contexts for better working with greenlets. - Removed custom JSON HTTP exception subclasses. If you were relying on them you can reintroduce them again yourself trivially. Using them however is strongly discouraged as the interface was flawed. - Python requirements changed: requiring Python 2.6 or 2.7 now to prepare for Python 3.3 port. - Changed how the teardown system is informed about exceptions. This is now more reliable in case something handles an exception halfway through the error handling process. - Request context preservation in debug mode now keeps the exception information around which means that teardown handlers are able to distinguish error from success cases. - Added the ``JSONIFY_PRETTYPRINT_REGULAR`` configuration variable. - Flask now orders JSON keys by default to not trash HTTP caches due to different hash seeds between different workers. - Added `appcontext_pushed` and `appcontext_popped` signals. - The builtin run method now takes the ``SERVER_NAME`` into account when picking the default port to run on. - Added `flask.request.get_json()` as a replacement for the old `flask.request.json` property. Version 0.9 ----------- Released on July 1st 2012, codename Campari. - The :func:`flask.Request.on_json_loading_failed` now returns a JSON formatted response by default. - The :func:`flask.url_for` function now can generate anchors to the generated links. - The :func:`flask.url_for` function now can also explicitly generate URL rules specific to a given HTTP method. - Logger now only returns the debug log setting if it was not set explicitly. - Unregister a circular dependency between the WSGI environment and the request object when shutting down the request. This means that environ ``werkzeug.request`` will be ``None`` after the response was returned to the WSGI server but has the advantage that the garbage collector is not needed on CPython to tear down the request unless the user created circular dependencies themselves. - Session is now stored after callbacks so that if the session payload is stored in the session you can still modify it in an after request callback. - The :class:`flask.Flask` class will avoid importing the provided import name if it can (the required first parameter), to benefit tools which build Flask instances programmatically. The Flask class will fall back to using import on systems with custom module hooks, e.g. Google App Engine, or when the import name is inside a zip archive (usually a .egg) prior to Python 2.7. - Blueprints now have a decorator to add custom template filters application wide, :meth:`flask.Blueprint.app_template_filter`. - The Flask and Blueprint classes now have a non-decorator method for adding custom template filters application wide, :meth:`flask.Flask.add_template_filter` and :meth:`flask.Blueprint.add_app_template_filter`. - The :func:`flask.get_flashed_messages` function now allows rendering flashed message categories in separate blocks, through a ``category_filter`` argument. - The :meth:`flask.Flask.run` method now accepts ``None`` for `host` and `port` arguments, using default values when ``None``. This allows for calling run using configuration values, e.g. ``app.run(app.config.get('MYHOST'), app.config.get('MYPORT'))``, with proper behavior whether or not a config file is provided. - The :meth:`flask.render_template` method now accepts a either an iterable of template names or a single template name. Previously, it only accepted a single template name. On an iterable, the first template found is rendered. - Added :meth:`flask.Flask.app_context` which works very similar to the request context but only provides access to the current application. This also adds support for URL generation without an active request context. - View functions can now return a tuple with the first instance being an instance of :class:`flask.Response`. This allows for returning ``jsonify(error="error msg"), 400`` from a view function. - :class:`~flask.Flask` and :class:`~flask.Blueprint` now provide a :meth:`~flask.Flask.get_send_file_max_age` hook for subclasses to override behavior of serving static files from Flask when using :meth:`flask.Flask.send_static_file` (used for the default static file handler) and :func:`~flask.helpers.send_file`. This hook is provided a filename, which for example allows changing cache controls by file extension. The default max-age for `send_file` and static files can be configured through a new ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, which is used in the default `get_send_file_max_age` implementation. - Fixed an assumption in sessions implementation which could break message flashing on sessions implementations which use external storage. - Changed the behavior of tuple return values from functions. They are no longer arguments to the response object, they now have a defined meaning. - Added :attr:`flask.Flask.request_globals_class` to allow a specific class to be used on creation of the :data:`~flask.g` instance of each request. - Added `required_methods` attribute to view functions to force-add methods on registration. - Added :func:`flask.after_this_request`. - Added :func:`flask.stream_with_context` and the ability to push contexts multiple times without producing unexpected behavior. Version 0.8.1 ------------- Bugfix release, released on July 1st 2012 - Fixed an issue with the undocumented `flask.session` module to not work properly on Python 2.5. It should not be used but did cause some problems for package managers. Version 0.8 ----------- Released on September 29th 2011, codename Rakija - Refactored session support into a session interface so that the implementation of the sessions can be changed without having to override the Flask class. - Empty session cookies are now deleted properly automatically. - View functions can now opt out of getting the automatic OPTIONS implementation. - HTTP exceptions and Bad Request errors can now be trapped so that they show up normally in the traceback. - Flask in debug mode is now detecting some common problems and tries to warn you about them. - Flask in debug mode will now complain with an assertion error if a view was attached after the first request was handled. This gives earlier feedback when users forget to import view code ahead of time. - Added the ability to register callbacks that are only triggered once at the beginning of the first request. (:meth:`Flask.before_first_request`) - Malformed JSON data will now trigger a bad request HTTP exception instead of a value error which usually would result in a 500 internal server error if not handled. This is a backwards incompatible change. - Applications now not only have a root path where the resources and modules are located but also an instance path which is the designated place to drop files that are modified at runtime (uploads etc.). Also this is conceptually only instance depending and outside version control so it's the perfect place to put configuration files etc. For more information see :ref:`instance-folders`. - Added the ``APPLICATION_ROOT`` configuration variable. - Implemented :meth:`~flask.testing.TestClient.session_transaction` to easily modify sessions from the test environment. - Refactored test client internally. The ``APPLICATION_ROOT`` configuration variable as well as ``SERVER_NAME`` are now properly used by the test client as defaults. - Added :attr:`flask.views.View.decorators` to support simpler decorating of pluggable (class-based) views. - Fixed an issue where the test client if used with the "with" statement did not trigger the execution of the teardown handlers. - Added finer control over the session cookie parameters. - HEAD requests to a method view now automatically dispatch to the `get` method if no handler was implemented. - Implemented the virtual :mod:`flask.ext` package to import extensions from. - The context preservation on exceptions is now an integral component of Flask itself and no longer of the test client. This cleaned up some internal logic and lowers the odds of runaway request contexts in unittests. Version 0.7.3 ------------- Bugfix release, release date to be decided - Fixed the Jinja2 environment's list_templates method not returning the correct names when blueprints or modules were involved. Version 0.7.2 ------------- Bugfix release, released on July 6th 2011 - Fixed an issue with URL processors not properly working on blueprints. Version 0.7.1 ------------- Bugfix release, released on June 29th 2011 - Added missing future import that broke 2.5 compatibility. - Fixed an infinite redirect issue with blueprints. Version 0.7 ----------- Released on June 28th 2011, codename Grappa - Added :meth:`~flask.Flask.make_default_options_response` which can be used by subclasses to alter the default behavior for ``OPTIONS`` responses. - Unbound locals now raise a proper :exc:`RuntimeError` instead of an :exc:`AttributeError`. - Mimetype guessing and etag support based on file objects is now deprecated for :func:`flask.send_file` because it was unreliable. Pass filenames instead or attach your own etags and provide a proper mimetype by hand. - Static file handling for modules now requires the name of the static folder to be supplied explicitly. The previous autodetection was not reliable and caused issues on Google's App Engine. Until 1.0 the old behavior will continue to work but issue dependency warnings. - fixed a problem for Flask to run on jython. - added a ``PROPAGATE_EXCEPTIONS`` configuration variable that can be used to flip the setting of exception propagation which previously was linked to ``DEBUG`` alone and is now linked to either ``DEBUG`` or ``TESTING``. - Flask no longer internally depends on rules being added through the `add_url_rule` function and can now also accept regular werkzeug rules added to the url map. - Added an `endpoint` method to the flask application object which allows one to register a callback to an arbitrary endpoint with a decorator. - Use Last-Modified for static file sending instead of Date which was incorrectly introduced in 0.6. - Added `create_jinja_loader` to override the loader creation process. - Implemented a silent flag for `config.from_pyfile`. - Added `teardown_request` decorator, for functions that should run at the end of a request regardless of whether an exception occurred. Also the behavior for `after_request` was changed. It's now no longer executed when an exception is raised. See :ref:`upgrading-to-new-teardown-handling` - Implemented :func:`flask.has_request_context` - Deprecated `init_jinja_globals`. Override the :meth:`~flask.Flask.create_jinja_environment` method instead to achieve the same functionality. - Added :func:`flask.safe_join` - The automatic JSON request data unpacking now looks at the charset mimetype parameter. - Don't modify the session on :func:`flask.get_flashed_messages` if there are no messages in the session. - `before_request` handlers are now able to abort requests with errors. - it is not possible to define user exception handlers. That way you can provide custom error messages from a central hub for certain errors that might occur during request processing (for instance database connection errors, timeouts from remote resources etc.). - Blueprints can provide blueprint specific error handlers. - Implemented generic :ref:`views` (class-based views). Version 0.6.1 ------------- Bugfix release, released on December 31st 2010 - Fixed an issue where the default ``OPTIONS`` response was not exposing all valid methods in the ``Allow`` header. - Jinja2 template loading syntax now allows "./" in front of a template load path. Previously this caused issues with module setups. - Fixed an issue where the subdomain setting for modules was ignored for the static folder. - Fixed a security problem that allowed clients to download arbitrary files if the host server was a windows based operating system and the client uses backslashes to escape the directory the files where exposed from. Version 0.6 ----------- Released on July 27th 2010, codename Whisky - after request functions are now called in reverse order of registration. - OPTIONS is now automatically implemented by Flask unless the application explicitly adds 'OPTIONS' as method to the URL rule. In this case no automatic OPTIONS handling kicks in. - static rules are now even in place if there is no static folder for the module. This was implemented to aid GAE which will remove the static folder if it's part of a mapping in the .yml file. - the :attr:`~flask.Flask.config` is now available in the templates as `config`. - context processors will no longer override values passed directly to the render function. - added the ability to limit the incoming request data with the new ``MAX_CONTENT_LENGTH`` configuration value. - the endpoint for the :meth:`flask.Module.add_url_rule` method is now optional to be consistent with the function of the same name on the application object. - added a :func:`flask.make_response` function that simplifies creating response object instances in views. - added signalling support based on blinker. This feature is currently optional and supposed to be used by extensions and applications. If you want to use it, make sure to have `blinker`_ installed. - refactored the way URL adapters are created. This process is now fully customizable with the :meth:`~flask.Flask.create_url_adapter` method. - modules can now register for a subdomain instead of just an URL prefix. This makes it possible to bind a whole module to a configurable subdomain. .. _blinker: https://pypi.python.org/pypi/blinker Version 0.5.2 ------------- Bugfix Release, released on July 15th 2010 - fixed another issue with loading templates from directories when modules were used. Version 0.5.1 ------------- Bugfix Release, released on July 6th 2010 - fixes an issue with template loading from directories when modules where used. Version 0.5 ----------- Released on July 6th 2010, codename Calvados - fixed a bug with subdomains that was caused by the inability to specify the server name. The server name can now be set with the ``SERVER_NAME`` config key. This key is now also used to set the session cookie cross-subdomain wide. - autoescaping is no longer active for all templates. Instead it is only active for ``.html``, ``.htm``, ``.xml`` and ``.xhtml``. Inside templates this behavior can be changed with the ``autoescape`` tag. - refactored Flask internally. It now consists of more than a single file. - :func:`flask.send_file` now emits etags and has the ability to do conditional responses builtin. - (temporarily) dropped support for zipped applications. This was a rarely used feature and led to some confusing behavior. - added support for per-package template and static-file directories. - removed support for `create_jinja_loader` which is no longer used in 0.5 due to the improved module support. - added a helper function to expose files from any directory. Version 0.4 ----------- Released on June 18th 2010, codename Rakia - added the ability to register application wide error handlers from modules. - :meth:`~flask.Flask.after_request` handlers are now also invoked if the request dies with an exception and an error handling page kicks in. - test client has not the ability to preserve the request context for a little longer. This can also be used to trigger custom requests that do not pop the request stack for testing. - because the Python standard library caches loggers, the name of the logger is configurable now to better support unittests. - added ``TESTING`` switch that can activate unittesting helpers. - the logger switches to ``DEBUG`` mode now if debug is enabled. Version 0.3.1 ------------- Bugfix release, released on May 28th 2010 - fixed a error reporting bug with :meth:`flask.Config.from_envvar` - removed some unused code from flask - release does no longer include development leftover files (.git folder for themes, built documentation in zip and pdf file and some .pyc files) Version 0.3 ----------- Released on May 28th 2010, codename Schnaps - added support for categories for flashed messages. - the application now configures a :class:`logging.Handler` and will log request handling exceptions to that logger when not in debug mode. This makes it possible to receive mails on server errors for example. - added support for context binding that does not require the use of the with statement for playing in the console. - the request context is now available within the with statement making it possible to further push the request context or pop it. - added support for configurations. Version 0.2 ----------- Released on May 12th 2010, codename Jägermeister - various bugfixes - integrated JSON support - added :func:`~flask.get_template_attribute` helper function. - :meth:`~flask.Flask.add_url_rule` can now also register a view function. - refactored internal request dispatching. - server listens on 127.0.0.1 by default now to fix issues with chrome. - added external URL support. - added support for :func:`~flask.send_file` - module support and internal request handling refactoring to better support pluggable applications. - sessions can be set to be permanent now on a per-session basis. - better error reporting on missing secret keys. - added support for Google Appengine. Version 0.1 ----------- First public preview release. Flask-0.12.2/setup.py0000644000175000001440000000464413106517205015543 0ustar untitakerusers00000000000000""" Flask ----- Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. And before you ask: It's BSD licensed! Flask is Fun ```````````` Save in a hello.py: .. code:: python from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() And Easy to Setup ````````````````` And run it: .. code:: bash $ pip install Flask $ python hello.py * Running on http://localhost:5000/ Ready for production? `Read this first `. Links ````` * `website `_ * `documentation `_ * `development version `_ """ import re import ast from setuptools import setup _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('flask/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) setup( name='Flask', version=version, url='http://github.com/pallets/flask/', license='BSD', author='Armin Ronacher', author_email='armin.ronacher@active-4.com', description='A microframework based on Werkzeug, Jinja2 ' 'and good intentions', long_description=__doc__, packages=['flask', 'flask.ext'], include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'Werkzeug>=0.7', 'Jinja2>=2.4', 'itsdangerous>=0.21', 'click>=2.0', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], entry_points=''' [console_scripts] flask=flask.cli:main ''' ) Flask-0.12.2/PKG-INFO0000644000175000001440000000422013106517244015117 0ustar untitakerusers00000000000000Metadata-Version: 1.1 Name: Flask Version: 0.12.2 Summary: A microframework based on Werkzeug, Jinja2 and good intentions Home-page: http://github.com/pallets/flask/ Author: Armin Ronacher Author-email: armin.ronacher@active-4.com License: BSD Description: Flask ----- Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. And before you ask: It's BSD licensed! Flask is Fun ```````````` Save in a hello.py: .. code:: python from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() And Easy to Setup ````````````````` And run it: .. code:: bash $ pip install Flask $ python hello.py * Running on http://localhost:5000/ Ready for production? `Read this first `. Links ````` * `website `_ * `documentation `_ * `development version `_ Platform: any Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Flask-0.12.2/artwork/0000755000175000001440000000000013106517244015515 5ustar untitakerusers00000000000000Flask-0.12.2/artwork/LICENSE0000644000175000001440000000144312163033661016522 0ustar untitakerusers00000000000000Copyright (c) 2010 by Armin Ronacher. Some rights reserved. This logo or a modified version may be used by anyone to refer to the Flask project, but does not indicate endorsement by the project. Redistribution and use in source (the SVG file) and binary forms (rendered PNG files etc.) of the image, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice and this list of conditions. * The names of the contributors to the Flask software (see AUTHORS) may not be used to endorse or promote products derived from this software without specific prior written permission. Note: we would appreciate that you make the image a link to http://flask.pocoo.org/ if you use it on a web page. Flask-0.12.2/artwork/logo-lineart.svg0000644000175000001440000001766712763616450020662 0ustar untitakerusers00000000000000 image/svg+xml Flask-0.12.2/artwork/logo-full.svg0000644000175000001440000023115712163033661020145 0ustar untitakerusers00000000000000 image/svg+xml Flask-0.12.2/MANIFEST.in0000644000175000001440000000023512763616450015571 0ustar untitakerusers00000000000000include Makefile CHANGES LICENSE AUTHORS graft artwork graft tests graft examples graft docs global-exclude *.py[co] prune docs/_build prune docs/_themes Flask-0.12.2/Flask.egg-info/0000755000175000001440000000000013106517244016556 5ustar untitakerusers00000000000000Flask-0.12.2/Flask.egg-info/top_level.txt0000644000175000001440000000000613106517242021302 0ustar untitakerusers00000000000000flask Flask-0.12.2/Flask.egg-info/PKG-INFO0000644000175000001440000000422013106517242017647 0ustar untitakerusers00000000000000Metadata-Version: 1.1 Name: Flask Version: 0.12.2 Summary: A microframework based on Werkzeug, Jinja2 and good intentions Home-page: http://github.com/pallets/flask/ Author: Armin Ronacher Author-email: armin.ronacher@active-4.com License: BSD Description: Flask ----- Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. And before you ask: It's BSD licensed! Flask is Fun ```````````` Save in a hello.py: .. code:: python from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() And Easy to Setup ````````````````` And run it: .. code:: bash $ pip install Flask $ python hello.py * Running on http://localhost:5000/ Ready for production? `Read this first `. Links ````` * `website `_ * `documentation `_ * `development version `_ Platform: any Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Flask-0.12.2/Flask.egg-info/dependency_links.txt0000644000175000001440000000000113106517242022622 0ustar untitakerusers00000000000000 Flask-0.12.2/Flask.egg-info/not-zip-safe0000644000175000001440000000000112465172166021013 0ustar untitakerusers00000000000000 Flask-0.12.2/Flask.egg-info/requires.txt0000644000175000001440000000006713106517242021157 0ustar untitakerusers00000000000000Werkzeug>=0.7 Jinja2>=2.4 itsdangerous>=0.21 click>=2.0Flask-0.12.2/Flask.egg-info/entry_points.txt0000644000175000001440000000007413106517242022053 0ustar untitakerusers00000000000000 [console_scripts] flask=flask.cli:main Flask-0.12.2/Flask.egg-info/SOURCES.txt0000644000175000001440000001455613106517244020455 0ustar untitakerusers00000000000000AUTHORS CHANGES LICENSE MANIFEST.in Makefile README setup.cfg setup.py Flask.egg-info/PKG-INFO Flask.egg-info/SOURCES.txt Flask.egg-info/dependency_links.txt Flask.egg-info/entry_points.txt Flask.egg-info/not-zip-safe Flask.egg-info/requires.txt Flask.egg-info/top_level.txt artwork/LICENSE artwork/logo-full.svg artwork/logo-lineart.svg docs/.gitignore docs/Makefile docs/advanced_foreword.rst docs/api.rst docs/appcontext.rst docs/becomingbig.rst docs/blueprints.rst docs/changelog.rst docs/cli.rst docs/conf.py docs/config.rst docs/contents.rst.inc docs/design.rst docs/errorhandling.rst docs/extensiondev.rst docs/extensions.rst docs/flaskdocext.py docs/flaskext.py docs/flaskstyle.sty docs/foreword.rst docs/htmlfaq.rst docs/index.rst docs/installation.rst docs/latexindex.rst docs/license.rst docs/logo.pdf docs/make.bat docs/python3.rst docs/quickstart.rst docs/reqcontext.rst docs/security.rst docs/server.rst docs/shell.rst docs/signals.rst docs/styleguide.rst docs/templating.rst docs/testing.rst docs/unicode.rst docs/upgrading.rst docs/views.rst docs/_static/debugger.png docs/_static/flask-favicon.ico docs/_static/flask.png docs/_static/flaskr.png docs/_static/logo-full.png docs/_static/no.png docs/_static/touch-icon.png docs/_static/yes.png docs/_templates/sidebarintro.html docs/_templates/sidebarlogo.html docs/deploying/cgi.rst docs/deploying/fastcgi.rst docs/deploying/index.rst docs/deploying/mod_wsgi.rst docs/deploying/uwsgi.rst docs/deploying/wsgi-standalone.rst docs/patterns/apierrors.rst docs/patterns/appdispatch.rst docs/patterns/appfactories.rst docs/patterns/caching.rst docs/patterns/celery.rst docs/patterns/deferredcallbacks.rst docs/patterns/distribute.rst docs/patterns/errorpages.rst docs/patterns/fabric.rst docs/patterns/favicon.rst docs/patterns/fileuploads.rst docs/patterns/flashing.rst docs/patterns/index.rst docs/patterns/jquery.rst docs/patterns/lazyloading.rst docs/patterns/methodoverrides.rst docs/patterns/mongokit.rst docs/patterns/packages.rst docs/patterns/requestchecksum.rst docs/patterns/sqlalchemy.rst docs/patterns/sqlite3.rst docs/patterns/streaming.rst docs/patterns/subclassing.rst docs/patterns/templateinheritance.rst docs/patterns/urlprocessors.rst docs/patterns/viewdecorators.rst docs/patterns/wtforms.rst docs/tutorial/css.rst docs/tutorial/dbcon.rst docs/tutorial/dbinit.rst docs/tutorial/folders.rst docs/tutorial/index.rst docs/tutorial/introduction.rst docs/tutorial/packaging.rst docs/tutorial/schema.rst docs/tutorial/setup.rst docs/tutorial/templates.rst docs/tutorial/testing.rst docs/tutorial/views.rst examples/blueprintexample/blueprintexample.py examples/blueprintexample/test_blueprintexample.py examples/blueprintexample/simple_page/__init__.py examples/blueprintexample/simple_page/simple_page.py examples/blueprintexample/simple_page/templates/pages/hello.html examples/blueprintexample/simple_page/templates/pages/index.html examples/blueprintexample/simple_page/templates/pages/layout.html examples/blueprintexample/simple_page/templates/pages/world.html examples/flaskr/.gitignore examples/flaskr/MANIFEST.in examples/flaskr/README examples/flaskr/pytest_runner-2.11.1-py2.7.egg examples/flaskr/setup.cfg examples/flaskr/setup.py examples/flaskr/flaskr/__init__.py examples/flaskr/flaskr/flaskr.py examples/flaskr/flaskr/schema.sql examples/flaskr/flaskr.egg-info/PKG-INFO examples/flaskr/flaskr.egg-info/SOURCES.txt examples/flaskr/flaskr.egg-info/dependency_links.txt examples/flaskr/flaskr.egg-info/requires.txt examples/flaskr/flaskr.egg-info/top_level.txt examples/flaskr/flaskr/static/style.css examples/flaskr/flaskr/templates/layout.html examples/flaskr/flaskr/templates/login.html examples/flaskr/flaskr/templates/show_entries.html examples/flaskr/tests/test_flaskr.py examples/jqueryexample/jqueryexample.py examples/jqueryexample/templates/index.html examples/jqueryexample/templates/layout.html examples/minitwit/.gitignore examples/minitwit/MANIFEST.in examples/minitwit/README examples/minitwit/setup.cfg examples/minitwit/setup.py examples/minitwit/minitwit/__init__.py examples/minitwit/minitwit/minitwit.py examples/minitwit/minitwit/schema.sql examples/minitwit/minitwit.egg-info/PKG-INFO examples/minitwit/minitwit.egg-info/SOURCES.txt examples/minitwit/minitwit.egg-info/dependency_links.txt examples/minitwit/minitwit.egg-info/requires.txt examples/minitwit/minitwit.egg-info/top_level.txt examples/minitwit/minitwit/static/style.css examples/minitwit/minitwit/templates/layout.html examples/minitwit/minitwit/templates/login.html examples/minitwit/minitwit/templates/register.html examples/minitwit/minitwit/templates/timeline.html examples/minitwit/tests/test_minitwit.py flask/__init__.py flask/__main__.py flask/_compat.py flask/app.py flask/blueprints.py flask/cli.py flask/config.py flask/ctx.py flask/debughelpers.py flask/exthook.py flask/globals.py flask/helpers.py flask/json.py flask/logging.py flask/sessions.py flask/signals.py flask/templating.py flask/testing.py flask/views.py flask/wrappers.py flask/ext/__init__.py tests/conftest.py tests/test_appctx.py tests/test_basic.py tests/test_blueprints.py tests/test_cli.py tests/test_config.py tests/test_deprecations.py tests/test_ext.py tests/test_helpers.py tests/test_instance_config.py tests/test_regression.py tests/test_reqctx.py tests/test_signals.py tests/test_subclassing.py tests/test_templating.py tests/test_testing.py tests/test_user_error_handler.py tests/test_views.py tests/static/config.json tests/static/index.html tests/templates/_macro.html tests/templates/context_template.html tests/templates/escaping_template.html tests/templates/mail.txt tests/templates/non_escaping_template.txt tests/templates/simple_template.html tests/templates/template_filter.html tests/templates/template_test.html tests/templates/nested/nested.txt tests/test_apps/blueprintapp/__init__.py tests/test_apps/blueprintapp/apps/__init__.py tests/test_apps/blueprintapp/apps/admin/__init__.py tests/test_apps/blueprintapp/apps/admin/static/test.txt tests/test_apps/blueprintapp/apps/admin/static/css/test.css tests/test_apps/blueprintapp/apps/admin/templates/admin/index.html tests/test_apps/blueprintapp/apps/frontend/__init__.py tests/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html tests/test_apps/cliapp/__init__.py tests/test_apps/cliapp/app.py tests/test_apps/cliapp/importerrorapp.py tests/test_apps/cliapp/multiapp.py tests/test_apps/subdomaintestmodule/__init__.py tests/test_apps/subdomaintestmodule/static/hello.txtFlask-0.12.2/flask/0000755000175000001440000000000013106517244015124 5ustar untitakerusers00000000000000Flask-0.12.2/flask/globals.py0000644000175000001440000000315512763616450017134 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.globals ~~~~~~~~~~~~~ Defines all the global objects that are proxies to the current active context. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from functools import partial from werkzeug.local import LocalStack, LocalProxy _request_ctx_err_msg = '''\ Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.\ ''' _app_ctx_err_msg = '''\ Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in a way. To solve this set up an application context with app.app_context(). See the documentation for more information.\ ''' def _lookup_req_object(name): top = _request_ctx_stack.top if top is None: raise RuntimeError(_request_ctx_err_msg) return getattr(top, name) def _lookup_app_object(name): top = _app_ctx_stack.top if top is None: raise RuntimeError(_app_ctx_err_msg) return getattr(top, name) def _find_app(): top = _app_ctx_stack.top if top is None: raise RuntimeError(_app_ctx_err_msg) return top.app # context locals _request_ctx_stack = LocalStack() _app_ctx_stack = LocalStack() current_app = LocalProxy(_find_app) request = LocalProxy(partial(_lookup_req_object, 'request')) session = LocalProxy(partial(_lookup_req_object, 'session')) g = LocalProxy(partial(_lookup_app_object, 'g')) Flask-0.12.2/flask/logging.py0000644000175000001440000000527713047321000017122 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.logging ~~~~~~~~~~~~~ Implements the logging support for Flask. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import sys from werkzeug.local import LocalProxy from logging import getLogger, StreamHandler, Formatter, getLoggerClass, \ DEBUG, ERROR from .globals import _request_ctx_stack PROD_LOG_FORMAT = '[%(asctime)s] %(levelname)s in %(module)s: %(message)s' DEBUG_LOG_FORMAT = ( '-' * 80 + '\n' + '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' + '%(message)s\n' + '-' * 80 ) @LocalProxy def _proxy_stream(): """Finds the most appropriate error stream for the application. If a WSGI request is in flight we log to wsgi.errors, otherwise this resolves to sys.stderr. """ ctx = _request_ctx_stack.top if ctx is not None: return ctx.request.environ['wsgi.errors'] return sys.stderr def _should_log_for(app, mode): policy = app.config['LOGGER_HANDLER_POLICY'] if policy == mode or policy == 'always': return True return False def create_logger(app): """Creates a logger for the given application. This logger works similar to a regular Python logger but changes the effective logging level based on the application's debug flag. Furthermore this function also removes all attached handlers in case there was a logger with the log name before. """ Logger = getLoggerClass() class DebugLogger(Logger): def getEffectiveLevel(self): if self.level == 0 and app.debug: return DEBUG return Logger.getEffectiveLevel(self) class DebugHandler(StreamHandler): def emit(self, record): if app.debug and _should_log_for(app, 'debug'): StreamHandler.emit(self, record) class ProductionHandler(StreamHandler): def emit(self, record): if not app.debug and _should_log_for(app, 'production'): StreamHandler.emit(self, record) debug_handler = DebugHandler() debug_handler.setLevel(DEBUG) debug_handler.setFormatter(Formatter(DEBUG_LOG_FORMAT)) prod_handler = ProductionHandler(_proxy_stream) prod_handler.setLevel(ERROR) prod_handler.setFormatter(Formatter(PROD_LOG_FORMAT)) logger = getLogger(app.logger_name) # just in case that was not a new logger, get rid of all the handlers # already attached to it. del logger.handlers[:] logger.__class__ = DebugLogger logger.addHandler(debug_handler) logger.addHandler(prod_handler) # Disable propagation by default logger.propagate = False return logger Flask-0.12.2/flask/signals.py0000644000175000001440000000424113047321000017122 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.signals ~~~~~~~~~~~~~ Implements signals based on blinker if available, otherwise falls silently back to a noop. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ signals_available = False try: from blinker import Namespace signals_available = True except ImportError: class Namespace(object): def signal(self, name, doc=None): return _FakeSignal(name, doc) class _FakeSignal(object): """If blinker is unavailable, create a fake class with the same interface that allows sending of signals but will fail with an error on anything else. Instead of doing anything on send, it will just ignore the arguments and do nothing instead. """ def __init__(self, name, doc=None): self.name = name self.__doc__ = doc def _fail(self, *args, **kwargs): raise RuntimeError('signalling support is unavailable ' 'because the blinker library is ' 'not installed.') send = lambda *a, **kw: None connect = disconnect = has_receivers_for = receivers_for = \ temporarily_connected_to = connected_to = _fail del _fail # The namespace for code signals. If you are not Flask code, do # not put signals in here. Create your own namespace instead. _signals = Namespace() # Core signals. For usage examples grep the source code or consult # the API documentation in docs/api.rst as well as docs/signals.rst template_rendered = _signals.signal('template-rendered') before_render_template = _signals.signal('before-render-template') request_started = _signals.signal('request-started') request_finished = _signals.signal('request-finished') request_tearing_down = _signals.signal('request-tearing-down') got_request_exception = _signals.signal('got-request-exception') appcontext_tearing_down = _signals.signal('appcontext-tearing-down') appcontext_pushed = _signals.signal('appcontext-pushed') appcontext_popped = _signals.signal('appcontext-popped') message_flashed = _signals.signal('message-flashed') Flask-0.12.2/flask/__init__.py0000644000175000001440000000321113106517242017230 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask ~~~~~ A microframework based on Werkzeug. It's extensively documented and follows best practice patterns. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ __version__ = '0.12.2' # utilities we import from Werkzeug and Jinja2 that are unused # in the module but are exported as public interface. from werkzeug.exceptions import abort from werkzeug.utils import redirect from jinja2 import Markup, escape from .app import Flask, Request, Response from .config import Config from .helpers import url_for, flash, send_file, send_from_directory, \ get_flashed_messages, get_template_attribute, make_response, safe_join, \ stream_with_context from .globals import current_app, g, request, session, _request_ctx_stack, \ _app_ctx_stack from .ctx import has_request_context, has_app_context, \ after_this_request, copy_current_request_context from .blueprints import Blueprint from .templating import render_template, render_template_string # the signals from .signals import signals_available, template_rendered, request_started, \ request_finished, got_request_exception, request_tearing_down, \ appcontext_tearing_down, appcontext_pushed, \ appcontext_popped, message_flashed, before_render_template # We're not exposing the actual json module but a convenient wrapper around # it. from . import json # This was the only thing that Flask used to export at one point and it had # a more generic name. jsonify = json.jsonify # backwards compat, goes away in 1.0 from .sessions import SecureCookieSession as Session json_available = True Flask-0.12.2/flask/exthook.py0000644000175000001440000001320212765277163017172 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.exthook ~~~~~~~~~~~~~ Redirect imports for extensions. This module basically makes it possible for us to transition from flaskext.foo to flask_foo without having to force all extensions to upgrade at the same time. When a user does ``from flask.ext.foo import bar`` it will attempt to import ``from flask_foo import bar`` first and when that fails it will try to import ``from flaskext.foo import bar``. We're switching from namespace packages because it was just too painful for everybody involved. This is used by `flask.ext`. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import sys import os import warnings from ._compat import reraise class ExtDeprecationWarning(DeprecationWarning): pass warnings.simplefilter('always', ExtDeprecationWarning) class ExtensionImporter(object): """This importer redirects imports from this submodule to other locations. This makes it possible to transition from the old flaskext.name to the newer flask_name without people having a hard time. """ def __init__(self, module_choices, wrapper_module): self.module_choices = module_choices self.wrapper_module = wrapper_module self.prefix = wrapper_module + '.' self.prefix_cutoff = wrapper_module.count('.') + 1 def __eq__(self, other): return self.__class__.__module__ == other.__class__.__module__ and \ self.__class__.__name__ == other.__class__.__name__ and \ self.wrapper_module == other.wrapper_module and \ self.module_choices == other.module_choices def __ne__(self, other): return not self.__eq__(other) def install(self): sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self] def find_module(self, fullname, path=None): if fullname.startswith(self.prefix) and \ fullname != 'flask.ext.ExtDeprecationWarning': return self def load_module(self, fullname): if fullname in sys.modules: return sys.modules[fullname] modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff] warnings.warn( "Importing flask.ext.{x} is deprecated, use flask_{x} instead." .format(x=modname), ExtDeprecationWarning, stacklevel=2 ) for path in self.module_choices: realname = path % modname try: __import__(realname) except ImportError: exc_type, exc_value, tb = sys.exc_info() # since we only establish the entry in sys.modules at the # very this seems to be redundant, but if recursive imports # happen we will call into the move import a second time. # On the second invocation we still don't have an entry for # fullname in sys.modules, but we will end up with the same # fake module name and that import will succeed since this # one already has a temporary entry in the modules dict. # Since this one "succeeded" temporarily that second # invocation now will have created a fullname entry in # sys.modules which we have to kill. sys.modules.pop(fullname, None) # If it's an important traceback we reraise it, otherwise # we swallow it and try the next choice. The skipped frame # is the one from __import__ above which we don't care about if self.is_important_traceback(realname, tb): reraise(exc_type, exc_value, tb.tb_next) continue module = sys.modules[fullname] = sys.modules[realname] if '.' not in modname: setattr(sys.modules[self.wrapper_module], modname, module) if realname.startswith('flaskext.'): warnings.warn( "Detected extension named flaskext.{x}, please rename it " "to flask_{x}. The old form is deprecated." .format(x=modname), ExtDeprecationWarning ) return module raise ImportError('No module named %s' % fullname) def is_important_traceback(self, important_module, tb): """Walks a traceback's frames and checks if any of the frames originated in the given important module. If that is the case then we were able to import the module itself but apparently something went wrong when the module was imported. (Eg: import of an import failed). """ while tb is not None: if self.is_important_frame(important_module, tb): return True tb = tb.tb_next return False def is_important_frame(self, important_module, tb): """Checks a single frame if it's important.""" g = tb.tb_frame.f_globals if '__name__' not in g: return False module_name = g['__name__'] # Python 2.7 Behavior. Modules are cleaned up late so the # name shows up properly here. Success! if module_name == important_module: return True # Some python versions will clean up modules so early that the # module name at that point is no longer set. Try guessing from # the filename then. filename = os.path.abspath(tb.tb_frame.f_code.co_filename) test_string = os.path.sep + important_module.replace('.', os.path.sep) return test_string + '.py' in filename or \ test_string + os.path.sep + '__init__.py' in filename Flask-0.12.2/flask/debughelpers.py0000644000175000001440000001361013106517205020145 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.debughelpers ~~~~~~~~~~~~~~~~~~ Various helpers to make the development experience better. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from ._compat import implements_to_string, text_type from .app import Flask from .blueprints import Blueprint from .globals import _request_ctx_stack class UnexpectedUnicodeError(AssertionError, UnicodeError): """Raised in places where we want some better error reporting for unexpected unicode or binary data. """ @implements_to_string class DebugFilesKeyError(KeyError, AssertionError): """Raised from request.files during debugging. The idea is that it can provide a better error message than just a generic KeyError/BadRequest. """ def __init__(self, request, key): form_matches = request.form.getlist(key) buf = ['You tried to access the file "%s" in the request.files ' 'dictionary but it does not exist. The mimetype for the request ' 'is "%s" instead of "multipart/form-data" which means that no ' 'file contents were transmitted. To fix this error you should ' 'provide enctype="multipart/form-data" in your form.' % (key, request.mimetype)] if form_matches: buf.append('\n\nThe browser instead transmitted some file names. ' 'This was submitted: %s' % ', '.join('"%s"' % x for x in form_matches)) self.msg = ''.join(buf) def __str__(self): return self.msg class FormDataRoutingRedirect(AssertionError): """This exception is raised by Flask in debug mode if it detects a redirect caused by the routing system when the request method is not GET, HEAD or OPTIONS. Reasoning: form data will be dropped. """ def __init__(self, request): exc = request.routing_exception buf = ['A request was sent to this URL (%s) but a redirect was ' 'issued automatically by the routing system to "%s".' % (request.url, exc.new_url)] # In case just a slash was appended we can be extra helpful if request.base_url + '/' == exc.new_url.split('?')[0]: buf.append(' The URL was defined with a trailing slash so ' 'Flask will automatically redirect to the URL ' 'with the trailing slash if it was accessed ' 'without one.') buf.append(' Make sure to directly send your %s-request to this URL ' 'since we can\'t make browsers or HTTP clients redirect ' 'with form data reliably or without user interaction.' % request.method) buf.append('\n\nNote: this exception is only raised in debug mode') AssertionError.__init__(self, ''.join(buf).encode('utf-8')) def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key): try: return oldcls.__getitem__(self, key) except KeyError: if key not in request.form: raise raise DebugFilesKeyError(request, key) newcls.__name__ = oldcls.__name__ newcls.__module__ = oldcls.__module__ request.files.__class__ = newcls def _dump_loader_info(loader): yield 'class: %s.%s' % (type(loader).__module__, type(loader).__name__) for key, value in sorted(loader.__dict__.items()): if key.startswith('_'): continue if isinstance(value, (tuple, list)): if not all(isinstance(x, (str, text_type)) for x in value): continue yield '%s:' % key for item in value: yield ' - %s' % item continue elif not isinstance(value, (str, text_type, int, float, bool)): continue yield '%s: %r' % (key, value) def explain_template_loading_attempts(app, template, attempts): """This should help developers understand what failed""" info = ['Locating template "%s":' % template] total_found = 0 blueprint = None reqctx = _request_ctx_stack.top if reqctx is not None and reqctx.request.blueprint is not None: blueprint = reqctx.request.blueprint for idx, (loader, srcobj, triple) in enumerate(attempts): if isinstance(srcobj, Flask): src_info = 'application "%s"' % srcobj.import_name elif isinstance(srcobj, Blueprint): src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name) else: src_info = repr(srcobj) info.append('% 5d: trying loader of %s' % ( idx + 1, src_info)) for line in _dump_loader_info(loader): info.append(' %s' % line) if triple is None: detail = 'no match' else: detail = 'found (%r)' % (triple[1] or '') total_found += 1 info.append(' -> %s' % detail) seems_fishy = False if total_found == 0: info.append('Error: the template could not be found.') seems_fishy = True elif total_found > 1: info.append('Warning: multiple loaders returned a match for the template.') seems_fishy = True if blueprint is not None and seems_fishy: info.append(' The template was looked up from an endpoint that ' 'belongs to the blueprint "%s".' % blueprint) info.append(' Maybe you did not place a template in the right folder?') info.append(' See http://flask.pocoo.org/docs/blueprints/#templates') app.logger.info('\n'.join(info)) Flask-0.12.2/flask/views.py0000644000175000001440000001277613106517205016645 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.views ~~~~~~~~~~~ This module provides class-based views inspired by the ones in Django. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from .globals import request from ._compat import with_metaclass http_method_funcs = frozenset(['get', 'post', 'head', 'options', 'delete', 'put', 'trace', 'patch']) class View(object): """Alternative way to use view functions. A subclass has to implement :meth:`dispatch_request` which is called with the view arguments from the URL routing system. If :attr:`methods` is provided the methods do not have to be passed to the :meth:`~flask.Flask.add_url_rule` method explicitly:: class MyView(View): methods = ['GET'] def dispatch_request(self, name): return 'Hello %s!' % name app.add_url_rule('/hello/', view_func=MyView.as_view('myview')) When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of :meth:`as_view`) or you can use the :attr:`decorators` attribute:: class SecretView(View): methods = ['GET'] decorators = [superuser_required] def dispatch_request(self): ... The decorators stored in the decorators list are applied one after another when the view function is created. Note that you can *not* use the class based decorators since those would decorate the view class and not the generated view function! """ #: A list of methods this view can handle. methods = None #: The canonical way to decorate class-based views is to decorate the #: return value of as_view(). However since this moves parts of the #: logic from the class declaration to the place where it's hooked #: into the routing system. #: #: You can place one or more decorators in this list and whenever the #: view function is created the result is automatically decorated. #: #: .. versionadded:: 0.8 decorators = () def dispatch_request(self): """Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule. """ raise NotImplementedError() @classmethod def as_view(cls, name, *class_args, **class_kwargs): """Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the :class:`View` on each request and call the :meth:`dispatch_request` method on it. The arguments passed to :meth:`as_view` are forwarded to the constructor of the class. """ def view(*args, **kwargs): self = view.view_class(*class_args, **class_kwargs) return self.dispatch_request(*args, **kwargs) if cls.decorators: view.__name__ = name view.__module__ = cls.__module__ for decorator in cls.decorators: view = decorator(view) # We attach the view class to the view function for two reasons: # first of all it allows us to easily figure out what class-based # view this thing came from, secondly it's also used for instantiating # the view class so you can actually replace it with something else # for testing purposes and debugging. view.view_class = cls view.__name__ = name view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.methods = cls.methods return view class MethodViewType(type): def __new__(cls, name, bases, d): rv = type.__new__(cls, name, bases, d) if 'methods' not in d: methods = set(rv.methods or []) for key in d: if key in http_method_funcs: methods.add(key.upper()) # If we have no method at all in there we don't want to # add a method list. (This is for instance the case for # the base class or another subclass of a base method view # that does not introduce new methods). if methods: rv.methods = sorted(methods) return rv class MethodView(with_metaclass(MethodViewType, View)): """Like a regular class-based view but that dispatches requests to particular methods. For instance if you implement a method called :meth:`get` it means it will respond to ``'GET'`` requests and the :meth:`dispatch_request` implementation will automatically forward your request to that. Also :attr:`options` is set for you automatically:: class CounterAPI(MethodView): def get(self): return session.get('counter', 0) def post(self): session['counter'] = session.get('counter', 0) + 1 return 'OK' app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter')) """ def dispatch_request(self, *args, **kwargs): meth = getattr(self, request.method.lower(), None) # If the request method is HEAD and we don't have a handler for it # retry with GET. if meth is None and request.method == 'HEAD': meth = getattr(self, 'get', None) assert meth is not None, 'Unimplemented method %r' % request.method return meth(*args, **kwargs) Flask-0.12.2/flask/config.py0000644000175000001440000002326113047321000016732 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.config ~~~~~~~~~~~~ Implements the configuration related objects. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os import types import errno from werkzeug.utils import import_string from ._compat import string_types, iteritems from . import json class ConfigAttribute(object): """Makes an attribute forward to the config""" def __init__(self, name, get_converter=None): self.__name__ = name self.get_converter = get_converter def __get__(self, obj, type=None): if obj is None: return self rv = obj.config[self.__name__] if self.get_converter is not None: rv = self.get_converter(rv) return rv def __set__(self, obj, value): obj.config[self.__name__] = value class Config(dict): """Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config. Either you can fill the config from a config file:: app.config.from_pyfile('yourconfig.cfg') Or alternatively you can define the configuration options in the module that calls :meth:`from_object` or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:: DEBUG = True SECRET_KEY = 'development key' app.config.from_object(__name__) In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application. Probably the most interesting way to load configurations is from an environment variable pointing to a file:: app.config.from_envvar('YOURAPPLICATION_SETTINGS') In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:: export YOURAPPLICATION_SETTINGS='/path/to/config/file' On windows use `set` instead. :param root_path: path to which files are read relative from. When the config object is created by the application, this is the application's :attr:`~flask.Flask.root_path`. :param defaults: an optional dictionary of default values """ def __init__(self, root_path, defaults=None): dict.__init__(self, defaults or {}) self.root_path = root_path def from_envvar(self, variable_name, silent=False): """Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) :param variable_name: name of the environment variable :param silent: set to ``True`` if you want silent failure for missing files. :return: bool. ``True`` if able to load config, ``False`` otherwise. """ rv = os.environ.get(variable_name) if not rv: if silent: return False raise RuntimeError('The environment variable %r is not set ' 'and as such configuration could not be ' 'loaded. Set this variable and make it ' 'point to a configuration file' % variable_name) return self.from_pyfile(rv, silent=silent) def from_pyfile(self, filename, silent=False): """Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the :meth:`from_object` function. :param filename: the filename of the config. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. .. versionadded:: 0.7 `silent` parameter. """ filename = os.path.join(self.root_path, filename) d = types.ModuleType('config') d.__file__ = filename try: with open(filename, mode='rb') as config_file: exec(compile(config_file.read(), filename, 'exec'), d.__dict__) except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = 'Unable to load configuration file (%s)' % e.strerror raise self.from_object(d) return True def from_object(self, obj): """Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually either modules or classes. :meth:`from_object` loads only the uppercase attributes of the module/class. A ``dict`` object will not work with :meth:`from_object` because the keys of a ``dict`` are not attributes of the ``dict`` class. Example of module-based configuration:: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. See :ref:`config-dev-prod` for an example of class-based configuration using :meth:`from_object`. :param obj: an import name or object """ if isinstance(obj, string_types): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) def from_json(self, filename, silent=False): """Updates the values in the config from a JSON file. This function behaves as if the JSON object was a dictionary and passed to the :meth:`from_mapping` function. :param filename: the filename of the JSON file. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. .. versionadded:: 0.11 """ filename = os.path.join(self.root_path, filename) try: with open(filename) as json_file: obj = json.loads(json_file.read()) except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = 'Unable to load configuration file (%s)' % e.strerror raise return self.from_mapping(obj) def from_mapping(self, *mapping, **kwargs): """Updates the config like :meth:`update` ignoring items with non-upper keys. .. versionadded:: 0.11 """ mappings = [] if len(mapping) == 1: if hasattr(mapping[0], 'items'): mappings.append(mapping[0].items()) else: mappings.append(mapping[0]) elif len(mapping) > 1: raise TypeError( 'expected at most 1 positional argument, got %d' % len(mapping) ) mappings.append(kwargs.items()) for mapping in mappings: for (key, value) in mapping: if key.isupper(): self[key] = value return True def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:: app.config['IMAGE_STORE_TYPE'] = 'fs' app.config['IMAGE_STORE_PATH'] = '/var/app/images' app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' image_store_config = app.config.get_namespace('IMAGE_STORE_') The resulting dictionary `image_store_config` would look like:: { 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace .. versionadded:: 0.11 """ rv = {} for k, v in iteritems(self): if not k.startswith(namespace): continue if trim_namespace: key = k[len(namespace):] else: key = k if lowercase: key = key.lower() rv[key] = v return rv def __repr__(self): return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self)) Flask-0.12.2/flask/ext/0000755000175000001440000000000013106517244015724 5ustar untitakerusers00000000000000Flask-0.12.2/flask/ext/__init__.py0000644000175000001440000000151212763616450020043 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.ext ~~~~~~~~~ Redirect imports for extensions. This module basically makes it possible for us to transition from flaskext.foo to flask_foo without having to force all extensions to upgrade at the same time. When a user does ``from flask.ext.foo import bar`` it will attempt to import ``from flask_foo import bar`` first and when that fails it will try to import ``from flaskext.foo import bar``. We're switching from namespace packages because it was just too painful for everybody involved. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ def setup(): from ..exthook import ExtensionImporter importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], __name__) importer.install() setup() del setup Flask-0.12.2/flask/app.py0000644000175000001440000024234113106517205016261 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.app ~~~~~~~~~ This module implements the central WSGI application object. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os import sys from threading import Lock from datetime import timedelta from itertools import chain from functools import update_wrapper from werkzeug.datastructures import ImmutableDict from werkzeug.routing import Map, Rule, RequestRedirect, BuildError from werkzeug.exceptions import HTTPException, InternalServerError, \ MethodNotAllowed, BadRequest, default_exceptions from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \ locked_cached_property, _endpoint_from_view_func, find_package, \ get_debug_flag from . import json, cli from .wrappers import Request, Response from .config import ConfigAttribute, Config from .ctx import RequestContext, AppContext, _AppCtxGlobals from .globals import _request_ctx_stack, request, session, g from .sessions import SecureCookieSessionInterface from .templating import DispatchingJinjaLoader, Environment, \ _default_template_ctx_processor from .signals import request_started, request_finished, got_request_exception, \ request_tearing_down, appcontext_tearing_down from ._compat import reraise, string_types, text_type, integer_types # a lock used for logger initialization _logger_lock = Lock() # a singleton sentinel value for parameter defaults _sentinel = object() def _make_timedelta(value): if not isinstance(value, timedelta): return timedelta(seconds=value) return value def setupmethod(f): """Wraps a method so that it performs a check in debug mode if the first request was already handled. """ def wrapper_func(self, *args, **kwargs): if self.debug and self._got_first_request: raise AssertionError('A setup function was called after the ' 'first request was handled. This usually indicates a bug ' 'in the application where a module was not imported ' 'and decorators or other functionality was called too late.\n' 'To fix this make sure to import all your view modules, ' 'database models and everything related at a central place ' 'before the application starts serving requests.') return f(self, *args, **kwargs) return update_wrapper(wrapper_func, f) class Flask(_PackageBoundObject): """The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file). For more information about resource loading, see :func:`open_resource`. Usually you create a :class:`Flask` instance in your main module or in the :file:`__init__.py` file of your package like this:: from flask import Flask app = Flask(__name__) .. admonition:: About the First Parameter The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more. So it's important what you provide there. If you are using a single module, `__name__` is always the correct value. If you however are using a package, it's usually recommended to hardcode the name of your package there. For example if your application is defined in :file:`yourapplication/app.py` you should create it with one of the two versions below:: app = Flask('yourapplication') app = Flask(__name__.split('.')[0]) Why is that? The application will work even with `__name__`, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in `yourapplication.app` and not `yourapplication.views.frontend`) .. versionadded:: 0.7 The `static_url_path`, `static_folder`, and `template_folder` parameters were added. .. versionadded:: 0.8 The `instance_path` and `instance_relative_config` parameters were added. .. versionadded:: 0.11 The `root_path` parameter was added. :param import_name: the name of the application package :param static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the `static_folder` folder. :param static_folder: the folder with static files that should be served at `static_url_path`. Defaults to the ``'static'`` folder in the root path of the application. :param template_folder: the folder that contains the templates that should be used by the application. Defaults to ``'templates'`` folder in the root path of the application. :param instance_path: An alternative instance path for the application. By default the folder ``'instance'`` next to the package or module is assumed to be the instance path. :param instance_relative_config: if set to ``True`` relative filenames for loading the config are assumed to be relative to the instance path instead of the application root. :param root_path: Flask by default will automatically calculate the path to the root of the application. In certain situations this cannot be achieved (for instance if the package is a Python 3 namespace package) and needs to be manually defined. """ #: The class that is used for request objects. See :class:`~flask.Request` #: for more information. request_class = Request #: The class that is used for response objects. See #: :class:`~flask.Response` for more information. response_class = Response #: The class that is used for the Jinja environment. #: #: .. versionadded:: 0.11 jinja_environment = Environment #: The class that is used for the :data:`~flask.g` instance. #: #: Example use cases for a custom class: #: #: 1. Store arbitrary attributes on flask.g. #: 2. Add a property for lazy per-request database connectors. #: 3. Return None instead of AttributeError on unexpected attributes. #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g. #: #: In Flask 0.9 this property was called `request_globals_class` but it #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the #: flask.g object is now application context scoped. #: #: .. versionadded:: 0.10 app_ctx_globals_class = _AppCtxGlobals # Backwards compatibility support def _get_request_globals_class(self): return self.app_ctx_globals_class def _set_request_globals_class(self, value): from warnings import warn warn(DeprecationWarning('request_globals_class attribute is now ' 'called app_ctx_globals_class')) self.app_ctx_globals_class = value request_globals_class = property(_get_request_globals_class, _set_request_globals_class) del _get_request_globals_class, _set_request_globals_class #: The class that is used for the ``config`` attribute of this app. #: Defaults to :class:`~flask.Config`. #: #: Example use cases for a custom class: #: #: 1. Default values for certain config options. #: 2. Access to config values through attributes in addition to keys. #: #: .. versionadded:: 0.11 config_class = Config #: The debug flag. Set this to ``True`` to enable debugging of the #: application. In debug mode the debugger will kick in when an unhandled #: exception occurs and the integrated server will automatically reload #: the application if changes in the code are detected. #: #: This attribute can also be configured from the config with the ``DEBUG`` #: configuration key. Defaults to ``False``. debug = ConfigAttribute('DEBUG') #: The testing flag. Set this to ``True`` to enable the test mode of #: Flask extensions (and in the future probably also Flask itself). #: For example this might activate unittest helpers that have an #: additional runtime cost which should not be enabled by default. #: #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the #: default it's implicitly enabled. #: #: This attribute can also be configured from the config with the #: ``TESTING`` configuration key. Defaults to ``False``. testing = ConfigAttribute('TESTING') #: If a secret key is set, cryptographic components can use this to #: sign cookies and other things. Set this to a complex random value #: when you want to use the secure cookie for instance. #: #: This attribute can also be configured from the config with the #: ``SECRET_KEY`` configuration key. Defaults to ``None``. secret_key = ConfigAttribute('SECRET_KEY') #: The secure cookie uses this for the name of the session cookie. #: #: This attribute can also be configured from the config with the #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'`` session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME') #: A :class:`~datetime.timedelta` which is used to set the expiration #: date of a permanent session. The default is 31 days which makes a #: permanent session survive for roughly one month. #: #: This attribute can also be configured from the config with the #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to #: ``timedelta(days=31)`` permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME', get_converter=_make_timedelta) #: A :class:`~datetime.timedelta` which is used as default cache_timeout #: for the :func:`send_file` functions. The default is 12 hours. #: #: This attribute can also be configured from the config with the #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration #: variable can also be set with an integer value used as seconds. #: Defaults to ``timedelta(hours=12)`` send_file_max_age_default = ConfigAttribute('SEND_FILE_MAX_AGE_DEFAULT', get_converter=_make_timedelta) #: Enable this if you want to use the X-Sendfile feature. Keep in #: mind that the server has to support this. This only affects files #: sent with the :func:`send_file` method. #: #: .. versionadded:: 0.2 #: #: This attribute can also be configured from the config with the #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``. use_x_sendfile = ConfigAttribute('USE_X_SENDFILE') #: The name of the logger to use. By default the logger name is the #: package name passed to the constructor. #: #: .. versionadded:: 0.4 logger_name = ConfigAttribute('LOGGER_NAME') #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`. #: #: .. versionadded:: 0.10 json_encoder = json.JSONEncoder #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`. #: #: .. versionadded:: 0.10 json_decoder = json.JSONDecoder #: Options that are passed directly to the Jinja2 environment. jinja_options = ImmutableDict( extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'] ) #: Default configuration parameters. default_config = ImmutableDict({ 'DEBUG': get_debug_flag(default=False), 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 'USE_X_SENDFILE': False, 'LOGGER_NAME': None, 'LOGGER_HANDLER_POLICY': 'always', 'SERVER_NAME': None, 'APPLICATION_ROOT': None, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), 'TRAP_BAD_REQUEST_ERRORS': False, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': True, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, }) #: The rule object to use for URL rules created. This is used by #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`. #: #: .. versionadded:: 0.7 url_rule_class = Rule #: the test client that is used with when `test_client` is used. #: #: .. versionadded:: 0.7 test_client_class = None #: the session interface to use. By default an instance of #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here. #: #: .. versionadded:: 0.8 session_interface = SecureCookieSessionInterface() def __init__(self, import_name, static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None): _PackageBoundObject.__init__(self, import_name, template_folder=template_folder, root_path=root_path) if static_path is not None: from warnings import warn warn(DeprecationWarning('static_path is now called ' 'static_url_path'), stacklevel=2) static_url_path = static_path if static_url_path is not None: self.static_url_path = static_url_path if static_folder is not None: self.static_folder = static_folder if instance_path is None: instance_path = self.auto_find_instance_path() elif not os.path.isabs(instance_path): raise ValueError('If an instance path is provided it must be ' 'absolute. A relative path was given instead.') #: Holds the path to the instance folder. #: #: .. versionadded:: 0.8 self.instance_path = instance_path #: The configuration dictionary as :class:`Config`. This behaves #: exactly like a regular dictionary but supports additional methods #: to load a config from files. self.config = self.make_config(instance_relative_config) # Prepare the deferred setup of the logger. self._logger = None self.logger_name = self.import_name #: A dictionary of all view functions registered. The keys will #: be function names which are also used to generate URLs and #: the values are the function objects themselves. #: To register a view function, use the :meth:`route` decorator. self.view_functions = {} # support for the now deprecated `error_handlers` attribute. The # :attr:`error_handler_spec` shall be used now. self._error_handlers = {} #: A dictionary of all registered error handlers. The key is ``None`` #: for error handlers active on the application, otherwise the key is #: the name of the blueprint. Each key points to another dictionary #: where the key is the status code of the http exception. The #: special key ``None`` points to a list of tuples where the first item #: is the class for the instance check and the second the error handler #: function. #: #: To register a error handler, use the :meth:`errorhandler` #: decorator. self.error_handler_spec = {None: self._error_handlers} #: A list of functions that are called when :meth:`url_for` raises a #: :exc:`~werkzeug.routing.BuildError`. Each function registered here #: is called with `error`, `endpoint` and `values`. If a function #: returns ``None`` or raises a :exc:`BuildError` the next function is #: tried. #: #: .. versionadded:: 0.9 self.url_build_error_handlers = [] #: A dictionary with lists of functions that should be called at the #: beginning of the request. The key of the dictionary is the name of #: the blueprint this function is active for, ``None`` for all requests. #: This can for example be used to open database connections or #: getting hold of the currently logged in user. To register a #: function here, use the :meth:`before_request` decorator. self.before_request_funcs = {} #: A lists of functions that should be called at the beginning of the #: first request to this instance. To register a function here, use #: the :meth:`before_first_request` decorator. #: #: .. versionadded:: 0.8 self.before_first_request_funcs = [] #: A dictionary with lists of functions that should be called after #: each request. The key of the dictionary is the name of the blueprint #: this function is active for, ``None`` for all requests. This can for #: example be used to close database connections. To register a function #: here, use the :meth:`after_request` decorator. self.after_request_funcs = {} #: A dictionary with lists of functions that are called after #: each request, even if an exception has occurred. The key of the #: dictionary is the name of the blueprint this function is active for, #: ``None`` for all requests. These functions are not allowed to modify #: the request, and their return values are ignored. If an exception #: occurred while processing the request, it gets passed to each #: teardown_request function. To register a function here, use the #: :meth:`teardown_request` decorator. #: #: .. versionadded:: 0.7 self.teardown_request_funcs = {} #: A list of functions that are called when the application context #: is destroyed. Since the application context is also torn down #: if the request ends this is the place to store code that disconnects #: from databases. #: #: .. versionadded:: 0.9 self.teardown_appcontext_funcs = [] #: A dictionary with lists of functions that can be used as URL #: value processor functions. Whenever a URL is built these functions #: are called to modify the dictionary of values in place. The key #: ``None`` here is used for application wide #: callbacks, otherwise the key is the name of the blueprint. #: Each of these functions has the chance to modify the dictionary #: #: .. versionadded:: 0.7 self.url_value_preprocessors = {} #: A dictionary with lists of functions that can be used as URL value #: preprocessors. The key ``None`` here is used for application wide #: callbacks, otherwise the key is the name of the blueprint. #: Each of these functions has the chance to modify the dictionary #: of URL values before they are used as the keyword arguments of the #: view function. For each function registered this one should also #: provide a :meth:`url_defaults` function that adds the parameters #: automatically again that were removed that way. #: #: .. versionadded:: 0.7 self.url_default_functions = {} #: A dictionary with list of functions that are called without argument #: to populate the template context. The key of the dictionary is the #: name of the blueprint this function is active for, ``None`` for all #: requests. Each returns a dictionary that the template context is #: updated with. To register a function here, use the #: :meth:`context_processor` decorator. self.template_context_processors = { None: [_default_template_ctx_processor] } #: A list of shell context processor functions that should be run #: when a shell context is created. #: #: .. versionadded:: 0.11 self.shell_context_processors = [] #: all the attached blueprints in a dictionary by name. Blueprints #: can be attached multiple times so this dictionary does not tell #: you how often they got attached. #: #: .. versionadded:: 0.7 self.blueprints = {} self._blueprint_order = [] #: a place where extensions can store application specific state. For #: example this is where an extension could store database engines and #: similar things. For backwards compatibility extensions should register #: themselves like this:: #: #: if not hasattr(app, 'extensions'): #: app.extensions = {} #: app.extensions['extensionname'] = SomeObject() #: #: The key must match the name of the extension module. For example in #: case of a "Flask-Foo" extension in `flask_foo`, the key would be #: ``'foo'``. #: #: .. versionadded:: 0.7 self.extensions = {} #: The :class:`~werkzeug.routing.Map` for this instance. You can use #: this to change the routing converters after the class was created #: but before any routes are connected. Example:: #: #: from werkzeug.routing import BaseConverter #: #: class ListConverter(BaseConverter): #: def to_python(self, value): #: return value.split(',') #: def to_url(self, values): #: return ','.join(super(ListConverter, self).to_url(value) #: for value in values) #: #: app = Flask(__name__) #: app.url_map.converters['list'] = ListConverter self.url_map = Map() # tracks internally if the application already handled at least one # request. self._got_first_request = False self._before_request_lock = Lock() # register the static folder for the application. Do that even # if the folder does not exist. First of all it might be created # while the server is running (usually happens during development) # but also because google appengine stores static files somewhere # else when mapped with the .yml file. if self.has_static_folder: self.add_url_rule(self.static_url_path + '/', endpoint='static', view_func=self.send_static_file) #: The click command line context for this application. Commands #: registered here show up in the :command:`flask` command once the #: application has been discovered. The default commands are #: provided by Flask itself and can be overridden. #: #: This is an instance of a :class:`click.Group` object. self.cli = cli.AppGroup(self.name) def _get_error_handlers(self): from warnings import warn warn(DeprecationWarning('error_handlers is deprecated, use the ' 'new error_handler_spec attribute instead.'), stacklevel=1) return self._error_handlers def _set_error_handlers(self, value): self._error_handlers = value self.error_handler_spec[None] = value error_handlers = property(_get_error_handlers, _set_error_handlers) del _get_error_handlers, _set_error_handlers @locked_cached_property def name(self): """The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value. .. versionadded:: 0.8 """ if self.import_name == '__main__': fn = getattr(sys.modules['__main__'], '__file__', None) if fn is None: return '__main__' return os.path.splitext(os.path.basename(fn))[0] return self.import_name @property def propagate_exceptions(self): """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration value in case it's set, otherwise a sensible default is returned. .. versionadded:: 0.7 """ rv = self.config['PROPAGATE_EXCEPTIONS'] if rv is not None: return rv return self.testing or self.debug @property def preserve_context_on_exception(self): """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration value in case it's set, otherwise a sensible default is returned. .. versionadded:: 0.7 """ rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION'] if rv is not None: return rv return self.debug @property def logger(self): """A :class:`logging.Logger` object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to (surprise) log messages. Here some examples:: app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred') .. versionadded:: 0.3 """ if self._logger and self._logger.name == self.logger_name: return self._logger with _logger_lock: if self._logger and self._logger.name == self.logger_name: return self._logger from flask.logging import create_logger self._logger = rv = create_logger(self) return rv @locked_cached_property def jinja_env(self): """The Jinja2 environment used to load templates.""" return self.create_jinja_environment() @property def got_first_request(self): """This attribute is set to ``True`` if the application started handling the first request. .. versionadded:: 0.8 """ return self._got_first_request def make_config(self, instance_relative=False): """Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the instance path or the root path of the application. .. versionadded:: 0.8 """ root_path = self.root_path if instance_relative: root_path = self.instance_path return self.config_class(root_path, self.default_config) def auto_find_instance_path(self): """Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named ``instance`` next to your main file or the package. .. versionadded:: 0.8 """ prefix, package_path = find_package(self.import_name) if prefix is None: return os.path.join(package_path, 'instance') return os.path.join(prefix, 'var', self.name + '-instance') def open_instance_resource(self, resource, mode='rb'): """Opens a resource from the application's instance folder (:attr:`instance_path`). Otherwise works like :meth:`open_resource`. Instance resources can also be opened for writing. :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. :param mode: resource file opening mode, default is 'rb'. """ return open(os.path.join(self.instance_path, resource), mode) def create_jinja_environment(self): """Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior. .. versionadded:: 0.5 .. versionchanged:: 0.11 ``Environment.auto_reload`` set in accordance with ``TEMPLATES_AUTO_RELOAD`` configuration option. """ options = dict(self.jinja_options) if 'autoescape' not in options: options['autoescape'] = self.select_jinja_autoescape if 'auto_reload' not in options: if self.config['TEMPLATES_AUTO_RELOAD'] is not None: options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD'] else: options['auto_reload'] = self.debug rv = self.jinja_environment(self, **options) rv.globals.update( url_for=url_for, get_flashed_messages=get_flashed_messages, config=self.config, # request, session and g are normally added with the # context processor for efficiency reasons but for imported # templates we also want the proxies in there. request=request, session=session, g=g ) rv.filters['tojson'] = json.tojson_filter return rv def create_global_jinja_loader(self): """Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It's discouraged to override this function. Instead one should override the :meth:`jinja_loader` function instead. The global loader dispatches between the loaders of the application and the individual blueprints. .. versionadded:: 0.7 """ return DispatchingJinjaLoader(self) def init_jinja_globals(self): """Deprecated. Used to initialize the Jinja2 globals. .. versionadded:: 0.5 .. versionchanged:: 0.7 This method is deprecated with 0.7. Override :meth:`create_jinja_environment` instead. """ def select_jinja_autoescape(self, filename): """Returns ``True`` if autoescaping should be active for the given template name. If no template name is given, returns `True`. .. versionadded:: 0.5 """ if filename is None: return True return filename.endswith(('.html', '.htm', '.xml', '.xhtml')) def update_template_context(self, context): """Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key. :param context: the context as a dictionary that is updated in place to add extra variables. """ funcs = self.template_context_processors[None] reqctx = _request_ctx_stack.top if reqctx is not None: bp = reqctx.request.blueprint if bp is not None and bp in self.template_context_processors: funcs = chain(funcs, self.template_context_processors[bp]) orig_ctx = context.copy() for func in funcs: context.update(func()) # make sure the original values win. This makes it possible to # easier add new variables in context processors without breaking # existing views. context.update(orig_ctx) def make_shell_context(self): """Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors. .. versionadded:: 0.11 """ rv = {'app': self, 'g': g} for processor in self.shell_context_processors: rv.update(processor()) return rv def run(self, host=None, port=None, debug=None, **options): """Runs the application on a local development server. Do not use ``run()`` in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see :ref:`deployment` for WSGI server recommendations. If the :attr:`debug` flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass ``use_evalex=False`` as parameter. This will keep the debugger's traceback screen active, but disable code execution. It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the :command:`flask` command line script's ``run`` support. .. admonition:: Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``. Setting ``use_debugger`` to ``True`` without being in debug mode won't catch any exceptions because there won't be any to catch. .. versionchanged:: 0.10 The default port is now picked from the ``SERVER_NAME`` variable. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to have the server available externally as well. Defaults to ``'127.0.0.1'``. :param port: the port of the webserver. Defaults to ``5000`` or the port defined in the ``SERVER_NAME`` config variable if present. :param debug: if given, enable or disable debug mode. See :attr:`debug`. :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.serving.run_simple` for more information. """ from werkzeug.serving import run_simple if host is None: host = '127.0.0.1' if port is None: server_name = self.config['SERVER_NAME'] if server_name and ':' in server_name: port = int(server_name.rsplit(':', 1)[1]) else: port = 5000 if debug is not None: self.debug = bool(debug) options.setdefault('use_reloader', self.debug) options.setdefault('use_debugger', self.debug) try: run_simple(host, port, self, **options) finally: # reset the first request information if the development server # reset normally. This makes it possible to restart the server # without reloader and that stuff from an interactive shell. self._got_first_request = False def test_client(self, use_cookies=True, **kwargs): """Creates a test client for this application. For information about unit testing head over to :ref:`testing`. Note that if you are testing for assertions or exceptions in your application code, you must set ``app.testing = True`` in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the :attr:`testing` attribute. For example:: app.testing = True client = app.test_client() The test client can be used in a ``with`` block to defer the closing down of the context until the end of the ``with`` block. This is useful if you want to access the context locals for testing:: with app.test_client() as c: rv = c.get('/?vodka=42') assert request.args['vodka'] == '42' Additionally, you may pass optional keyword arguments that will then be passed to the application's :attr:`test_client_class` constructor. For example:: from flask.testing import FlaskClient class CustomClient(FlaskClient): def __init__(self, *args, **kwargs): self._authentication = kwargs.pop("authentication") super(CustomClient,self).__init__( *args, **kwargs) app.test_client_class = CustomClient client = app.test_client(authentication='Basic ....') See :class:`~flask.testing.FlaskClient` for more information. .. versionchanged:: 0.4 added support for ``with`` block usage for the client. .. versionadded:: 0.7 The `use_cookies` parameter was added as well as the ability to override the client to be used by setting the :attr:`test_client_class` attribute. .. versionchanged:: 0.11 Added `**kwargs` to support passing additional keyword arguments to the constructor of :attr:`test_client_class`. """ cls = self.test_client_class if cls is None: from flask.testing import FlaskClient as cls return cls(self, self.response_class, use_cookies=use_cookies, **kwargs) def open_session(self, request): """Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the :attr:`secret_key` is set. Instead of overriding this method we recommend replacing the :class:`session_interface`. :param request: an instance of :attr:`request_class`. """ return self.session_interface.open_session(self, request) def save_session(self, session, response): """Saves the session if it needs updates. For the default implementation, check :meth:`open_session`. Instead of overriding this method we recommend replacing the :class:`session_interface`. :param session: the session to be saved (a :class:`~werkzeug.contrib.securecookie.SecureCookie` object) :param response: an instance of :attr:`response_class` """ return self.session_interface.save_session(self, session, response) def make_null_session(self): """Creates a new instance of a missing session. Instead of overriding this method we recommend replacing the :class:`session_interface`. .. versionadded:: 0.7 """ return self.session_interface.make_null_session(self) @setupmethod def register_blueprint(self, blueprint, **options): """Registers a blueprint on the application. .. versionadded:: 0.7 """ first_registration = False if blueprint.name in self.blueprints: assert self.blueprints[blueprint.name] is blueprint, \ 'A blueprint\'s name collision occurred between %r and ' \ '%r. Both share the same name "%s". Blueprints that ' \ 'are created on the fly need unique names.' % \ (blueprint, self.blueprints[blueprint.name], blueprint.name) else: self.blueprints[blueprint.name] = blueprint self._blueprint_order.append(blueprint) first_registration = True blueprint.register(self, options, first_registration) def iter_blueprints(self): """Iterates over all blueprints by the order they were registered. .. versionadded:: 0.11 """ return iter(self._blueprint_order) @setupmethod def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint to a view function like so:: app.view_functions['index'] = index Internally :meth:`route` invokes :meth:`add_url_rule` so if you want to customize the behavior via subclassing you only need to change this method. For more information refer to :ref:`url-route-registrations`. .. versionchanged:: 0.2 `view_func` parameter added. .. versionchanged:: 0.6 ``OPTIONS`` is added automatically as method. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. """ if endpoint is None: endpoint = _endpoint_from_view_func(view_func) options['endpoint'] = endpoint methods = options.pop('methods', None) # if the methods are not given and the view_func object knows its # methods we can use that instead. If neither exists, we go with # a tuple of only ``GET`` as default. if methods is None: methods = getattr(view_func, 'methods', None) or ('GET',) if isinstance(methods, string_types): raise TypeError('Allowed methods have to be iterables of strings, ' 'for example: @app.route(..., methods=["POST"])') methods = set(item.upper() for item in methods) # Methods that should always be added required_methods = set(getattr(view_func, 'required_methods', ())) # starting with Flask 0.8 the view_func object can disable and # force-enable the automatic options handling. provide_automatic_options = getattr(view_func, 'provide_automatic_options', None) if provide_automatic_options is None: if 'OPTIONS' not in methods: provide_automatic_options = True required_methods.add('OPTIONS') else: provide_automatic_options = False # Add the required methods now. methods |= required_methods rule = self.url_rule_class(rule, methods=methods, **options) rule.provide_automatic_options = provide_automatic_options self.url_map.add(rule) if view_func is not None: old_func = self.view_functions.get(endpoint) if old_func is not None and old_func != view_func: raise AssertionError('View function mapping is overwriting an ' 'existing endpoint function: %s' % endpoint) self.view_functions[endpoint] = view_func def route(self, rule, **options): """A decorator that is used to register a view function for a given URL rule. This does the same thing as :meth:`add_url_rule` but is intended for decorator usage:: @app.route('/') def index(): return 'Hello World' For more information refer to :ref:`url-route-registrations`. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. """ def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator @setupmethod def endpoint(self, endpoint): """A decorator to register a function as an endpoint. Example:: @app.endpoint('example.endpoint') def example(): return "example" :param endpoint: the name of the endpoint """ def decorator(f): self.view_functions[endpoint] = f return f return decorator @staticmethod def _get_exc_class_and_code(exc_class_or_code): """Ensure that we register only exceptions as handler keys""" if isinstance(exc_class_or_code, integer_types): exc_class = default_exceptions[exc_class_or_code] else: exc_class = exc_class_or_code assert issubclass(exc_class, Exception) if issubclass(exc_class, HTTPException): return exc_class, exc_class.code else: return exc_class, None @setupmethod def errorhandler(self, code_or_exception): """A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions:: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 You can also register a function as error handler without using the :meth:`errorhandler` decorator. The following example is equivalent to the one above:: def page_not_found(error): return 'This page does not exist', 404 app.error_handler_spec[None][404] = page_not_found Setting error handlers via assignments to :attr:`error_handler_spec` however is discouraged as it requires fiddling with nested dictionaries and the special case for arbitrary exception types. The first ``None`` refers to the active blueprint. If the error handler should be application wide ``None`` shall be used. .. versionadded:: 0.7 Use :meth:`register_error_handler` instead of modifying :attr:`error_handler_spec` directly, for application wide error handlers. .. versionadded:: 0.7 One can now additionally also register custom exception types that do not necessarily have to be a subclass of the :class:`~werkzeug.exceptions.HTTPException` class. :param code_or_exception: the code as integer for the handler, or an arbitrary exception """ def decorator(f): self._register_error_handler(None, code_or_exception, f) return f return decorator def register_error_handler(self, code_or_exception, f): """Alternative error attach function to the :meth:`errorhandler` decorator that is more straightforward to use for non decorator usage. .. versionadded:: 0.7 """ self._register_error_handler(None, code_or_exception, f) @setupmethod def _register_error_handler(self, key, code_or_exception, f): """ :type key: None|str :type code_or_exception: int|T<=Exception :type f: callable """ if isinstance(code_or_exception, HTTPException): # old broken behavior raise ValueError( 'Tried to register a handler for an exception instance {0!r}. ' 'Handlers can only be registered for exception classes or HTTP error codes.' .format(code_or_exception)) exc_class, code = self._get_exc_class_and_code(code_or_exception) handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {}) handlers[exc_class] = f @setupmethod def template_filter(self, name=None): """A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:: @app.template_filter() def reverse(s): return s[::-1] :param name: the optional name of the filter, otherwise the function name will be used. """ def decorator(f): self.add_template_filter(f, name=name) return f return decorator @setupmethod def add_template_filter(self, f, name=None): """Register a custom template filter. Works exactly like the :meth:`template_filter` decorator. :param name: the optional name of the filter, otherwise the function name will be used. """ self.jinja_env.filters[name or f.__name__] = f @setupmethod def template_test(self, name=None): """A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:: @app.template_test() def is_prime(n): if n == 2: return True for i in range(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ def decorator(f): self.add_template_test(f, name=name) return f return decorator @setupmethod def add_template_test(self, f, name=None): """Register a custom template test. Works exactly like the :meth:`template_test` decorator. .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ self.jinja_env.tests[name or f.__name__] = f @setupmethod def template_global(self, name=None): """A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:: @app.template_global() def double(n): return 2 * n .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used. """ def decorator(f): self.add_template_global(f, name=name) return f return decorator @setupmethod def add_template_global(self, f, name=None): """Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used. """ self.jinja_env.globals[name or f.__name__] = f @setupmethod def before_request(self, f): """Registers a function to run before each request. The function will be called without any arguments. If the function returns a non-None value, it's handled as if it was the return value from the view and further request handling is stopped. """ self.before_request_funcs.setdefault(None, []).append(f) return f @setupmethod def before_first_request(self, f): """Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. .. versionadded:: 0.8 """ self.before_first_request_funcs.append(f) return f @setupmethod def after_request(self, f): """Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred. """ self.after_request_funcs.setdefault(None, []).append(f) return f @setupmethod def teardown_request(self, f): """Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed. Example:: ctx = app.test_request_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of a exception it will be passed an error object. The return values of teardown functions are ignored. .. admonition:: Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. """ self.teardown_request_funcs.setdefault(None, []).append(f) return f @setupmethod def teardown_appcontext(self, f): """Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped. Example:: ctx = app.app_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored. .. versionadded:: 0.9 """ self.teardown_appcontext_funcs.append(f) return f @setupmethod def context_processor(self, f): """Registers a template context processor function.""" self.template_context_processors[None].append(f) return f @setupmethod def shell_context_processor(self, f): """Registers a shell context processor function. .. versionadded:: 0.11 """ self.shell_context_processors.append(f) return f @setupmethod def url_value_preprocessor(self, f): """Registers a function as URL value preprocessor for all view functions of the application. It's called before the view functions are called and can modify the url values provided. """ self.url_value_preprocessors.setdefault(None, []).append(f) return f @setupmethod def url_defaults(self, f): """Callback function for URL defaults for all view functions of the application. It's called with the endpoint and values and should update the values passed in place. """ self.url_default_functions.setdefault(None, []).append(f) return f def _find_error_handler(self, e): """Finds a registered error handler for the request’s blueprint. Otherwise falls back to the app, returns None if not a suitable handler is found. """ exc_class, code = self._get_exc_class_and_code(type(e)) def find_handler(handler_map): if not handler_map: return for cls in exc_class.__mro__: handler = handler_map.get(cls) if handler is not None: # cache for next time exc_class is raised handler_map[exc_class] = handler return handler # try blueprint handlers handler = find_handler(self.error_handler_spec .get(request.blueprint, {}) .get(code)) if handler is not None: return handler # fall back to app handlers return find_handler(self.error_handler_spec[None].get(code)) def handle_http_exception(self, e): """Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionadded:: 0.3 """ # Proxy exceptions don't have error codes. We want to always return # those unchanged as errors if e.code is None: return e handler = self._find_error_handler(e) if handler is None: return e return handler(e) def trap_http_exception(self, e): """Checks if an HTTP exception should be trapped or not. By default this will return ``False`` for all exceptions except for a bad request key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``. This is called for all HTTP exceptions raised by a view function. If it returns ``True`` for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions. .. versionadded:: 0.8 """ if self.config['TRAP_HTTP_EXCEPTIONS']: return True if self.config['TRAP_BAD_REQUEST_ERRORS']: return isinstance(e, BadRequest) return False def handle_user_exception(self, e): """This method is called whenever an exception occurs that should be handled. A special case are :class:`~werkzeug.exception.HTTPException`\s which are forwarded by this function to the :meth:`handle_http_exception` method. This function will either return a response value or reraise the exception with the same traceback. .. versionadded:: 0.7 """ exc_type, exc_value, tb = sys.exc_info() assert exc_value is e # ensure not to trash sys.exc_info() at that point in case someone # wants the traceback preserved in handle_http_exception. Of course # we cannot prevent users from trashing it themselves in a custom # trap_http_exception method so that's their fault then. if isinstance(e, HTTPException) and not self.trap_http_exception(e): return self.handle_http_exception(e) handler = self._find_error_handler(e) if handler is None: reraise(exc_type, exc_value, tb) return handler(e) def handle_exception(self, e): """Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed. .. versionadded:: 0.3 """ exc_type, exc_value, tb = sys.exc_info() got_request_exception.send(self, exception=e) handler = self._find_error_handler(InternalServerError()) if self.propagate_exceptions: # if we want to repropagate the exception, we can attempt to # raise it with the whole traceback in case we can do that # (the function was actually called from the except part) # otherwise, we just raise the error again if exc_value is e: reraise(exc_type, exc_value, tb) else: raise e self.log_exception((exc_type, exc_value, tb)) if handler is None: return InternalServerError() return self.finalize_request(handler(e), from_error_handler=True) def log_exception(self, exc_info): """Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. .. versionadded:: 0.8 """ self.logger.error('Exception on %s [%s]' % ( request.path, request.method ), exc_info=exc_info) def raise_routing_exception(self, request): """Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising a different error instead to help debug situations. :internal: """ if not self.debug \ or not isinstance(request.routing_exception, RequestRedirect) \ or request.method in ('GET', 'HEAD', 'OPTIONS'): raise request.routing_exception from .debughelpers import FormDataRoutingRedirect raise FormDataRoutingRedirect(request) def dispatch_request(self): """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .. versionchanged:: 0.7 This no longer does the exception handling, this code was moved to the new :meth:`full_dispatch_request`. """ req = _request_ctx_stack.top.request if req.routing_exception is not None: self.raise_routing_exception(req) rule = req.url_rule # if we provide automatic options for this URL and the # request came with the OPTIONS method, reply automatically if getattr(rule, 'provide_automatic_options', False) \ and req.method == 'OPTIONS': return self.make_default_options_response() # otherwise dispatch to the handler for that endpoint return self.view_functions[rule.endpoint](**req.view_args) def full_dispatch_request(self): """Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. .. versionadded:: 0.7 """ self.try_trigger_before_first_request_functions() try: request_started.send(self) rv = self.preprocess_request() if rv is None: rv = self.dispatch_request() except Exception as e: rv = self.handle_user_exception(e) return self.finalize_request(rv) def finalize_request(self, rv, from_error_handler=False): """Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers. Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the `from_error_handler` flag. If enabled, failures in response processing will be logged and otherwise ignored. :internal: """ response = self.make_response(rv) try: response = self.process_response(response) request_finished.send(self, response=response) except Exception: if not from_error_handler: raise self.logger.exception('Request finalizing failed with an ' 'error while handling an error') return response def try_trigger_before_first_request_functions(self): """Called before each request and will ensure that it triggers the :attr:`before_first_request_funcs` and only exactly once per application instance (which means process usually). :internal: """ if self._got_first_request: return with self._before_request_lock: if self._got_first_request: return for func in self.before_first_request_funcs: func() self._got_first_request = True def make_default_options_response(self): """This method is called to create the default ``OPTIONS`` response. This can be changed through subclassing to change the default behavior of ``OPTIONS`` responses. .. versionadded:: 0.7 """ adapter = _request_ctx_stack.top.url_adapter if hasattr(adapter, 'allowed_methods'): methods = adapter.allowed_methods() else: # fallback for Werkzeug < 0.7 methods = [] try: adapter.match(method='--') except MethodNotAllowed as e: methods = e.valid_methods except HTTPException as e: pass rv = self.response_class() rv.allow.update(methods) return rv def should_ignore_error(self, error): """This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns ``True`` then the teardown handlers will not be passed the error. .. versionadded:: 0.10 """ return False def make_response(self, rv): """Converts the return value from a view function to a real response object that is an instance of :attr:`response_class`. The following types are allowed for `rv`: .. tabularcolumns:: |p{3.5cm}|p{9.5cm}| ======================= =========================================== :attr:`response_class` the object is returned unchanged :class:`str` a response object is created with the string as body :class:`unicode` a response object is created with the string encoded to utf-8 as body a WSGI function the function is called as WSGI application and buffered as response object :class:`tuple` A tuple in the form ``(response, status, headers)`` or ``(response, headers)`` where `response` is any of the types defined here, `status` is a string or an integer and `headers` is a list or a dictionary with header values. ======================= =========================================== :param rv: the return value from the view function .. versionchanged:: 0.9 Previously a tuple was interpreted as the arguments for the response object. """ status_or_headers = headers = None if isinstance(rv, tuple): rv, status_or_headers, headers = rv + (None,) * (3 - len(rv)) if rv is None: raise ValueError('View function did not return a response') if isinstance(status_or_headers, (dict, list)): headers, status_or_headers = status_or_headers, None if not isinstance(rv, self.response_class): # When we create a response object directly, we let the constructor # set the headers and status. We do this because there can be # some extra logic involved when creating these objects with # specific values (like default content type selection). if isinstance(rv, (text_type, bytes, bytearray)): rv = self.response_class(rv, headers=headers, status=status_or_headers) headers = status_or_headers = None else: rv = self.response_class.force_type(rv, request.environ) if status_or_headers is not None: if isinstance(status_or_headers, string_types): rv.status = status_or_headers else: rv.status_code = status_or_headers if headers: rv.headers.extend(headers) return rv def create_url_adapter(self, request): """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6 .. versionchanged:: 0.9 This can now also be called without a request object when the URL adapter is created for the application context. """ if request is not None: return self.url_map.bind_to_environ(request.environ, server_name=self.config['SERVER_NAME']) # We need at the very least the server name to be set for this # to work. if self.config['SERVER_NAME'] is not None: return self.url_map.bind( self.config['SERVER_NAME'], script_name=self.config['APPLICATION_ROOT'] or '/', url_scheme=self.config['PREFERRED_URL_SCHEME']) def inject_url_defaults(self, endpoint, values): """Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7 """ funcs = self.url_default_functions.get(None, ()) if '.' in endpoint: bp = endpoint.rsplit('.', 1)[0] funcs = chain(funcs, self.url_default_functions.get(bp, ())) for func in funcs: func(endpoint, values) def handle_url_build_error(self, error, endpoint, values): """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`. """ exc_type, exc_value, tb = sys.exc_info() for handler in self.url_build_error_handlers: try: rv = handler(error, endpoint, values) if rv is not None: return rv except BuildError as e: # make error available outside except block (py3) error = e # At this point we want to reraise the exception. If the error is # still the same one we can reraise it with the original traceback, # otherwise we raise it from here. if error is exc_value: reraise(exc_type, exc_value, tb) raise error def preprocess_request(self): """Called before the actual request dispatching and will call each :meth:`before_request` decorated function, passing no arguments. If any of these functions returns a value, it's handled as if it was the return value from the view and further request handling is stopped. This also triggers the :meth:`url_value_preprocessor` functions before the actual :meth:`before_request` functions are called. """ bp = _request_ctx_stack.top.request.blueprint funcs = self.url_value_preprocessors.get(None, ()) if bp is not None and bp in self.url_value_preprocessors: funcs = chain(funcs, self.url_value_preprocessors[bp]) for func in funcs: func(request.endpoint, request.view_args) funcs = self.before_request_funcs.get(None, ()) if bp is not None and bp in self.before_request_funcs: funcs = chain(funcs, self.before_request_funcs[bp]) for func in funcs: rv = func() if rv is not None: return rv def process_response(self, response): """Can be overridden in order to modify the response object before it's sent to the WSGI server. By default this will call all the :meth:`after_request` decorated functions. .. versionchanged:: 0.5 As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration. :param response: a :attr:`response_class` object. :return: a new response object or the same, has to be an instance of :attr:`response_class`. """ ctx = _request_ctx_stack.top bp = ctx.request.blueprint funcs = ctx._after_request_functions if bp is not None and bp in self.after_request_funcs: funcs = chain(funcs, reversed(self.after_request_funcs[bp])) if None in self.after_request_funcs: funcs = chain(funcs, reversed(self.after_request_funcs[None])) for handler in funcs: response = handler(response) if not self.session_interface.is_null_session(ctx.session): self.save_session(ctx.session, response) return response def do_teardown_request(self, exc=_sentinel): """Called after the actual request dispatching and will call every as :meth:`teardown_request` decorated function. This is not actually called by the :class:`Flask` object itself but is always triggered when the request context is popped. That way we have a tighter control over certain resources under testing environments. .. versionchanged:: 0.9 Added the `exc` argument. Previously this was always using the current exception information. """ if exc is _sentinel: exc = sys.exc_info()[1] funcs = reversed(self.teardown_request_funcs.get(None, ())) bp = _request_ctx_stack.top.request.blueprint if bp is not None and bp in self.teardown_request_funcs: funcs = chain(funcs, reversed(self.teardown_request_funcs[bp])) for func in funcs: func(exc) request_tearing_down.send(self, exc=exc) def do_teardown_appcontext(self, exc=_sentinel): """Called when an application context is popped. This works pretty much the same as :meth:`do_teardown_request` but for the application context. .. versionadded:: 0.9 """ if exc is _sentinel: exc = sys.exc_info()[1] for func in reversed(self.teardown_appcontext_funcs): func(exc) appcontext_tearing_down.send(self, exc=exc) def app_context(self): """Binds the application only. For as long as the application is bound to the current context the :data:`flask.current_app` points to that application. An application context is automatically created when a request context is pushed if necessary. Example usage:: with app.app_context(): ... .. versionadded:: 0.9 """ return AppContext(self) def request_context(self, environ): """Creates a :class:`~flask.ctx.RequestContext` from the given environment and binds it to the current context. This must be used in combination with the ``with`` statement because the request is only bound to the current context for the duration of the ``with`` block. Example usage:: with app.request_context(environ): do_something_with(request) The object returned can also be used without the ``with`` statement which is useful for working in the shell. The example above is doing exactly the same as this code:: ctx = app.request_context(environ) ctx.push() try: do_something_with(request) finally: ctx.pop() .. versionchanged:: 0.3 Added support for non-with statement usage and ``with`` statement is now passed the ctx object. :param environ: a WSGI environment """ return RequestContext(self, environ) def test_request_context(self, *args, **kwargs): """Creates a WSGI environment from the given values (see :class:`werkzeug.test.EnvironBuilder` for more information, this function accepts the same arguments). """ from flask.testing import make_test_environ_builder builder = make_test_environ_builder(self, *args, **kwargs) try: return self.request_context(builder.get_environ()) finally: builder.close() def wsgi_app(self, environ, start_response): """The actual WSGI application. This is not implemented in `__call__` so that middlewares can be applied without losing a reference to the class. So instead of doing this:: app = MyMiddleware(app) It's a better idea to do this instead:: app.wsgi_app = MyMiddleware(app.wsgi_app) Then you still have the original application object around and can continue to call methods on it. .. versionchanged:: 0.7 The behavior of the before and after request callbacks was changed under error conditions and a new callback was added that will always execute at the end of the request, independent on if an error occurred or not. See :ref:`callbacks-and-errors`. :param environ: a WSGI environment :param start_response: a callable accepting a status code, a list of headers and an optional exception context to start the response """ ctx = self.request_context(environ) ctx.push() error = None try: try: response = self.full_dispatch_request() except Exception as e: error = e response = self.handle_exception(e) except: error = sys.exc_info()[1] raise return response(environ, start_response) finally: if self.should_ignore_error(error): error = None ctx.auto_pop(error) def __call__(self, environ, start_response): """Shortcut for :attr:`wsgi_app`.""" return self.wsgi_app(environ, start_response) def __repr__(self): return '<%s %r>' % ( self.__class__.__name__, self.name, ) Flask-0.12.2/flask/__main__.py0000644000175000001440000000044312763616450017226 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.__main__ ~~~~~~~~~~~~~~ Alias for flask.run for the command line. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ if __name__ == '__main__': from .cli import main main(as_module=True) Flask-0.12.2/flask/ctx.py0000644000175000001440000003462312763616450016313 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.ctx ~~~~~~~~~ Implements the objects required to keep the context. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import sys from functools import update_wrapper from werkzeug.exceptions import HTTPException from .globals import _request_ctx_stack, _app_ctx_stack from .signals import appcontext_pushed, appcontext_popped from ._compat import BROKEN_PYPY_CTXMGR_EXIT, reraise # a singleton sentinel value for parameter defaults _sentinel = object() class _AppCtxGlobals(object): """A plain object.""" def get(self, name, default=None): return self.__dict__.get(name, default) def pop(self, name, default=_sentinel): if default is _sentinel: return self.__dict__.pop(name) else: return self.__dict__.pop(name, default) def setdefault(self, name, default=None): return self.__dict__.setdefault(name, default) def __contains__(self, item): return item in self.__dict__ def __iter__(self): return iter(self.__dict__) def __repr__(self): top = _app_ctx_stack.top if top is not None: return '' % top.app.name return object.__repr__(self) def after_this_request(f): """Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one. Example:: @app.route('/') def index(): @after_this_request def add_header(response): response.headers['X-Foo'] = 'Parachute' return response return 'Hello World!' This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object. .. versionadded:: 0.9 """ _request_ctx_stack.top._after_request_functions.append(f) return f def copy_current_request_context(f): """A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. Example:: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request like you # would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' .. versionadded:: 0.10 """ top = _request_ctx_stack.top if top is None: raise RuntimeError('This decorator can only be used at local scopes ' 'when a request context is on the stack. For instance within ' 'view functions.') reqctx = top.copy() def wrapper(*args, **kwargs): with reqctx: return f(*args, **kwargs) return update_wrapper(wrapper, f) def has_request_context(): """If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable. :: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and has_request_context(): remote_addr = request.remote_addr self.remote_addr = remote_addr Alternatively you can also just test any of the context bound objects (such as :class:`request` or :class:`g` for truthness):: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and request: remote_addr = request.remote_addr self.remote_addr = remote_addr .. versionadded:: 0.7 """ return _request_ctx_stack.top is not None def has_app_context(): """Works like :func:`has_request_context` but for the application context. You can also just do a boolean check on the :data:`current_app` object instead. .. versionadded:: 0.9 """ return _app_ctx_stack.top is not None class AppContext(object): """The application context binds an application object implicitly to the current thread or greenlet, similar to how the :class:`RequestContext` binds request information. The application context is also implicitly created if a request context is created but the application is not on top of the individual application context. """ def __init__(self, app): self.app = app self.url_adapter = app.create_url_adapter(None) self.g = app.app_ctx_globals_class() # Like request context, app contexts can be pushed multiple times # but there a basic "refcount" is enough to track them. self._refcnt = 0 def push(self): """Binds the app context to the current context.""" self._refcnt += 1 if hasattr(sys, 'exc_clear'): sys.exc_clear() _app_ctx_stack.push(self) appcontext_pushed.send(self.app) def pop(self, exc=_sentinel): """Pops the app context.""" try: self._refcnt -= 1 if self._refcnt <= 0: if exc is _sentinel: exc = sys.exc_info()[1] self.app.do_teardown_appcontext(exc) finally: rv = _app_ctx_stack.pop() assert rv is self, 'Popped wrong app context. (%r instead of %r)' \ % (rv, self) appcontext_popped.send(self.app) def __enter__(self): self.push() return self def __exit__(self, exc_type, exc_value, tb): self.pop(exc_value) if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None: reraise(exc_type, exc_value, tb) class RequestContext(object): """The request context contains all request relevant information. It is created at the beginning of the request and pushed to the `_request_ctx_stack` and removed at the end of it. It will create the URL adapter and request object for the WSGI environment provided. Do not attempt to use this class directly, instead use :meth:`~flask.Flask.test_request_context` and :meth:`~flask.Flask.request_context` to create this object. When the request context is popped, it will evaluate all the functions registered on the application for teardown execution (:meth:`~flask.Flask.teardown_request`). The request context is automatically popped at the end of the request for you. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. With 0.4 this can also be forced for requests that did not fail and outside of ``DEBUG`` mode. By setting ``'flask._preserve_context'`` to ``True`` on the WSGI environment the context will not pop itself at the end of the request. This is used by the :meth:`~flask.Flask.test_client` for example to implement the deferred cleanup functionality. You might find this helpful for unittests where you need the information from the context local around for a little longer. Make sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in that situation, otherwise your unittests will leak memory. """ def __init__(self, app, environ, request=None): self.app = app if request is None: request = app.request_class(environ) self.request = request self.url_adapter = app.create_url_adapter(self.request) self.flashes = None self.session = None # Request contexts can be pushed multiple times and interleaved with # other request contexts. Now only if the last level is popped we # get rid of them. Additionally if an application context is missing # one is created implicitly so for each level we add this information self._implicit_app_ctx_stack = [] # indicator if the context was preserved. Next time another context # is pushed the preserved context is popped. self.preserved = False # remembers the exception for pop if there is one in case the context # preservation kicks in. self._preserved_exc = None # Functions that should be executed after the request on the response # object. These will be called before the regular "after_request" # functions. self._after_request_functions = [] self.match_request() def _get_g(self): return _app_ctx_stack.top.g def _set_g(self, value): _app_ctx_stack.top.g = value g = property(_get_g, _set_g) del _get_g, _set_g def copy(self): """Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked. .. versionadded:: 0.10 """ return self.__class__(self.app, environ=self.request.environ, request=self.request ) def match_request(self): """Can be overridden by a subclass to hook into the matching of the request. """ try: url_rule, self.request.view_args = \ self.url_adapter.match(return_rule=True) self.request.url_rule = url_rule except HTTPException as e: self.request.routing_exception = e def push(self): """Binds the request context to the current context.""" # If an exception occurs in debug mode or if context preservation is # activated under exception situations exactly one context stays # on the stack. The rationale is that you want to access that # information under debug situations. However if someone forgets to # pop that context again we want to make sure that on the next push # it's invalidated, otherwise we run at risk that something leaks # memory. This is usually only a problem in test suite since this # functionality is not active in production environments. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop(top._preserved_exc) # Before we push the request context we have to ensure that there # is an application context. app_ctx = _app_ctx_stack.top if app_ctx is None or app_ctx.app != self.app: app_ctx = self.app.app_context() app_ctx.push() self._implicit_app_ctx_stack.append(app_ctx) else: self._implicit_app_ctx_stack.append(None) if hasattr(sys, 'exc_clear'): sys.exc_clear() _request_ctx_stack.push(self) # Open the session at the moment that the request context is # available. This allows a custom open_session method to use the # request context (e.g. code that access database information # stored on `g` instead of the appcontext). self.session = self.app.open_session(self.request) if self.session is None: self.session = self.app.make_null_session() def pop(self, exc=_sentinel): """Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the :meth:`~flask.Flask.teardown_request` decorator. .. versionchanged:: 0.9 Added the `exc` argument. """ app_ctx = self._implicit_app_ctx_stack.pop() try: clear_request = False if not self._implicit_app_ctx_stack: self.preserved = False self._preserved_exc = None if exc is _sentinel: exc = sys.exc_info()[1] self.app.do_teardown_request(exc) # If this interpreter supports clearing the exception information # we do that now. This will only go into effect on Python 2.x, # on 3.x it disappears automatically at the end of the exception # stack. if hasattr(sys, 'exc_clear'): sys.exc_clear() request_close = getattr(self.request, 'close', None) if request_close is not None: request_close() clear_request = True finally: rv = _request_ctx_stack.pop() # get rid of circular dependencies at the end of the request # so that we don't require the GC to be active. if clear_request: rv.request.environ['werkzeug.request'] = None # Get rid of the app as well if necessary. if app_ctx is not None: app_ctx.pop(exc) assert rv is self, 'Popped wrong request context. ' \ '(%r instead of %r)' % (rv, self) def auto_pop(self, exc): if self.request.environ.get('flask._preserve_context') or \ (exc is not None and self.app.preserve_context_on_exception): self.preserved = True self._preserved_exc = exc else: self.pop(exc) def __enter__(self): self.push() return self def __exit__(self, exc_type, exc_value, tb): # do not pop the request stack if we are in debug mode and an # exception happened. This will allow the debugger to still # access the request object in the interactive shell. Furthermore # the context can be force kept alive for the test client. # See flask.testing for how this works. self.auto_pop(exc_value) if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None: reraise(exc_type, exc_value, tb) def __repr__(self): return '<%s \'%s\' [%s] of %s>' % ( self.__class__.__name__, self.request.url, self.request.method, self.app.name, ) Flask-0.12.2/flask/_compat.py0000644000175000001440000000536212764036656017142 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask._compat ~~~~~~~~~~~~~ Some py2/py3 compatibility support based on a stripped down version of six so we don't have to depend on a specific version of it. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import sys PY2 = sys.version_info[0] == 2 _identity = lambda x: x if not PY2: text_type = str string_types = (str,) integer_types = (int,) iterkeys = lambda d: iter(d.keys()) itervalues = lambda d: iter(d.values()) iteritems = lambda d: iter(d.items()) from io import StringIO def reraise(tp, value, tb=None): if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value implements_to_string = _identity else: text_type = unicode string_types = (str, unicode) integer_types = (int, long) iterkeys = lambda d: d.iterkeys() itervalues = lambda d: d.itervalues() iteritems = lambda d: d.iteritems() from cStringIO import StringIO exec('def reraise(tp, value, tb=None):\n raise tp, value, tb') def implements_to_string(cls): cls.__unicode__ = cls.__str__ cls.__str__ = lambda x: x.__unicode__().encode('utf-8') return cls def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a # dummy metaclass for one level of class instantiation that replaces # itself with the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) # Certain versions of pypy have a bug where clearing the exception stack # breaks the __exit__ function in a very peculiar way. The second level of # exception blocks is necessary because pypy seems to forget to check if an # exception happened until the next bytecode instruction? # # Relevant PyPy bugfix commit: # https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df4003301 # According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later # versions. # # Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug. BROKEN_PYPY_CTXMGR_EXIT = False if hasattr(sys, 'pypy_version_info'): class _Mgr(object): def __enter__(self): return self def __exit__(self, *args): if hasattr(sys, 'exc_clear'): # Python 3 (PyPy3) doesn't have exc_clear sys.exc_clear() try: try: with _Mgr(): raise AssertionError() except: raise except TypeError: BROKEN_PYPY_CTXMGR_EXIT = True except AssertionError: pass Flask-0.12.2/flask/json.py0000644000175000001440000002173713106517205016456 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ flask.jsonimpl ~~~~~~~~~~~~~~ Implementation helpers for the JSON support in Flask. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import io import uuid from datetime import date from .globals import current_app, request from ._compat import text_type, PY2 from werkzeug.http import http_date from jinja2 import Markup # Use the same json implementation as itsdangerous on which we # depend anyways. from itsdangerous import json as _json # Figure out if simplejson escapes slashes. This behavior was changed # from one version to another without reason. _slash_escape = '\\/' not in _json.dumps('/') __all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump', 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder', 'jsonify'] def _wrap_reader_for_text(fp, encoding): if isinstance(fp.read(0), bytes): fp = io.TextIOWrapper(io.BufferedReader(fp), encoding) return fp def _wrap_writer_for_text(fp, encoding): try: fp.write('') except TypeError: fp = io.TextIOWrapper(fp, encoding) return fp class JSONEncoder(_json.JSONEncoder): """The default Flask JSON encoder. This one extends the default simplejson encoder by also supporting ``datetime`` objects, ``UUID`` as well as ``Markup`` objects which are serialized as RFC 822 datetime strings (same as the HTTP date format). In order to support more data types override the :meth:`default` method. """ def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a :exc:`TypeError`). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ if isinstance(o, date): return http_date(o.timetuple()) if isinstance(o, uuid.UUID): return str(o) if hasattr(o, '__html__'): return text_type(o.__html__()) return _json.JSONEncoder.default(self, o) class JSONDecoder(_json.JSONDecoder): """The default JSON decoder. This one does not change the behavior from the default simplejson decoder. Consult the :mod:`json` documentation for more information. This decoder is not only used for the load functions of this module but also :attr:`~flask.Request`. """ def _dump_arg_defaults(kwargs): """Inject default arguments for dump functions.""" if current_app: kwargs.setdefault('cls', current_app.json_encoder) if not current_app.config['JSON_AS_ASCII']: kwargs.setdefault('ensure_ascii', False) kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS']) else: kwargs.setdefault('sort_keys', True) kwargs.setdefault('cls', JSONEncoder) def _load_arg_defaults(kwargs): """Inject default arguments for load functions.""" if current_app: kwargs.setdefault('cls', current_app.json_decoder) else: kwargs.setdefault('cls', JSONDecoder) def dumps(obj, **kwargs): """Serialize ``obj`` to a JSON formatted ``str`` by using the application's configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an application on the stack. This function can return ``unicode`` strings or ascii-only bytestrings by default which coerce into unicode strings automatically. That behavior by default is controlled by the ``JSON_AS_ASCII`` configuration variable and can be overridden by the simplejson ``ensure_ascii`` parameter. """ _dump_arg_defaults(kwargs) encoding = kwargs.pop('encoding', None) rv = _json.dumps(obj, **kwargs) if encoding is not None and isinstance(rv, text_type): rv = rv.encode(encoding) return rv def dump(obj, fp, **kwargs): """Like :func:`dumps` but writes into a file object.""" _dump_arg_defaults(kwargs) encoding = kwargs.pop('encoding', None) if encoding is not None: fp = _wrap_writer_for_text(fp, encoding) _json.dump(obj, fp, **kwargs) def loads(s, **kwargs): """Unserialize a JSON object from a string ``s`` by using the application's configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an application on the stack. """ _load_arg_defaults(kwargs) if isinstance(s, bytes): s = s.decode(kwargs.pop('encoding', None) or 'utf-8') return _json.loads(s, **kwargs) def load(fp, **kwargs): """Like :func:`loads` but reads from a file object. """ _load_arg_defaults(kwargs) if not PY2: fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8') return _json.load(fp, **kwargs) def htmlsafe_dumps(obj, **kwargs): """Works exactly like :func:`dumps` but is safe for use in ``

jQuery Example

+ = ?

calculate server side {% endblock %} Flask-0.12.2/examples/jqueryexample/templates/layout.html0000644000175000001440000000044412763616450024747 0ustar untitakerusers00000000000000 jQuery Example {% block body %}{% endblock %} Flask-0.12.2/examples/minitwit/0000755000175000001440000000000013106517244017506 5ustar untitakerusers00000000000000Flask-0.12.2/examples/minitwit/README0000644000175000001440000000150213047321000020347 0ustar untitakerusers00000000000000 / MiniTwit / because writing todo lists is not fun ~ What is MiniTwit? A SQLite and Flask powered twitter clone ~ How do I use it? 1. edit the configuration in the minitwit.py file or export an MINITWIT_SETTINGS environment variable pointing to a configuration file. 2. install the app from the root of the project directory pip install --editable . 3. tell flask about the right application: export FLASK_APP=minitwit 4. fire up a shell and run this: flask initdb 5. now you can run minitwit: flask run the application will greet you on http://localhost:5000/ ~ Is it tested? You betcha. Run the `python setup.py test` file to see the tests pass. Flask-0.12.2/examples/minitwit/setup.py0000644000175000001440000000040612765277142021232 0ustar untitakerusers00000000000000from setuptools import setup setup( name='minitwit', packages=['minitwit'], include_package_data=True, install_requires=[ 'flask', ], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', ], )Flask-0.12.2/examples/minitwit/MANIFEST.in0000644000175000001440000000011212765277142021250 0ustar untitakerusers00000000000000graft minitwit/templates graft minitwit/static include minitwit/schema.sqlFlask-0.12.2/examples/minitwit/.gitignore0000644000175000001440000000002312765277142021503 0ustar untitakerusers00000000000000minitwit.db .eggs/ Flask-0.12.2/examples/minitwit/setup.cfg0000644000175000001440000000002612765277142021337 0ustar untitakerusers00000000000000[aliases] test=pytest Flask-0.12.2/examples/minitwit/tests/0000755000175000001440000000000013106517244020650 5ustar untitakerusers00000000000000Flask-0.12.2/examples/minitwit/tests/test_minitwit.py0000644000175000001440000001131412765277142024137 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ MiniTwit Tests ~~~~~~~~~~~~~~ Tests the MiniTwit application. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os import tempfile import pytest from minitwit import minitwit @pytest.fixture def client(request): db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp() client = minitwit.app.test_client() with minitwit.app.app_context(): minitwit.init_db() def teardown(): """Get rid of the database again after each test.""" os.close(db_fd) os.unlink(minitwit.app.config['DATABASE']) request.addfinalizer(teardown) return client def register(client, username, password, password2=None, email=None): """Helper function to register a user""" if password2 is None: password2 = password if email is None: email = username + '@example.com' return client.post('/register', data={ 'username': username, 'password': password, 'password2': password2, 'email': email, }, follow_redirects=True) def login(client, username, password): """Helper function to login""" return client.post('/login', data={ 'username': username, 'password': password }, follow_redirects=True) def register_and_login(client, username, password): """Registers and logs in in one go""" register(client, username, password) return login(client, username, password) def logout(client): """Helper function to logout""" return client.get('/logout', follow_redirects=True) def add_message(client, text): """Records a message""" rv = client.post('/add_message', data={'text': text}, follow_redirects=True) if text: assert b'Your message was recorded' in rv.data return rv def test_register(client): """Make sure registering works""" rv = register(client, 'user1', 'default') assert b'You were successfully registered ' \ b'and can login now' in rv.data rv = register(client, 'user1', 'default') assert b'The username is already taken' in rv.data rv = register(client, '', 'default') assert b'You have to enter a username' in rv.data rv = register(client, 'meh', '') assert b'You have to enter a password' in rv.data rv = register(client, 'meh', 'x', 'y') assert b'The two passwords do not match' in rv.data rv = register(client, 'meh', 'foo', email='broken') assert b'You have to enter a valid email address' in rv.data def test_login_logout(client): """Make sure logging in and logging out works""" rv = register_and_login(client, 'user1', 'default') assert b'You were logged in' in rv.data rv = logout(client) assert b'You were logged out' in rv.data rv = login(client, 'user1', 'wrongpassword') assert b'Invalid password' in rv.data rv = login(client, 'user2', 'wrongpassword') assert b'Invalid username' in rv.data def test_message_recording(client): """Check if adding messages works""" register_and_login(client, 'foo', 'default') add_message(client, 'test message 1') add_message(client, '') rv = client.get('/') assert b'test message 1' in rv.data assert b'<test message 2>' in rv.data def test_timelines(client): """Make sure that timelines work""" register_and_login(client, 'foo', 'default') add_message(client, 'the message by foo') logout(client) register_and_login(client, 'bar', 'default') add_message(client, 'the message by bar') rv = client.get('/public') assert b'the message by foo' in rv.data assert b'the message by bar' in rv.data # bar's timeline should just show bar's message rv = client.get('/') assert b'the message by foo' not in rv.data assert b'the message by bar' in rv.data # now let's follow foo rv = client.get('/foo/follow', follow_redirects=True) assert b'You are now following "foo"' in rv.data # we should now see foo's message rv = client.get('/') assert b'the message by foo' in rv.data assert b'the message by bar' in rv.data # but on the user's page we only want the user's message rv = client.get('/bar') assert b'the message by foo' not in rv.data assert b'the message by bar' in rv.data rv = client.get('/foo') assert b'the message by foo' in rv.data assert b'the message by bar' not in rv.data # now unfollow and check if that worked rv = client.get('/foo/unfollow', follow_redirects=True) assert b'You are no longer following "foo"' in rv.data rv = client.get('/') assert b'the message by foo' not in rv.data assert b'the message by bar' in rv.data Flask-0.12.2/examples/minitwit/minitwit/0000755000175000001440000000000013106517244021352 5ustar untitakerusers00000000000000Flask-0.12.2/examples/minitwit/minitwit/schema.sql0000644000175000001440000000066712765277142023356 0ustar untitakerusers00000000000000drop table if exists user; create table user ( user_id integer primary key autoincrement, username text not null, email text not null, pw_hash text not null ); drop table if exists follower; create table follower ( who_id integer, whom_id integer ); drop table if exists message; create table message ( message_id integer primary key autoincrement, author_id integer not null, text text not null, pub_date integer ); Flask-0.12.2/examples/minitwit/minitwit/__init__.py0000644000175000001440000000003213047321000023441 0ustar untitakerusers00000000000000from .minitwit import app Flask-0.12.2/examples/minitwit/minitwit/minitwit.py0000644000175000001440000002045413106517205023572 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ MiniTwit ~~~~~~~~ A microblogging application written with Flask and sqlite3. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import time from sqlite3 import dbapi2 as sqlite3 from hashlib import md5 from datetime import datetime from flask import Flask, request, session, url_for, redirect, \ render_template, abort, g, flash, _app_ctx_stack from werkzeug import check_password_hash, generate_password_hash # configuration DATABASE = '/tmp/minitwit.db' PER_PAGE = 30 DEBUG = True SECRET_KEY = 'development key' # create our little application :) app = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('MINITWIT_SETTINGS', silent=True) def get_db(): """Opens a new database connection if there is none yet for the current application context. """ top = _app_ctx_stack.top if not hasattr(top, 'sqlite_db'): top.sqlite_db = sqlite3.connect(app.config['DATABASE']) top.sqlite_db.row_factory = sqlite3.Row return top.sqlite_db @app.teardown_appcontext def close_database(exception): """Closes the database again at the end of the request.""" top = _app_ctx_stack.top if hasattr(top, 'sqlite_db'): top.sqlite_db.close() def init_db(): """Initializes the database.""" db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() @app.cli.command('initdb') def initdb_command(): """Creates the database tables.""" init_db() print('Initialized the database.') def query_db(query, args=(), one=False): """Queries the database and returns a list of dictionaries.""" cur = get_db().execute(query, args) rv = cur.fetchall() return (rv[0] if rv else None) if one else rv def get_user_id(username): """Convenience method to look up the id for a username.""" rv = query_db('select user_id from user where username = ?', [username], one=True) return rv[0] if rv else None def format_datetime(timestamp): """Format a timestamp for display.""" return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M') def gravatar_url(email, size=80): """Return the gravatar image for the given email address.""" return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \ (md5(email.strip().lower().encode('utf-8')).hexdigest(), size) @app.before_request def before_request(): g.user = None if 'user_id' in session: g.user = query_db('select * from user where user_id = ?', [session['user_id']], one=True) @app.route('/') def timeline(): """Shows a users timeline or if no user is logged in it will redirect to the public timeline. This timeline shows the user's messages as well as all the messages of followed users. """ if not g.user: return redirect(url_for('public_timeline')) return render_template('timeline.html', messages=query_db(''' select message.*, user.* from message, user where message.author_id = user.user_id and ( user.user_id = ? or user.user_id in (select whom_id from follower where who_id = ?)) order by message.pub_date desc limit ?''', [session['user_id'], session['user_id'], PER_PAGE])) @app.route('/public') def public_timeline(): """Displays the latest messages of all users.""" return render_template('timeline.html', messages=query_db(''' select message.*, user.* from message, user where message.author_id = user.user_id order by message.pub_date desc limit ?''', [PER_PAGE])) @app.route('/') def user_timeline(username): """Display's a users tweets.""" profile_user = query_db('select * from user where username = ?', [username], one=True) if profile_user is None: abort(404) followed = False if g.user: followed = query_db('''select 1 from follower where follower.who_id = ? and follower.whom_id = ?''', [session['user_id'], profile_user['user_id']], one=True) is not None return render_template('timeline.html', messages=query_db(''' select message.*, user.* from message, user where user.user_id = message.author_id and user.user_id = ? order by message.pub_date desc limit ?''', [profile_user['user_id'], PER_PAGE]), followed=followed, profile_user=profile_user) @app.route('//follow') def follow_user(username): """Adds the current user as follower of the given user.""" if not g.user: abort(401) whom_id = get_user_id(username) if whom_id is None: abort(404) db = get_db() db.execute('insert into follower (who_id, whom_id) values (?, ?)', [session['user_id'], whom_id]) db.commit() flash('You are now following "%s"' % username) return redirect(url_for('user_timeline', username=username)) @app.route('//unfollow') def unfollow_user(username): """Removes the current user as follower of the given user.""" if not g.user: abort(401) whom_id = get_user_id(username) if whom_id is None: abort(404) db = get_db() db.execute('delete from follower where who_id=? and whom_id=?', [session['user_id'], whom_id]) db.commit() flash('You are no longer following "%s"' % username) return redirect(url_for('user_timeline', username=username)) @app.route('/add_message', methods=['POST']) def add_message(): """Registers a new message for the user.""" if 'user_id' not in session: abort(401) if request.form['text']: db = get_db() db.execute('''insert into message (author_id, text, pub_date) values (?, ?, ?)''', (session['user_id'], request.form['text'], int(time.time()))) db.commit() flash('Your message was recorded') return redirect(url_for('timeline')) @app.route('/login', methods=['GET', 'POST']) def login(): """Logs the user in.""" if g.user: return redirect(url_for('timeline')) error = None if request.method == 'POST': user = query_db('''select * from user where username = ?''', [request.form['username']], one=True) if user is None: error = 'Invalid username' elif not check_password_hash(user['pw_hash'], request.form['password']): error = 'Invalid password' else: flash('You were logged in') session['user_id'] = user['user_id'] return redirect(url_for('timeline')) return render_template('login.html', error=error) @app.route('/register', methods=['GET', 'POST']) def register(): """Registers the user.""" if g.user: return redirect(url_for('timeline')) error = None if request.method == 'POST': if not request.form['username']: error = 'You have to enter a username' elif not request.form['email'] or \ '@' not in request.form['email']: error = 'You have to enter a valid email address' elif not request.form['password']: error = 'You have to enter a password' elif request.form['password'] != request.form['password2']: error = 'The two passwords do not match' elif get_user_id(request.form['username']) is not None: error = 'The username is already taken' else: db = get_db() db.execute('''insert into user ( username, email, pw_hash) values (?, ?, ?)''', [request.form['username'], request.form['email'], generate_password_hash(request.form['password'])]) db.commit() flash('You were successfully registered and can login now') return redirect(url_for('login')) return render_template('register.html', error=error) @app.route('/logout') def logout(): """Logs the user out.""" flash('You were logged out') session.pop('user_id', None) return redirect(url_for('public_timeline')) # add some filters to jinja app.jinja_env.filters['datetimeformat'] = format_datetime app.jinja_env.filters['gravatar'] = gravatar_url Flask-0.12.2/examples/minitwit/minitwit/static/0000755000175000001440000000000013106517244022641 5ustar untitakerusers00000000000000Flask-0.12.2/examples/minitwit/minitwit/static/style.css0000644000175000001440000000601012765277142024522 0ustar untitakerusers00000000000000body { background: #CAECE9; font-family: 'Trebuchet MS', sans-serif; font-size: 14px; } a { color: #26776F; } a:hover { color: #333; } input[type="text"], input[type="password"] { background: white; border: 1px solid #BFE6E2; padding: 2px; font-family: 'Trebuchet MS', sans-serif; font-size: 14px; -moz-border-radius: 2px; -webkit-border-radius: 2px; color: #105751; } input[type="submit"] { background: #105751; border: 1px solid #073B36; padding: 1px 3px; font-family: 'Trebuchet MS', sans-serif; font-size: 14px; font-weight: bold; -moz-border-radius: 2px; -webkit-border-radius: 2px; color: white; } div.page { background: white; border: 1px solid #6ECCC4; width: 700px; margin: 30px auto; } div.page h1 { background: #6ECCC4; margin: 0; padding: 10px 14px; color: white; letter-spacing: 1px; text-shadow: 0 0 3px #24776F; font-weight: normal; } div.page div.navigation { background: #DEE9E8; padding: 4px 10px; border-top: 1px solid #ccc; border-bottom: 1px solid #eee; color: #888; font-size: 12px; letter-spacing: 0.5px; } div.page div.navigation a { color: #444; font-weight: bold; } div.page h2 { margin: 0 0 15px 0; color: #105751; text-shadow: 0 1px 2px #ccc; } div.page div.body { padding: 10px; } div.page div.footer { background: #eee; color: #888; padding: 5px 10px; font-size: 12px; } div.page div.followstatus { border: 1px solid #ccc; background: #E3EBEA; -moz-border-radius: 2px; -webkit-border-radius: 2px; padding: 3px; font-size: 13px; } div.page ul.messages { list-style: none; margin: 0; padding: 0; } div.page ul.messages li { margin: 10px 0; padding: 5px; background: #F0FAF9; border: 1px solid #DBF3F1; -moz-border-radius: 5px; -webkit-border-radius: 5px; min-height: 48px; } div.page ul.messages p { margin: 0; } div.page ul.messages li img { float: left; padding: 0 10px 0 0; } div.page ul.messages li small { font-size: 0.9em; color: #888; } div.page div.twitbox { margin: 10px 0; padding: 5px; background: #F0FAF9; border: 1px solid #94E2DA; -moz-border-radius: 5px; -webkit-border-radius: 5px; } div.page div.twitbox h3 { margin: 0; font-size: 1em; color: #2C7E76; } div.page div.twitbox p { margin: 0; } div.page div.twitbox input[type="text"] { width: 585px; } div.page div.twitbox input[type="submit"] { width: 70px; margin-left: 5px; } ul.flashes { list-style: none; margin: 10px 10px 0 10px; padding: 0; } ul.flashes li { background: #B9F3ED; border: 1px solid #81CEC6; -moz-border-radius: 2px; -webkit-border-radius: 2px; padding: 4px; font-size: 13px; } div.error { margin: 10px 0; background: #FAE4E4; border: 1px solid #DD6F6F; -moz-border-radius: 2px; -webkit-border-radius: 2px; padding: 4px; font-size: 13px; } Flask-0.12.2/examples/minitwit/minitwit/templates/0000755000175000001440000000000013106517244023350 5ustar untitakerusers00000000000000Flask-0.12.2/examples/minitwit/minitwit/templates/register.html0000644000175000001440000000134212765277142026074 0ustar untitakerusers00000000000000{% extends "layout.html" %} {% block title %}Sign Up{% endblock %} {% block body %}

Sign Up

{% if error %}
Error: {{ error }}
{% endif %}
Username:
E-Mail:
Password:
Password (repeat):
{% endblock %} Flask-0.12.2/examples/minitwit/minitwit/templates/timeline.html0000644000175000001440000000324112765277142026056 0ustar untitakerusers00000000000000{% extends "layout.html" %} {% block title %} {% if request.endpoint == 'public_timeline' %} Public Timeline {% elif request.endpoint == 'user_timeline' %} {{ profile_user.username }}'s Timeline {% else %} My Timeline {% endif %} {% endblock %} {% block body %}

{{ self.title() }}

{% if g.user %} {% if request.endpoint == 'user_timeline' %}
{% if g.user.user_id == profile_user.user_id %} This is you! {% elif followed %} You are currently following this user. Unfollow user. {% else %} You are not yet following this user. . {% endif %}
{% elif request.endpoint == 'timeline' %}

What's on your mind {{ g.user.username }}?

{% endif %} {% endif %}
    {% for message in messages %}
  • {{ message.username }} {{ message.text }} — {{ message.pub_date|datetimeformat }} {% else %}

  • There's no message so far. {% endfor %}
{% endblock %} Flask-0.12.2/examples/minitwit/minitwit/templates/login.html0000644000175000001440000000102212765277142025353 0ustar untitakerusers00000000000000{% extends "layout.html" %} {% block title %}Sign In{% endblock %} {% block body %}

Sign In

{% if error %}
Error: {{ error }}
{% endif %}
Username:
Password:
{% endblock %} Flask-0.12.2/examples/minitwit/minitwit/templates/layout.html0000644000175000001440000000200512765277142025562 0ustar untitakerusers00000000000000 {% block title %}Welcome{% endblock %} | MiniTwit

MiniTwit

{% with flashes = get_flashed_messages() %} {% if flashes %}
    {% for message in flashes %}
  • {{ message }} {% endfor %}
{% endif %} {% endwith %}
{% block body %}{% endblock %}
Flask-0.12.2/examples/minitwit/minitwit.egg-info/0000755000175000001440000000000013106517244023044 5ustar untitakerusers00000000000000Flask-0.12.2/examples/minitwit/minitwit.egg-info/top_level.txt0000644000175000001440000000001113067503415025567 0ustar untitakerusers00000000000000minitwit Flask-0.12.2/examples/minitwit/minitwit.egg-info/PKG-INFO0000644000175000001440000000026613067503415024146 0ustar untitakerusers00000000000000Metadata-Version: 1.0 Name: minitwit Version: 0.0.0 Summary: UNKNOWN Home-page: UNKNOWN Author: UNKNOWN Author-email: UNKNOWN License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN Flask-0.12.2/examples/minitwit/minitwit.egg-info/dependency_links.txt0000644000175000001440000000000113067503415027113 0ustar untitakerusers00000000000000 Flask-0.12.2/examples/minitwit/minitwit.egg-info/requires.txt0000644000175000001440000000000513067503415025440 0ustar untitakerusers00000000000000flaskFlask-0.12.2/examples/minitwit/minitwit.egg-info/SOURCES.txt0000644000175000001440000000062213067503415024731 0ustar untitakerusers00000000000000MANIFEST.in README setup.cfg minitwit/__init__.py minitwit/minitwit.py minitwit/schema.sql minitwit.egg-info/PKG-INFO minitwit.egg-info/SOURCES.txt minitwit.egg-info/dependency_links.txt minitwit.egg-info/requires.txt minitwit.egg-info/top_level.txt minitwit/static/style.css minitwit/templates/layout.html minitwit/templates/login.html minitwit/templates/register.html minitwit/templates/timeline.htmlFlask-0.12.2/examples/blueprintexample/0000755000175000001440000000000013106517244021222 5ustar untitakerusers00000000000000Flask-0.12.2/examples/blueprintexample/simple_page/0000755000175000001440000000000013106517244023507 5ustar untitakerusers00000000000000Flask-0.12.2/examples/blueprintexample/simple_page/__init__.py0000644000175000001440000000000012425200262025576 0ustar untitakerusers00000000000000Flask-0.12.2/examples/blueprintexample/simple_page/simple_page.py0000644000175000001440000000062212513765466026362 0ustar untitakerusers00000000000000from flask import Blueprint, render_template, abort from jinja2 import TemplateNotFound simple_page = Blueprint('simple_page', __name__, template_folder='templates') @simple_page.route('/', defaults={'page': 'index'}) @simple_page.route('/') def show(page): try: return render_template('pages/%s.html' % page) except TemplateNotFound: abort(404) Flask-0.12.2/examples/blueprintexample/simple_page/templates/0000755000175000001440000000000013106517244025505 5ustar untitakerusers00000000000000Flask-0.12.2/examples/blueprintexample/simple_page/templates/pages/0000755000175000001440000000000013106517244026604 5ustar untitakerusers00000000000000Flask-0.12.2/examples/blueprintexample/simple_page/templates/pages/world.html0000644000175000001440000000011212425200262030603 0ustar untitakerusers00000000000000{% extends "pages/layout.html" %} {% block body %} World {% endblock %} Flask-0.12.2/examples/blueprintexample/simple_page/templates/pages/index.html0000644000175000001440000000013412425200262030567 0ustar untitakerusers00000000000000{% extends "pages/layout.html" %} {% block body %} Blueprint example page {% endblock %} Flask-0.12.2/examples/blueprintexample/simple_page/templates/pages/hello.html0000644000175000001440000000011312425200262030560 0ustar untitakerusers00000000000000{% extends "pages/layout.html" %} {% block body %} Hello {% endblock %} Flask-0.12.2/examples/blueprintexample/simple_page/templates/pages/layout.html0000644000175000001440000000113612763616450031017 0ustar untitakerusers00000000000000 Simple Page Blueprint

This is blueprint example

A simple page blueprint is registered under / and /pages you can access it using this URLs:

Also you can register the same blueprint under another path

{% block body %}{% endblock %}
Flask-0.12.2/examples/blueprintexample/test_blueprintexample.py0000644000175000001440000000113612763616450026223 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ Blueprint Example Tests ~~~~~~~~~~~~~~ Tests the Blueprint example app """ import pytest import blueprintexample @pytest.fixture def client(): return blueprintexample.app.test_client() def test_urls(client): r = client.get('/') assert r.status_code == 200 r = client.get('/hello') assert r.status_code == 200 r = client.get('/world') assert r.status_code == 200 # second blueprint instance r = client.get('/pages/hello') assert r.status_code == 200 r = client.get('/pages/world') assert r.status_code == 200 Flask-0.12.2/examples/blueprintexample/blueprintexample.py0000644000175000001440000000041312763616450025161 0ustar untitakerusers00000000000000from flask import Flask from simple_page.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page) # Blueprint can be registered many times app.register_blueprint(simple_page, url_prefix='/pages') if __name__=='__main__': app.run() Flask-0.12.2/docs/0000755000175000001440000000000013106517244014754 5ustar untitakerusers00000000000000Flask-0.12.2/docs/conf.py0000644000175000001440000002266413106517205016262 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- # # Flask documentation build configuration file, created by # sphinx-quickstart on Tue Apr 6 15:24:58 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. from __future__ import print_function from datetime import datetime import os import sys import pkg_resources # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(os.path.join(os.path.dirname(__file__), '_themes')) sys.path.append(os.path.dirname(__file__)) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'flaskdocext' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Flask' copyright = u'2010 - {0}, Armin Ronacher'.format(datetime.utcnow().year) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. try: release = pkg_resources.get_distribution('Flask').version except pkg_resources.DistributionNotFound: print('Flask must be installed to build the documentation.') print('Install from source using `pip install -e .` in a virtualenv.') sys.exit(1) if 'dev' in release: release = ''.join(release.partition('dev')[:2]) version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. # html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. Do not set, template magic! #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = '_static/flask-favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { 'index': [ 'sidebarintro.html', 'sourcelink.html', 'searchbox.html' ], '**': [ 'sidebarlogo.html', 'localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html' ] } # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_use_modindex = False # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Flaskdoc' # -- Options for LaTeX output -------------------------------------------------- # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('latexindex', 'Flask.tex', u'Flask Documentation', u'Armin Ronacher', 'manual'), ] # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. latex_use_modindex = False latex_elements = { 'fontpkg': r'\usepackage{mathpazo}', 'papersize': 'a4paper', 'pointsize': '12pt', 'preamble': r'\usepackage{flaskstyle}' } latex_use_parts = True latex_additional_files = ['flaskstyle.sty', 'logo.pdf'] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. #epub_title = '' #epub_author = '' #epub_publisher = '' #epub_copyright = '' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 intersphinx_mapping = { 'python': ('https://docs.python.org/3/', None), 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None), 'click': ('http://click.pocoo.org/', None), 'jinja': ('http://jinja.pocoo.org/docs/', None), 'sqlalchemy': ('http://docs.sqlalchemy.org/en/latest/', None), 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None), 'blinker': ('https://pythonhosted.org/blinker/', None) } try: __import__('flask_theme_support') pygments_style = 'flask_theme_support.FlaskyStyle' html_theme = 'flask' html_theme_options = { 'touch_icon': 'touch-icon.png' } except ImportError: print('-' * 74) print('Warning: Flask themes unavailable. Building with default theme') print('If you want the Flask themes, run this command and build again:') print() print(' git submodule update --init') print('-' * 74) # unwrap decorators def unwrap_decorators(): import sphinx.util.inspect as inspect import functools old_getargspec = inspect.getargspec def getargspec(x): return old_getargspec(getattr(x, '_original_function', x)) inspect.getargspec = getargspec old_update_wrapper = functools.update_wrapper def update_wrapper(wrapper, wrapped, *a, **kw): rv = old_update_wrapper(wrapper, wrapped, *a, **kw) rv._original_function = wrapped return rv functools.update_wrapper = update_wrapper unwrap_decorators() del unwrap_decorators Flask-0.12.2/docs/shell.rst0000644000175000001440000000715612763616450016635 0ustar untitakerusers00000000000000.. _shell: Working with the Shell ====================== .. versionadded:: 0.3 One of the reasons everybody loves Python is the interactive shell. It basically allows you to execute Python commands in real time and immediately get results back. Flask itself does not come with an interactive shell, because it does not require any specific setup upfront, just import your application and start playing around. There are however some handy helpers to make playing around in the shell a more pleasant experience. The main issue with interactive console sessions is that you're not triggering a request like a browser does which means that :data:`~flask.g`, :data:`~flask.request` and others are not available. But the code you want to test might depend on them, so what can you do? This is where some helper functions come in handy. Keep in mind however that these functions are not only there for interactive shell usage, but also for unittesting and other situations that require a faked request context. Generally it's recommended that you read the :ref:`request-context` chapter of the documentation first. Command Line Interface ---------------------- Starting with Flask 0.11 the recommended way to work with the shell is the ``flask shell`` command which does a lot of this automatically for you. For instance the shell is automatically initialized with a loaded application context. For more information see :ref:`cli`. Creating a Request Context -------------------------- The easiest way to create a proper request context from the shell is by using the :attr:`~flask.Flask.test_request_context` method which creates us a :class:`~flask.ctx.RequestContext`: >>> ctx = app.test_request_context() Normally you would use the ``with`` statement to make this request object active, but in the shell it's easier to use the :meth:`~flask.ctx.RequestContext.push` and :meth:`~flask.ctx.RequestContext.pop` methods by hand: >>> ctx.push() From that point onwards you can work with the request object until you call `pop`: >>> ctx.pop() Firing Before/After Request --------------------------- By just creating a request context, you still don't have run the code that is normally run before a request. This might result in your database being unavailable if you are connecting to the database in a before-request callback or the current user not being stored on the :data:`~flask.g` object etc. This however can easily be done yourself. Just call :meth:`~flask.Flask.preprocess_request`: >>> ctx = app.test_request_context() >>> ctx.push() >>> app.preprocess_request() Keep in mind that the :meth:`~flask.Flask.preprocess_request` function might return a response object, in that case just ignore it. To shutdown a request, you need to trick a bit before the after request functions (triggered by :meth:`~flask.Flask.process_response`) operate on a response object: >>> app.process_response(app.response_class()) >>> ctx.pop() The functions registered as :meth:`~flask.Flask.teardown_request` are automatically called when the context is popped. So this is the perfect place to automatically tear down resources that were needed by the request context (such as database connections). Further Improving the Shell Experience -------------------------------------- If you like the idea of experimenting in a shell, create yourself a module with stuff you want to star import into your interactive session. There you could also define some more helper methods for common things such as initializing the database, dropping tables etc. Just put them into a module (like `shelltools`) and import from there: >>> from shelltools import * Flask-0.12.2/docs/tutorial/0000755000175000001440000000000013106517244016617 5ustar untitakerusers00000000000000Flask-0.12.2/docs/tutorial/css.rst0000644000175000001440000000237012765277142020155 0ustar untitakerusers00000000000000.. _tutorial-css: Step 8: Adding Style ==================== Now that everything else works, it's time to add some style to the application. Just create a stylesheet called :file:`style.css` in the :file:`static` folder: .. sourcecode:: css body { font-family: sans-serif; background: #eee; } a, h1, h2 { color: #377ba8; } h1, h2 { font-family: 'Georgia', serif; margin: 0; } h1 { border-bottom: 2px solid #eee; } h2 { font-size: 1.2em; } .page { margin: 2em auto; width: 35em; border: 5px solid #ccc; padding: 0.8em; background: white; } .entries { list-style: none; margin: 0; padding: 0; } .entries li { margin: 0.8em 1.2em; } .entries li h2 { margin-left: -1em; } .add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; } .add-entry dl { font-weight: bold; } .metanav { text-align: right; font-size: 0.8em; padding: 0.3em; margin-bottom: 1em; background: #fafafa; } .flash { background: #cee5F5; padding: 0.5em; border: 1px solid #aacbe2; } .error { background: #f0d6d6; padding: 0.5em; } Continue with :ref:`tutorial-testing`. Flask-0.12.2/docs/tutorial/dbcon.rst0000644000175000001440000000647712765277142020466 0ustar untitakerusers00000000000000.. _tutorial-dbcon: Step 4: Database Connections ---------------------------- You currently have a function for establishing a database connection with `connect_db`, but by itself, it is not particularly useful. Creating and closing database connections all the time is very inefficient, so you will need to keep it around for longer. Because database connections encapsulate a transaction, you will need to make sure that only one request at a time uses the connection. An elegant way to do this is by utilizing the *application context*. Flask provides two contexts: the *application context* and the *request context*. For the time being, all you have to know is that there are special variables that use these. For instance, the :data:`~flask.request` variable is the request object associated with the current request, whereas :data:`~flask.g` is a general purpose variable associated with the current application context. The tutorial will cover some more details of this later on. For the time being, all you have to know is that you can store information safely on the :data:`~flask.g` object. So when do you put it on there? To do that you can make a helper function. The first time the function is called, it will create a database connection for the current context, and successive calls will return the already established connection:: def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db Now you know how to connect, but how can you properly disconnect? For that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext` decorator. It's executed every time the application context tears down:: @app.teardown_appcontext def close_db(error): """Closes the database again at the end of the request.""" if hasattr(g, 'sqlite_db'): g.sqlite_db.close() Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called every time the app context tears down. What does this mean? Essentially, the app context is created before the request comes in and is destroyed (torn down) whenever the request finishes. A teardown can happen because of two reasons: either everything went well (the error parameter will be ``None``) or an exception happened, in which case the error is passed to the teardown function. Curious about what these contexts mean? Have a look at the :ref:`app-context` documentation to learn more. Continue to :ref:`tutorial-dbinit`. .. hint:: Where do I put this code? If you've been following along in this tutorial, you might be wondering where to put the code from this step and the next. A logical place is to group these module-level functions together, and put your new ``get_db`` and ``close_db`` functions below your existing ``connect_db`` function (following the tutorial line-by-line). If you need a moment to find your bearings, take a look at how the `example source`_ is organized. In Flask, you can put all of your application code into a single Python module. You don't have to, and if your app :ref:`grows larger `, it's a good idea not to. .. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/ Flask-0.12.2/docs/tutorial/introduction.rst0000644000175000001440000000254013106517205022070 0ustar untitakerusers00000000000000.. _tutorial-introduction: Introducing Flaskr ================== This tutorial will demonstrate a blogging application named Flaskr, but feel free to choose your own less Web-2.0-ish name ;) Essentially, it will do the following things: 1. Let the user sign in and out with credentials specified in the configuration. Only one user is supported. 2. When the user is logged in, they can add new entries to the page consisting of a text-only title and some HTML for the text. This HTML is not sanitized because we trust the user here. 3. The index page shows all entries so far in reverse chronological order (newest on top) and the user can add new ones from there if logged in. SQLite3 will be used directly for this application because it's good enough for an application of this size. For larger applications, however, it makes a lot of sense to use `SQLAlchemy`_, as it handles database connections in a more intelligent way, allowing you to target different relational databases at once and more. You might also want to consider one of the popular NoSQL databases if your data is more suited for those. Here a screenshot of the final application: .. image:: ../_static/flaskr.png :align: center :class: screenshot :alt: screenshot of the final application Continue with :ref:`tutorial-folders`. .. _SQLAlchemy: http://www.sqlalchemy.org/ Flask-0.12.2/docs/tutorial/packaging.rst0000644000175000001440000000732613047321000021270 0ustar untitakerusers00000000000000.. _tutorial-packaging: Step 3: Installing flaskr as a Package ====================================== Flask is now shipped with built-in support for `Click`_. Click provides Flask with enhanced and extensible command line utilities. Later in this tutorial you will see exactly how to extend the ``flask`` command line interface (CLI). A useful pattern to manage a Flask application is to install your app following the `Python Packaging Guide`_. Presently this involves creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the projects root directory. You also need to add an :file:`__init__.py` file to make the :file:`flaskr/flaskr` directory a package. After these changes, your code structure should be:: /flaskr /flaskr __init__.py /static /templates flaskr.py schema.sql setup.py MANIFEST.in The content of the ``setup.py`` file for ``flaskr`` is: .. sourcecode:: python from setuptools import setup setup( name='flaskr', packages=['flaskr'], include_package_data=True, install_requires=[ 'flask', ], ) When using setuptools, it is also necessary to specify any special files that should be included in your package (in the :file:`MANIFEST.in`). In this case, the static and templates directories need to be included, as well as the schema. Create the :file:`MANIFEST.in` and add the following lines:: graft flaskr/templates graft flaskr/static include flaskr/schema.sql To simplify locating the application, add the following import statement into this file, :file:`flaskr/__init__.py`: .. sourcecode:: python from .flaskr import app This import statement brings the application instance into the top-level of the application package. When it is time to run the application, the Flask development server needs the location of the app instance. This import statement simplifies the location process. Without it the export statement a few steps below would need to be ``export FLASK_APP=flaskr.flaskr``. At this point you should be able to install the application. As usual, it is recommended to install your Flask application within a `virtualenv`_. With that said, go ahead and install the application with:: pip install --editable . The above installation command assumes that it is run within the projects root directory, `flaskr/`. The `editable` flag allows editing source code without having to reinstall the Flask app each time you make changes. The flaskr app is now installed in your virtualenv (see output of ``pip freeze``). With that out of the way, you should be able to start up the application. Do this with the following commands:: export FLASK_APP=flaskr export FLASK_DEBUG=true flask run (In case you are on Windows you need to use `set` instead of `export`). The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger. *Never leave debug mode activated in a production system*, because it will allow users to execute code on the server! You will see a message telling you that server has started along with the address at which you can access it. When you head over to the server in your browser, you will get a 404 error because we don't have any views yet. That will be addressed a little later, but first, you should get the database working. .. admonition:: Externally Visible Server Want your server to be publicly available? Check out the :ref:`externally visible server ` section for more information. Continue with :ref:`tutorial-dbcon`. .. _Click: http://click.pocoo.org .. _Python Packaging Guide: https://packaging.python.org .. _virtualenv: https://virtualenv.pypa.io Flask-0.12.2/docs/tutorial/dbinit.rst0000644000175000001440000000604112765277163020640 0ustar untitakerusers00000000000000.. _tutorial-dbinit: Step 5: Creating The Database ============================= As outlined earlier, Flaskr is a database powered application, and more precisely, it is an application powered by a relational database system. Such systems need a schema that tells them how to store that information. Before starting the server for the first time, it's important to create that schema. Such a schema can be created by piping the ``schema.sql`` file into the `sqlite3` command as follows:: sqlite3 /tmp/flaskr.db < schema.sql The downside of this is that it requires the ``sqlite3`` command to be installed, which is not necessarily the case on every system. This also requires that you provide the path to the database, which can introduce errors. It's a good idea to add a function that initializes the database for you, to the application. To do this, you can create a function and hook it into a :command:`flask` command that initializes the database. For now just take a look at the code segment below. A good place to add this function, and command, is just below the `connect_db` function in :file:`flaskr.py`:: def init_db(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() @app.cli.command('initdb') def initdb_command(): """Initializes the database.""" init_db() print('Initialized the database.') The ``app.cli.command()`` decorator registers a new command with the :command:`flask` script. When the command executes, Flask will automatically create an application context which is bound to the right application. Within the function, you can then access :attr:`flask.g` and other things as you might expect. When the script ends, the application context tears down and the database connection is released. You will want to keep an actual function around that initializes the database, though, so that we can easily create databases in unit tests later on. (For more information see :ref:`testing`.) The :func:`~flask.Flask.open_resource` method of the application object is a convenient helper function that will open a resource that the application provides. This function opens a file from the resource location (the :file:`flaskr/flaskr` folder) and allows you to read from it. It is used in this example to execute a script on the database connection. The connection object provided by SQLite can give you a cursor object. On that cursor, there is a method to execute a complete script. Finally, you only have to commit the changes. SQLite3 and other transactional databases will not commit unless you explicitly tell it to. Now, it is possible to create a database with the :command:`flask` script:: flask initdb Initialized the database. .. admonition:: Troubleshooting If you get an exception later on stating that a table cannot be found, check that you did execute the ``initdb`` command and that your table names are correct (singular vs. plural, for example). Continue with :ref:`tutorial-views` Flask-0.12.2/docs/tutorial/schema.rst0000644000175000001440000000144612764262664020632 0ustar untitakerusers00000000000000.. _tutorial-schema: Step 1: Database Schema ======================= In this step, you will create the database schema. Only a single table is needed for this application and it will only support SQLite. All you need to do is put the following contents into a file named :file:`schema.sql` in the :file:`flaskr/flaskr` folder: .. sourcecode:: sql drop table if exists entries; create table entries ( id integer primary key autoincrement, title text not null, 'text' text not null ); This schema consists of a single table called ``entries``. Each row in this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an automatically incrementing integer and a primary key, the other two are strings that must not be null. Continue with :ref:`tutorial-setup`. Flask-0.12.2/docs/tutorial/setup.rst0000644000175000001440000000755612765277142020540 0ustar untitakerusers00000000000000.. _tutorial-setup: Step 2: Application Setup Code ============================== Now that the schema is in place, you can create the application module, :file:`flaskr.py`. This file should be placed inside of the :file:`flaskr/flaskr` folder. The first several lines of code in the application module are the needed import statements. After that there will be a few lines of configuration code. For small applications like ``flaskr``, it is possible to drop the configuration directly into the module. However, a cleaner solution is to create a separate ``.ini`` or ``.py`` file, load that, and import the values from there. Here are the import statements (in :file:`flaskr.py`):: # all the imports import os import sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash The next couple lines will create the actual application instance and initialize it with the config from the same file in :file:`flaskr.py`: .. sourcecode:: python app = Flask(__name__) # create the application instance :) app.config.from_object(__name__) # load config from this file , flaskr.py # Load default config and override config from an environment variable app.config.update(dict( DATABASE=os.path.join(app.root_path, 'flaskr.db'), SECRET_KEY='development key', USERNAME='admin', PASSWORD='default' )) app.config.from_envvar('FLASKR_SETTINGS', silent=True) The :class:`~flask.Config` object works similarly to a dictionary, so it can be updated with new values. .. admonition:: Database Path Operating systems know the concept of a current working directory for each process. Unfortunately, you cannot depend on this in web applications because you might have more than one application in the same process. For this reason the ``app.root_path`` attribute can be used to get the path to the application. Together with the ``os.path`` module, files can then easily be found. In this example, we place the database right next to it. For a real-world application, it's recommended to use :ref:`instance-folders` instead. Usually, it is a good idea to load a separate, environment-specific configuration file. Flask allows you to import multiple configurations and it will use the setting defined in the last import. This enables robust configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this. .. sourcecode:: python app.config.from_envvar('FLASKR_SETTINGS', silent=True) Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to a config file to be loaded. The silent switch just tells Flask to not complain if no such environment key is set. In addition to that, you can use the :meth:`~flask.Config.from_object` method on the config object and provide it with an import name of a module. Flask will then initialize the variable from that module. Note that in all cases, only variable names that are uppercase are considered. The ``SECRET_KEY`` is needed to keep the client-side sessions secure. Choose that key wisely and as hard to guess and complex as possible. Lastly, you will add a method that allows for easy connections to the specified database. This can be used to open a connection on request and also from the interactive Python shell or a script. This will come in handy later. You can create a simple database connection through SQLite and then tell it to use the :class:`sqlite3.Row` object to represent rows. This allows the rows to be treated as if they were dictionaries instead of tuples. .. sourcecode:: python def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv In the next section you will see how to run the application. Continue with :ref:`tutorial-packaging`. Flask-0.12.2/docs/tutorial/testing.rst0000644000175000001440000000560113106517205021025 0ustar untitakerusers00000000000000.. _tutorial-testing: Bonus: Testing the Application ============================== Now that you have finished the application and everything works as expected, it's probably not a bad idea to add automated tests to simplify modifications in the future. The application above is used as a basic example of how to perform unit testing in the :ref:`testing` section of the documentation. Go there to see how easy it is to test Flask applications. Adding tests to flaskr ---------------------- Assuming you have seen the :ref:`testing` section and have either written your own tests for ``flaskr`` or have followed along with the examples provided, you might be wondering about ways to organize the project. One possible and recommended project structure is:: flaskr/ flaskr/ __init__.py static/ templates/ tests/ test_flaskr.py setup.py MANIFEST.in For now go ahead a create the :file:`tests/` directory as well as the :file:`test_flaskr.py` file. Running the tests ----------------- At this point you can run the tests. Here ``pytest`` will be used. .. note:: Make sure that ``pytest`` is installed in the same virtualenv as flaskr. Otherwise ``pytest`` test will not be able to import the required components to test the application:: pip install -e . pip install pytest Run and watch the tests pass, within the top-level :file:`flaskr/` directory as:: py.test Testing + setuptools -------------------- One way to handle testing is to integrate it with ``setuptools``. Here that requires adding a couple of lines to the :file:`setup.py` file and creating a new file :file:`setup.cfg`. One benefit of running the tests this way is that you do not have to install ``pytest``. Go ahead and update the :file:`setup.py` file to contain:: from setuptools import setup setup( name='flaskr', packages=['flaskr'], include_package_data=True, install_requires=[ 'flask', ], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', ], ) Now create :file:`setup.cfg` in the project root (alongside :file:`setup.py`):: [aliases] test=pytest Now you can run:: python setup.py test This calls on the alias created in :file:`setup.cfg` which in turn runs ``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has been called. (Recall the `setup_requires` argument in :file:`setup.py`) Following the standard rules of test-discovery your tests will be found, run, and hopefully pass. This is one possible way to run and manage testing. Here ``pytest`` is used, but there are other options such as ``nose``. Integrating testing with ``setuptools`` is convenient because it is not necessary to actually download ``pytest`` or any other testing framework one might use. Flask-0.12.2/docs/tutorial/index.rst0000644000175000001440000000146012765277142020473 0ustar untitakerusers00000000000000.. _tutorial: Tutorial ======== You want to develop an application with Python and Flask? Here you have the chance to learn by example. In this tutorial, we will create a simple microblogging application. It only supports one user that can create text-only entries and there are no feeds or comments, but it still features everything you need to get started. We will use Flask and SQLite as a database (which comes out of the box with Python) so there is nothing else you need. If you want the full source code in advance or for comparison, check out the `example source`_. .. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/ .. toctree:: :maxdepth: 2 introduction folders schema setup packaging dbcon dbinit views templates css testing Flask-0.12.2/docs/tutorial/folders.rst0000644000175000001440000000174212765277163021030 0ustar untitakerusers00000000000000.. _tutorial-folders: Step 0: Creating The Folders ============================ Before getting started, you will need to create the folders needed for this application:: /flaskr /flaskr /static /templates The application will be installed and run as Python package. This is the recommended way to install and run Flask applications. You will see exactly how to run ``flaskr`` later on in this tutorial. For now go ahead and create the applications directory structure. In the next few steps you will be creating the database schema as well as the main module. As a quick side note, the files inside of the :file:`static` folder are available to users of the application via HTTP. This is the place where CSS and JavaScript files go. Inside the :file:`templates` folder, Flask will look for `Jinja2`_ templates. You will see examples of this later on. For now you should continue with :ref:`tutorial-schema`. .. _Jinja2: http://jinja.pocoo.org/ Flask-0.12.2/docs/tutorial/views.rst0000644000175000001440000001100012765277142020510 0ustar untitakerusers00000000000000.. _tutorial-views: Step 6: The View Functions ========================== Now that the database connections are working, you can start writing the view functions. You will need four of them: Show Entries ------------ This view shows all the entries stored in the database. It listens on the root of the application and will select title and text from the database. The one with the highest id (the newest entry) will be on top. The rows returned from the cursor look a bit like dictionaries because we are using the :class:`sqlite3.Row` row factory. The view function will pass the entries to the :file:`show_entries.html` template and return the rendered one:: @app.route('/') def show_entries(): db = get_db() cur = db.execute('select title, text from entries order by id desc') entries = cur.fetchall() return render_template('show_entries.html', entries=entries) Add New Entry ------------- This view lets the user add new entries if they are logged in. This only responds to ``POST`` requests; the actual form is shown on the `show_entries` page. If everything worked out well, it will :func:`~flask.flash` an information message to the next request and redirect back to the `show_entries` page:: @app.route('/add', methods=['POST']) def add_entry(): if not session.get('logged_in'): abort(401) db = get_db() db.execute('insert into entries (title, text) values (?, ?)', [request.form['title'], request.form['text']]) db.commit() flash('New entry was successfully posted') return redirect(url_for('show_entries')) Note that this view checks that the user is logged in (that is, if the `logged_in` key is present in the session and ``True``). .. admonition:: Security Note Be sure to use question marks when building SQL statements, as done in the example above. Otherwise, your app will be vulnerable to SQL injection when you use string formatting to build SQL statements. See :ref:`sqlite3` for more. Login and Logout ---------------- These functions are used to sign the user in and out. Login checks the username and password against the ones from the configuration and sets the `logged_in` key for the session. If the user logged in successfully, that key is set to ``True``, and the user is redirected back to the `show_entries` page. In addition, a message is flashed that informs the user that he or she was logged in successfully. If an error occurred, the template is notified about that, and the user is asked again:: @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != app.config['USERNAME']: error = 'Invalid username' elif request.form['password'] != app.config['PASSWORD']: error = 'Invalid password' else: session['logged_in'] = True flash('You were logged in') return redirect(url_for('show_entries')) return render_template('login.html', error=error) The `logout` function, on the other hand, removes that key from the session again. There is a neat trick here: if you use the :meth:`~dict.pop` method of the dict and pass a second parameter to it (the default), the method will delete the key from the dictionary if present or do nothing when that key is not in there. This is helpful because now it is not necessary to check if the user was logged in. :: @app.route('/logout') def logout(): session.pop('logged_in', None) flash('You were logged out') return redirect(url_for('show_entries')) .. admonition:: Security Note Passwords should never be stored in plain text in a production system. This tutorial uses plain text passwords for simplicity. If you plan to release a project based off this tutorial out into the world, passwords should be both `hashed and salted`_ before being stored in a database or file. Fortunately, there are Flask extensions for the purpose of hashing passwords and verifying passwords against hashes, so adding this functionality is fairly straight forward. There are also many general python libraries that can be used for hashing. You can find a list of recommended Flask extensions `here `_ Continue with :ref:`tutorial-templates`. .. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/ Flask-0.12.2/docs/tutorial/templates.rst0000644000175000001440000000722213106517205021347 0ustar untitakerusers00000000000000.. _tutorial-templates: Step 7: The Templates ===================== Now it is time to start working on the templates. As you may have noticed, if you make requests with the app running, you will get an exception that Flask cannot find the templates. The templates are using `Jinja2`_ syntax and have autoescaping enabled by default. This means that unless you mark a value in the code with :class:`~flask.Markup` or with the ``|safe`` filter in the template, Jinja2 will ensure that special characters such as ``<`` or ``>`` are escaped with their XML equivalents. We are also using template inheritance which makes it possible to reuse the layout of the website in all pages. Put the following templates into the :file:`templates` folder: .. _Jinja2: http://jinja.pocoo.org/docs/templates layout.html ----------- This template contains the HTML skeleton, the header and a link to log in (or log out if the user was already logged in). It also displays the flashed messages if there are any. The ``{% block body %}`` block can be replaced by a block of the same name (``body``) in a child template. The :class:`~flask.session` dict is available in the template as well and you can use that to check if the user is logged in or not. Note that in Jinja you can access missing attributes and items of objects / dicts which makes the following code work, even if there is no ``'logged_in'`` key in the session: .. sourcecode:: html+jinja Flaskr

Flaskr

{% if not session.logged_in %} log in {% else %} log out {% endif %}
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %} {% block body %}{% endblock %}
show_entries.html ----------------- This template extends the :file:`layout.html` template from above to display the messages. Note that the ``for`` loop iterates over the messages we passed in with the :func:`~flask.render_template` function. Notice that the form is configured to to submit to the `add_entry` view function and use ``POST`` as HTTP method: .. sourcecode:: html+jinja {% extends "layout.html" %} {% block body %} {% if session.logged_in %}
Title:
Text:
{% endif %}
    {% for entry in entries %}
  • {{ entry.title }}

    {{ entry.text|safe }} {% else %}
  • Unbelievable. No entries here so far {% endfor %}
{% endblock %} login.html ---------- This is the login template, which basically just displays a form to allow the user to login: .. sourcecode:: html+jinja {% extends "layout.html" %} {% block body %}

Login

{% if error %}

Error: {{ error }}{% endif %}

Username:
Password:
{% endblock %} Continue with :ref:`tutorial-css`. Flask-0.12.2/docs/_static/0000755000175000001440000000000013106517244016402 5ustar untitakerusers00000000000000Flask-0.12.2/docs/_static/logo-full.png0000644000175000001440000005050612163033661021014 0ustar untitakerusers00000000000000PNG  IHDR:AsBIT|d pHYs tEXtSoftwarewww.inkscape.org< IDATxwU+! @舡KI^HSQ:"UPAQ:*E "Mz Х$ə;w93ޛ;gΙ]gf^{sw (P@vWP@ Ĩ@ 1*P@mGA (P@1C;*5π-E])>*P@AwFf6pp>%xou (P@6O^>~ _U@ڄvd jf[ڪ 0^f6,gEu1lnf({жjmf٩f6)=af[/oAeF;7EPSJh˙ yѶ7">H7髄7 Y Q~ \,Nc3vJdH0AJƵ`v7x=gXU_ՠ b ْSTϋCl DpWGnOi.Y/z @g[T-2bdfkÁa5d4/u=+p8 x CeHLDx_(~$?cO?6/~! ʻ =-:^Cܜipm1Gʛ*̨@'#diV[Z-Mg&6(ľ+G3)Dǻ~hTmm`gL_ d,Qn?ق׎ht|"7!mV<= !sK]~pN$:ZeE3* w<1yYԴrx =`/T3spM[ZW{fhkvk \CXt 'Gڂ'21;٦3YH5clkBEa8 vS__CCgg{X»n@5x3; %%i{̊@M(X45fIiMs)H"eԒā`Ad}O3; Z&ʰ~Uf<Ψ@%|1]Y4Yor,므V鏅80"s01嵽8p]($߉{ Fr1H0:c3j 4='D}ݟ1M}2v2rP v^3l˘up5VM'31* TAw_-ACV7Y'x*hgsX#xIlȒc1^0Sl*di+x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:$^T'VGg7"sJM@ Q4UZ R(*$|GV,C=Hk ` $~X{͑4/gAs$?fMf3$VwDܱ[^ e&5 H?"&Ӽ)GRBIiޱvmvdIɩc8]:k5dڶ iC} N뱃faWt5 u3HT{+$8Q7 T1O@WbZqhx >uW&{$2+0&~zf/sޔ.w2MI_o2e]1j0썑&E=ƮQ23x,Ph:v)ަ&h0 b Vё@%Ü߳يB5LAD+"b_ ". {^Yu"[yQ۾Vh$ b<9DfCo˅R@V F (P(\H(P@ F (Pw5LIENDB`Flask-0.12.2/docs/_static/flask.png0000644000175000001440000002330512163033661020211 0ustar untitakerusers00000000000000PNG  IHDRn֕sBIT|d pHYs utEXtSoftwarewww.inkscape.org< IDATxweǿgSHB%HлP)& **XRDTE4! E !$gνwٽ}>s<9s<=3$p0!0 \͹uV@ ,/6a}f~Gؾp-7 HASm83bfw883 h<%S>}e.(@L3#Z@` , h<'E82L*sD:OXQs@6ȍIt`Wjaj^(<%4X`IC_I~ 707eyW@34OI%3;N;zYdmoKldf33[ =fM@EnV L,lC1~}}WG#w mfPbN{8!y@G4JOls Xc=r3تLsS[50~|*) T 5k$ڭCf_]rOiڠ] Ll[ĝH)W_^1h/CfP] GGLrX < <R}C R F)ym<9=y0:Of~`αűbfo#2ڌT#a>+uw"%{vVlZ-˱¾)e`wGl9P@ }!h:L Ǥ pb@-Bj`)rkf$u%tWyLݽHZe]KP^a}iX ܌]2=)3P38zk;\ w&CZEwKX+. 2=$$r^A3Soj>>4;P,Q\](`" GAZ \ \F. mf[v%?)1L$]B 3Orefp8z#fnh:Ɠ]_B̆Q[l<@" ;a%p p=z8e4_Fe `>nArߗI>;ӕzp1WV;pKcc;VL{3=kvyn(9G*ef}uSe軐S$HWJvH>$=fl x]+@Ouf6ϐ^@7L^G7Y3uLCR߁c!s)e(R`S2XL_JL $U!H}{EX;_Xd&lD9On ((_"HAqNl244\VuIQlH- <EC[1PP~D벵:q qQ*oPx8v73̬62,Q >8\d'5X9jAdrܠ taFVM6}=3ND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"A.)uKd P|p>_FuOɺl!en:@<)X#}I܅QXn2)pK-%qAHXDgޘlʋB].Ltd.Dol?`m 3,Մl`,. 6vJzB=0zOrsڗ^wŽ<.Q-r 4}sw*A&~?Z[[c6]v食ֶ &ځLMG?bͰ `wg03J ~&7 R3j7J"(@ PI(Q*PVqRhгrOϓL&!47n  f02tZնi^(N)Cnֹ P[`:@T I][ ~΍F}gg:QahcJ;NCk_N9.#eE\rY\xӾg5 B E>7Ee5=+(@ P$pJ-}җkN >ak =( h *^lįS7(@ 츀N黥%wa\~Ǐ8yNgYQ`{Jvk%zu6(@ P`䐺pJ]&YrHoիWyNgnzR[_A'86(@ PB0e8eVf(@ P  N R:ms P(tF4G8er]oh"hooiATWWS(@ GCC77Y|2%围\̕ &fSIENDB`Flask-0.12.2/docs/_static/flaskr.png0000644000175000001440000015050312163033661020374 0ustar untitakerusers00000000000000PNG  IHDR\GIiCCPICC ProfilexYgXKKNK99GXsAI $EQA$""fAIQD2A|~wyywZ !!j"¬  `H10r? }߿ @ ׯnɃb?]B~ X%,o 1;ã` (h://_}6Z !L@ n88 t_8X?q # ctM7{D61ǧ/9@w0pWcqlv %AɡQj(uBQ,@%RDi4P*N iس9l* U,6/1>@'8$6'K ޹b\FAD 1.)i gկ\_##l烷C߃ ?2Ax߫pK8@PfxeI'^=)9+R#ҴˈeJd^8(нCdEe=eKeəʝەW!pQ"bbZI[)QUiSY^9BQJʼ)55Zڸ:eq n FƤ&f朖Vֲv]ue:H]t=Z=[bO~A3GG_{NX';*#zG8999*x46W*Wm7[PAXs7rB!xhzy,xyzyyz{y^[Яo~}@C I[`KmPw0GpLPhHZxrh~JIXU8~4^=|8<9Um};&&(?V$L\~ccc]Iǵ'@ ]3' NT''K%&HOʞz"uɺ4ʴTNF==pЙ3{O32.dd3>[xv׹,lLvP\ܸܩ~? {WY0^x^_QvNO풆l\\qiTF{YFe ʛ**.Tb**g]齪x*jZеjZڬ:D]dBsun(o7d7#o~vMIcm7߹xnz۴<~PqK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///000111555666999:::;;;>>>???@@@BBBCCCEEEFFFGGGHHHIIIJJJLLLMMMNNNRRRSSSTTTUUUVVVWWWXXXZZZ[[[\\\^^^```aaabbbcccdddeeefffgggkkklllmmmoooqqqssstttyyyzzz|||}}}~yV;GD*! %6d~}ieE# !^U/+0HF^zB )TYlNhNb5QB2L4(9X];T: 3}Ps>.Vg: Ex^B q3"[cXZ,R1d8N tjuMaY'?wzO\S`!qkXfob&m=@47K$pr@Flask-0.12.2/docs/flaskstyle.sty0000644000175000001440000000604212163033661017676 0ustar untitakerusers00000000000000\definecolor{TitleColor}{rgb}{0,0,0} \definecolor{InnerLinkColor}{rgb}{0,0,0} \renewcommand{\maketitle}{% \begin{titlepage}% \let\footnotesize\small \let\footnoterule\relax \ifsphinxpdfoutput \begingroup % This \def is required to deal with multi-line authors; it % changes \\ to ', ' (comma-space), making it pass muster for % generating document info in the PDF file. \def\\{, } \pdfinfo{ /Author (\@author) /Title (\@title) } \endgroup \fi \begin{flushright}% %\sphinxlogo% {\center \vspace*{3cm} \includegraphics{logo.pdf} \vspace{3cm} \par {\rm\Huge \@title \par}% {\em\LARGE \py@release\releaseinfo \par} {\large \@date \par \py@authoraddress \par }}% \end{flushright}%\par \@thanks \end{titlepage}% \cleardoublepage% \setcounter{footnote}{0}% \let\thanks\relax\let\maketitle\relax %\gdef\@thanks{}\gdef\@author{}\gdef\@title{} } \fancypagestyle{normal}{ \fancyhf{} \fancyfoot[LE,RO]{{\thepage}} \fancyfoot[LO]{{\nouppercase{\rightmark}}} \fancyfoot[RE]{{\nouppercase{\leftmark}}} \fancyhead[LE,RO]{{ \@title, \py@release}} \renewcommand{\headrulewidth}{0.4pt} \renewcommand{\footrulewidth}{0.4pt} } \fancypagestyle{plain}{ \fancyhf{} \fancyfoot[LE,RO]{{\thepage}} \renewcommand{\headrulewidth}{0pt} \renewcommand{\footrulewidth}{0.4pt} } \titleformat{\section}{\Large}% {\py@TitleColor\thesection}{0.5em}{\py@TitleColor}{\py@NormalColor} \titleformat{\subsection}{\large}% {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} \titleformat{\subsubsection}{}% {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} \titleformat{\paragraph}{\large}% {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor} \ChNameVar{\raggedleft\normalsize} \ChNumVar{\raggedleft \bfseries\Large} \ChTitleVar{\raggedleft \rm\Huge} \renewcommand\thepart{\@Roman\c@part} \renewcommand\part{% \pagestyle{plain} \if@noskipsec \leavevmode \fi \cleardoublepage \vspace*{6cm}% \@afterindentfalse \secdef\@part\@spart} \def\@part[#1]#2{% \ifnum \c@secnumdepth >\m@ne \refstepcounter{part}% \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}% \else \addcontentsline{toc}{part}{#1}% \fi {\parindent \z@ %\center \interlinepenalty \@M \normalfont \ifnum \c@secnumdepth >\m@ne \rm\Large \partname~\thepart \par\nobreak \fi \MakeUppercase{\rm\Huge #2}% \markboth{}{}\par}% \nobreak \vskip 8ex \@afterheading} \def\@spart#1{% {\parindent \z@ %\center \interlinepenalty \@M \normalfont \huge \bfseries #1\par}% \nobreak \vskip 3ex \@afterheading} % use inconsolata font \usepackage{inconsolata} % fix single quotes, for inconsolata. (does not work) %%\usepackage{textcomp} %%\begingroup %% \catcode`'=\active %% \g@addto@macro\@noligs{\let'\textsinglequote} %% \endgroup %%\endinput Flask-0.12.2/docs/signals.rst0000644000175000001440000001566412763616450017171 0ustar untitakerusers00000000000000.. _signals: Signals ======= .. versionadded:: 0.6 Starting with Flask 0.6, there is integrated support for signalling in Flask. This support is provided by the excellent `blinker`_ library and will gracefully fall back if it is not available. What are signals? Signals help you decouple applications by sending notifications when actions occur elsewhere in the core framework or another Flask extensions. In short, signals allow certain senders to notify subscribers that something happened. Flask comes with a couple of signals and other extensions might provide more. Also keep in mind that signals are intended to notify subscribers and should not encourage subscribers to modify data. You will notice that there are signals that appear to do the same thing like some of the builtin decorators do (eg: :data:`~flask.request_started` is very similar to :meth:`~flask.Flask.before_request`). However, there are differences in how they work. The core :meth:`~flask.Flask.before_request` handler, for example, is executed in a specific order and is able to abort the request early by returning a response. In contrast all signal handlers are executed in undefined order and do not modify any data. The big advantage of signals over handlers is that you can safely subscribe to them for just a split second. These temporary subscriptions are helpful for unittesting for example. Say you want to know what templates were rendered as part of a request: signals allow you to do exactly that. Subscribing to Signals ---------------------- To subscribe to a signal, you can use the :meth:`~blinker.base.Signal.connect` method of a signal. The first argument is the function that should be called when the signal is emitted, the optional second argument specifies a sender. To unsubscribe from a signal, you can use the :meth:`~blinker.base.Signal.disconnect` method. For all core Flask signals, the sender is the application that issued the signal. When you subscribe to a signal, be sure to also provide a sender unless you really want to listen for signals from all applications. This is especially true if you are developing an extension. For example, here is a helper context manager that can be used in a unittest to determine which templates were rendered and what variables were passed to the template:: from flask import template_rendered from contextlib import contextmanager @contextmanager def captured_templates(app): recorded = [] def record(sender, template, context, **extra): recorded.append((template, context)) template_rendered.connect(record, app) try: yield recorded finally: template_rendered.disconnect(record, app) This can now easily be paired with a test client:: with captured_templates(app) as templates: rv = app.test_client().get('/') assert rv.status_code == 200 assert len(templates) == 1 template, context = templates[0] assert template.name == 'index.html' assert len(context['items']) == 10 Make sure to subscribe with an extra ``**extra`` argument so that your calls don't fail if Flask introduces new arguments to the signals. All the template rendering in the code issued by the application `app` in the body of the ``with`` block will now be recorded in the `templates` variable. Whenever a template is rendered, the template object as well as context are appended to it. Additionally there is a convenient helper method (:meth:`~blinker.base.Signal.connected_to`) that allows you to temporarily subscribe a function to a signal with a context manager on its own. Because the return value of the context manager cannot be specified that way, you have to pass the list in as an argument:: from flask import template_rendered def captured_templates(app, recorded, **extra): def record(sender, template, context): recorded.append((template, context)) return template_rendered.connected_to(record, app) The example above would then look like this:: templates = [] with captured_templates(app, templates, **extra): ... template, context = templates[0] .. admonition:: Blinker API Changes The :meth:`~blinker.base.Signal.connected_to` method arrived in Blinker with version 1.1. Creating Signals ---------------- If you want to use signals in your own application, you can use the blinker library directly. The most common use case are named signals in a custom :class:`~blinker.base.Namespace`.. This is what is recommended most of the time:: from blinker import Namespace my_signals = Namespace() Now you can create new signals like this:: model_saved = my_signals.signal('model-saved') The name for the signal here makes it unique and also simplifies debugging. You can access the name of the signal with the :attr:`~blinker.base.NamedSignal.name` attribute. .. admonition:: For Extension Developers If you are writing a Flask extension and you want to gracefully degrade for missing blinker installations, you can do so by using the :class:`flask.signals.Namespace` class. .. _signals-sending: Sending Signals --------------- If you want to emit a signal, you can do so by calling the :meth:`~blinker.base.Signal.send` method. It accepts a sender as first argument and optionally some keyword arguments that are forwarded to the signal subscribers:: class Model(object): ... def save(self): model_saved.send(self) Try to always pick a good sender. If you have a class that is emitting a signal, pass ``self`` as sender. If you are emitting a signal from a random function, you can pass ``current_app._get_current_object()`` as sender. .. admonition:: Passing Proxies as Senders Never pass :data:`~flask.current_app` as sender to a signal. Use ``current_app._get_current_object()`` instead. The reason for this is that :data:`~flask.current_app` is a proxy and not the real application object. Signals and Flask's Request Context ----------------------------------- Signals fully support :ref:`request-context` when receiving signals. Context-local variables are consistently available between :data:`~flask.request_started` and :data:`~flask.request_finished`, so you can rely on :class:`flask.g` and others as needed. Note the limitations described in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal. Decorator Based Signal Subscriptions ------------------------------------ With Blinker 1.1 you can also easily subscribe to signals by using the new :meth:`~blinker.base.NamedSignal.connect_via` decorator:: from flask import template_rendered @template_rendered.connect_via(app) def when_template_rendered(sender, template, context, **extra): print 'Template %s is rendered with %s' % (template.name, context) Core Signals ------------ Take a look at :ref:`core-signals-list` for a list of all builtin signals. .. _blinker: https://pypi.python.org/pypi/blinker Flask-0.12.2/docs/cli.rst0000644000175000001440000002127713106517205016263 0ustar untitakerusers00000000000000.. _cli: Command Line Interface ====================== .. versionadded:: 0.11 .. currentmodule:: flask One of the nice new features in Flask 0.11 is the built-in integration of the `click `_ command line interface. This enables a wide range of new features for the Flask ecosystem and your own applications. Basic Usage ----------- After installation of Flask you will now find a :command:`flask` script installed into your virtualenv. If you don't want to install Flask or you have a special use-case you can also use ``python -m flask`` to accomplish exactly the same. The way this script works is by providing access to all the commands on your Flask application's :attr:`Flask.cli` instance as well as some built-in commands that are always there. Flask extensions can also register more commands there if they desire so. For the :command:`flask` script to work, an application needs to be discovered. This is achieved by exporting the ``FLASK_APP`` environment variable. It can be either set to an import path or to a filename of a Python module that contains a Flask application. In that imported file the name of the app needs to be called ``app`` or optionally be specified after a colon. For instance ``mymodule:application`` would tell it to use the `application` object in the :file:`mymodule.py` file. Given a :file:`hello.py` file with the application in it named ``app`` this is how it can be run. Environment variables (On Windows use ``set`` instead of ``export``):: export FLASK_APP=hello flask run Or with a filename:: export FLASK_APP=/path/to/hello.py flask run Virtualenv Integration ---------------------- If you are constantly working with a virtualenv you can also put the ``export FLASK_APP`` into your ``activate`` script by adding it to the bottom of the file. That way every time you activate your virtualenv you automatically also activate the correct application name. Debug Flag ---------- The :command:`flask` script can also be instructed to enable the debug mode of the application automatically by exporting ``FLASK_DEBUG``. If set to ``1`` debug is enabled or ``0`` disables it:: export FLASK_DEBUG=1 Running a Shell --------------- To run an interactive Python shell you can use the ``shell`` command:: flask shell This will start up an interactive Python shell, setup the correct application context and setup the local variables in the shell. This is done by invoking the :meth:`Flask.make_shell_context` method of the application. By default you have access to your ``app`` and :data:`g`. Custom Commands --------------- If you want to add more commands to the shell script you can do this easily. Flask uses `click`_ for the command interface which makes creating custom commands very easy. For instance if you want a shell command to initialize the database you can do this:: import click from flask import Flask app = Flask(__name__) @app.cli.command() def initdb(): """Initialize the database.""" click.echo('Init the db') The command will then show up on the command line:: $ flask initdb Init the db Application Context ------------------- Most commands operate on the application so it makes a lot of sense if they have the application context setup. Because of this, if you register a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the callback will automatically be wrapped through :func:`cli.with_appcontext` which informs the cli system to ensure that an application context is set up. This behavior is not available if a command is added later with :func:`~click.Group.add_command` or through other means. It can also be disabled by passing ``with_appcontext=False`` to the decorator:: @app.cli.command(with_appcontext=False) def example(): pass Factory Functions ----------------- In case you are using factory functions to create your application (see :ref:`app-factories`) you will discover that the :command:`flask` command cannot work with them directly. Flask won't be able to figure out how to instantiate your application properly by itself. Because of this reason the recommendation is to create a separate file that instantiates applications. This is not the only way to make this work. Another is the :ref:`custom-scripts` support. For instance if you have a factory function that creates an application from a filename you could make a separate file that creates such an application from an environment variable. This could be a file named :file:`autoapp.py` with these contents:: import os from yourapplication import create_app app = create_app(os.environ['YOURAPPLICATION_CONFIG']) Once this has happened you can make the :command:`flask` command automatically pick it up:: export YOURAPPLICATION_CONFIG=/path/to/config.cfg export FLASK_APP=/path/to/autoapp.py From this point onwards :command:`flask` will find your application. .. _custom-scripts: Custom Scripts -------------- While the most common way is to use the :command:`flask` command, you can also make your own "driver scripts". Since Flask uses click for the scripts there is no reason you cannot hook these scripts into any click application. There is one big caveat and that is, that commands registered to :attr:`Flask.cli` will expect to be (indirectly at least) launched from a :class:`flask.cli.FlaskGroup` click group. This is necessary so that the commands know which Flask application they have to work with. To understand why you might want custom scripts you need to understand how click finds and executes the Flask application. If you use the :command:`flask` script you specify the application to work with on the command line or environment variable as an import name. This is simple but it has some limitations. Primarily it does not work with application factory functions (see :ref:`app-factories`). With a custom script you don't have this problem as you can fully customize how the application will be created. This is very useful if you write reusable applications that you want to ship to users and they should be presented with a custom management script. To explain all of this, here is an example :file:`manage.py` script that manages a hypothetical wiki application. We will go through the details afterwards:: import os import click from flask.cli import FlaskGroup def create_wiki_app(info): from yourwiki import create_app return create_app( config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py')) @click.group(cls=FlaskGroup, create_app=create_wiki_app) def cli(): """This is a management script for the wiki application.""" if __name__ == '__main__': cli() That's a lot of code for not much, so let's go through all parts step by step. 1. First we import the ``click`` library as well as the click extensions from the ``flask.cli`` package. Primarily we are here interested in the :class:`~flask.cli.FlaskGroup` click group. 2. The next thing we do is defining a function that is invoked with the script info object (:class:`~flask.cli.ScriptInfo`) from Flask and its purpose is to fully import and create the application. This can either directly import an application object or create it (see :ref:`app-factories`). In this case we load the config from an environment variable. 3. Next step is to create a :class:`FlaskGroup`. In this case we just make an empty function with a help doc string that just does nothing and then pass the ``create_wiki_app`` function as a factory function. Whenever click now needs to operate on a Flask application it will call that function with the script info and ask for it to be created. 4. All is rounded up by invoking the script. CLI Plugins ----------- Flask extensions can always patch the :attr:`Flask.cli` instance with more commands if they want. However there is a second way to add CLI plugins to Flask which is through ``setuptools``. If you make a Python package that should export a Flask command line plugin you can ship a :file:`setup.py` file that declares an entrypoint that points to a click command: Example :file:`setup.py`:: from setuptools import setup setup( name='flask-my-extension', ... entry_points=''' [flask.commands] my-command=mypackage.commands:cli ''', ) Inside :file:`mypackage/commands.py` you can then export a Click object:: import click @click.command() def cli(): """This is an example command.""" Once that package is installed in the same virtualenv as Flask itself you can run ``flask my-command`` to invoke your command. This is useful to provide extra functionality that Flask itself cannot ship. Flask-0.12.2/docs/reqcontext.rst0000644000175000001440000002175612763616450017724 0ustar untitakerusers00000000000000.. _request-context: The Request Context =================== This document describes the behavior in Flask 0.7 which is mostly in line with the old behavior but has some small, subtle differences. It is recommended that you read the :ref:`app-context` chapter first. Diving into Context Locals -------------------------- Say you have a utility function that returns the URL the user should be redirected to. Imagine it would always redirect to the URL's ``next`` parameter or the HTTP referrer or the index page:: from flask import request, url_for def redirect_url(): return request.args.get('next') or \ request.referrer or \ url_for('index') As you can see, it accesses the request object. If you try to run this from a plain Python shell, this is the exception you will see: >>> redirect_url() Traceback (most recent call last): File "", line 1, in AttributeError: 'NoneType' object has no attribute 'request' That makes a lot of sense because we currently do not have a request we could access. So we have to make a request and bind it to the current context. The :attr:`~flask.Flask.test_request_context` method can create us a :class:`~flask.ctx.RequestContext`: >>> ctx = app.test_request_context('/?next=http://example.com/') This context can be used in two ways. Either with the ``with`` statement or by calling the :meth:`~flask.ctx.RequestContext.push` and :meth:`~flask.ctx.RequestContext.pop` methods: >>> ctx.push() From that point onwards you can work with the request object: >>> redirect_url() u'http://example.com/' Until you call `pop`: >>> ctx.pop() Because the request context is internally maintained as a stack you can push and pop multiple times. This is very handy to implement things like internal redirects. For more information of how to utilize the request context from the interactive Python shell, head over to the :ref:`shell` chapter. How the Context Works --------------------- If you look into how the Flask WSGI application internally works, you will find a piece of code that looks very much like this:: def wsgi_app(self, environ): with self.request_context(environ): try: response = self.full_dispatch_request() except Exception as e: response = self.make_response(self.handle_exception(e)) return response(environ, start_response) The method :meth:`~Flask.request_context` returns a new :class:`~flask.ctx.RequestContext` object and uses it in combination with the ``with`` statement to bind the context. Everything that is called from the same thread from this point onwards until the end of the ``with`` statement will have access to the request globals (:data:`flask.request` and others). The request context internally works like a stack: The topmost level on the stack is the current active request. :meth:`~flask.ctx.RequestContext.push` adds the context to the stack on the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the stack again. On popping the application's :func:`~flask.Flask.teardown_request` functions are also executed. Another thing of note is that the request context will automatically also create an :ref:`application context ` when it's pushed and there is no application context for that application so far. .. _callbacks-and-errors: Callbacks and Errors -------------------- What happens if an error occurs in Flask during request processing? This particular behavior changed in 0.7 because we wanted to make it easier to understand what is actually happening. The new behavior is quite simple: 1. Before each request, :meth:`~flask.Flask.before_request` functions are executed. If one of these functions return a response, the other functions are no longer called. In any case however the return value is treated as a replacement for the view's return value. 2. If the :meth:`~flask.Flask.before_request` functions did not return a response, the regular request handling kicks in and the view function that was matched has the chance to return a response. 3. The return value of the view is then converted into an actual response object and handed over to the :meth:`~flask.Flask.after_request` functions which have the chance to replace it or modify it in place. 4. At the end of the request the :meth:`~flask.Flask.teardown_request` functions are executed. This always happens, even in case of an unhandled exception down the road or if a before-request handler was not executed yet or at all (for example in test environments sometimes you might want to not execute before-request callbacks). Now what happens on errors? In production mode if an exception is not caught, the 500 internal server handler is called. In development mode however the exception is not further processed and bubbles up to the WSGI server. That way things like the interactive debugger can provide helpful debug information. An important change in 0.7 is that the internal server error is now no longer post processed by the after request callbacks and after request callbacks are no longer guaranteed to be executed. This way the internal dispatching code looks cleaner and is easier to customize and understand. The new teardown functions are supposed to be used as a replacement for things that absolutely need to happen at the end of request. Teardown Callbacks ------------------ The teardown callbacks are special callbacks in that they are executed at a different point. Strictly speaking they are independent of the actual request handling as they are bound to the lifecycle of the :class:`~flask.ctx.RequestContext` object. When the request context is popped, the :meth:`~flask.Flask.teardown_request` functions are called. This is important to know if the life of the request context is prolonged by using the test client in a with statement or when using the request context from the command line:: with app.test_client() as client: resp = client.get('/foo') # the teardown functions are still not called at that point # even though the response ended and you have the response # object in your hand # only when the code reaches this point the teardown functions # are called. Alternatively the same thing happens if another # request was triggered from the test client It's easy to see the behavior from the command line: >>> app = Flask(__name__) >>> @app.teardown_request ... def teardown_request(exception=None): ... print 'this runs after request' ... >>> ctx = app.test_request_context() >>> ctx.push() >>> ctx.pop() this runs after request >>> Keep in mind that teardown callbacks are always executed, even if before-request callbacks were not executed yet but an exception happened. Certain parts of the test system might also temporarily create a request context without calling the before-request handlers. Make sure to write your teardown-request handlers in a way that they will never fail. .. _notes-on-proxies: Notes On Proxies ---------------- Some of the objects provided by Flask are proxies to other objects. The reason behind this is that these proxies are shared between threads and they have to dispatch to the actual object bound to a thread behind the scenes as necessary. Most of the time you don't have to care about that, but there are some exceptions where it is good to know that this object is an actual proxy: - The proxy objects do not fake their inherited types, so if you want to perform actual instance checks, you have to do that on the instance that is being proxied (see `_get_current_object` below). - if the object reference is important (so for example for sending :ref:`signals`) If you need to get access to the underlying object that is proxied, you can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method:: app = current_app._get_current_object() my_signal.send(app) Context Preservation on Error ----------------------------- If an error occurs or not, at the end of the request the request context is popped and all data associated with it is destroyed. During development however that can be problematic as you might want to have the information around for a longer time in case an exception occurred. In Flask 0.6 and earlier in debug mode, if an exception occurred, the request context was not popped so that the interactive debugger can still provide you with important information. Starting with Flask 0.7 you have finer control over that behavior by setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By default it's linked to the setting of ``DEBUG``. If the application is in debug mode the context is preserved, in production mode it's not. Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode as it will cause your application to leak memory on exceptions. However it can be useful during development to get the same error preserving behavior as in development mode when attempting to debug an error that only occurs under production settings. Flask-0.12.2/docs/latexindex.rst0000644000175000001440000000012112500054716017642 0ustar untitakerusers00000000000000:orphan: Flask Documentation =================== .. include:: contents.rst.inc Flask-0.12.2/docs/contents.rst.inc0000644000175000001440000000172212763616450020124 0ustar untitakerusers00000000000000User's Guide ------------ This part of the documentation, which is mostly prose, begins with some background information about Flask, then focuses on step-by-step instructions for web development with Flask. .. toctree:: :maxdepth: 2 foreword advanced_foreword installation quickstart tutorial/index templating testing errorhandling config signals views appcontext reqcontext blueprints extensions cli server shell patterns/index deploying/index becomingbig API Reference ------------- If you are looking for information on a specific function, class or method, this part of the documentation is for you. .. toctree:: :maxdepth: 2 api Additional Notes ---------------- Design notes, legal information and changelog are here for the interested. .. toctree:: :maxdepth: 2 design htmlfaq security unicode extensiondev styleguide python3 upgrading changelog license Flask-0.12.2/docs/foreword.rst0000644000175000001440000000536712763616450017357 0ustar untitakerusers00000000000000Foreword ======== Read this before you get started with Flask. This hopefully answers some questions about the purpose and goals of the project, and when you should or should not be using it. What does "micro" mean? ----------------------- “Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The "micro" in microframework means Flask aims to keep the core simple but extensible. Flask won't make many decisions for you, such as what database to use. Those decisions that it does make, such as what templating engine to use, are easy to change. Everything else is up to you, so that Flask can be everything you need and nothing you don't. By default, Flask does not include a database abstraction layer, form validation or anything else where different libraries already exist that can handle that. Instead, Flask supports extensions to add such functionality to your application as if it was implemented in Flask itself. Numerous extensions provide database integration, form validation, upload handling, various open authentication technologies, and more. Flask may be "micro", but it's ready for production use on a variety of needs. Configuration and Conventions ----------------------------- Flask has many configuration values, with sensible defaults, and a few conventions when getting started. By convention, templates and static files are stored in subdirectories within the application's Python source tree, with the names :file:`templates` and :file:`static` respectively. While this can be changed, you usually don't have to, especially when getting started. Growing with Flask ------------------ Once you have Flask up and running, you'll find a variety of extensions available in the community to integrate your project for production. The Flask core team reviews extensions and ensures approved extensions do not break with future releases. As your codebase grows, you are free to make the design decisions appropriate for your project. Flask will continue to provide a very simple glue layer to the best that Python has to offer. You can implement advanced patterns in SQLAlchemy or another database tool, introduce non-relational data persistence as appropriate, and take advantage of framework-agnostic tools built for WSGI, the Python web interface. Flask includes many hooks to customize its behavior. Should you need more customization, the Flask class is built for subclassing. If you are interested in that, check out the :ref:`becomingbig` chapter. If you are curious about the Flask design principles, head over to the section about :ref:`design`. Continue to :ref:`installation`, the :ref:`quickstart`, or the :ref:`advanced_foreword`. Flask-0.12.2/docs/api.rst0000644000175000001440000006562413106517205016271 0ustar untitakerusers00000000000000.. _api: API === .. module:: flask This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation. Application Object ------------------ .. autoclass:: Flask :members: :inherited-members: Blueprint Objects ----------------- .. autoclass:: Blueprint :members: :inherited-members: Incoming Request Data --------------------- .. autoclass:: Request :members: .. attribute:: form A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST`` or ``PUT`` requests. Please keep in mind that file uploads will not end up here, but instead in the :attr:`files` attribute. .. attribute:: args A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query string. (The part in the URL after the question mark). .. attribute:: values A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both :attr:`form` and :attr:`args`. .. attribute:: cookies A :class:`dict` with the contents of all cookies transmitted with the request. .. attribute:: stream If the incoming form data was not encoded with a known mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use :attr:`data` which will give you that data as a string. The stream only returns the data once. .. attribute:: headers The incoming request headers as a dictionary like object. .. attribute:: data Contains the incoming request data as string in case it came with a mimetype Flask does not handle. .. attribute:: files A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a ``POST`` or ``PUT`` request. Each file is stored as :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a standard file object you know from Python, with the difference that it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can store the file on the filesystem. .. attribute:: environ The underlying WSGI environment. .. attribute:: method The current request method (``POST``, ``GET`` etc.) .. attribute:: path .. attribute:: full_path .. attribute:: script_root .. attribute:: url .. attribute:: base_url .. attribute:: url_root Provides different ways to look at the current `IRI `_. Imagine your application is listening on the following application root:: http://www.example.com/myapplication And a user requests the following URI:: http://www.example.com/myapplication/%CF%80/page.html?x=y In this case the values of the above mentioned attributes would be the following: ============= ====================================================== `path` ``u'/π/page.html'`` `full_path` ``u'/π/page.html?x=y'`` `script_root` ``u'/myapplication'`` `base_url` ``u'http://www.example.com/myapplication/π/page.html'`` `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'`` `url_root` ``u'http://www.example.com/myapplication/'`` ============= ====================================================== .. attribute:: is_xhr ``True`` if the request was triggered via a JavaScript `XMLHttpRequest`. This only works with libraries that support the ``X-Requested-With`` header and set it to `XMLHttpRequest`. Libraries that do that are prototype, jQuery and Mochikit and probably some more. .. class:: request To access incoming request data, you can use the global `request` object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment. This is a proxy. See :ref:`notes-on-proxies` for more information. The request object is an instance of a :class:`~werkzeug.wrappers.Request` subclass and provides all of the attributes Werkzeug defines. This just shows a quick overview of the most important ones. Response Objects ---------------- .. autoclass:: flask.Response :members: set_cookie, data, mimetype .. attribute:: headers A :class:`~werkzeug.datastructures.Headers` object representing the response headers. .. attribute:: status A string with a response status. .. attribute:: status_code The response status as integer. Sessions -------- If you have the :attr:`Flask.secret_key` set you can use sessions in Flask applications. A session basically makes it possible to remember information from one request to another. The way Flask does this is by using a signed cookie. So the user can look at the session contents, but not modify it unless they know the secret key, so make sure to set that to something complex and unguessable. To access the current session you can use the :class:`session` object: .. class:: session The session object works pretty much like an ordinary dict, with the difference that it keeps track on modifications. This is a proxy. See :ref:`notes-on-proxies` for more information. The following attributes are interesting: .. attribute:: new ``True`` if the session is new, ``False`` otherwise. .. attribute:: modified ``True`` if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the attribute to ``True`` yourself. Here an example:: # this change is not picked up because a mutable object (here # a list) is changed. session['objects'].append(42) # so mark it as modified yourself session.modified = True .. attribute:: permanent If set to ``True`` the session lives for :attr:`~flask.Flask.permanent_session_lifetime` seconds. The default is 31 days. If set to ``False`` (which is the default) the session will be deleted when the user closes the browser. Session Interface ----------------- .. versionadded:: 0.8 The session interface provides a simple way to replace the session implementation that Flask is using. .. currentmodule:: flask.sessions .. autoclass:: SessionInterface :members: .. autoclass:: SecureCookieSessionInterface :members: .. autoclass:: SecureCookieSession :members: .. autoclass:: NullSession :members: .. autoclass:: SessionMixin :members: .. autodata:: session_json_serializer This object provides dumping and loading methods similar to simplejson but it also tags certain builtin Python objects that commonly appear in sessions. Currently the following extended values are supported in the JSON it dumps: - :class:`~markupsafe.Markup` objects - :class:`~uuid.UUID` objects - :class:`~datetime.datetime` objects - :class:`tuple`\s .. admonition:: Notice The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer starting with Flask 0.8. Either catch this down yourself or use the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the app which converts the result to an integer automatically. Test Client ----------- .. currentmodule:: flask.testing .. autoclass:: FlaskClient :members: Application Globals ------------------- .. currentmodule:: flask To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. In a nutshell: it does the right thing, like it does for :class:`request` and :class:`session`. .. data:: g Just store on this whatever you want. For example a database connection or the user that is currently logged in. Starting with Flask 0.10 this is stored on the application context and no longer on the request context which means it becomes available if only the application context is bound and not yet a request. This is especially useful when combined with the :ref:`faking-resources` pattern for testing. Additionally as of 0.10 you can use the :meth:`get` method to get an attribute or ``None`` (or the second argument) if it's not set. These two usages are now equivalent:: user = getattr(flask.g, 'user', None) user = flask.g.get('user', None) It's now also possible to use the ``in`` operator on it to see if an attribute is defined and it yields all keys on iteration. As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same way you would use them on a dictionary. This is a proxy. See :ref:`notes-on-proxies` for more information. Useful Functions and Classes ---------------------------- .. data:: current_app Points to the application handling the request. This is useful for extensions that want to support multiple applications running side by side. This is powered by the application context and not by the request context, so you can change the value of this proxy by using the :meth:`~flask.Flask.app_context` method. This is a proxy. See :ref:`notes-on-proxies` for more information. .. autofunction:: has_request_context .. autofunction:: copy_current_request_context .. autofunction:: has_app_context .. autofunction:: url_for .. autofunction:: abort .. autofunction:: redirect .. autofunction:: make_response .. autofunction:: after_this_request .. autofunction:: send_file .. autofunction:: send_from_directory .. autofunction:: safe_join .. autofunction:: escape .. autoclass:: Markup :members: escape, unescape, striptags Message Flashing ---------------- .. autofunction:: flash .. autofunction:: get_flashed_messages JSON Support ------------ .. module:: flask.json Flask uses ``simplejson`` for the JSON implementation. Since simplejson is provided by both the standard library as well as extension, Flask will try simplejson first and then fall back to the stdlib json module. On top of that it will delegate access to the current application's JSON encoders and decoders for easier customization. So for starters instead of doing:: try: import simplejson as json except ImportError: import json You can instead just do this:: from flask import json For usage examples, read the :mod:`json` documentation in the standard library. The following extensions are by default applied to the stdlib's JSON module: 1. ``datetime`` objects are serialized as :rfc:`822` strings. 2. Any object with an ``__html__`` method (like :class:`~flask.Markup`) will have that method called and then the return value is serialized as string. The :func:`~htmlsafe_dumps` function of this json module is also available as filter called ``|tojson`` in Jinja2. Note that inside ``script`` tags no escaping must take place, so make sure to disable escaping with ``|safe`` if you intend to use it inside ``script`` tags unless you are using Flask 0.10 which implies that: .. sourcecode:: html+jinja .. admonition:: Auto-Sort JSON Keys The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be set to false to stop Flask from auto-sorting keys. By default sorting is enabled and outside of the app context sorting is turned on. Notice that disabling key sorting can cause issues when using content based HTTP caches and Python's hash randomization feature. .. autofunction:: jsonify .. autofunction:: dumps .. autofunction:: dump .. autofunction:: loads .. autofunction:: load .. autoclass:: JSONEncoder :members: .. autoclass:: JSONDecoder :members: Template Rendering ------------------ .. currentmodule:: flask .. autofunction:: render_template .. autofunction:: render_template_string .. autofunction:: get_template_attribute Configuration ------------- .. autoclass:: Config :members: Extensions ---------- .. data:: flask.ext This module acts as redirect import module to Flask extensions. It was added in 0.8 as the canonical way to import Flask extensions and makes it possible for us to have more flexibility in how we distribute extensions. If you want to use an extension named “Flask-Foo” you would import it from :data:`~flask.ext` as follows:: from flask.ext import foo .. versionadded:: 0.8 Stream Helpers -------------- .. autofunction:: stream_with_context Useful Internals ---------------- .. autoclass:: flask.ctx.RequestContext :members: .. data:: _request_ctx_stack The internal :class:`~werkzeug.local.LocalStack` that is used to implement all the context local objects used in Flask. This is a documented instance and can be used by extensions and application code but the use is discouraged in general. The following attributes are always present on each layer of the stack: `app` the active Flask application. `url_adapter` the URL adapter that was used to match the request. `request` the current request object. `session` the active session object. `g` an object with all the attributes of the :data:`flask.g` object. `flashes` an internal cache for the flashed messages. Example usage:: from flask import _request_ctx_stack def get_session(): ctx = _request_ctx_stack.top if ctx is not None: return ctx.session .. autoclass:: flask.ctx.AppContext :members: .. data:: _app_ctx_stack Works similar to the request context but only binds the application. This is mainly there for extensions to store data. .. versionadded:: 0.9 .. autoclass:: flask.blueprints.BlueprintSetupState :members: .. _core-signals-list: Signals ------- .. versionadded:: 0.6 .. data:: signals.signals_available ``True`` if the signaling system is available. This is the case when `blinker`_ is installed. The following signals exist in Flask: .. data:: template_rendered This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as `template` and the context as dictionary (named `context`). Example subscriber:: def log_template_renders(sender, template, context, **extra): sender.logger.debug('Rendering template "%s" with context %s', template.name or 'string template', context) from flask import template_rendered template_rendered.connect(log_template_renders, app) .. data:: flask.before_render_template :noindex: This signal is sent before template rendering process. The signal is invoked with the instance of the template as `template` and the context as dictionary (named `context`). Example subscriber:: def log_template_renders(sender, template, context, **extra): sender.logger.debug('Rendering template "%s" with context %s', template.name or 'string template', context) from flask import before_render_template before_render_template.connect(log_template_renders, app) .. data:: request_started This signal is sent when the request context is set up, before any request processing happens. Because the request context is already bound, the subscriber can access the request with the standard global proxies such as :class:`~flask.request`. Example subscriber:: def log_request(sender, **extra): sender.logger.debug('Request context is set up') from flask import request_started request_started.connect(log_request, app) .. data:: request_finished This signal is sent right before the response is sent to the client. It is passed the response to be sent named `response`. Example subscriber:: def log_response(sender, response, **extra): sender.logger.debug('Request context is about to close down. ' 'Response: %s', response) from flask import request_finished request_finished.connect(log_response, app) .. data:: got_request_exception This signal is sent when an exception happens during request processing. It is sent *before* the standard exception handling kicks in and even in debug mode, where no exception handling happens. The exception itself is passed to the subscriber as `exception`. Example subscriber:: def log_exception(sender, exception, **extra): sender.logger.debug('Got exception during processing: %s', exception) from flask import got_request_exception got_request_exception.connect(log_exception, app) .. data:: request_tearing_down This signal is sent when the request is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on. Example subscriber:: def close_db_connection(sender, **extra): session.close() from flask import request_tearing_down request_tearing_down.connect(close_db_connection, app) As of Flask 0.9, this will also be passed an `exc` keyword argument that has a reference to the exception that caused the teardown if there was one. .. data:: appcontext_tearing_down This signal is sent when the app context is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on. Example subscriber:: def close_db_connection(sender, **extra): session.close() from flask import appcontext_tearing_down appcontext_tearing_down.connect(close_db_connection, app) This will also be passed an `exc` keyword argument that has a reference to the exception that caused the teardown if there was one. .. data:: appcontext_pushed This signal is sent when an application context is pushed. The sender is the application. This is usually useful for unittests in order to temporarily hook in information. For instance it can be used to set a resource early onto the `g` object. Example usage:: from contextlib import contextmanager from flask import appcontext_pushed @contextmanager def user_set(app, user): def handler(sender, **kwargs): g.user = user with appcontext_pushed.connected_to(handler, app): yield And in the testcode:: def test_user_me(self): with user_set(app, 'john'): c = app.test_client() resp = c.get('/users/me') assert resp.data == 'username=john' .. versionadded:: 0.10 .. data:: appcontext_popped This signal is sent when an application context is popped. The sender is the application. This usually falls in line with the :data:`appcontext_tearing_down` signal. .. versionadded:: 0.10 .. data:: message_flashed This signal is sent when the application is flashing a message. The messages is sent as `message` keyword argument and the category as `category`. Example subscriber:: recorded = [] def record(sender, message, category, **extra): recorded.append((message, category)) from flask import message_flashed message_flashed.connect(record, app) .. versionadded:: 0.10 .. class:: signals.Namespace An alias for :class:`blinker.base.Namespace` if blinker is available, otherwise a dummy class that creates fake signals. This class is available for Flask extensions that want to provide the same fallback system as Flask itself. .. method:: signal(name, doc=None) Creates a new signal for this namespace if blinker is available, otherwise returns a fake signal that has a send method that will do nothing but will fail with a :exc:`RuntimeError` for all other operations, including connecting. .. _blinker: https://pypi.python.org/pypi/blinker Class-Based Views ----------------- .. versionadded:: 0.7 .. currentmodule:: None .. autoclass:: flask.views.View :members: .. autoclass:: flask.views.MethodView :members: .. _url-route-registrations: URL Route Registrations ----------------------- Generally there are three ways to define rules for the routing system: 1. You can use the :meth:`flask.Flask.route` decorator. 2. You can use the :meth:`flask.Flask.add_url_rule` function. 3. You can directly access the underlying Werkzeug routing system which is exposed as :attr:`flask.Flask.url_map`. Variable parts in the route can be specified with angular brackets (``/user/``). By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using ````. Variable parts are passed to the view function as keyword arguments. The following converters are available: =========== =============================================== `string` accepts any text without a slash (the default) `int` accepts integers `float` like `int` but for floating point values `path` like the default but also accepts slashes `any` matches one of the items provided `uuid` accepts UUID strings =========== =============================================== Custom converters can be defined using :attr:`flask.Flask.url_map`. Here are some examples:: @app.route('/') def index(): pass @app.route('/') def show_user(username): pass @app.route('/post/') def show_post(post_id): pass An important detail to keep in mind is how Flask deals with trailing slashes. The idea is to keep each URL unique so the following rules apply: 1. If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached. 2. If a rule does not end with a trailing slash and the user requests the page with a trailing slash, a 404 not found is raised. This is consistent with how web servers deal with static files. This also makes it possible to use relative link targets safely. You can also define multiple rules for the same function. They have to be unique however. Defaults can also be specified. Here for example is a definition for a URL that accepts an optional page:: @app.route('/users/', defaults={'page': 1}) @app.route('/users/page/') def show_users(page): pass This specifies that ``/users/`` will be the URL for page one and ``/users/page/N`` will be the URL for page `N`. Here are the parameters that :meth:`~flask.Flask.route` and :meth:`~flask.Flask.add_url_rule` accept. The only difference is that with the route parameter the view function is defined with the decorator instead of the `view_func` parameter. =============== ========================================================== `rule` the URL rule as string `endpoint` the endpoint for the registered URL rule. Flask itself assumes that the name of the view function is the name of the endpoint if not explicitly stated. `view_func` the function to call when serving a request to the provided endpoint. If this is not provided one can specify the function later by storing it in the :attr:`~flask.Flask.view_functions` dictionary with the endpoint as key. `defaults` A dictionary with defaults for this rule. See the example above for how defaults work. `subdomain` specifies the rule for the subdomain in case subdomain matching is in use. If not specified the default subdomain is assumed. `**options` the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. They have to be specified as keyword arguments. =============== ========================================================== .. _view-func-options: View Function Options --------------------- For internal usage the view functions can have some attributes attached to customize behavior the view function would normally not have control over. The following attributes can be provided optionally to either override some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior: - `__name__`: The name of a function is by default used as endpoint. If endpoint is provided explicitly this value is used. Additionally this will be prefixed with the name of the blueprint by default which cannot be customized from the function itself. - `methods`: If methods are not provided when the URL rule is added, Flask will look on the view function object itself if a `methods` attribute exists. If it does, it will pull the information for the methods from there. - `provide_automatic_options`: if this attribute is set Flask will either force enable or disable the automatic implementation of the HTTP ``OPTIONS`` response. This can be useful when working with decorators that want to customize the ``OPTIONS`` response on a per-view basis. - `required_methods`: if this attribute is set, Flask will always add these methods when registering a URL rule even if the methods were explicitly overridden in the ``route()`` call. Full example:: def index(): if request.method == 'OPTIONS': # custom options handling here ... return 'Hello World!' index.provide_automatic_options = False index.methods = ['GET', 'OPTIONS'] app.add_url_rule('/', index) .. versionadded:: 0.8 The `provide_automatic_options` functionality was added. Command Line Interface ---------------------- .. currentmodule:: flask.cli .. autoclass:: FlaskGroup :members: .. autoclass:: AppGroup :members: .. autoclass:: ScriptInfo :members: .. autofunction:: with_appcontext .. autofunction:: pass_script_info Marks a function so that an instance of :class:`ScriptInfo` is passed as first argument to the click callback. .. autodata:: run_command .. autodata:: shell_command Flask-0.12.2/docs/upgrading.rst0000644000175000001440000004610313106517205017467 0ustar untitakerusers00000000000000Upgrading to Newer Releases =========================== Flask itself is changing like any software is changing over time. Most of the changes are the nice kind, the kind where you don't have to change anything in your code to profit from a new release. However every once in a while there are changes that do require some changes in your code or there are changes that make it possible for you to improve your own code quality by taking advantage of new features in Flask. This section of the documentation enumerates all the changes in Flask from release to release and how you can change your code to have a painless updating experience. Use the :command:`pip` command to upgrade your existing Flask installation by providing the ``--upgrade`` parameter:: $ pip install --upgrade Flask .. _upgrading-to-012: Version 0.12 ------------ Changes to send_file ```````````````````` The ``filename`` is no longer automatically inferred from file-like objects. This means that the following code will no longer automatically have ``X-Sendfile`` support, etag generation or MIME-type guessing:: response = send_file(open('/path/to/file.txt')) Any of the following is functionally equivalent:: fname = '/path/to/file.txt' # Just pass the filepath directly response = send_file(fname) # Set the MIME-type and ETag explicitly response = send_file(open(fname), mimetype='text/plain') response.set_etag(...) # Set `attachment_filename` for MIME-type guessing # ETag still needs to be manually set response = send_file(open(fname), attachment_filename=fname) response.set_etag(...) The reason for this is that some file-like objects have a invalid or even misleading ``name`` attribute. Silently swallowing errors in such cases was not a satisfying solution. Additionally the default of falling back to ``application/octet-stream`` has been restricted. If Flask can't guess one or the user didn't provide one, the function fails if no filename information was provided. .. _upgrading-to-011: Version 0.11 ------------ 0.11 is an odd release in the Flask release cycle because it was supposed to be the 1.0 release. However because there was such a long lead time up to the release we decided to push out a 0.11 release first with some changes removed to make the transition easier. If you have been tracking the master branch which was 1.0 you might see some unexpected changes. In case you did track the master branch you will notice that :command:`flask --app` is removed now. You need to use the environment variable to specify an application. Debugging ````````` Flask 0.11 removed the ``debug_log_format`` attribute from Flask applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can be used to disable the default log handlers and custom log handlers can be set up. Error handling `````````````` The behavior of error handlers was changed. The precedence of handlers used to be based on the decoration/call order of :meth:`~flask.Flask.errorhandler` and :meth:`~flask.Flask.register_error_handler`, respectively. Now the inheritance hierarchy takes precedence and handlers for more specific exception classes are executed instead of more general ones. See :ref:`error-handlers` for specifics. Trying to register a handler on an instance now raises :exc:`ValueError`. .. note:: There used to be a logic error allowing you to register handlers only for exception *instances*. This was unintended and plain wrong, and therefore was replaced with the intended behavior of registering handlers only using exception classes and HTTP error codes. Templating `````````` The :func:`~flask.templating.render_template_string` function has changed to autoescape template variables by default. This better matches the behavior of :func:`~flask.templating.render_template`. Extension imports ````````````````` Extension imports of the form ``flask.ext.foo`` are deprecated, you should use ``flask_foo``. The old form still works, but Flask will issue a ``flask.exthook.ExtDeprecationWarning`` for each extension you import the old way. We also provide a migration utility called `flask-ext-migrate `_ that is supposed to automatically rewrite your imports for this. .. _upgrading-to-010: Version 0.10 ------------ The biggest change going from 0.9 to 0.10 is that the cookie serialization format changed from pickle to a specialized JSON format. This change has been done in order to avoid the damage an attacker can do if the secret key is leaked. When you upgrade you will notice two major changes: all sessions that were issued before the upgrade are invalidated and you can only store a limited amount of types in the session. The new sessions are by design much more restricted to only allow JSON with a few small extensions for tuples and strings with HTML markup. In order to not break people's sessions it is possible to continue using the old session system by using the `Flask-OldSessions`_ extension. Flask also started storing the :data:`flask.g` object on the application context instead of the request context. This change should be transparent for you but it means that you now can store things on the ``g`` object when there is no request context yet but an application context. The old ``flask.Flask.request_globals_class`` attribute was renamed to :attr:`flask.Flask.app_ctx_globals_class`. .. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/ Version 0.9 ----------- The behavior of returning tuples from a function was simplified. If you return a tuple it no longer defines the arguments for the response object you're creating, it's now always a tuple in the form ``(response, status, headers)`` where at least one item has to be provided. If you depend on the old behavior, you can add it easily by subclassing Flask:: class TraditionalFlask(Flask): def make_response(self, rv): if isinstance(rv, tuple): return self.response_class(*rv) return Flask.make_response(self, rv) If you maintain an extension that was using :data:`~flask._request_ctx_stack` before, please consider changing to :data:`~flask._app_ctx_stack` if it makes sense for your extension. For instance, the app context stack makes sense for extensions which connect to databases. Using the app context stack instead of the request context stack will make extensions more readily handle use cases outside of requests. Version 0.8 ----------- Flask introduced a new session interface system. We also noticed that there was a naming collision between ``flask.session`` the module that implements sessions and :data:`flask.session` which is the global session object. With that introduction we moved the implementation details for the session system into a new module called :mod:`flask.sessions`. If you used the previously undocumented session support we urge you to upgrade. If invalid JSON data was submitted Flask will now raise a :exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the default :exc:`ValueError` bubble up. This has the advantage that you no longer have to handle that error to avoid an internal server error showing up for the user. If you were catching this down explicitly in the past as :exc:`ValueError` you will need to change this. Due to a bug in the test client Flask 0.7 did not trigger teardown handlers when the test client was used in a with statement. This was since fixed but might require some changes in your test suites if you relied on this behavior. Version 0.7 ----------- In Flask 0.7 we cleaned up the code base internally a lot and did some backwards incompatible changes that make it easier to implement larger applications with Flask. Because we want to make upgrading as easy as possible we tried to counter the problems arising from these changes by providing a script that can ease the transition. The script scans your whole application and generates an unified diff with changes it assumes are safe to apply. However as this is an automated tool it won't be able to find all use cases and it might miss some. We internally spread a lot of deprecation warnings all over the place to make it easy to find pieces of code that it was unable to upgrade. We strongly recommend that you hand review the generated patchfile and only apply the chunks that look good. If you are using git as version control system for your project we recommend applying the patch with ``path -p1 < patchfile.diff`` and then using the interactive commit feature to only apply the chunks that look good. To apply the upgrade script do the following: 1. Download the script: `flask-07-upgrade.py `_ 2. Run it in the directory of your application:: python flask-07-upgrade.py > patchfile.diff 3. Review the generated patchfile. 4. Apply the patch:: patch -p1 < patchfile.diff 5. If you were using per-module template folders you need to move some templates around. Previously if you had a folder named :file:`templates` next to a blueprint named ``admin`` the implicit template path automatically was :file:`admin/index.html` for a template file called :file:`templates/index.html`. This no longer is the case. Now you need to name the template :file:`templates/admin/index.html`. The tool will not detect this so you will have to do that on your own. Please note that deprecation warnings are disabled by default starting with Python 2.7. In order to see the deprecation warnings that might be emitted you have to enabled them with the :mod:`warnings` module. If you are working with windows and you lack the ``patch`` command line utility you can get it as part of various Unix runtime environments for windows including cygwin, msysgit or ming32. Also source control systems like svn, hg or git have builtin support for applying unified diffs as generated by the tool. Check the manual of your version control system for more information. Bug in Request Locals ````````````````````` Due to a bug in earlier implementations the request local proxies now raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they are unbound. If you caught these exceptions with :exc:`AttributeError` before, you should catch them with :exc:`RuntimeError` now. Additionally the :func:`~flask.send_file` function is now issuing deprecation warnings if you depend on functionality that will be removed in Flask 0.11. Previously it was possible to use etags and mimetypes when file objects were passed. This was unreliable and caused issues for a few setups. If you get a deprecation warning, make sure to update your application to work with either filenames there or disable etag attaching and attach them yourself. Old code:: return send_file(my_file_object) return send_file(my_file_object) New code:: return send_file(my_file_object, add_etags=False) .. _upgrading-to-new-teardown-handling: Upgrading to new Teardown Handling `````````````````````````````````` We streamlined the behavior of the callbacks for request handling. For things that modify the response the :meth:`~flask.Flask.after_request` decorators continue to work as expected, but for things that absolutely must happen at the end of request we introduced the new :meth:`~flask.Flask.teardown_request` decorator. Unfortunately that change also made after-request work differently under error conditions. It's not consistently skipped if exceptions happen whereas previously it might have been called twice to ensure it is executed at the end of the request. If you have database connection code that looks like this:: @app.after_request def after_request(response): g.db.close() return response You are now encouraged to use this instead:: @app.teardown_request def after_request(exception): if hasattr(g, 'db'): g.db.close() On the upside this change greatly improves the internal code flow and makes it easier to customize the dispatching and error handling. This makes it now a lot easier to write unit tests as you can prevent closing down of database connections for a while. You can take advantage of the fact that the teardown callbacks are called when the response context is removed from the stack so a test can query the database after request handling:: with app.test_client() as client: resp = client.get('/') # g.db is still bound if there is such a thing # and here it's gone Manual Error Handler Attaching `````````````````````````````` While it is still possible to attach error handlers to :attr:`Flask.error_handlers` it's discouraged to do so and in fact deprecated. In general we no longer recommend custom error handler attaching via assignments to the underlying dictionary due to the more complex internal handling to support arbitrary exception classes and blueprints. See :meth:`Flask.errorhandler` for more information. The proper upgrade is to change this:: app.error_handlers[403] = handle_error Into this:: app.register_error_handler(403, handle_error) Alternatively you should just attach the function with a decorator:: @app.errorhandler(403) def handle_error(e): ... (Note that :meth:`register_error_handler` is new in Flask 0.7) Blueprint Support ````````````````` Blueprints replace the previous concept of “Modules” in Flask. They provide better semantics for various features and work better with large applications. The update script provided should be able to upgrade your applications automatically, but there might be some cases where it fails to upgrade. What changed? - Blueprints need explicit names. Modules had an automatic name guessing scheme where the shortname for the module was taken from the last part of the import module. The upgrade script tries to guess that name but it might fail as this information could change at runtime. - Blueprints have an inverse behavior for :meth:`url_for`. Previously ``.foo`` told :meth:`url_for` that it should look for the endpoint ``foo`` on the application. Now it means “relative to current module”. The script will inverse all calls to :meth:`url_for` automatically for you. It will do this in a very eager way so you might end up with some unnecessary leading dots in your code if you're not using modules. - Blueprints do not automatically provide static folders. They will also no longer automatically export templates from a folder called :file:`templates` next to their location however but it can be enabled from the constructor. Same with static files: if you want to continue serving static files you need to tell the constructor explicitly the path to the static folder (which can be relative to the blueprint's module path). - Rendering templates was simplified. Now the blueprints can provide template folders which are added to a general template searchpath. This means that you need to add another subfolder with the blueprint's name into that folder if you want :file:`blueprintname/template.html` as the template name. If you continue to use the ``Module`` object which is deprecated, Flask will restore the previous behavior as good as possible. However we strongly recommend upgrading to the new blueprints as they provide a lot of useful improvement such as the ability to attach a blueprint multiple times, blueprint specific error handlers and a lot more. Version 0.6 ----------- Flask 0.6 comes with a backwards incompatible change which affects the order of after-request handlers. Previously they were called in the order of the registration, now they are called in reverse order. This change was made so that Flask behaves more like people expected it to work and how other systems handle request pre- and post-processing. If you depend on the order of execution of post-request functions, be sure to change the order. Another change that breaks backwards compatibility is that context processors will no longer override values passed directly to the template rendering function. If for example ``request`` is as variable passed directly to the template, the default context processor will not override it with the current request object. This makes it easier to extend context processors later to inject additional variables without breaking existing template not expecting them. Version 0.5 ----------- Flask 0.5 is the first release that comes as a Python package instead of a single module. There were a couple of internal refactoring so if you depend on undocumented internal details you probably have to adapt the imports. The following changes may be relevant to your application: - autoescaping no longer happens for all templates. Instead it is configured to only happen on files ending with ``.html``, ``.htm``, ``.xml`` and ``.xhtml``. If you have templates with different extensions you should override the :meth:`~flask.Flask.select_jinja_autoescape` method. - Flask no longer supports zipped applications in this release. This functionality might come back in future releases if there is demand for this feature. Removing support for this makes the Flask internal code easier to understand and fixes a couple of small issues that make debugging harder than necessary. - The ``create_jinja_loader`` function is gone. If you want to customize the Jinja loader now, use the :meth:`~flask.Flask.create_jinja_environment` method instead. Version 0.4 ----------- For application developers there are no changes that require changes in your code. In case you are developing on a Flask extension however, and that extension has a unittest-mode you might want to link the activation of that mode to the new ``TESTING`` flag. Version 0.3 ----------- Flask 0.3 introduces configuration support and logging as well as categories for flashing messages. All these are features that are 100% backwards compatible but you might want to take advantage of them. Configuration Support ````````````````````` The configuration support makes it easier to write any kind of application that requires some sort of configuration. (Which most likely is the case for any application out there). If you previously had code like this:: app.debug = DEBUG app.secret_key = SECRET_KEY You no longer have to do that, instead you can just load a configuration into the config object. How this works is outlined in :ref:`config`. Logging Integration ``````````````````` Flask now configures a logger for you with some basic and useful defaults. If you run your application in production and want to profit from automatic error logging, you might be interested in attaching a proper log handler. Also you can start logging warnings and errors into the logger when appropriately. For more information on that, read :ref:`application-errors`. Categories for Flash Messages ````````````````````````````` Flash messages can now have categories attached. This makes it possible to render errors, warnings or regular messages differently for example. This is an opt-in feature because it requires some rethinking in the code. Read all about that in the :ref:`message-flashing-pattern` pattern. Flask-0.12.2/docs/logo.pdf0000644000175000001440000005655312500054716016422 0ustar untitakerusers00000000000000%PDF-1.4 % 3 0 obj << /Length 4 0 R /Filter /FlateDecode >> stream xmIr:&)t51#٫ZHYП s__Z.wJ;Uw+W-߹ͯל]Rw9;x>yrpOr\[3zo}_LNڈgt̶W{o,&]]aUK+{@X1nnugc/apGYuϵ>h}߯I_aOo\n"p͊( pon1ͤbs1Z&rK{ Psa8=F ﻻ7m n;|+B w)DS#,~ +8R\@WWnl?p8mh K,jw{%cX}l>X/~D{xanF2++侗҅bjrThx_hs}OR=M&+~zD׻qۻ-d7 u.sӍ gpq'^khݻ~g/ݫ ɹ<ڿi%-0GW^4}4p4٧/߮ {n0TE@U| L''+_Yq3HNb}w\`ceIY}ۉm/"/&mtnifx{Oq5@ݧ&싷MF pg!Y&&sO~w nm{#@?xuX ݆]99E쭞4sM`;˷@Uem8,Ex1#U``{R{I>K!}U __ t={% ЖϟG`Y3bQ3Ϯ"|p@ikM'F{صG|}~{`pctqB6NB{p8#]_om,sςiCRMBE/i"&݁G6 qdg߸ (f#p/ 75P2uu z}v#obž(H><7YϾD?3;Cco|j >c'xMhVIO7}D Iظir#zg_}Mt=J7gA%3SKWik’DH?bwT}22)*_* aUL#k1%e3\QT$ al8n`d՘@B38J . 8@|xCX3{ݵc&±L7xP Y%s<d%r VeWɅ5Y\'K&4H(6Ħi0I3AJ A!]"{;Yitߔ(ooBI qaIemmId_%N >8o` S:=lؿD>ok RiOc$p骚Z}F]m n4t'HIQ$\Ժ@=I\[lB?8P^[%>UQR$0U-o$qc%}Al ႣB[3DfM0vsҧZ# ~&hRo@)F#M |Ƚ}p03#wVŗ8^5 mH͉_pANyz" FY(Oz2FcY5WĔd C<¹խםt/^Jo0t3@a]N&% W2"ץ7%9dHA n,SZ.wݘotyW23wM (Y⳶Q>ăGL)Q݋+}`?>nNjؤ$" = tU@! L/ U x< nm-1 o~L8y⥢$[hPpd>ep->t@q%3 GW }m#0V0}4|t`|ojS(n,þC&}@lR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;\3p`ZvA8'e ; xc`7WpaB S#oLo>!72!YU{_`ӷ«@>9N$pDa(2=+|f24pa!ذz6If* slMɫR|Xȴ3A5͇kS>'mh 64XWHUÇ䌨CbĘKoLj,H3b:ZÆ9UʳÃ]ũ4lϩ`xj}0e琲Oo)e\i'K(y_꣘bsl)ցf8^ sdDZa&h'EywEdC`[RX0.z80u3;Дm2 pdD܂X0^k3@R0N*-Pv?H?f#O[5#O (9j*-+A'ϋ>H$=-JmbV$L~f.noJnm0U.Uz3bLr5W3J\XQĥSBs)_zλ0H5awO .pM r6"%\fFfTtݲ#ayetuehm4K_CP,p+jP }Ȏ?aPHij`G)٠\pHdaSk;8pwi.Ov zs -jș ;Lq FA *+,c)yd!h_6I䭛) T L2.8EJ|Z;8QMp2C1E??Ɗp2\oNu*++K!JAQʗa\It jy KH9,ݒDk]S|~mBV/[K"L248?>մ'~§PUD}TY#{, }ei,|8uCBZ: 5-S$h^sЫǿ|Й܀o5lyr0p=j*0( G`">)f3 *Ϳm:LWpr[pN r嬚VM9o|s0#ٔiip"_En;F`~ZYRiKQEl)Oʺ-R6FC 50uE[O[SZZhܚRZ4+D2L%*xYAܰ( XkSY꣢TwFeQZa׋Y4X͠ecln@x$v8I-};{R$oRXuETO? JT"PEi1ȼpH5vpc{?fI~耊= q #]B) sbKb Vy'y` RE)FY>]jk+( X efNJ~<~t0 5tӠLg93".3~9.9 endstream endobj 4 0 obj 23043 endobj 2 0 obj << /ExtGState << /a0 << /CA 1 /ca 1 >> >> >> endobj 5 0 obj << /Type /Page /Parent 1 0 R /MediaBox [ 0 0 368 144 ] /Contents 3 0 R /Group << /Type /Group /S /Transparency /CS /DeviceRGB >> /Resources 2 0 R >> endobj 1 0 obj << /Type /Pages /Kids [ 5 0 R ] /Count 1 >> endobj 6 0 obj << /Creator (cairo 1.8.6 (http://cairographics.org)) /Producer (cairo 1.8.6 (http://cairographics.org)) >> endobj 7 0 obj << /Type /Catalog /Pages 1 0 R >> endobj xref 0 8 0000000000 65535 f 0000023430 00000 n 0000023158 00000 n 0000000015 00000 n 0000023134 00000 n 0000023230 00000 n 0000023495 00000 n 0000023620 00000 n trailer << /Size 8 /Root 7 0 R /Info 6 0 R >> startxref 23672 %%EOF Flask-0.12.2/docs/extensions.rst0000644000175000001440000000415712765277163017731 0ustar untitakerusers00000000000000.. _extensions: Flask Extensions ================ Flask extensions extend the functionality of Flask in various different ways. For instance they add support for databases and other common tasks. Finding Extensions ------------------ Flask extensions are listed on the `Flask Extension Registry`_ and can be downloaded with :command:`easy_install` or :command:`pip`. If you add a Flask extension as dependency to your :file:`requirements.txt` or :file:`setup.py` file they are usually installed with a simple command or when your application installs. Using Extensions ---------------- Extensions typically have documentation that goes along that shows how to use it. There are no general rules in how extensions are supposed to behave but they are imported from common locations. If you have an extension called ``Flask-Foo`` or ``Foo-Flask`` it should be always importable from ``flask_foo``:: import flask_foo Building Extensions ------------------- While `Flask Extension Registry`_ contains many Flask extensions, you may not find an extension that fits your need. If this is the case, you can always create your own. Consider reading :ref:`extension-dev` to develop your own Flask extension. Flask Before 0.8 ---------------- If you are using Flask 0.7 or earlier the :data:`flask.ext` package will not exist, instead you have to import from ``flaskext.foo`` or ``flask_foo`` depending on how the extension is distributed. If you want to develop an application that supports Flask 0.7 or earlier you should still import from the :data:`flask.ext` package. We provide you with a compatibility module that provides this package for older versions of Flask. You can download it from GitHub: `flaskext_compat.py`_ And here is how you can use it:: import flaskext_compat flaskext_compat.activate() from flask.ext import foo Once the ``flaskext_compat`` module is activated the :data:`flask.ext` will exist and you can start importing from there. .. _Flask Extension Registry: http://flask.pocoo.org/extensions/ .. _flaskext_compat.py: https://raw.githubusercontent.com/pallets/flask/master/scripts/flaskext_compat.py Flask-0.12.2/docs/server.rst0000644000175000001440000000314212763616450017023 0ustar untitakerusers00000000000000.. _server: Development Server ================== .. currentmodule:: flask Starting with Flask 0.11 there are multiple built-in ways to run a development server. The best one is the :command:`flask` command line utility but you can also continue using the :meth:`Flask.run` method. Command Line ------------ The :command:`flask` command line script (:ref:`cli`) is strongly recommended for development because it provides a superior reload experience due to how it loads the application. The basic usage is like this:: $ export FLASK_APP=my_application $ export FLASK_DEBUG=1 $ flask run This will enable the debugger, the reloader and then start the server on *http://localhost:5000/*. The individual features of the server can be controlled by passing more arguments to the ``run`` option. For instance the reloader can be disabled:: $ flask run --no-reload In Code ------- The alternative way to start the application is through the :meth:`Flask.run` method. This will immediately launch a local server exactly the same way the :command:`flask` script does. Example:: if __name__ == '__main__': app.run() This works well for the common case but it does not work well for development which is why from Flask 0.11 onwards the :command:`flask` method is recommended. The reason for this is that due to how the reload mechanism works there are some bizarre side-effects (like executing certain code twice, sometimes crashing without message or dying when a syntax or import error happens). It is however still a perfectly valid method for invoking a non automatic reloading application. Flask-0.12.2/docs/htmlfaq.rst0000644000175000001440000002271612763616450017161 0ustar untitakerusers00000000000000HTML/XHTML FAQ ============== The Flask documentation and example applications are using HTML5. You may notice that in many situations, when end tags are optional they are not used, so that the HTML is cleaner and faster to load. Because there is much confusion about HTML and XHTML among developers, this document tries to answer some of the major questions. History of XHTML ---------------- For a while, it appeared that HTML was about to be replaced by XHTML. However, barely any websites on the Internet are actual XHTML (which is HTML processed using XML rules). There are a couple of major reasons why this is the case. One of them is Internet Explorer's lack of proper XHTML support. The XHTML spec states that XHTML must be served with the MIME type :mimetype:`application/xhtml+xml`, but Internet Explorer refuses to read files with that MIME type. While it is relatively easy to configure Web servers to serve XHTML properly, few people do. This is likely because properly using XHTML can be quite painful. One of the most important causes of pain is XML's draconian (strict and ruthless) error handling. When an XML parsing error is encountered, the browser is supposed to show the user an ugly error message, instead of attempting to recover from the error and display what it can. Most of the (X)HTML generation on the web is based on non-XML template engines (such as Jinja, the one used in Flask) which do not protect you from accidentally creating invalid XHTML. There are XML based template engines, such as Kid and the popular Genshi, but they often come with a larger runtime overhead and are not as straightforward to use because they have to obey XML rules. The majority of users, however, assumed they were properly using XHTML. They wrote an XHTML doctype at the top of the document and self-closed all the necessary tags (``
`` becomes ``
`` or ``

`` in XHTML). However, even if the document properly validates as XHTML, what really determines XHTML/HTML processing in browsers is the MIME type, which as said before is often not set properly. So the valid XHTML was being treated as invalid HTML. XHTML also changed the way JavaScript is used. To properly work with XHTML, programmers have to use the namespaced DOM interface with the XHTML namespace to query for HTML elements. History of HTML5 ---------------- Development of the HTML5 specification was started in 2004 under the name "Web Applications 1.0" by the Web Hypertext Application Technology Working Group, or WHATWG (which was formed by the major browser vendors Apple, Mozilla, and Opera) with the goal of writing a new and improved HTML specification, based on existing browser behavior instead of unrealistic and backwards-incompatible specifications. For example, in HTML4 ``Hello``. However, since people were using XHTML-like tags along the lines of ````, browser vendors implemented the XHTML syntax over the syntax defined by the specification. In 2007, the specification was adopted as the basis of a new HTML specification under the umbrella of the W3C, known as HTML5. Currently, it appears that XHTML is losing traction, as the XHTML 2 working group has been disbanded and HTML5 is being implemented by all major browser vendors. HTML versus XHTML ----------------- The following table gives you a quick overview of features available in HTML 4.01, XHTML 1.1 and HTML5. (XHTML 1.0 is not included, as it was superseded by XHTML 1.1 and the barely-used XHTML5.) .. tabularcolumns:: |p{9cm}|p{2cm}|p{2cm}|p{2cm}| +-----------------------------------------+----------+----------+----------+ | | HTML4.01 | XHTML1.1 | HTML5 | +=========================================+==========+==========+==========+ | ``value`` | |Y| [1]_ | |N| | |N| | +-----------------------------------------+----------+----------+----------+ | ``
`` supported | |N| | |Y| | |Y| [2]_ | +-----------------------------------------+----------+----------+----------+ | `` Another method is using Google's `AJAX Libraries API `_ to load jQuery: .. sourcecode:: html In this case you have to put jQuery into your static folder as a fallback, but it will first try to load it directly from Google. This has the advantage that your website will probably load faster for users if they went to at least one other website before using the same jQuery version from Google because it will already be in the browser cache. Where is My Site? ----------------- Do you know where your application is? If you are developing the answer is quite simple: it's on localhost port something and directly on the root of that server. But what if you later decide to move your application to a different location? For example to ``http://example.com/myapp``? On the server side this never was a problem because we were using the handy :func:`~flask.url_for` function that could answer that question for us, but if we are using jQuery we should not hardcode the path to the application but make that dynamic, so how can we do that? A simple method would be to add a script tag to our page that sets a global variable to the prefix to the root of the application. Something like this: .. sourcecode:: html+jinja The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not escape the JSON encoded string with HTML rules. Usually this would be necessary, but we are inside a ``script`` block here where different rules apply. .. admonition:: Information for Pros In HTML the ``script`` tag is declared ``CDATA`` which means that entities will not be parsed. Everything until ```` is handled as script. This also means that there must never be any ``"|tojson|safe }}`` is rendered as ``"<\/script>"``). In Flask 0.10 it goes a step further and escapes all HTML tags with unicode escapes. This makes it possible for Flask to automatically mark the result as HTML safe. JSON View Functions ------------------- Now let's create a server side function that accepts two URL arguments of numbers which should be added together and then sent back to the application in a JSON object. This is a really ridiculous example and is something you usually would do on the client side alone, but a simple example that shows how you would use jQuery and Flask nonetheless:: from flask import Flask, jsonify, render_template, request app = Flask(__name__) @app.route('/_add_numbers') def add_numbers(): a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) return jsonify(result=a + b) @app.route('/') def index(): return render_template('index.html') As you can see I also added an `index` method here that renders a template. This template will load jQuery as above and have a little form we can add two numbers and a link to trigger the function on the server side. Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here which will never fail. If the key is missing a default value (here ``0``) is returned. Furthermore it can convert values to a specific type (like in our case `int`). This is especially handy for code that is triggered by a script (APIs, JavaScript etc.) because you don't need special error reporting in that case. The HTML -------- Your index.html template either has to extend a :file:`layout.html` template with jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top. Here's the HTML code needed for our little application (:file:`index.html`). Notice that we also drop the script directly into the HTML here. It is usually a better idea to have that in a separate script file: .. sourcecode:: html

jQuery Example

+ = ?

calculate server side I won't go into detail here about how jQuery works, just a very quick explanation of the little bit of code above: 1. ``$(function() { ... })`` specifies code that should run once the browser is done loading the basic parts of the page. 2. ``$('selector')`` selects an element and lets you operate on it. 3. ``element.bind('event', func)`` specifies a function that should run when the user clicked on the element. If that function returns `false`, the default behavior will not kick in (in this case, navigate to the `#` URL). 4. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will send the contents of the `data` object as query parameters. Once the data arrived, it will call the given function with the return value as argument. Note that we can use the `$SCRIPT_ROOT` variable here that we set earlier. If you don't get the whole picture, download the `sourcecode for this example `_ from GitHub. Flask-0.12.2/docs/patterns/viewdecorators.rst0000644000175000001440000001434512765277163022432 0ustar untitakerusers00000000000000View Decorators =============== Python has a really interesting feature called function decorators. This allows some really neat things for web applications. Because each view in Flask is a function, decorators can be used to inject additional functionality to one or more functions. The :meth:`~flask.Flask.route` decorator is the one you probably used already. But there are use cases for implementing your own decorator. For instance, imagine you have a view that should only be used by people that are logged in. If a user goes to the site and is not logged in, they should be redirected to the login page. This is a good example of a use case where a decorator is an excellent solution. Login Required Decorator ------------------------ So let's implement such a decorator. A decorator is a function that wraps and replaces another function. Since the original function is replaced, you need to remember to copy the original function's information to the new function. Use :func:`functools.wraps` to handle this for you. This example assumes that the login page is called ``'login'`` and that the current user is stored in ``g.user`` and is ``None`` if there is no-one logged in. :: from functools import wraps from flask import g, request, redirect, url_for def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.user is None: return redirect(url_for('login', next=request.url)) return f(*args, **kwargs) return decorated_function To use the decorator, apply it as innermost decorator to a view function. When applying further decorators, always remember that the :meth:`~flask.Flask.route` decorator is the outermost. :: @app.route('/secret_page') @login_required def secret_page(): pass .. note:: The ``next`` value will exist in ``request.args`` after a ``GET`` request for the login page. You'll have to pass it along when sending the ``POST`` request from the login form. You can do this with a hidden input tag, then retrieve it from ``request.form`` when logging the user in. :: Caching Decorator ----------------- Imagine you have a view function that does an expensive calculation and because of that you would like to cache the generated results for a certain amount of time. A decorator would be nice for that. We're assuming you have set up a cache like mentioned in :ref:`caching-pattern`. Here is an example cache function. It generates the cache key from a specific prefix (actually a format string) and the current path of the request. Notice that we are using a function that first creates the decorator that then decorates the function. Sounds awful? Unfortunately it is a little bit more complex, but the code should still be straightforward to read. The decorated function will then work as follows 1. get the unique cache key for the current request base on the current path. 2. get the value for that key from the cache. If the cache returned something we will return that value. 3. otherwise the original function is called and the return value is stored in the cache for the timeout provided (by default 5 minutes). Here the code:: from functools import wraps from flask import request def cached(timeout=5 * 60, key='view/%s'): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): cache_key = key % request.path rv = cache.get(cache_key) if rv is not None: return rv rv = f(*args, **kwargs) cache.set(cache_key, rv, timeout=timeout) return rv return decorated_function return decorator Notice that this assumes an instantiated `cache` object is available, see :ref:`caching-pattern` for more information. Templating Decorator -------------------- A common pattern invented by the TurboGears guys a while back is a templating decorator. The idea of that decorator is that you return a dictionary with the values passed to the template from the view function and the template is automatically rendered. With that, the following three examples do exactly the same:: @app.route('/') def index(): return render_template('index.html', value=42) @app.route('/') @templated('index.html') def index(): return dict(value=42) @app.route('/') @templated() def index(): return dict(value=42) As you can see, if no template name is provided it will use the endpoint of the URL map with dots converted to slashes + ``'.html'``. Otherwise the provided template name is used. When the decorated function returns, the dictionary returned is passed to the template rendering function. If ``None`` is returned, an empty dictionary is assumed, if something else than a dictionary is returned we return it from the function unchanged. That way you can still use the redirect function or return simple strings. Here is the code for that decorator:: from functools import wraps from flask import request, render_template def templated(template=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): template_name = template if template_name is None: template_name = request.endpoint \ .replace('.', '/') + '.html' ctx = f(*args, **kwargs) if ctx is None: ctx = {} elif not isinstance(ctx, dict): return ctx return render_template(template_name, **ctx) return decorated_function return decorator Endpoint Decorator ------------------ When you want to use the werkzeug routing system for more flexibility you need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule` to a view function. This is possible with this decorator. For example:: from flask import Flask from werkzeug.routing import Rule app = Flask(__name__) app.url_map.add(Rule('/', endpoint='index')) @app.endpoint('index') def my_index(): return "Hello world" Flask-0.12.2/docs/patterns/packages.rst0000644000175000001440000001046213106517205021124 0ustar untitakerusers00000000000000.. _larger-applications: Larger Applications =================== For larger applications it's a good idea to use a package instead of a module. That is quite simple. Imagine a small application looks like this:: /yourapplication yourapplication.py /static style.css /templates layout.html index.html login.html ... Simple Packages --------------- To convert that into a larger one, just create a new folder :file:`yourapplication` inside the existing one and move everything below it. Then rename :file:`yourapplication.py` to :file:`__init__.py`. (Make sure to delete all ``.pyc`` files first, otherwise things would most likely break) You should then end up with something like that:: /yourapplication /yourapplication __init__.py /static style.css /templates layout.html index.html login.html ... But how do you run your application now? The naive ``python yourapplication/__init__.py`` will not work. Let's just say that Python does not want modules in packages to be the startup file. But that is not a big problem, just add a new file called :file:`setup.py` next to the inner :file:`yourapplication` folder with the following contents:: from setuptools import setup setup( name='yourapplication', packages=['yourapplication'], include_package_data=True, install_requires=[ 'flask', ], ) In order to run the application you need to export an environment variable that tells Flask where to find the application instance:: export FLASK_APP=yourapplication If you are outside of the project directory make sure to provide the exact path to your application directory. Similiarly you can turn on "debug mode" with this environment variable:: export FLASK_DEBUG=true In order to install and run the application you need to issue the following commands:: pip install -e . flask run What did we gain from this? Now we can restructure the application a bit into multiple modules. The only thing you have to remember is the following quick checklist: 1. the `Flask` application object creation has to be in the :file:`__init__.py` file. That way each module can import it safely and the `__name__` variable will resolve to the correct package. 2. all the view functions (the ones with a :meth:`~flask.Flask.route` decorator on top) have to be imported in the :file:`__init__.py` file. Not the object itself, but the module it is in. Import the view module **after the application object is created**. Here's an example :file:`__init__.py`:: from flask import Flask app = Flask(__name__) import yourapplication.views And this is what :file:`views.py` would look like:: from yourapplication import app @app.route('/') def index(): return 'Hello World!' You should then end up with something like that:: /yourapplication setup.py /yourapplication __init__.py views.py /static style.css /templates layout.html index.html login.html ... .. admonition:: Circular Imports Every Python programmer hates them, and yet we just added some: circular imports (That's when two modules depend on each other. In this case :file:`views.py` depends on :file:`__init__.py`). Be advised that this is a bad idea in general but here it is actually fine. The reason for this is that we are not actually using the views in :file:`__init__.py` and just ensuring the module is imported and we are doing that at the bottom of the file. There are still some problems with that approach but if you want to use decorators there is no way around that. Check out the :ref:`becomingbig` section for some inspiration how to deal with that. .. _working-with-modules: Working with Blueprints ----------------------- If you have larger applications it's recommended to divide them into smaller groups where each group is implemented with the help of a blueprint. For a gentle introduction into this topic refer to the :ref:`blueprints` chapter of the documentation. Flask-0.12.2/docs/patterns/lazyloading.rst0000644000175000001440000000740112765277163021702 0ustar untitakerusers00000000000000Lazily Loading Views ==================== Flask is usually used with the decorators. Decorators are simple and you have the URL right next to the function that is called for that specific URL. However there is a downside to this approach: it means all your code that uses decorators has to be imported upfront or Flask will never actually find your function. This can be a problem if your application has to import quick. It might have to do that on systems like Google's App Engine or other systems. So if you suddenly notice that your application outgrows this approach you can fall back to a centralized URL mapping. The system that enables having a central URL map is the :meth:`~flask.Flask.add_url_rule` function. Instead of using decorators, you have a file that sets up the application with all URLs. Converting to Centralized URL Map --------------------------------- Imagine the current application looks somewhat like this:: from flask import Flask app = Flask(__name__) @app.route('/') def index(): pass @app.route('/user/') def user(username): pass Then, with the centralized approach you would have one file with the views (:file:`views.py`) but without any decorator:: def index(): pass def user(username): pass And then a file that sets up an application which maps the functions to URLs:: from flask import Flask from yourapplication import views app = Flask(__name__) app.add_url_rule('/', view_func=views.index) app.add_url_rule('/user/', view_func=views.user) Loading Late ------------ So far we only split up the views and the routing, but the module is still loaded upfront. The trick is to actually load the view function as needed. This can be accomplished with a helper class that behaves just like a function but internally imports the real function on first use:: from werkzeug import import_string, cached_property class LazyView(object): def __init__(self, import_name): self.__module__, self.__name__ = import_name.rsplit('.', 1) self.import_name = import_name @cached_property def view(self): return import_string(self.import_name) def __call__(self, *args, **kwargs): return self.view(*args, **kwargs) What's important here is is that `__module__` and `__name__` are properly set. This is used by Flask internally to figure out how to name the URL rules in case you don't provide a name for the rule yourself. Then you can define your central place to combine the views like this:: from flask import Flask from yourapplication.helpers import LazyView app = Flask(__name__) app.add_url_rule('/', view_func=LazyView('yourapplication.views.index')) app.add_url_rule('/user/', view_func=LazyView('yourapplication.views.user')) You can further optimize this in terms of amount of keystrokes needed to write this by having a function that calls into :meth:`~flask.Flask.add_url_rule` by prefixing a string with the project name and a dot, and by wrapping `view_func` in a `LazyView` as needed. :: def url(import_name, url_rules=[], **options): view = LazyView('yourapplication.' + import_name) for url_rule in url_rules: app.add_url_rule(url_rule, view_func=view, **options) # add a single route to the index view url('views.index', ['/']) # add two routes to a single function endpoint url_rules = ['/user/','/user/'] url('views.user', url_rules) One thing to keep in mind is that before and after request handlers have to be in a file that is imported upfront to work properly on the first request. The same goes for any kind of remaining decorator. Flask-0.12.2/docs/patterns/subclassing.rst0000644000175000001440000000124412765277163021701 0ustar untitakerusers00000000000000Subclassing Flask ================= The :class:`~flask.Flask` class is designed for subclassing. For example, you may want to override how request parameters are handled to preserve their order:: from flask import Flask, Request from werkzeug.datastructures import ImmutableOrderedMultiDict class MyRequest(Request): """Request subclass to override request parameter storage""" parameter_storage_class = ImmutableOrderedMultiDict class MyFlask(Flask): """Flask subclass using the custom request class""" request_class = MyRequest This is the recommended approach for overriding or augmenting Flask's internal functionality. Flask-0.12.2/docs/patterns/sqlalchemy.rst0000644000175000001440000001643013106517205021511 0ustar untitakerusers00000000000000.. _sqlalchemy-pattern: SQLAlchemy in Flask =================== Many people prefer `SQLAlchemy`_ for database access. In this case it's encouraged to use a package instead of a module for your flask application and drop the models into a separate module (:ref:`larger-applications`). While that is not necessary, it makes a lot of sense. There are four very common ways to use SQLAlchemy. I will outline each of them here: Flask-SQLAlchemy Extension -------------------------- Because SQLAlchemy is a common database abstraction layer and object relational mapper that requires a little bit of configuration effort, there is a Flask extension that handles that for you. This is recommended if you want to get started quickly. You can download `Flask-SQLAlchemy`_ from `PyPI `_. .. _Flask-SQLAlchemy: http://pythonhosted.org/Flask-SQLAlchemy/ Declarative ----------- The declarative extension in SQLAlchemy is the most recent method of using SQLAlchemy. It allows you to define tables and models in one go, similar to how Django works. In addition to the following text I recommend the official documentation on the `declarative`_ extension. Here's the example :file:`database.py` module for your application:: from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import yourapplication.models Base.metadata.create_all(bind=engine) To define your models, just subclass the `Base` class that was created by the code above. If you are wondering why we don't have to care about threads here (like we did in the SQLite3 example above with the :data:`~flask.g` object): that's because SQLAlchemy does that for us already with the :class:`~sqlalchemy.orm.scoped_session`. To use SQLAlchemy in a declarative way with your application, you just have to put the following code into your application module. Flask will automatically remove database sessions at the end of the request or when the application shuts down:: from yourapplication.database import db_session @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() Here is an example model (put this into :file:`models.py`, e.g.):: from sqlalchemy import Column, Integer, String from yourapplication.database import Base class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50), unique=True) email = Column(String(120), unique=True) def __init__(self, name=None, email=None): self.name = name self.email = email def __repr__(self): return '' % (self.name) To create the database you can use the `init_db` function: >>> from yourapplication.database import init_db >>> init_db() You can insert entries into the database like this: >>> from yourapplication.database import db_session >>> from yourapplication.models import User >>> u = User('admin', 'admin@localhost') >>> db_session.add(u) >>> db_session.commit() Querying is simple as well: >>> User.query.all() [] >>> User.query.filter(User.name == 'admin').first() .. _SQLAlchemy: http://www.sqlalchemy.org/ .. _declarative: http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/ Manual Object Relational Mapping -------------------------------- Manual object relational mapping has a few upsides and a few downsides versus the declarative approach from above. The main difference is that you define tables and classes separately and map them together. It's more flexible but a little more to type. In general it works like the declarative approach, so make sure to also split up your application into multiple modules in a package. Here is an example :file:`database.py` module for your application:: from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) metadata = MetaData() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) def init_db(): metadata.create_all(bind=engine) As in the declarative approach, you need to close the session after each request or application context shutdown. Put this into your application module:: from yourapplication.database import db_session @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() Here is an example table and model (put this into :file:`models.py`):: from sqlalchemy import Table, Column, Integer, String from sqlalchemy.orm import mapper from yourapplication.database import metadata, db_session class User(object): query = db_session.query_property() def __init__(self, name=None, email=None): self.name = name self.email = email def __repr__(self): return '' % (self.name) users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String(50), unique=True), Column('email', String(120), unique=True) ) mapper(User, users) Querying and inserting works exactly the same as in the example above. SQL Abstraction Layer --------------------- If you just want to use the database system (and SQL) abstraction layer you basically only need the engine:: from sqlalchemy import create_engine, MetaData, Table engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) metadata = MetaData(bind=engine) Then you can either declare the tables in your code like in the examples above, or automatically load them:: from sqlalchemy import Table users = Table('users', metadata, autoload=True) To insert data you can use the `insert` method. We have to get a connection first so that we can use a transaction: >>> con = engine.connect() >>> con.execute(users.insert(), name='admin', email='admin@localhost') SQLAlchemy will automatically commit for us. To query your database, you use the engine directly or use a connection: >>> users.select(users.c.id == 1).execute().first() (1, u'admin', u'admin@localhost') These results are also dict-like tuples: >>> r = users.select(users.c.id == 1).execute().first() >>> r['name'] u'admin' You can also pass strings of SQL statements to the :meth:`~sqlalchemy.engine.base.Connection.execute` method: >>> engine.execute('select * from users where id = :1', [1]).first() (1, u'admin', u'admin@localhost') For more information about SQLAlchemy, head over to the `website `_. Flask-0.12.2/docs/patterns/methodoverrides.rst0000644000175000001440000000273612425200262022551 0ustar untitakerusers00000000000000Adding HTTP Method Overrides ============================ Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP methods (such as PATCH). In that case it's possible to “proxy” HTTP methods through another HTTP method in total violation of the protocol. The way this works is by letting the client do an HTTP POST request and set the ``X-HTTP-Method-Override`` header and set the value to the intended HTTP method (such as ``PATCH``). This can easily be accomplished with an HTTP middleware:: class HTTPMethodOverrideMiddleware(object): allowed_methods = frozenset([ 'GET', 'HEAD', 'POST', 'DELETE', 'PUT', 'PATCH', 'OPTIONS' ]) bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE']) def __init__(self, app): self.app = app def __call__(self, environ, start_response): method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper() if method in self.allowed_methods: method = method.encode('ascii', 'replace') environ['REQUEST_METHOD'] = method if method in self.bodyless_methods: environ['CONTENT_LENGTH'] = '0' return self.app(environ, start_response) To use this with Flask this is all that is necessary:: from flask import Flask app = Flask(__name__) app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) Flask-0.12.2/docs/patterns/mongokit.rst0000644000175000001440000001124612763616450021210 0ustar untitakerusers00000000000000.. mongokit-pattern: MongoKit in Flask ================= Using a document database rather than a full DBMS gets more common these days. This pattern shows how to use MongoKit, a document mapper library, to integrate with MongoDB. This pattern requires a running MongoDB server and the MongoKit library installed. There are two very common ways to use MongoKit. I will outline each of them here: Declarative ----------- The default behavior of MongoKit is the declarative one that is based on common ideas from Django or the SQLAlchemy declarative extension. Here an example :file:`app.py` module for your application:: from flask import Flask from mongokit import Connection, Document # configuration MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 # create the little application object app = Flask(__name__) app.config.from_object(__name__) # connect to the database connection = Connection(app.config['MONGODB_HOST'], app.config['MONGODB_PORT']) To define your models, just subclass the `Document` class that is imported from MongoKit. If you've seen the SQLAlchemy pattern you may wonder why we do not have a session and even do not define a `init_db` function here. On the one hand, MongoKit does not have something like a session. This sometimes makes it more to type but also makes it blazingly fast. On the other hand, MongoDB is schemaless. This means you can modify the data structure from one insert query to the next without any problem. MongoKit is just schemaless too, but implements some validation to ensure data integrity. Here is an example document (put this also into :file:`app.py`, e.g.):: from mongokit import ValidationError def max_length(length): def validate(value): if len(value) <= length: return True # must have %s in error format string to have mongokit place key in there raise ValidationError('%s must be at most {} characters long'.format(length)) return validate class User(Document): structure = { 'name': unicode, 'email': unicode, } validators = { 'name': max_length(50), 'email': max_length(120) } use_dot_notation = True def __repr__(self): return '' % (self.name) # register the User document with our current connection connection.register([User]) This example shows you how to define your schema (named structure), a validator for the maximum character length and uses a special MongoKit feature called `use_dot_notation`. Per default MongoKit behaves like a python dictionary but with `use_dot_notation` set to ``True`` you can use your documents like you use models in nearly any other ORM by using dots to separate between attributes. You can insert entries into the database like this: >>> from yourapplication.database import connection >>> from yourapplication.models import User >>> collection = connection['test'].users >>> user = collection.User() >>> user['name'] = u'admin' >>> user['email'] = u'admin@localhost' >>> user.save() Note that MongoKit is kinda strict with used column types, you must not use a common `str` type for either `name` or `email` but unicode. Querying is simple as well: >>> list(collection.User.find()) [] >>> collection.User.find_one({'name': u'admin'}) .. _MongoKit: http://bytebucket.org/namlook/mongokit/ PyMongo Compatibility Layer --------------------------- If you just want to use PyMongo, you can do that with MongoKit as well. You may use this process if you need the best performance to get. Note that this example does not show how to couple it with Flask, see the above MongoKit code for examples:: from MongoKit import Connection connection = Connection() To insert data you can use the `insert` method. We have to get a collection first, this is somewhat the same as a table in the SQL world. >>> collection = connection['test'].users >>> user = {'name': u'admin', 'email': u'admin@localhost'} >>> collection.insert(user) MongoKit will automatically commit for us. To query your database, you use the collection directly: >>> list(collection.find()) [{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}] >>> collection.find_one({'name': u'admin'}) {u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'} These results are also dict-like objects: >>> r = collection.find_one({'name': u'admin'}) >>> r['email'] u'admin@localhost' For more information about MongoKit, head over to the `website `_. Flask-0.12.2/docs/patterns/sqlite3.rst0000644000175000001440000001206513106517205020733 0ustar untitakerusers00000000000000.. _sqlite3: Using SQLite 3 with Flask ========================= In Flask you can easily implement the opening of database connections on demand and closing them when the context dies (usually at the end of the request). Here is a simple example of how you can use SQLite 3 with Flask:: import sqlite3 from flask import g DATABASE = '/path/to/database.db' def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close() Now, to use the database, the application must either have an active application context (which is always true if there is a request in flight) or create an application context itself. At that point the ``get_db`` function can be used to get the current database connection. Whenever the context is destroyed the database connection will be terminated. Note: if you use Flask 0.9 or older you need to use ``flask._app_ctx_stack.top`` instead of ``g`` as the :data:`flask.g` object was bound to the request and not application context. Example:: @app.route('/') def index(): cur = get_db().cursor() ... .. note:: Please keep in mind that the teardown request and appcontext functions are always executed, even if a before-request handler failed or was never executed. Because of this we have to make sure here that the database is there before we close it. Connect on Demand ----------------- The upside of this approach (connecting on first use) is that this will only open the connection if truly necessary. If you want to use this code outside a request context you can use it in a Python shell by opening the application context by hand:: with app.app_context(): # now you can use get_db() .. _easy-querying: Easy Querying ------------- Now in each request handling function you can access `g.db` to get the current open database connection. To simplify working with SQLite, a row factory function is useful. It is executed for every result returned from the database to convert the result. For instance, in order to get dictionaries instead of tuples, this could be inserted into the ``get_db`` function we created above:: def make_dicts(cursor, row): return dict((cursor.description[idx][0], value) for idx, value in enumerate(row)) db.row_factory = make_dicts This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead:: db.row_factory = sqlite3.Row This would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``:: >>> # You can get values based on the row's name >>> r['FirstName'] John >>> # Or, you can get them based on index >>> r[1] John # Row objects are also iterable: >>> for value in r: ... print(value) 1 John Doe M Additionally, it is a good idea to provide a query function that combines getting the cursor, executing and fetching the results:: def query_db(query, args=(), one=False): cur = get_db().execute(query, args) rv = cur.fetchall() cur.close() return (rv[0] if rv else None) if one else rv This handy little function, in combination with a row factory, makes working with the database much more pleasant than it is by just using the raw cursor and connection objects. Here is how you can use it:: for user in query_db('select * from users'): print user['username'], 'has the id', user['user_id'] Or if you just want a single result:: user = query_db('select * from users where username = ?', [the_username], one=True) if user is None: print 'No such user' else: print the_username, 'has the id', user['user_id'] To pass variable parts to the SQL statement, use a question mark in the statement and pass in the arguments as a list. Never directly add them to the SQL statement with string formatting because this makes it possible to attack the application using `SQL Injections `_. Initial Schemas --------------- Relational databases need schemas, so applications often ship a `schema.sql` file that creates the database. It's a good idea to provide a function that creates the database based on that schema. This function can do that for you:: def init_db(): with app.app_context(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() You can then create such a database from the Python shell: >>> from yourapplication import init_db >>> init_db() Flask-0.12.2/docs/patterns/caching.rst0000644000175000001440000000476412763616450020764 0ustar untitakerusers00000000000000.. _caching-pattern: Caching ======= When your application runs slow, throw some caches in. Well, at least it's the easiest way to speed up things. What does a cache do? Say you have a function that takes some time to complete but the results would still be good enough if they were 5 minutes old. So then the idea is that you actually put the result of that calculation into a cache for some time. Flask itself does not provide caching for you, but Werkzeug, one of the libraries it is based on, has some very basic cache support. It supports multiple cache backends, normally you want to use a memcached server. Setting up a Cache ------------------ You create a cache object once and keep it around, similar to how :class:`~flask.Flask` objects are created. If you are using the development server you can create a :class:`~werkzeug.contrib.cache.SimpleCache` object, that one is a simple cache that keeps the item stored in the memory of the Python interpreter:: from werkzeug.contrib.cache import SimpleCache cache = SimpleCache() If you want to use memcached, make sure to have one of the memcache modules supported (you get them from `PyPI `_) and a memcached server running somewhere. This is how you connect to such an memcached server then:: from werkzeug.contrib.cache import MemcachedCache cache = MemcachedCache(['127.0.0.1:11211']) If you are using App Engine, you can connect to the App Engine memcache server easily:: from werkzeug.contrib.cache import GAEMemcachedCache cache = GAEMemcachedCache() Using a Cache ------------- Now how can one use such a cache? There are two very important operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and :meth:`~werkzeug.contrib.cache.BaseCache.set`. This is how to use them: To get an item from the cache call :meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name. If something is in the cache, it is returned. Otherwise that function will return ``None``:: rv = cache.get('my-item') To add items to the cache, use the :meth:`~werkzeug.contrib.cache.BaseCache.set` method instead. The first argument is the key and the second the value that should be set. Also a timeout can be provided after which the cache will automatically remove item. Here a full example how this looks like normally:: def get_my_item(): rv = cache.get('my-item') if rv is None: rv = calculate_value() cache.set('my-item', rv, timeout=5 * 60) return rv Flask-0.12.2/docs/patterns/requestchecksum.rst0000644000175000001440000000350712425200262022556 0ustar untitakerusers00000000000000Request Content Checksums ========================= Various pieces of code can consume the request data and preprocess it. For instance JSON data ends up on the request object already read and processed, form data ends up there as well but goes through a different code path. This seems inconvenient when you want to calculate the checksum of the incoming request data. This is necessary sometimes for some APIs. Fortunately this is however very simple to change by wrapping the input stream. The following example calculates the SHA1 checksum of the incoming data as it gets read and stores it in the WSGI environment:: import hashlib class ChecksumCalcStream(object): def __init__(self, stream): self._stream = stream self._hash = hashlib.sha1() def read(self, bytes): rv = self._stream.read(bytes) self._hash.update(rv) return rv def readline(self, size_hint): rv = self._stream.readline(size_hint) self._hash.update(rv) return rv def generate_checksum(request): env = request.environ stream = ChecksumCalcStream(env['wsgi.input']) env['wsgi.input'] = stream return stream._hash To use this, all you need to do is to hook the calculating stream in before the request starts consuming data. (Eg: be careful accessing ``request.form`` or anything of that nature. ``before_request_handlers`` for instance should be careful not to access it). Example usage:: @app.route('/special-api', methods=['POST']) def special_api(): hash = generate_checksum(request) # Accessing this parses the input stream files = request.files # At this point the hash is fully constructed. checksum = hash.hexdigest() return 'Hash was: %s' % checksum Flask-0.12.2/docs/advanced_foreword.rst0000644000175000001440000000520712765277163021203 0ustar untitakerusers00000000000000.. _advanced_foreword: Foreword for Experienced Programmers ==================================== Thread-Locals in Flask ---------------------- One of the design decisions in Flask was that simple tasks should be simple; they should not take a lot of code and yet they should not limit you. Because of that, Flask has a few design choices that some people might find surprising or unorthodox. For example, Flask uses thread-local objects internally so that you don’t have to pass objects around from function to function within a request in order to stay threadsafe. This approach is convenient, but requires a valid request context for dependency injection or when attempting to reuse code which uses a value pegged to the request. The Flask project is honest about thread-locals, does not hide them, and calls out in the code and documentation where they are used. Develop for the Web with Caution -------------------------------- Always keep security in mind when building web applications. If you write a web application, you are probably allowing users to register and leave their data on your server. The users are entrusting you with data. And even if you are the only user that might leave data in your application, you still want that data to be stored securely. Unfortunately, there are many ways the security of a web application can be compromised. Flask protects you against one of the most common security problems of modern web applications: cross-site scripting (XSS). Unless you deliberately mark insecure HTML as secure, Flask and the underlying Jinja2 template engine have you covered. But there are many more ways to cause security problems. The documentation will warn you about aspects of web development that require attention to security. Some of these security concerns are far more complex than one might think, and we all sometimes underestimate the likelihood that a vulnerability will be exploited - until a clever attacker figures out a way to exploit our applications. And don't think that your application is not important enough to attract an attacker. Depending on the kind of attack, chances are that automated bots are probing for ways to fill your database with spam, links to malicious software, and the like. Flask is no different from any other framework in that you the developer must build with caution, watching for exploits when building to your requirements. Python 3 Support in Flask ------------------------- Flask, its dependencies, and most Flask extensions all support Python 3. If you want to use Flask with Python 3 have a look at the :ref:`python3-support` page. Continue to :ref:`installation` or the :ref:`quickstart`. Flask-0.12.2/docs/becomingbig.rst0000644000175000001440000001110513047321000017734 0ustar untitakerusers00000000000000.. _becomingbig: Becoming Big ============ Here are your options when growing your codebase or scaling your application. Read the Source. ---------------- Flask started in part to demonstrate how to build your own framework on top of existing well-used tools Werkzeug (WSGI) and Jinja (templating), and as it developed, it became useful to a wide audience. As you grow your codebase, don't just use Flask -- understand it. Read the source. Flask's code is written to be read; its documentation is published so you can use its internal APIs. Flask sticks to documented APIs in upstream libraries, and documents its internal utilities so that you can find the hook points needed for your project. Hook. Extend. ------------- The :ref:`api` docs are full of available overrides, hook points, and :ref:`signals`. You can provide custom classes for things like the request and response objects. Dig deeper on the APIs you use, and look for the customizations which are available out of the box in a Flask release. Look for ways in which your project can be refactored into a collection of utilities and Flask extensions. Explore the many `extensions `_ in the community, and look for patterns to build your own extensions if you do not find the tools you need. Subclass. --------- The :class:`~flask.Flask` class has many methods designed for subclassing. You can quickly add or customize behavior by subclassing :class:`~flask.Flask` (see the linked method docs) and using that subclass wherever you instantiate an application class. This works well with :ref:`app-factories`. See :doc:`/patterns/subclassing` for an example. Wrap with middleware. --------------------- The :ref:`app-dispatch` chapter shows in detail how to apply middleware. You can introduce WSGI middleware to wrap your Flask instances and introduce fixes and changes at the layer between your Flask application and your HTTP server. Werkzeug includes several `middlewares `_. Fork. ----- If none of the above options work, fork Flask. The majority of code of Flask is within Werkzeug and Jinja2. These libraries do the majority of the work. Flask is just the paste that glues those together. For every project there is the point where the underlying framework gets in the way (due to assumptions the original developers had). This is natural because if this would not be the case, the framework would be a very complex system to begin with which causes a steep learning curve and a lot of user frustration. This is not unique to Flask. Many people use patched and modified versions of their framework to counter shortcomings. This idea is also reflected in the license of Flask. You don't have to contribute any changes back if you decide to modify the framework. The downside of forking is of course that Flask extensions will most likely break because the new framework has a different import name. Furthermore integrating upstream changes can be a complex process, depending on the number of changes. Because of that, forking should be the very last resort. Scale like a pro. ----------------- For many web applications the complexity of the code is less an issue than the scaling for the number of users or data entries expected. Flask by itself is only limited in terms of scaling by your application code, the data store you want to use and the Python implementation and webserver you are running on. Scaling well means for example that if you double the amount of servers you get about twice the performance. Scaling bad means that if you add a new server the application won't perform any better or would not even support a second server. There is only one limiting factor regarding scaling in Flask which are the context local proxies. They depend on context which in Flask is defined as being either a thread, process or greenlet. If your server uses some kind of concurrency that is not based on threads or greenlets, Flask will no longer be able to support these global proxies. However the majority of servers are using either threads, greenlets or separate processes to achieve concurrency which are all methods well supported by the underlying Werkzeug library. Discuss with the community. --------------------------- The Flask developers keep the framework accessible to users with codebases big and small. If you find an obstacle in your way, caused by Flask, don't hesitate to contact the developers on the mailinglist or IRC channel. The best way for the Flask and Flask extension developers to improve the tools for larger applications is getting feedback from users. Flask-0.12.2/docs/Makefile0000644000175000001440000001007612163033661016416 0ustar untitakerusers00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp epub latex changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) _build/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask" @echo "# ln -s _build/devhelp $$HOME/.local/share/devhelp/Flask" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." latexpdf: latex $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex @echo "Running LaTeX files through pdflatex..." make -C _build/latex all-pdf @echo "pdflatex finished; the PDF files are in _build/latex." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." Flask-0.12.2/docs/flaskext.py0000644000175000001440000001141312163033661017145 0ustar untitakerusers00000000000000# flasky extensions. flasky pygments style based on tango style from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace, Punctuation, Other, Literal class FlaskyStyle(Style): background_color = "#f8f8f8" default_style = "" styles = { # No corresponding class for the following: #Text: "", # class: '' Whitespace: "underline #f8f8f8", # class: 'w' Error: "#a40000 border:#ef2929", # class: 'err' Other: "#000000", # class 'x' Comment: "italic #8f5902", # class: 'c' Comment.Preproc: "noitalic", # class: 'cp' Keyword: "bold #004461", # class: 'k' Keyword.Constant: "bold #004461", # class: 'kc' Keyword.Declaration: "bold #004461", # class: 'kd' Keyword.Namespace: "bold #004461", # class: 'kn' Keyword.Pseudo: "bold #004461", # class: 'kp' Keyword.Reserved: "bold #004461", # class: 'kr' Keyword.Type: "bold #004461", # class: 'kt' Operator: "#582800", # class: 'o' Operator.Word: "bold #004461", # class: 'ow' - like keywords Punctuation: "bold #000000", # class: 'p' # because special names such as Name.Class, Name.Function, etc. # are not recognized as such later in the parsing, we choose them # to look the same as ordinary variables. Name: "#000000", # class: 'n' Name.Attribute: "#c4a000", # class: 'na' - to be revised Name.Builtin: "#004461", # class: 'nb' Name.Builtin.Pseudo: "#3465a4", # class: 'bp' Name.Class: "#000000", # class: 'nc' - to be revised Name.Constant: "#000000", # class: 'no' - to be revised Name.Decorator: "#888", # class: 'nd' - to be revised Name.Entity: "#ce5c00", # class: 'ni' Name.Exception: "bold #cc0000", # class: 'ne' Name.Function: "#000000", # class: 'nf' Name.Property: "#000000", # class: 'py' Name.Label: "#f57900", # class: 'nl' Name.Namespace: "#000000", # class: 'nn' - to be revised Name.Other: "#000000", # class: 'nx' Name.Tag: "bold #004461", # class: 'nt' - like a keyword Name.Variable: "#000000", # class: 'nv' - to be revised Name.Variable.Class: "#000000", # class: 'vc' - to be revised Name.Variable.Global: "#000000", # class: 'vg' - to be revised Name.Variable.Instance: "#000000", # class: 'vi' - to be revised Number: "#990000", # class: 'm' Literal: "#000000", # class: 'l' Literal.Date: "#000000", # class: 'ld' String: "#4e9a06", # class: 's' String.Backtick: "#4e9a06", # class: 'sb' String.Char: "#4e9a06", # class: 'sc' String.Doc: "italic #8f5902", # class: 'sd' - like a comment String.Double: "#4e9a06", # class: 's2' String.Escape: "#4e9a06", # class: 'se' String.Heredoc: "#4e9a06", # class: 'sh' String.Interpol: "#4e9a06", # class: 'si' String.Other: "#4e9a06", # class: 'sx' String.Regex: "#4e9a06", # class: 'sr' String.Single: "#4e9a06", # class: 's1' String.Symbol: "#4e9a06", # class: 'ss' Generic: "#000000", # class: 'g' Generic.Deleted: "#a40000", # class: 'gd' Generic.Emph: "italic #000000", # class: 'ge' Generic.Error: "#ef2929", # class: 'gr' Generic.Heading: "bold #000080", # class: 'gh' Generic.Inserted: "#00A000", # class: 'gi' Generic.Output: "#888", # class: 'go' Generic.Prompt: "#745334", # class: 'gp' Generic.Strong: "bold #000000", # class: 'gs' Generic.Subheading: "bold #800080", # class: 'gu' Generic.Traceback: "bold #a40000", # class: 'gt' } Flask-0.12.2/docs/templating.rst0000644000175000001440000001661312763616450017670 0ustar untitakerusers00000000000000Templates ========= Flask leverages Jinja2 as template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present. This section only gives a very quick introduction into how Jinja2 is integrated into Flask. If you want information on the template engine's syntax itself, head over to the official `Jinja2 Template Documentation `_ for more information. Jinja Setup ----------- Unless customized, Jinja2 is configured by Flask as follows: - autoescaping is enabled for all templates ending in ``.html``, ``.htm``, ``.xml`` as well as ``.xhtml`` when using :func:`~flask.templating.render_template`. - autoescaping is enabled for all strings when using :func:`~flask.templating.render_template_string`. - a template has the ability to opt in/out autoescaping with the ``{% autoescape %}`` tag. - Flask inserts a couple of global functions and helpers into the Jinja2 context, additionally to the values that are present by default. Standard Context ---------------- The following global variables are available within Jinja2 templates by default: .. data:: config :noindex: The current configuration object (:data:`flask.config`) .. versionadded:: 0.6 .. versionchanged:: 0.10 This is now always available, even in imported templates. .. data:: request :noindex: The current request object (:class:`flask.request`). This variable is unavailable if the template was rendered without an active request context. .. data:: session :noindex: The current session object (:class:`flask.session`). This variable is unavailable if the template was rendered without an active request context. .. data:: g :noindex: The request-bound object for global variables (:data:`flask.g`). This variable is unavailable if the template was rendered without an active request context. .. function:: url_for :noindex: The :func:`flask.url_for` function. .. function:: get_flashed_messages :noindex: The :func:`flask.get_flashed_messages` function. .. admonition:: The Jinja Context Behavior These variables are added to the context of variables, they are not global variables. The difference is that by default these will not show up in the context of imported templates. This is partially caused by performance considerations, partially to keep things explicit. What does this mean for you? If you have a macro you want to import, that needs to access the request object you have two possibilities: 1. you explicitly pass the request to the macro as parameter, or the attribute of the request object you are interested in. 2. you import the macro "with context". Importing with context looks like this: .. sourcecode:: jinja {% from '_helpers.html' import my_macro with context %} Standard Filters ---------------- These filters are available in Jinja2 additionally to the filters provided by Jinja2 itself: .. function:: tojson :noindex: This function converts the given object into JSON representation. This is for example very helpful if you try to generate JavaScript on the fly. Note that inside ``script`` tags no escaping must take place, so make sure to disable escaping with ``|safe`` before Flask 0.10 if you intend to use it inside ``script`` tags: .. sourcecode:: html+jinja Controlling Autoescaping ------------------------ Autoescaping is the concept of automatically escaping special characters for you. Special characters in the sense of HTML (or XML, and thus XHTML) are ``&``, ``>``, ``<``, ``"`` as well as ``'``. Because these characters carry specific meanings in documents on their own you have to replace them by so called "entities" if you want to use them for text. Not doing so would not only cause user frustration by the inability to use these characters in text, but can also lead to security problems. (see :ref:`xss`) Sometimes however you will need to disable autoescaping in templates. This can be the case if you want to explicitly inject HTML into pages, for example if they come from a system that generates secure HTML like a markdown to HTML converter. There are three ways to accomplish that: - In the Python code, wrap the HTML string in a :class:`~flask.Markup` object before passing it to the template. This is in general the recommended way. - Inside the template, use the ``|safe`` filter to explicitly mark a string as safe HTML (``{{ myvariable|safe }}``) - Temporarily disable the autoescape system altogether. To disable the autoescape system in templates, you can use the ``{% autoescape %}`` block: .. sourcecode:: html+jinja {% autoescape false %}

autoescaping is disabled here

{{ will_not_be_escaped }} {% endautoescape %} Whenever you do this, please be very cautious about the variables you are using in this block. .. _registering-filters: Registering Filters ------------------- If you want to register your own filters in Jinja2 you have two ways to do that. You can either put them by hand into the :attr:`~flask.Flask.jinja_env` of the application or use the :meth:`~flask.Flask.template_filter` decorator. The two following examples work the same and both reverse an object:: @app.template_filter('reverse') def reverse_filter(s): return s[::-1] def reverse_filter(s): return s[::-1] app.jinja_env.filters['reverse'] = reverse_filter In case of the decorator the argument is optional if you want to use the function name as name of the filter. Once registered, you can use the filter in your templates in the same way as Jinja2's builtin filters, for example if you have a Python list in context called `mylist`:: {% for x in mylist | reverse %} {% endfor %} Context Processors ------------------ To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app:: @app.context_processor def inject_user(): return dict(user=g.user) The context processor above makes a variable called `user` available in the template with the value of `g.user`. This example is not very interesting because `g` is available in templates anyways, but it gives an idea how this works. Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions):: @app.context_processor def utility_processor(): def format_price(amount, currency=u'€'): return u'{0:.2f}{1}'.format(amount, currency) return dict(format_price=format_price) The context processor above makes the `format_price` function available to all templates:: {{ format_price(0.33) }} You could also build `format_price` as a template filter (see :ref:`registering-filters`), but this demonstrates how to pass functions in a context processor. Flask-0.12.2/docs/security.rst0000644000175000001440000001112113106517205017346 0ustar untitakerusers00000000000000Security Considerations ======================= Web applications usually face all kinds of security problems and it's very hard to get everything right. Flask tries to solve a few of these things for you, but there are a couple more you have to take care of yourself. .. _xss: Cross-Site Scripting (XSS) -------------------------- Cross site scripting is the concept of injecting arbitrary HTML (and with it JavaScript) into the context of a website. To remedy this, developers have to properly escape text so that it cannot include arbitrary HTML tags. For more information on that have a look at the Wikipedia article on `Cross-Site Scripting `_. Flask configures Jinja2 to automatically escape all values unless explicitly told otherwise. This should rule out all XSS problems caused in templates, but there are still other places where you have to be careful: - generating HTML without the help of Jinja2 - calling :class:`~flask.Markup` on data submitted by users - sending out HTML from uploaded files, never do that, use the ``Content-Disposition: attachment`` header to prevent that problem. - sending out textfiles from uploaded files. Some browsers are using content-type guessing based on the first few bytes so users could trick a browser to execute HTML. Another thing that is very important are unquoted attributes. While Jinja2 can protect you from XSS issues by escaping HTML, there is one thing it cannot protect you from: XSS by attribute injection. To counter this possible attack vector, be sure to always quote your attributes with either double or single quotes when using Jinja expressions in them: .. sourcecode:: html+jinja the text Why is this necessary? Because if you would not be doing that, an attacker could easily inject custom JavaScript handlers. For example an attacker could inject this piece of HTML+JavaScript: .. sourcecode:: html onmouseover=alert(document.cookie) When the user would then move with the mouse over the link, the cookie would be presented to the user in an alert window. But instead of showing the cookie to the user, a good attacker might also execute any other JavaScript code. In combination with CSS injections the attacker might even make the element fill out the entire page so that the user would just have to have the mouse anywhere on the page to trigger the attack. Cross-Site Request Forgery (CSRF) --------------------------------- Another big problem is CSRF. This is a very complex topic and I won't outline it here in detail just mention what it is and how to theoretically prevent it. If your authentication information is stored in cookies, you have implicit state management. The state of "being logged in" is controlled by a cookie, and that cookie is sent with each request to a page. Unfortunately that includes requests triggered by 3rd party sites. If you don't keep that in mind, some people might be able to trick your application's users with social engineering to do stupid things without them knowing. Say you have a specific URL that, when you sent ``POST`` requests to will delete a user's profile (say ``http://example.com/user/delete``). If an attacker now creates a page that sends a post request to that page with some JavaScript they just have to trick some users to load that page and their profiles will end up being deleted. Imagine you were to run Facebook with millions of concurrent users and someone would send out links to images of little kittens. When users would go to that page, their profiles would get deleted while they are looking at images of fluffy cats. How can you prevent that? Basically for each request that modifies content on the server you would have to either use a one-time token and store that in the cookie **and** also transmit it with the form data. After receiving the data on the server again, you would then have to compare the two tokens and ensure they are equal. Why does Flask not do that for you? The ideal place for this to happen is the form validation framework, which does not exist in Flask. .. _json-security: JSON Security ------------- In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level arrays to JSON. This was because of a security vulnerability in ECMAScript 4. ECMAScript 5 closed this vulnerability, so only extremely old browsers are still vulnerable. All of these browsers have `other more serious vulnerabilities `_, so this behavior was changed and :func:`~flask.jsonify` now supports serializing arrays. Flask-0.12.2/docs/extensiondev.rst0000644000175000001440000004021213106517205020215 0ustar untitakerusers00000000000000.. _extension-dev: Flask Extension Development =========================== Flask, being a microframework, often requires some repetitive steps to get a third party library working. Because very often these steps could be abstracted to support multiple projects the `Flask Extension Registry`_ was created. If you want to create your own Flask extension for something that does not exist yet, this guide to extension development will help you get your extension running in no time and to feel like users would expect your extension to behave. .. _Flask Extension Registry: http://flask.pocoo.org/extensions/ Anatomy of an Extension ----------------------- Extensions are all located in a package called ``flask_something`` where "something" is the name of the library you want to bridge. So for example if you plan to add support for a library named `simplexml` to Flask, you would name your extension's package ``flask_simplexml``. The name of the actual extension (the human readable name) however would be something like "Flask-SimpleXML". Make sure to include the name "Flask" somewhere in that name and that you check the capitalization. This is how users can then register dependencies to your extension in their :file:`setup.py` files. Flask sets up a redirect package called :data:`flask.ext` where users should import the extensions from. If you for instance have a package called ``flask_something`` users would import it as ``flask.ext.something``. This is done to transition from the old namespace packages. See :ref:`ext-import-transition` for more details. But what do extensions look like themselves? An extension has to ensure that it works with multiple Flask application instances at once. This is a requirement because many people will use patterns like the :ref:`app-factories` pattern to create their application as needed to aid unittests and to support multiple configurations. Because of that it is crucial that your application supports that kind of behavior. Most importantly the extension must be shipped with a :file:`setup.py` file and registered on PyPI. Also the development checkout link should work so that people can easily install the development version into their virtualenv without having to download the library by hand. Flask extensions must be licensed under a BSD, MIT or more liberal license to be able to be enlisted in the Flask Extension Registry. Keep in mind that the Flask Extension Registry is a moderated place and libraries will be reviewed upfront if they behave as required. "Hello Flaskext!" ----------------- So let's get started with creating such a Flask extension. The extension we want to create here will provide very basic support for SQLite3. First we create the following folder structure:: flask-sqlite3/ flask_sqlite3.py LICENSE README Here's the contents of the most important files: setup.py ```````` The next file that is absolutely required is the :file:`setup.py` file which is used to install your Flask extension. The following contents are something you can work with:: """ Flask-SQLite3 ------------- This is the description for that library """ from setuptools import setup setup( name='Flask-SQLite3', version='1.0', url='http://example.com/flask-sqlite3/', license='BSD', author='Your Name', author_email='your-email@example.com', description='Very short description', long_description=__doc__, py_modules=['flask_sqlite3'], # if you would be using a package instead use packages instead # of py_modules: # packages=['flask_sqlite3'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) That's a lot of code but you can really just copy/paste that from existing extensions and adapt. flask_sqlite3.py ```````````````` Now this is where your extension code goes. But how exactly should such an extension look like? What are the best practices? Continue reading for some insight. Initializing Extensions ----------------------- Many extensions will need some kind of initialization step. For example, consider an application that's currently connecting to SQLite like the documentation suggests (:ref:`sqlite3`). So how does the extension know the name of the application object? Quite simple: you pass it to it. There are two recommended ways for an extension to initialize: initialization functions: If your extension is called `helloworld` you might have a function called ``init_helloworld(app[, extra_args])`` that initializes the extension for that application. It could attach before / after handlers etc. classes: Classes work mostly like initialization functions but can later be used to further change the behavior. For an example look at how the `OAuth extension`_ works: there is an `OAuth` object that provides some helper functions like `OAuth.remote_app` to create a reference to a remote application that uses OAuth. What to use depends on what you have in mind. For the SQLite 3 extension we will use the class-based approach because it will provide users with an object that handles opening and closing database connections. What's important about classes is that they encourage to be shared around on module level. In that case, the object itself must not under any circumstances store any application specific state and must be shareable between different application. The Extension Code ------------------ Here's the contents of the `flask_sqlite3.py` for copy/paste:: import sqlite3 from flask import current_app # Find the stack on which we want to store the database connection. # Starting with Flask 0.9, the _app_ctx_stack is the correct one, # before that we need to use the _request_ctx_stack. try: from flask import _app_ctx_stack as stack except ImportError: from flask import _request_ctx_stack as stack class SQLite3(object): def __init__(self, app=None): self.app = app if app is not None: self.init_app(app) def init_app(self, app): app.config.setdefault('SQLITE3_DATABASE', ':memory:') # Use the newstyle teardown_appcontext if it's available, # otherwise fall back to the request context if hasattr(app, 'teardown_appcontext'): app.teardown_appcontext(self.teardown) else: app.teardown_request(self.teardown) def connect(self): return sqlite3.connect(current_app.config['SQLITE3_DATABASE']) def teardown(self, exception): ctx = stack.top if hasattr(ctx, 'sqlite3_db'): ctx.sqlite3_db.close() @property def connection(self): ctx = stack.top if ctx is not None: if not hasattr(ctx, 'sqlite3_db'): ctx.sqlite3_db = self.connect() return ctx.sqlite3_db So here's what these lines of code do: 1. The ``__init__`` method takes an optional app object and, if supplied, will call ``init_app``. 2. The ``init_app`` method exists so that the ``SQLite3`` object can be instantiated without requiring an app object. This method supports the factory pattern for creating applications. The ``init_app`` will set the configuration for the database, defaulting to an in memory database if no configuration is supplied. In addition, the ``init_app`` method attaches the ``teardown`` handler. It will try to use the newstyle app context handler and if it does not exist, falls back to the request context one. 3. Next, we define a ``connect`` method that opens a database connection. 4. Finally, we add a ``connection`` property that on first access opens the database connection and stores it on the context. This is also the recommended way to handling resources: fetch resources lazily the first time they are used. Note here that we're attaching our database connection to the top application context via ``_app_ctx_stack.top``. Extensions should use the top context for storing their own information with a sufficiently complex name. Note that we're falling back to the ``_request_ctx_stack.top`` if the application is using an older version of Flask that does not support it. So why did we decide on a class-based approach here? Because using our extension looks something like this:: from flask import Flask from flask_sqlite3 import SQLite3 app = Flask(__name__) app.config.from_pyfile('the-config.cfg') db = SQLite3(app) You can then use the database from views like this:: @app.route('/') def show_all(): cur = db.connection.cursor() cur.execute(...) Likewise if you are outside of a request but you are using Flask 0.9 or later with the app context support, you can use the database in the same way:: with app.app_context(): cur = db.connection.cursor() cur.execute(...) At the end of the ``with`` block the teardown handles will be executed automatically. Additionally, the ``init_app`` method is used to support the factory pattern for creating apps:: db = Sqlite3() # Then later on. app = create_app('the-config.cfg') db.init_app(app) Keep in mind that supporting this factory pattern for creating apps is required for approved flask extensions (described below). .. admonition:: Note on ``init_app`` As you noticed, ``init_app`` does not assign ``app`` to ``self``. This is intentional! Class based Flask extensions must only store the application on the object when the application was passed to the constructor. This tells the extension: I am not interested in using multiple applications. When the extension needs to find the current application and it does not have a reference to it, it must either use the :data:`~flask.current_app` context local or change the API in a way that you can pass the application explicitly. Using _app_ctx_stack -------------------- In the example above, before every request, a ``sqlite3_db`` variable is assigned to ``_app_ctx_stack.top``. In a view function, this variable is accessible using the ``connection`` property of ``SQLite3``. During the teardown of a request, the ``sqlite3_db`` connection is closed. By using this pattern, the *same* connection to the sqlite3 database is accessible to anything that needs it for the duration of the request. If the :data:`~flask._app_ctx_stack` does not exist because the user uses an old version of Flask, it is recommended to fall back to :data:`~flask._request_ctx_stack` which is bound to a request. Teardown Behavior ----------------- *This is only relevant if you want to support Flask 0.6 and older* Due to the change in Flask 0.7 regarding functions that are run at the end of the request your extension will have to be extra careful there if it wants to continue to support older versions of Flask. The following pattern is a good way to support both:: def close_connection(response): ctx = _request_ctx_stack.top ctx.sqlite3_db.close() return response if hasattr(app, 'teardown_request'): app.teardown_request(close_connection) else: app.after_request(close_connection) Strictly speaking the above code is wrong, because teardown functions are passed the exception and typically don't return anything. However because the return value is discarded this will just work assuming that the code in between does not touch the passed parameter. Learn from Others ----------------- This documentation only touches the bare minimum for extension development. If you want to learn more, it's a very good idea to check out existing extensions on the `Flask Extension Registry`_. If you feel lost there is still the `mailinglist`_ and the `IRC channel`_ to get some ideas for nice looking APIs. Especially if you do something nobody before you did, it might be a very good idea to get some more input. This not only to get an idea about what people might want to have from an extension, but also to avoid having multiple developers working on pretty much the same side by side. Remember: good API design is hard, so introduce your project on the mailinglist, and let other developers give you a helping hand with designing the API. The best Flask extensions are extensions that share common idioms for the API. And this can only work if collaboration happens early. Approved Extensions ------------------- Flask also has the concept of approved extensions. Approved extensions are tested as part of Flask itself to ensure extensions do not break on new releases. These approved extensions are listed on the `Flask Extension Registry`_ and marked appropriately. If you want your own extension to be approved you have to follow these guidelines: 0. An approved Flask extension requires a maintainer. In the event an extension author would like to move beyond the project, the project should find a new maintainer including full source hosting transition and PyPI access. If no maintainer is available, give access to the Flask core team. 1. An approved Flask extension must provide exactly one package or module named ``flask_extensionname``. 2. It must ship a testing suite that can either be invoked with ``make test`` or ``python setup.py test``. For test suites invoked with ``make test`` the extension has to ensure that all dependencies for the test are installed automatically. If tests are invoked with ``python setup.py test``, test dependencies can be specified in the :file:`setup.py` file. The test suite also has to be part of the distribution. 3. APIs of approved extensions will be checked for the following characteristics: - an approved extension has to support multiple applications running in the same Python process. - it must be possible to use the factory pattern for creating applications. 4. The license must be BSD/MIT/WTFPL licensed. 5. The naming scheme for official extensions is *Flask-ExtensionName* or *ExtensionName-Flask*. 6. Approved extensions must define all their dependencies in the :file:`setup.py` file unless a dependency cannot be met because it is not available on PyPI. 7. The extension must have documentation that uses one of the two Flask themes for Sphinx documentation. 8. The setup.py description (and thus the PyPI description) has to link to the documentation, website (if there is one) and there must be a link to automatically install the development version (``PackageName==dev``). 9. The ``zip_safe`` flag in the setup script must be set to ``False``, even if the extension would be safe for zipping. 10. An extension currently has to support Python 2.6 as well as Python 2.7 .. _ext-import-transition: Extension Import Transition --------------------------- In early versions of Flask we recommended using namespace packages for Flask extensions, of the form ``flaskext.foo``. This turned out to be problematic in practice because it meant that multiple ``flaskext`` packages coexist. Consequently we have recommended to name extensions ``flask_foo`` over ``flaskext.foo`` for a long time. Flask 0.8 introduced a redirect import system as a compatibility aid for app developers: Importing ``flask.ext.foo`` would try ``flask_foo`` and ``flaskext.foo`` in that order. As of Flask 0.11, most Flask extensions have transitioned to the new naming schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is now deprecated -- you should use ``flask_foo``. .. _OAuth extension: http://pythonhosted.org/Flask-OAuth/ .. _mailinglist: http://flask.pocoo.org/mailinglist/ .. _IRC channel: http://flask.pocoo.org/community/irc/ Flask-0.12.2/docs/errorhandling.rst0000644000175000001440000003672313106517205020354 0ustar untitakerusers00000000000000.. _application-errors: Application Errors ================== .. versionadded:: 0.3 Applications fail, servers fail. Sooner or later you will see an exception in production. Even if your code is 100% correct, you will still see exceptions from time to time. Why? Because everything else involved will fail. Here are some situations where perfectly fine code can lead to server errors: - the client terminated the request early and the application was still reading from the incoming data - the database server was overloaded and could not handle the query - a filesystem is full - a harddrive crashed - a backend server overloaded - a programming error in a library you are using - network connection of the server to another system failed And that's just a small sample of issues you could be facing. So how do we deal with that sort of problem? By default if your application runs in production mode, Flask will display a very simple page for you and log the exception to the :attr:`~flask.Flask.logger`. But there is more you can do, and we will cover some better setups to deal with errors. Error Logging Tools ------------------- Sending error mails, even if just for critical ones, can become overwhelming if enough users are hitting the error and log files are typically never looked at. This is why we recommend using `Sentry `_ for dealing with application errors. It's available as an Open Source project `on GitHub `__ and is also available as a `hosted version `_ which you can try for free. Sentry aggregates duplicate errors, captures the full stack trace and local variables for debugging, and sends you mails based on new errors or frequency thresholds. To use Sentry you need to install the `raven` client:: $ pip install raven And then add this to your Flask app:: from raven.contrib.flask import Sentry sentry = Sentry(app, dsn='YOUR_DSN_HERE') Or if you are using factories you can also init it later:: from raven.contrib.flask import Sentry sentry = Sentry(dsn='YOUR_DSN_HERE') def create_app(): app = Flask(__name__) sentry.init_app(app) ... return app The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get from your Sentry installation. Afterwards failures are automatically reported to Sentry and from there you can receive error notifications. .. _error-handlers: Error handlers -------------- You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers. Error handlers are normal :ref:`views` but instead of being registered for routes, they are registered for exceptions that are raised while trying to do something else. Registering ``````````` Register error handlers using :meth:`~flask.Flask.errorhandler` or :meth:`~flask.Flask.register_error_handler`:: @app.errorhandler(werkzeug.exceptions.BadRequest) def handle_bad_request(e): return 'bad request!' app.register_error_handler(400, lambda e: 'bad request!') Those two ways are equivalent, but the first one is more clear and leaves you with a function to call on your whim (and in tests). Note that :exc:`werkzeug.exceptions.HTTPException` subclasses like :exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes are interchangeable when handed to the registration methods or decorator (``BadRequest.code == 400``). You are however not limited to :exc:`~werkzeug.exceptions.HTTPException` or HTTP status codes but can register a handler for every exception class you like. .. versionchanged:: 0.11 Errorhandlers are now prioritized by specificity of the exception classes they are registered for instead of the order they are registered in. Handling ```````` Once an exception instance is raised, its class hierarchy is traversed, and searched for in the exception classes for which handlers are registered. The most specific handler is selected. E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError` handler is called on the exception instance, and its response is shown to the user. Error Mails ----------- If the application runs in production mode (which it will do on your server) you might not see any log messages. The reason for that is that Flask by default will just report to the WSGI error stream or stderr (depending on what's available). Where this ends up is sometimes hard to find. Often it's in your webserver's log files. I can pretty much promise you however that if you only use a logfile for the application errors you will never look at it except for debugging an issue when a user reported it for you. What you probably want instead is a mail the second the exception happened. Then you get an alert and you can do something about it. Flask uses the Python builtin logging system, and it can actually send you mails for errors which is probably what you want. Here is how you can configure the Flask logger to send you mails for exceptions:: ADMINS = ['yourname@example.com'] if not app.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler('127.0.0.1', 'server-error@example.com', ADMINS, 'YourApplication Failed') mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) So what just happened? We created a new :class:`~logging.handlers.SMTPHandler` that will send mails with the mail server listening on ``127.0.0.1`` to all the `ADMINS` from the address *server-error@example.com* with the subject "YourApplication Failed". If your mail server requires credentials, these can also be provided. For that check out the documentation for the :class:`~logging.handlers.SMTPHandler`. We also tell the handler to only send errors and more critical messages. Because we certainly don't want to get a mail for warnings or other useless logs that might happen during request handling. Before you run that in production, please also look at :ref:`logformat` to put more information into that error mail. That will save you from a lot of frustration. Logging to a File ----------------- Even if you get mails, you probably also want to log warnings. It's a good idea to keep as much information around that might be required to debug a problem. By default as of Flask 0.11, errors are logged to your webserver's log automatically. Warnings however are not. Please note that Flask itself will not issue any warnings in the core system, so it's your responsibility to warn in the code if something seems odd. There are a couple of handlers provided by the logging system out of the box but not all of them are useful for basic error logging. The most interesting are probably the following: - :class:`~logging.FileHandler` - logs messages to a file on the filesystem. - :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file on the filesystem and will rotate after a certain number of messages. - :class:`~logging.handlers.NTEventLogHandler` - will log to the system event log of a Windows system. If you are deploying on a Windows box, this is what you want to use. - :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX syslog. Once you picked your log handler, do like you did with the SMTP handler above, just make sure to use a lower setting (I would recommend `WARNING`):: if not app.debug: import logging from themodule import TheHandlerYouWant file_handler = TheHandlerYouWant(...) file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) .. _logformat: Controlling the Log Format -------------------------- By default a handler will only write the message string into a file or send you that message as mail. A log record stores more information, and it makes a lot of sense to configure your logger to also contain that information so that you have a better idea of why that error happened, and more importantly, where it did. A formatter can be instantiated with a format string. Note that tracebacks are appended to the log entry automatically. You don't have to do that in the log formatter format string. Here are some example setups: Email ````` :: from logging import Formatter mail_handler.setFormatter(Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''')) File logging ```````````` :: from logging import Formatter file_handler.setFormatter(Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' )) Complex Log Formatting `````````````````````` Here is a list of useful formatting variables for the format string. Note that this list is not complete, consult the official documentation of the :mod:`logging` package for a full list. .. tabularcolumns:: |p{3cm}|p{12cm}| +------------------+----------------------------------------------------+ | Format | Description | +==================+====================================================+ | ``%(levelname)s``| Text logging level for the message | | | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, | | | ``'ERROR'``, ``'CRITICAL'``). | +------------------+----------------------------------------------------+ | ``%(pathname)s`` | Full pathname of the source file where the | | | logging call was issued (if available). | +------------------+----------------------------------------------------+ | ``%(filename)s`` | Filename portion of pathname. | +------------------+----------------------------------------------------+ | ``%(module)s`` | Module (name portion of filename). | +------------------+----------------------------------------------------+ | ``%(funcName)s`` | Name of function containing the logging call. | +------------------+----------------------------------------------------+ | ``%(lineno)d`` | Source line number where the logging call was | | | issued (if available). | +------------------+----------------------------------------------------+ | ``%(asctime)s`` | Human-readable time when the | | | :class:`~logging.LogRecord` was created. | | | By default this is of the form | | | ``"2003-07-08 16:49:45,896"`` (the numbers after | | | the comma are millisecond portion of the time). | | | This can be changed by subclassing the formatter | | | and overriding the | | | :meth:`~logging.Formatter.formatTime` method. | +------------------+----------------------------------------------------+ | ``%(message)s`` | The logged message, computed as ``msg % args`` | +------------------+----------------------------------------------------+ If you want to further customize the formatting, you can subclass the formatter. The formatter has three interesting methods: :meth:`~logging.Formatter.format`: handles the actual formatting. It is passed a :class:`~logging.LogRecord` object and has to return the formatted string. :meth:`~logging.Formatter.formatTime`: called for `asctime` formatting. If you want a different time format you can override this method. :meth:`~logging.Formatter.formatException` called for exception formatting. It is passed an :attr:`~sys.exc_info` tuple and has to return a string. The default is usually fine, you don't have to override it. For more information, head over to the official documentation. Other Libraries --------------- So far we only configured the logger your application created itself. Other libraries might log themselves as well. For example, SQLAlchemy uses logging heavily in its core. While there is a method to configure all loggers at once in the :mod:`logging` package, I would not recommend using it. There might be a situation in which you want to have multiple separate applications running side by side in the same Python interpreter and then it becomes impossible to have different logging setups for those. Instead, I would recommend figuring out which loggers you are interested in, getting the loggers with the :func:`~logging.getLogger` function and iterating over them to attach handlers:: from logging import getLogger loggers = [app.logger, getLogger('sqlalchemy'), getLogger('otherlibrary')] for logger in loggers: logger.addHandler(mail_handler) logger.addHandler(file_handler) Debugging Application Errors ============================ For production applications, configure your application with logging and notifications as described in :ref:`application-errors`. This section provides pointers when debugging deployment configuration and digging deeper with a full-featured Python debugger. When in Doubt, Run Manually --------------------------- Having problems getting your application configured for production? If you have shell access to your host, verify that you can run your application manually from the shell in the deployment environment. Be sure to run under the same user account as the configured deployment to troubleshoot permission issues. You can use Flask's builtin development server with `debug=True` on your production host, which is helpful in catching configuration issues, but **be sure to do this temporarily in a controlled environment.** Do not run in production with `debug=True`. .. _working-with-debuggers: Working with Debuggers ---------------------- To dig deeper, possibly to trace code execution, Flask provides a debugger out of the box (see :ref:`debug-mode`). If you would like to use another Python debugger, note that debuggers interfere with each other. You have to set some options in order to use your favorite debugger: * ``debug`` - whether to enable debug mode and catch exceptions * ``use_debugger`` - whether to use the internal Flask debugger * ``use_reloader`` - whether to reload and fork the process on exception ``debug`` must be True (i.e., exceptions must be caught) in order for the other two options to have any value. If you're using Aptana/Eclipse for debugging you'll need to set both ``use_debugger`` and ``use_reloader`` to False. A possible useful pattern for configuration is to set the following in your config.yaml (change the block as appropriate for your application, of course):: FLASK: DEBUG: True DEBUG_WITH_APTANA: True Then in your application's entry-point (main.py), you could have something like:: if __name__ == "__main__": # To allow aptana to receive errors, set use_debugger=False app = create_app(config="config.yaml") if app.debug: use_debugger = True try: # Disable Flask's debugger if external debugger is requested use_debugger = not(app.config.get('DEBUG_WITH_APTANA')) except: pass app.run(use_debugger=use_debugger, debug=app.debug, use_reloader=use_debugger, host='0.0.0.0') Flask-0.12.2/docs/appcontext.rst0000644000175000001440000001253212765277163017713 0ustar untitakerusers00000000000000.. _app-context: The Application Context ======================= .. versionadded:: 0.9 One of the design ideas behind Flask is that there are two different “states” in which code is executed. The application setup state in which the application implicitly is on the module level. It starts when the :class:`Flask` object is instantiated, and it implicitly ends when the first request comes in. While the application is in this state a few assumptions are true: - the programmer can modify the application object safely. - no request handling happened so far - you have to have a reference to the application object in order to modify it, there is no magic proxy that can give you a reference to the application object you're currently creating or modifying. In contrast, during request handling, a couple of other rules exist: - while a request is active, the context local objects (:data:`flask.request` and others) point to the current request. - any code can get hold of these objects at any time. There is a third state which is sitting in between a little bit. Sometimes you are dealing with an application in a way that is similar to how you interact with applications during request handling; just that there is no request active. Consider, for instance, that you're sitting in an interactive Python shell and interacting with the application, or a command line application. The application context is what powers the :data:`~flask.current_app` context local. Purpose of the Application Context ---------------------------------- The main reason for the application's context existence is that in the past a bunch of functionality was attached to the request context for lack of a better solution. Since one of the pillars of Flask's design is that you can have more than one application in the same Python process. So how does the code find the “right” application? In the past we recommended passing applications around explicitly, but that caused issues with libraries that were not designed with that in mind. A common workaround for that problem was to use the :data:`~flask.current_app` proxy later on, which was bound to the current request's application reference. Since creating such a request context is an unnecessarily expensive operation in case there is no request around, the application context was introduced. Creating an Application Context ------------------------------- There are two ways to make an application context. The first one is implicit: whenever a request context is pushed, an application context will be created alongside if this is necessary. As a result, you can ignore the existence of the application context unless you need it. The second way is the explicit way using the :meth:`~flask.Flask.app_context` method:: from flask import Flask, current_app app = Flask(__name__) with app.app_context(): # within this block, current_app points to app. print current_app.name The application context is also used by the :func:`~flask.url_for` function in case a ``SERVER_NAME`` was configured. This allows you to generate URLs even in the absence of a request. If no request context has been pushed and an application context has not been explicitly set, a ``RuntimeError`` will be raised. :: RuntimeError: Working outside of application context. Locality of the Context ----------------------- The application context is created and destroyed as necessary. It never moves between threads and it will not be shared between requests. As such it is the perfect place to store database connection information and other things. The internal stack object is called :data:`flask._app_ctx_stack`. Extensions are free to store additional information on the topmost level, assuming they pick a sufficiently unique name and should put their information there, instead of on the :data:`flask.g` object which is reserved for user code. For more information about that, see :ref:`extension-dev`. Context Usage ------------- The context is typically used to cache resources that need to be created on a per-request or usage case. For instance, database connections are destined to go there. When storing things on the application context unique names should be chosen as this is a place that is shared between Flask applications and extensions. The most common usage is to split resource management into two parts: 1. an implicit resource caching on the context. 2. a context teardown based resource deallocation. Generally there would be a ``get_X()`` function that creates resource ``X`` if it does not exist yet and otherwise returns the same resource, and a ``teardown_X()`` function that is registered as teardown handler. This is an example that connects to a database:: import sqlite3 from flask import g def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = connect_to_database() return db @app.teardown_appcontext def teardown_db(exception): db = getattr(g, '_database', None) if db is not None: db.close() The first time ``get_db()`` is called the connection will be established. To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used:: from werkzeug.local import LocalProxy db = LocalProxy(get_db) That way a user can directly access ``db`` which internally calls ``get_db()``. Flask-0.12.2/docs/_templates/0000755000175000001440000000000013106517244017111 5ustar untitakerusers00000000000000Flask-0.12.2/docs/_templates/sidebarlogo.html0000644000175000001440000000021112500054707022260 0ustar untitakerusers00000000000000

Flask-0.12.2/docs/_templates/sidebarintro.html0000644000175000001440000000156513106517205022470 0ustar untitakerusers00000000000000

About Flask

Flask is a micro webdevelopment framework for Python. You are currently looking at the documentation of the development version.

Other Formats

You can download the documentation in other formats as well:

Useful Links

Flask-0.12.2/LICENSE0000644000175000001440000000305612763616450015044 0ustar untitakerusers00000000000000Copyright (c) 2015 by Armin Ronacher and contributors. See AUTHORS for more details. Some rights reserved. Redistribution and use in source and binary forms of the software as well as documentation, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Flask-0.12.2/setup.cfg0000644000175000001440000000034013106517244015642 0ustar untitakerusers00000000000000[aliases] release = egg_info -RDb '' [wheel] universal = 1 [metadata] license_file = LICENSE [tool:pytest] norecursedirs = .* *.egg *.egg-info env* artwork docs [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 Flask-0.12.2/tests/0000755000175000001440000000000013106517244015166 5ustar untitakerusers00000000000000Flask-0.12.2/tests/test_reqctx.py0000644000175000001440000001212013106517205020076 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ tests.reqctx ~~~~~~~~~~~~ Tests the request context. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import pytest import flask try: from greenlet import greenlet except ImportError: greenlet = None def test_teardown_on_pop(): buffer = [] app = flask.Flask(__name__) @app.teardown_request def end_of_request(exception): buffer.append(exception) ctx = app.test_request_context() ctx.push() assert buffer == [] ctx.pop() assert buffer == [None] def test_teardown_with_previous_exception(): buffer = [] app = flask.Flask(__name__) @app.teardown_request def end_of_request(exception): buffer.append(exception) try: raise Exception('dummy') except Exception: pass with app.test_request_context(): assert buffer == [] assert buffer == [None] def test_teardown_with_handled_exception(): buffer = [] app = flask.Flask(__name__) @app.teardown_request def end_of_request(exception): buffer.append(exception) with app.test_request_context(): assert buffer == [] try: raise Exception('dummy') except Exception: pass assert buffer == [None] def test_proper_test_request_context(): app = flask.Flask(__name__) app.config.update( SERVER_NAME='localhost.localdomain:5000' ) @app.route('/') def index(): return None @app.route('/', subdomain='foo') def sub(): return None with app.test_request_context('/'): assert flask.url_for('index', _external=True) == \ 'http://localhost.localdomain:5000/' with app.test_request_context('/'): assert flask.url_for('sub', _external=True) == \ 'http://foo.localhost.localdomain:5000/' try: with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): pass except ValueError as e: assert str(e) == ( "the server name provided " "('localhost.localdomain:5000') does not match the " "server name from the WSGI environment ('localhost')" ) app.config.update(SERVER_NAME='localhost') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}): pass app.config.update(SERVER_NAME='localhost:80') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): pass def test_context_binding(): app = flask.Flask(__name__) @app.route('/') def index(): return 'Hello %s!' % flask.request.args['name'] @app.route('/meh') def meh(): return flask.request.url with app.test_request_context('/?name=World'): assert index() == 'Hello World!' with app.test_request_context('/meh'): assert meh() == 'http://localhost/meh' assert flask._request_ctx_stack.top is None def test_context_test(): app = flask.Flask(__name__) assert not flask.request assert not flask.has_request_context() ctx = app.test_request_context() ctx.push() try: assert flask.request assert flask.has_request_context() finally: ctx.pop() def test_manual_context_binding(): app = flask.Flask(__name__) @app.route('/') def index(): return 'Hello %s!' % flask.request.args['name'] ctx = app.test_request_context('/?name=World') ctx.push() assert index() == 'Hello World!' ctx.pop() with pytest.raises(RuntimeError): index() @pytest.mark.skipif(greenlet is None, reason='greenlet not installed') def test_greenlet_context_copying(): app = flask.Flask(__name__) greenlets = [] @app.route('/') def index(): reqctx = flask._request_ctx_stack.top.copy() def g(): assert not flask.request assert not flask.current_app with reqctx: assert flask.request assert flask.current_app == app assert flask.request.path == '/' assert flask.request.args['foo'] == 'bar' assert not flask.request return 42 greenlets.append(greenlet(g)) return 'Hello World!' rv = app.test_client().get('/?foo=bar') assert rv.data == b'Hello World!' result = greenlets[0].run() assert result == 42 @pytest.mark.skipif(greenlet is None, reason='greenlet not installed') def test_greenlet_context_copying_api(): app = flask.Flask(__name__) greenlets = [] @app.route('/') def index(): reqctx = flask._request_ctx_stack.top.copy() @flask.copy_current_request_context def g(): assert flask.request assert flask.current_app == app assert flask.request.path == '/' assert flask.request.args['foo'] == 'bar' return 42 greenlets.append(greenlet(g)) return 'Hello World!' rv = app.test_client().get('/?foo=bar') assert rv.data == b'Hello World!' result = greenlets[0].run() assert result == 42 Flask-0.12.2/tests/test_helpers.py0000644000175000001440000007564213106517205020254 0ustar untitakerusers00000000000000# -*- coding: utf-8 -*- """ tests.helpers ~~~~~~~~~~~~~~~~~~~~~~~ Various helpers. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import pytest import os import uuid import datetime import flask from logging import StreamHandler from werkzeug.datastructures import Range from werkzeug.exceptions import BadRequest, NotFound from werkzeug.http import parse_cache_control_header, parse_options_header from werkzeug.http import http_date from flask._compat import StringIO, text_type def has_encoding(name): try: import codecs codecs.lookup(name) return True except LookupError: return False class TestJSON(object): def test_ignore_cached_json(self): app = flask.Flask(__name__) with app.test_request_context('/', method='POST', data='malformed', content_type='application/json'): assert flask.request.get_json(silent=True, cache=True) is None with pytest.raises(BadRequest): flask.request.get_json(silent=False, cache=False) def test_post_empty_json_adds_exception_to_response_content_in_debug(self): app = flask.Flask(__name__) app.config['DEBUG'] = True @app.route('/json', methods=['POST']) def post_json(): flask.request.get_json() return None c = app.test_client() rv = c.post('/json', data=None, content_type='application/json') assert rv.status_code == 400 assert b'Failed to decode JSON object' in rv.data def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self): app = flask.Flask(__name__) app.config['DEBUG'] = False @app.route('/json', methods=['POST']) def post_json(): flask.request.get_json() return None c = app.test_client() rv = c.post('/json', data=None, content_type='application/json') assert rv.status_code == 400 assert b'Failed to decode JSON object' not in rv.data def test_json_bad_requests(self): app = flask.Flask(__name__) @app.route('/json', methods=['POST']) def return_json(): return flask.jsonify(foo=text_type(flask.request.get_json())) c = app.test_client() rv = c.post('/json', data='malformed', content_type='application/json') assert rv.status_code == 400 def test_json_custom_mimetypes(self): app = flask.Flask(__name__) @app.route('/json', methods=['POST']) def return_json(): return flask.request.get_json() c = app.test_client() rv = c.post('/json', data='"foo"', content_type='application/x+json') assert rv.data == b'foo' def test_json_body_encoding(self): app = flask.Flask(__name__) app.testing = True @app.route('/') def index(): return flask.request.get_json() c = app.test_client() resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'), content_type='application/json; charset=iso-8859-15') assert resp.data == u'Hällo Wörld'.encode('utf-8') def test_json_as_unicode(self): app = flask.Flask(__name__) app.config['JSON_AS_ASCII'] = True with app.app_context(): rv = flask.json.dumps(u'\N{SNOWMAN}') assert rv == '"\\u2603"' app.config['JSON_AS_ASCII'] = False with app.app_context(): rv = flask.json.dumps(u'\N{SNOWMAN}') assert rv == u'"\u2603"' def test_json_dump_to_file(self): app = flask.Flask(__name__) test_data = {'name': 'Flask'} out = StringIO() with app.app_context(): flask.json.dump(test_data, out) out.seek(0) rv = flask.json.load(out) assert rv == test_data @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None]) def test_jsonify_basic_types(self, test_value): """Test jsonify with basic types.""" app = flask.Flask(__name__) c = app.test_client() url = '/jsonify_basic_types' app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x)) rv = c.get(url) assert rv.mimetype == 'application/json' assert flask.json.loads(rv.data) == test_value def test_jsonify_dicts(self): """Test jsonify with dicts and kwargs unpacking.""" d = dict( a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False, h=['test list', 10, False], i={'test':'dict'} ) app = flask.Flask(__name__) @app.route('/kw') def return_kwargs(): return flask.jsonify(**d) @app.route('/dict') def return_dict(): return flask.jsonify(d) c = app.test_client() for url in '/kw', '/dict': rv = c.get(url) assert rv.mimetype == 'application/json' assert flask.json.loads(rv.data) == d def test_jsonify_arrays(self): """Test jsonify of lists and args unpacking.""" l = [ 0, 42, 3.14, 't', 'hello', True, False, ['test list', 2, False], {'test':'dict'} ] app = flask.Flask(__name__) @app.route('/args_unpack') def return_args_unpack(): return flask.jsonify(*l) @app.route('/array') def return_array(): return flask.jsonify(l) c = app.test_client() for url in '/args_unpack', '/array': rv = c.get(url) assert rv.mimetype == 'application/json' assert flask.json.loads(rv.data) == l def test_jsonify_date_types(self): """Test jsonify with datetime.date and datetime.datetime types.""" test_dates = ( datetime.datetime(1973, 3, 11, 6, 30, 45), datetime.date(1975, 1, 5) ) app = flask.Flask(__name__) c = app.test_client() for i, d in enumerate(test_dates): url = '/datetest{0}'.format(i) app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val)) rv = c.get(url) assert rv.mimetype == 'application/json' assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple()) def test_jsonify_uuid_types(self): """Test jsonify with uuid.UUID types""" test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4) app = flask.Flask(__name__) url = '/uuid_test' app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid)) c = app.test_client() rv = c.get(url) rv_x = flask.json.loads(rv.data)['x'] assert rv_x == str(test_uuid) rv_uuid = uuid.UUID(rv_x) assert rv_uuid == test_uuid def test_json_attr(self): app = flask.Flask(__name__) @app.route('/add', methods=['POST']) def add(): json = flask.request.get_json() return text_type(json['a'] + json['b']) c = app.test_client() rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}), content_type='application/json') assert rv.data == b'3' def test_template_escaping(self): app = flask.Flask(__name__) render = flask.render_template_string with app.test_request_context(): rv = flask.json.htmlsafe_dumps('') assert rv == u'"\\u003c/script\\u003e"' assert type(rv) == text_type rv = render('{{ ""|tojson }}') assert rv == '"\\u003c/script\\u003e"' rv = render('{{ "<\0/script>"|tojson }}') assert rv == '"\\u003c\\u0000/script\\u003e"' rv = render('{{ "