Flask-1.1.1/0000755000175000017500000000000013510702200012740 5ustar daviddavid00000000000000Flask-1.1.1/CHANGES.rst0000644000175000017500000013132613510701642014561 0ustar daviddavid00000000000000.. currentmodule:: flask Version 1.1.1 ------------- Released 2019-07-08 - The ``flask.json_available`` flag was added back for compatibility with some extensions. It will raise a deprecation warning when used, and will be removed in version 2.0.0. :issue:`3288` Version 1.1.0 ------------- Released 2019-07-04 - Bump minimum Werkzeug version to >= 0.15. - Drop support for Python 3.4. - Error handlers for ``InternalServerError`` or ``500`` will always be passed an instance of ``InternalServerError``. If they are invoked due to an unhandled exception, that original exception is now available as ``e.original_exception`` rather than being passed directly to the handler. The same is true if the handler is for the base ``HTTPException``. This makes error handler behavior more consistent. :pr:`3266` - :meth:`Flask.finalize_request` is called for all unhandled exceptions even if there is no ``500`` error handler. - :attr:`Flask.logger` takes the same name as :attr:`Flask.name` (the value passed as ``Flask(import_name)``. This reverts 1.0's behavior of always logging to ``"flask.app"``, in order to support multiple apps in the same process. A warning will be shown if old configuration is detected that needs to be moved. :issue:`2866` - :meth:`flask.RequestContext.copy` includes the current session object in the request context copy. This prevents ``session`` pointing to an out-of-date object. :issue:`2935` - Using built-in RequestContext, unprintable Unicode characters in Host header will result in a HTTP 400 response and not HTTP 500 as previously. :pr:`2994` - :func:`send_file` supports :class:`~os.PathLike` objects as described in PEP 0519, to support :mod:`pathlib` in Python 3. :pr:`3059` - :func:`send_file` supports :class:`~io.BytesIO` partial content. :issue:`2957` - :func:`open_resource` accepts the "rt" file mode. This still does the same thing as "r". :issue:`3163` - The :attr:`MethodView.methods` attribute set in a base class is used by subclasses. :issue:`3138` - :attr:`Flask.jinja_options` is a ``dict`` instead of an ``ImmutableDict`` to allow easier configuration. Changes must still be made before creating the environment. :pr:`3190` - Flask's ``JSONMixin`` for the request and response wrappers was moved into Werkzeug. Use Werkzeug's version with Flask-specific support. This bumps the Werkzeug dependency to >= 0.15. :issue:`3125` - The ``flask`` command entry point is simplified to take advantage of Werkzeug 0.15's better reloader support. This bumps the Werkzeug dependency to >= 0.15. :issue:`3022` - Support ``static_url_path`` that ends with a forward slash. :issue:`3134` - Support empty ``static_folder`` without requiring setting an empty ``static_url_path`` as well. :pr:`3124` - :meth:`jsonify` supports :class:`dataclasses.dataclass` objects. :pr:`3195` - Allow customizing the :attr:`Flask.url_map_class` used for routing. :pr:`3069` - The development server port can be set to 0, which tells the OS to pick an available port. :issue:`2926` - The return value from :meth:`cli.load_dotenv` is more consistent with the documentation. It will return ``False`` if python-dotenv is not installed, or if the given path isn't a file. :issue:`2937` - Signaling support has a stub for the ``connect_via`` method when the Blinker library is not installed. :pr:`3208` - Add an ``--extra-files`` option to the ``flask run`` CLI command to specify extra files that will trigger the reloader on change. :issue:`2897` - Allow returning a dictionary from a view function. Similar to how returning a string will produce a ``text/html`` response, returning a dict will call ``jsonify`` to produce a ``application/json`` response. :pr:`3111` - Blueprints have a ``cli`` Click group like ``app.cli``. CLI commands registered with a blueprint will be available as a group under the ``flask`` command. :issue:`1357`. - When using the test client as a context manager (``with client:``), all preserved request contexts are popped when the block exits, ensuring nested contexts are cleaned up correctly. :pr:`3157` - Show a better error message when the view return type is not supported. :issue:`3214` - ``flask.testing.make_test_environ_builder()`` has been deprecated in favour of a new class ``flask.testing.EnvironBuilder``. :pr:`3232` - The ``flask run`` command no longer fails if Python is not built with SSL support. Using the ``--cert`` option will show an appropriate error message. :issue:`3211` - URL matching now occurs after the request context is pushed, rather than when it's created. This allows custom URL converters to access the app and request contexts, such as to query a database for an id. :issue:`3088` Version 1.0.4 ------------- Released 2019-07-04 - The key information for ``BadRequestKeyError`` is no longer cleared outside debug mode, so error handlers can still access it. This requires upgrading to Werkzeug 0.15.5. :issue:`3249` - ``send_file`` url quotes the ":" and "/" characters for more compatible UTF-8 filename support in some browsers. :issue:`3074` - Fixes for PEP451 import loaders and pytest 5.x. :issue:`3275` - Show message about dotenv on stderr instead of stdout. :issue:`3285` Version 1.0.3 ------------- Released 2019-05-17 - :func:`send_file` encodes filenames as ASCII instead of Latin-1 (ISO-8859-1). This fixes compatibility with Gunicorn, which is stricter about header encodings than PEP 3333. :issue:`2766` - Allow custom CLIs using ``FlaskGroup`` to set the debug flag without it always being overwritten based on environment variables. :pr:`2765` - ``flask --version`` outputs Werkzeug's version and simplifies the Python version. :pr:`2825` - :func:`send_file` handles an ``attachment_filename`` that is a native Python 2 string (bytes) with UTF-8 coded bytes. :issue:`2933` - A catch-all error handler registered for ``HTTPException`` will not handle ``RoutingException``, which is used internally during routing. This fixes the unexpected behavior that had been introduced in 1.0. :pr:`2986` - Passing the ``json`` argument to ``app.test_client`` does not push/pop an extra app context. :issue:`2900` Version 1.0.2 ------------- Released 2018-05-02 - Fix more backwards compatibility issues with merging slashes between a blueprint prefix and route. :pr:`2748` - Fix error with ``flask routes`` command when there are no routes. :issue:`2751` Version 1.0.1 ------------- Released 2018-04-29 - Fix registering partials (with no ``__name__``) as view functions. :pr:`2730` - Don't treat lists returned from view functions the same as tuples. Only tuples are interpreted as response data. :issue:`2736` - Extra slashes between a blueprint's ``url_prefix`` and a route URL are merged. This fixes some backwards compatibility issues with the change in 1.0. :issue:`2731`, :issue:`2742` - Only trap ``BadRequestKeyError`` errors in debug mode, not all ``BadRequest`` errors. This allows ``abort(400)`` to continue working as expected. :issue:`2735` - The ``FLASK_SKIP_DOTENV`` environment variable can be set to ``1`` to skip automatically loading dotenv files. :issue:`2722` Version 1.0 ----------- Released 2018-04-26 - Python 2.6 and 3.3 are no longer supported. - Bump minimum dependency versions to the latest stable versions: Werkzeug >= 0.14, Jinja >= 2.10, itsdangerous >= 0.24, Click >= 5.1. :issue:`2586` - Skip :meth:`app.run ` when a Flask application is run from the command line. This avoids some behavior that was confusing to debug. - Change the default for :data:`JSONIFY_PRETTYPRINT_REGULAR` to ``False``. :func:`~json.jsonify` returns a compact format by default, and an indented format in debug mode. :pr:`2193` - :meth:`Flask.__init__ ` accepts the ``host_matching`` argument and sets it on :attr:`~Flask.url_map`. :issue:`1559` - :meth:`Flask.__init__ ` accepts the ``static_host`` argument and passes it as the ``host`` argument when defining the static route. :issue:`1559` - :func:`send_file` supports Unicode in ``attachment_filename``. :pr:`2223` - Pass ``_scheme`` argument from :func:`url_for` to :meth:`~Flask.handle_url_build_error`. :pr:`2017` - :meth:`~Flask.add_url_rule` accepts the ``provide_automatic_options`` argument to disable adding the ``OPTIONS`` method. :pr:`1489` - :class:`~views.MethodView` subclasses inherit method handlers from base classes. :pr:`1936` - Errors caused while opening the session at the beginning of the request are handled by the app's error handlers. :pr:`2254` - Blueprints gained :attr:`~Blueprint.json_encoder` and :attr:`~Blueprint.json_decoder` attributes to override the app's encoder and decoder. :pr:`1898` - :meth:`Flask.make_response` raises ``TypeError`` instead of ``ValueError`` for bad response types. The error messages have been improved to describe why the type is invalid. :pr:`2256` - Add ``routes`` CLI command to output routes registered on the application. :pr:`2259` - Show warning when session cookie domain is a bare hostname or an IP address, as these may not behave properly in some browsers, such as Chrome. :pr:`2282` - Allow IP address as exact session cookie domain. :pr:`2282` - ``SESSION_COOKIE_DOMAIN`` is set if it is detected through ``SERVER_NAME``. :pr:`2282` - Auto-detect zero-argument app factory called ``create_app`` or ``make_app`` from ``FLASK_APP``. :pr:`2297` - Factory functions are not required to take a ``script_info`` parameter to work with the ``flask`` command. If they take a single parameter or a parameter named ``script_info``, the :class:`~cli.ScriptInfo` object will be passed. :pr:`2319` - ``FLASK_APP`` can be set to an app factory, with arguments if needed, for example ``FLASK_APP=myproject.app:create_app('dev')``. :pr:`2326` - ``FLASK_APP`` can point to local packages that are not installed in editable mode, although ``pip install -e`` is still preferred. :pr:`2414` - The :class:`~views.View` class attribute :attr:`~views.View.provide_automatic_options` is set in :meth:`~views.View.as_view`, to be detected by :meth:`~Flask.add_url_rule`. :pr:`2316` - Error handling will try handlers registered for ``blueprint, code``, ``app, code``, ``blueprint, exception``, ``app, exception``. :pr:`2314` - ``Cookie`` is added to the response's ``Vary`` header if the session is accessed at all during the request (and not deleted). :pr:`2288` - :meth:`~Flask.test_request_context` accepts ``subdomain`` and ``url_scheme`` arguments for use when building the base URL. :pr:`1621` - Set :data:`APPLICATION_ROOT` to ``'/'`` by default. This was already the implicit default when it was set to ``None``. - :data:`TRAP_BAD_REQUEST_ERRORS` is enabled by default in debug mode. ``BadRequestKeyError`` has a message with the bad key in debug mode instead of the generic bad request message. :pr:`2348` - Allow registering new tags with :class:`~json.tag.TaggedJSONSerializer` to support storing other types in the session cookie. :pr:`2352` - Only open the session if the request has not been pushed onto the context stack yet. This allows :func:`~stream_with_context` generators to access the same session that the containing view uses. :pr:`2354` - Add ``json`` keyword argument for the test client request methods. This will dump the given object as JSON and set the appropriate content type. :pr:`2358` - Extract JSON handling to a mixin applied to both the :class:`Request` and :class:`Response` classes. This adds the :meth:`~Response.is_json` and :meth:`~Response.get_json` methods to the response to make testing JSON response much easier. :pr:`2358` - Removed error handler caching because it caused unexpected results for some exception inheritance hierarchies. Register handlers explicitly for each exception if you want to avoid traversing the MRO. :pr:`2362` - Fix incorrect JSON encoding of aware, non-UTC datetimes. :pr:`2374` - Template auto reloading will honor debug mode even even if :attr:`~Flask.jinja_env` was already accessed. :pr:`2373` - The following old deprecated code was removed. :issue:`2385` - ``flask.ext`` - import extensions directly by their name instead of through the ``flask.ext`` namespace. For example, ``import flask.ext.sqlalchemy`` becomes ``import flask_sqlalchemy``. - ``Flask.init_jinja_globals`` - extend :meth:`Flask.create_jinja_environment` instead. - ``Flask.error_handlers`` - tracked by :attr:`Flask.error_handler_spec`, use :meth:`Flask.errorhandler` to register handlers. - ``Flask.request_globals_class`` - use :attr:`Flask.app_ctx_globals_class` instead. - ``Flask.static_path`` - use :attr:`Flask.static_url_path` instead. - ``Request.module`` - use :attr:`Request.blueprint` instead. - The :attr:`Request.json` property is no longer deprecated. :issue:`1421` - Support passing a :class:`~werkzeug.test.EnvironBuilder` or ``dict`` to :meth:`test_client.open `. :pr:`2412` - The ``flask`` command and :meth:`Flask.run` will load environment variables from ``.env`` and ``.flaskenv`` files if python-dotenv is installed. :pr:`2416` - When passing a full URL to the test client, the scheme in the URL is used instead of :data:`PREFERRED_URL_SCHEME`. :pr:`2430` - :attr:`Flask.logger` has been simplified. ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` config was removed. The logger is always named ``flask.app``. The level is only set on first access, it doesn't check :attr:`Flask.debug` each time. Only one format is used, not different ones depending on :attr:`Flask.debug`. No handlers are removed, and a handler is only added if no handlers are already configured. :pr:`2436` - Blueprint view function names may not contain dots. :pr:`2450` - Fix a ``ValueError`` caused by invalid ``Range`` requests in some cases. :issue:`2526` - The development server uses threads by default. :pr:`2529` - Loading config files with ``silent=True`` will ignore :data:`~errno.ENOTDIR` errors. :pr:`2581` - Pass ``--cert`` and ``--key`` options to ``flask run`` to run the development server over HTTPS. :pr:`2606` - Added :data:`SESSION_COOKIE_SAMESITE` to control the ``SameSite`` attribute on the session cookie. :pr:`2607` - Added :meth:`~flask.Flask.test_cli_runner` to create a Click runner that can invoke Flask CLI commands for testing. :pr:`2636` - Subdomain matching is disabled by default and setting :data:`SERVER_NAME` does not implicitly enable it. It can be enabled by passing ``subdomain_matching=True`` to the ``Flask`` constructor. :pr:`2635` - A single trailing slash is stripped from the blueprint ``url_prefix`` when it is registered with the app. :pr:`2629` - :meth:`Request.get_json` doesn't cache the result if parsing fails when ``silent`` is true. :issue:`2651` - :func:`Request.get_json` no longer accepts arbitrary encodings. Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but Flask will autodetect UTF-8, -16, or -32. :pr:`2691` - Added :data:`MAX_COOKIE_SIZE` and :attr:`Response.max_cookie_size` to control when Werkzeug warns about large cookies that browsers may ignore. :pr:`2693` - Updated documentation theme to make docs look better in small windows. :pr:`2709` - Rewrote the tutorial docs and example project to take a more structured approach to help new users avoid common pitfalls. :pr:`2676` Version 0.12.4 -------------- Released 2018-04-29 - Repackage 0.12.3 to fix package layout issue. :issue:`2728` Version 0.12.3 -------------- Released 2018-04-26 - :func:`Request.get_json` no longer accepts arbitrary encodings. Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but Flask will autodetect UTF-8, -16, or -32. :issue:`2692` - Fix a Python warning about imports when using ``python -m flask``. :issue:`2666` - Fix a ``ValueError`` caused by invalid ``Range`` requests in some cases. Version 0.12.2 -------------- Released 2017-05-16 - Fix a bug in ``safe_join`` on Windows. Version 0.12.1 -------------- Released 2017-03-31 - 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. :issue:`2118` - Use the ``SERVER_NAME`` config if it is present as default values for ``app.run``. :issue:`2109`, :pr:`2152` - 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 2016-12-21, codename Punsch - The cli command now responds to ``--version``. - Mimetype guessing and ETag generation for file-like objects in ``send_file`` has been removed. :issue:`104`, :pr`1849` - Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to ``application/octet-stream``. :pr:`1988` - Make ``flask.safe_join`` able to join multiple paths like ``os.path.join`` :pr:`1730` - Revert a behavior change that made the dev server crash instead of returning an Internal Server Error. :pr:`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``. - Fix crash when running under PyPy3. :pr:`1814` Version 0.11.1 -------------- Released 2016-06-07 - Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. :pr:`1872` Version 0.11 ------------ Released 2016-05-29, 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. This came up originally as a part of https://github.com/postmanlabs/httpbin/issues/168. :pr:`1262` - 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. :pr:`1326` - Don't leak exception info of already caught exceptions to context teardown handlers. :pr:`1393` - Allow custom Jinja environment subclasses. :pr:`1422` - Updated extension dev guidelines. - ``flask.g`` now has ``pop()`` and ``setdefault`` methods. - Turn on autoescape for ``flask.templating.render_template_string`` by default. :pr:`1515` - ``flask.ext`` is now deprecated. :pr:`1484` - ``send_from_directory`` now raises BadRequest if the filename is invalid on the server OS. :pr:`1763` - Added the ``JSONIFY_MIMETYPE`` configuration variable. :pr:`1728` - Exceptions during teardown handling will no longer leave bad application contexts lingering around. - 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 -------------- Released 2013-06-14 - 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 2013-06-13, 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 2012-07-01, 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 ------------- Released 2012-07-01 - 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 2011-09-29, 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. - Fixed the Jinja2 environment's ``list_templates`` method not returning the correct names when blueprints or modules were involved. Version 0.7.2 ------------- Released 2011-07-06 - Fixed an issue with URL processors not properly working on blueprints. Version 0.7.1 ------------- Released 2011-06-29 - Added missing future import that broke 2.5 compatibility. - Fixed an infinite redirect issue with blueprints. Version 0.7 ----------- Released 2011-06-28, 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 ------------- Released 2010-12-31 - 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 2010-07-27, 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.org/project/blinker/ Version 0.5.2 ------------- Released 2010-07-15 - Fixed another issue with loading templates from directories when modules were used. Version 0.5.1 ------------- Released 2010-07-06 - Fixes an issue with template loading from directories when modules where used. Version 0.5 ----------- Released 2010-07-06, 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 2010-06-18, 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 ------------- Released 2010-05-28 - 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 2010-05-28, 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 2010-05-12, 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 ----------- Released 2010-04-16 - First public preview release. Flask-1.1.1/CONTRIBUTING.rst0000644000175000017500000001453213510701642015417 0ustar daviddavid00000000000000How to contribute to Flask ========================== Thank you for considering contributing to Flask! Support questions ----------------- Please, don't use the issue tracker for this. Use one of the following resources for questions about your own code: * The ``#get-help`` channel on our Discord chat: https://discordapp.com/invite/t6rrQZH * The IRC channel ``#pocoo`` on FreeNode is linked to Discord, but Discord is preferred. * The mailing list flask@python.org for long term discussion or larger issues. * Ask on `Stack Overflow`_. Search with Google first using: ``site:stackoverflow.com flask {search term, exception message, etc.}`` .. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?sort=linked Reporting issues ---------------- - Describe what you expected to happen. - If possible, include a `minimal reproducible example`_ to help us identify the issue. This also helps check that the issue is not with your own code. - Describe what actually happened. Include the full traceback if there was an exception. - List your Python, Flask, and Werkzeug versions. If possible, check if this issue is already fixed in the repository. .. _minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example Submitting patches ------------------ - Use `Black`_ to autoformat your code. This should be done for you as a git `pre-commit`_ hook, which gets installed when you run ``pip install -e .[dev]``. You may also wish to use Black's `Editor integration`_. - Include tests if your patch is supposed to solve a bug, and explain clearly under which circumstances the bug happens. Make sure the test fails without your patch. - Include a string like "Fixes #123" in your commit message (where 123 is the issue you fixed). See `Closing issues using keywords `__. First time setup ~~~~~~~~~~~~~~~~ - Download and install the `latest version of git`_. - Configure git with your `username`_ and `email`_:: git config --global user.name 'your name' git config --global user.email 'your email' - Make sure you have a `GitHub account`_. - Fork Flask to your GitHub account by clicking the `Fork`_ button. - `Clone`_ your GitHub fork locally:: git clone https://github.com/{username}/flask cd flask - Add the main repository as a remote to update later:: git remote add pallets https://github.com/pallets/flask git fetch pallets - Create a virtualenv:: python3 -m venv env . env/bin/activate # or "env\Scripts\activate" on Windows - Install Flask in editable mode with development dependencies:: pip install -e ".[dev]" - Install the pre-commit hooks: pre-commit install --install-hooks .. _GitHub account: https://github.com/join .. _latest version of git: https://git-scm.com/downloads .. _username: https://help.github.com/en/articles/setting-your-username-in-git .. _email: https://help.github.com/en/articles/setting-your-commit-email-address-in-git .. _Fork: https://github.com/pallets/flask/fork .. _Clone: https://help.github.com/en/articles/fork-a-repo#step-2-create-a-local-clone-of-your-fork Start coding ~~~~~~~~~~~~ - Create a branch to identify the issue you would like to work on. If you're submitting a bug or documentation fix, branch off of the latest ".x" branch:: git checkout -b your-branch-name origin/1.0.x If you're submitting a feature addition or change, branch off of the "master" branch:: git checkout -b your-branch-name origin/master - Using your favorite editor, make your changes, `committing as you go`_. - Include tests that cover any code changes you make. Make sure the test fails without your patch. `Run the tests. `_. - Push your commits to GitHub and `create a pull request`_ by using:: git push --set-upstream origin your-branch-name - Celebrate 🎉 .. _committing as you go: https://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes .. _Black: https://black.readthedocs.io .. _Editor integration: https://black.readthedocs.io/en/stable/editor_integration.html .. _pre-commit: https://pre-commit.com .. _create a pull request: https://help.github.com/en/articles/creating-a-pull-request .. _contributing-testsuite: Running the tests ~~~~~~~~~~~~~~~~~ Run the basic test suite with:: pytest This only runs the tests for the current environment. Whether this is relevant depends on which part of Flask you're working on. Travis-CI will run the full suite when you submit your pull request. The full test suite takes a long time to run because it tests multiple combinations of Python and dependencies. You need to have Python 2.7, 3.4, 3.5 3.6, and PyPy 2.7 installed to run all of the environments. Then run:: tox Running test coverage ~~~~~~~~~~~~~~~~~~~~~ Generating a report of lines that do not have test coverage can indicate where to start contributing. Run ``pytest`` using ``coverage`` and generate a report on the terminal and as an interactive HTML document:: coverage run -m pytest coverage report coverage html # then open htmlcov/index.html Read more about `coverage `_. Running the full test suite with ``tox`` will combine the coverage reports from all runs. Building the docs ~~~~~~~~~~~~~~~~~ Build the docs in the ``docs`` directory using Sphinx:: cd docs make html Open ``_build/html/index.html`` in your browser to view the docs. Read more about `Sphinx `_. Caution: zero-padded file modes ------------------------------- This repository contains several zero-padded file modes that may cause issues when pushing this repository to git hosts other than GitHub. Fixing this is destructive to the commit history, so we suggest ignoring these warnings. If it fails to push and you're using a self-hosted git service like GitLab, you can turn off repository checks in the admin panel. These files can also cause issues while cloning. If you have :: [fetch] fsckobjects = true or :: [receive] fsckObjects = true set in your git configuration file, cloning this repository will fail. The only solution is to set both of the above settings to false while cloning, and then setting them back to true after the cloning is finished. Flask-1.1.1/LICENSE.rst0000644000175000017500000000270313510701642014567 0ustar daviddavid00000000000000Copyright 2010 Pallets Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE 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 HOLDER 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, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Flask-1.1.1/MANIFEST.in0000644000175000017500000000020313510701642014502 0ustar daviddavid00000000000000include CHANGES.rst include CONTRIBUTING.rst include tox.ini graft artwork graft docs prune docs/_build graft examples graft tests Flask-1.1.1/PKG-INFO0000644000175000017500000001040413510702200014034 0ustar daviddavid00000000000000Metadata-Version: 2.1 Name: Flask Version: 1.1.1 Summary: A simple framework for building complex web applications. Home-page: https://palletsprojects.com/p/flask/ Author: Armin Ronacher Author-email: armin.ronacher@active-4.com Maintainer: Pallets Maintainer-email: contact@palletsprojects.com License: BSD-3-Clause Project-URL: Documentation, https://flask.palletsprojects.com/ Project-URL: Code, https://github.com/pallets/flask Project-URL: Issue tracker, https://github.com/pallets/flask/issues Description: Flask ===== Flask is a lightweight `WSGI`_ web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around `Werkzeug`_ and `Jinja`_ and has become one of the most popular Python web application frameworks. Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. Installing ---------- Install and update using `pip`_: .. code-block:: text pip install -U Flask A Simple Example ---------------- .. code-block:: python from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" .. code-block:: text $ env FLASK_APP=hello.py flask run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Contributing ------------ For guidance on setting up a development environment and how to make a contribution to Flask, see the `contributing guidelines`_. .. _contributing guidelines: https://github.com/pallets/flask/blob/master/CONTRIBUTING.rst Donate ------ The Pallets organization develops and supports Flask and the libraries it uses. In order to grow the community of contributors and users, and allow the maintainers to devote more time to the projects, `please donate today`_. .. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=20 Links ----- * Website: https://palletsprojects.com/p/flask/ * Documentation: https://flask.palletsprojects.com/ * Releases: https://pypi.org/project/Flask/ * Code: https://github.com/pallets/flask * Issue tracker: https://github.com/pallets/flask/issues * Test status: https://dev.azure.com/pallets/flask/_build * Official chat: https://discord.gg/t6rrQZH .. _WSGI: https://wsgi.readthedocs.io .. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/ .. _Jinja: https://www.palletsprojects.com/p/jinja/ .. _pip: https://pip.pypa.io/en/stable/quickstart/ Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Framework :: Flask 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.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application Classifier: Topic :: Software Development :: Libraries :: Application Frameworks Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* Provides-Extra: dotenv Provides-Extra: dev Provides-Extra: docs Flask-1.1.1/README.rst0000644000175000017500000000416113510702163014441 0ustar daviddavid00000000000000Flask ===== Flask is a lightweight `WSGI`_ web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around `Werkzeug`_ and `Jinja`_ and has become one of the most popular Python web application frameworks. Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. Installing ---------- Install and update using `pip`_: .. code-block:: text pip install -U Flask A Simple Example ---------------- .. code-block:: python from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" .. code-block:: text $ env FLASK_APP=hello.py flask run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Contributing ------------ For guidance on setting up a development environment and how to make a contribution to Flask, see the `contributing guidelines`_. .. _contributing guidelines: https://github.com/pallets/flask/blob/master/CONTRIBUTING.rst Donate ------ The Pallets organization develops and supports Flask and the libraries it uses. In order to grow the community of contributors and users, and allow the maintainers to devote more time to the projects, `please donate today`_. .. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=20 Links ----- * Website: https://palletsprojects.com/p/flask/ * Documentation: https://flask.palletsprojects.com/ * Releases: https://pypi.org/project/Flask/ * Code: https://github.com/pallets/flask * Issue tracker: https://github.com/pallets/flask/issues * Test status: https://dev.azure.com/pallets/flask/_build * Official chat: https://discord.gg/t6rrQZH .. _WSGI: https://wsgi.readthedocs.io .. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/ .. _Jinja: https://www.palletsprojects.com/p/jinja/ .. _pip: https://pip.pypa.io/en/stable/quickstart/ Flask-1.1.1/artwork/0000755000175000017500000000000013510702200014431 5ustar daviddavid00000000000000Flask-1.1.1/artwork/LICENSE.rst0000644000175000017500000000141413510701642016256 0ustar daviddavid00000000000000Copyright 2010 Pallets 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 (SVG) and binary (renders in PNG, etc.) forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice and this list of conditions. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. We would appreciate that you make the image a link to https://palletsprojects.com/p/flask/ if you use it in a medium that supports links. Flask-1.1.1/artwork/logo-full.svg0000644000175000017500000023115713510701642017074 0ustar daviddavid00000000000000 image/svg+xml Flask-1.1.1/artwork/logo-lineart.svg0000644000175000017500000001766713510701642017600 0ustar daviddavid00000000000000 image/svg+xml Flask-1.1.1/docs/0000755000175000017500000000000013510702200013670 5ustar daviddavid00000000000000Flask-1.1.1/docs/Makefile0000644000175000017500000000110513510701642015336 0ustar daviddavid00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) Flask-1.1.1/docs/_static/0000755000175000017500000000000013510702200015316 5ustar daviddavid00000000000000Flask-1.1.1/docs/_static/debugger.png0000644000175000017500000062602113510701642017630 0ustar daviddavid00000000000000PNG  IHDRvV9IDATxwxT?g{K!$:{fD@DP{ë׊^w vE (Mz$dl?MHv7yx){Μy0o'Np8Zn BP(x4 WUUm|뭷׿5jW^y{ԩ'ٳǣbKP( BqHvyWs9L\sSN=yӦM~4MSP( B8$*++)//gԩ'o7~Ngjyy BP(ÂiB!F# v=*P( B8bs [U( BP([ "RQP( B8RHȤF(& @(R. a._F] |) _ %:#*1T*`0Hfp:! B\p4@ @~~>yyyFQ8̝ݻwuVZliM, #90 "l66nHrr2m۶U+GS^^Ύ;hݺ5G + _ƋN0m6nKXO q71=h!AV H41i AQ{`0z *w)K^^-b0SP(֢S $İs*<B !4BZZN ؚ;c74cLUG'ØB.{Q_̙tME0iXضmɤSQQrBqBAA|>1 Bh֝4YXYz.)| ӎ-`ٛOȇdK`**-gLѻ?/NkS6W-K(IL0&UPrx4C=܉C#biߟʈYèijoJEC?yBt:?>"BVV~_EBPQb2Dvڥ.:EJjXU><'v ݁dӻ#ĔDLuCXi+ؓ60:\hd )eh鸛ZY͠#aW%̦-PY|<5Ml6n::t@vvvdVVo@ѣ!K1`B'sYMh(5bv;wfڶmK0<3ͿKE պ ZՈ؇ BN*}cK$|}s, Vw9Uf dL%^=`uOz2Xl{H9>y ՕN_Z|~ÝU=ō3LakLU>T]?(h"hz]A]G7a2*o%ԬI݄/I`^ 5*_2̘͵ߧ!0i3Jjʊ8l44P(_GLzdgguVȈh` FLӦM1j_PϊmB)ևV "W& 8Q.պZ|zՄkSPn`uH | I_! jv B1$@bٷV!V+Z[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if$>G i=MM ӟJiDw{Pjj[Dr5O!4ݜn_¡**|!YѺM7 U!Oks˧AM +~cLA@ hi44h 4 AMA@ hi4iA7poe1*iIENDB`Flask-1.1.1/docs/_static/yes.png0000644000175000017500000000036113510701642016635 0ustar daviddavid00000000000000PNG  IHDR7IDAT(} P?0VdVL>i L$V`$`2&, c܉ݓ_8m|,qxA&S 'RGZ7GOv׸QSy@Wr0A8QGn4GZJPtA>G8fn(D;ࡐIENDB`Flask-1.1.1/docs/advanced_foreword.rst0000644000175000017500000000456613510701642020122 0ustar daviddavid00000000000000.. _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. Flask-1.1.1/docs/api.rst0000644000175000017500000006125713510701642015217 0ustar daviddavid00000000000000.. _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: :inherited-members: .. attribute:: environ The underlying WSGI environment. .. attribute:: path .. attribute:: full_path .. attribute:: script_root .. attribute:: url .. attribute:: base_url .. attribute:: url_root Provides different ways to look at the current :rfc:`3987`. 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:: 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, max_cookie_size, data, mimetype, is_json, get_json .. 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 set :attr:`Flask.secret_key` (or configured it from :data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes it possible to remember information from one request to another. The way Flask does this is by using a signed cookie. The user can look at the session contents, but can't 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 of 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: .. 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: Test CLI Runner --------------- .. currentmodule:: flask.testing .. autoclass:: FlaskCliRunner :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 A namespace object that can store data during an :doc:`application context `. This is an instance of :attr:`Flask.app_ctx_globals_class`, which defaults to :class:`ctx._AppCtxGlobals`. This is a good place to store resources during a request. During testing, you can use the :ref:`faking-resources` pattern to pre-configure such resources. This is a proxy. See :ref:`notes-on-proxies` for more information. .. versionchanged:: 0.10 Bound to the application context instead of the request context. .. autoclass:: flask.ctx._AppCtxGlobals :members: Useful Functions and Classes ---------------------------- .. data:: current_app A proxy to the application handling the current request. This is useful to access the application without needing to import it, or if it can't be imported, such as when using the application factory pattern or in blueprints and extensions. This is only available when an :doc:`application context ` is pushed. This happens automatically during requests and CLI commands. It can be controlled manually with :meth:`~flask.Flask.app_context`. 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 a filter called ``|tojson`` in Jinja2. Note that in versions of Flask prior to Flask 0.10, you must disable escaping with ``|safe`` if you intend to use ``|tojson`` output inside ``script`` tags. In Flask 0.10 and above, this happens automatically (but it's harmless to include ``|safe`` anyway). .. 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: .. automodule:: flask.json.tag Template Rendering ------------------ .. currentmodule:: flask .. autofunction:: render_template .. autofunction:: render_template_string .. autofunction:: get_template_attribute Configuration ------------- .. autoclass:: Config :members: Stream Helpers -------------- .. autofunction:: stream_with_context Useful Internals ---------------- .. autoclass:: flask.ctx.RequestContext :members: .. data:: _request_ctx_stack The internal :class:`~werkzeug.local.LocalStack` that holds :class:`~flask.ctx.RequestContext` instances. Typically, the :data:`request` and :data:`session` proxies should be accessed instead of the stack. It may be useful to access the stack in extension code. 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 The internal :class:`~werkzeug.local.LocalStack` that holds :class:`~flask.ctx.AppContext` instances. Typically, the :data:`current_app` and :data:`g` proxies should be accessed instead of the stack. Extensions can access the contexts on the stack as a namespace 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.org/project/blinker/ .. _class-based-views: 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``. If a URL contains a default value, it will be redirected to its simpler form with a 301 redirect. In the above example, ``/users/page/1`` will be redirected to ``/users/``. If your route handles ``GET`` and ``POST`` requests, make sure the default route only handles ``GET``, as redirects can't preserve form data. :: @app.route('/region/', defaults={'id': 1}) @app.route('/region/', methods=['GET', 'POST']) def region(id): pass 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:: load_dotenv .. 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-1.1.1/docs/appcontext.rst0000644000175000017500000001257013510701642016625 0ustar daviddavid00000000000000.. currentmodule:: flask .. _app-context: The Application Context ======================= The application context keeps track of the application-level data during a request, CLI command, or other activity. Rather than passing the application around to each function, the :data:`current_app` and :data:`g` proxies are accessed instead. This is similar to the :doc:`/reqcontext`, which keeps track of request-level data during a request. A corresponding application context is pushed when a request context is pushed. Purpose of the Context ---------------------- The :class:`Flask` application object has attributes, such as :attr:`~Flask.config`, that are useful to access within views and :doc:`CLI commands `. However, importing the ``app`` instance within the modules in your project is prone to circular import issues. When using the :doc:`app factory pattern ` or writing reusable :doc:`blueprints ` or :doc:`extensions ` there won't be an ``app`` instance to import at all. Flask solves this issue with the *application context*. Rather than referring to an ``app`` directly, you use the :data:`current_app` proxy, which points to the application handling the current activity. Flask automatically *pushes* an application context when handling a request. View functions, error handlers, and other functions that run during a request will have access to :data:`current_app`. Flask will also automatically push an app context when running CLI commands registered with :attr:`Flask.cli` using ``@app.cli.command()``. Lifetime of the Context ----------------------- The application context is created and destroyed as necessary. When a Flask application begins handling a request, it pushes an application context and a :doc:`request context `. When the request ends it pops the request context then the application context. Typically, an application context will have the same lifetime as a request. See :doc:`/reqcontext` for more information about how the contexts work and the full life cycle of a request. Manually Push a Context ----------------------- If you try to access :data:`current_app`, or anything that uses it, outside an application context, you'll get this error message: .. code-block:: pytb RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context(). If you see that error while configuring your application, such as when initializing an extension, you can push a context manually since you have direct access to the ``app``. Use :meth:`~Flask.app_context` in a ``with`` block, and everything that runs in the block will have access to :data:`current_app`. :: def create_app(): app = Flask(__name__) with app.app_context(): init_db() return app If you see that error somewhere else in your code not related to configuring the application, it most likely indicates that you should move that code into a view function or CLI command. Storing Data ------------ The application context is a good place to store common data during a request or CLI command. Flask provides the :data:`g object ` for this purpose. It is a simple namespace object that has the same lifetime as an application context. .. note:: The ``g`` name stands for "global", but that is referring to the data being global *within a context*. The data on ``g`` is lost after the context ends, and it is not an appropriate place to store data between requests. Use the :data:`session` or a database to store data across requests. A common use for :data:`g` is to manage resources during a request. 1. ``get_X()`` creates resource ``X`` if it does not exist, caching it as ``g.X``. 2. ``teardown_X()`` closes or otherwise deallocates the resource if it exists. It is registered as a :meth:`~Flask.teardown_appcontext` handler. For example, you can manage a database connection using this pattern:: from flask import g def get_db(): if 'db' not in g: g.db = connect_to_database() return g.db @app.teardown_appcontext def teardown_db(): db = g.pop('db', None) if db is not None: db.close() During a request, every call to ``get_db()`` will return the same connection, and it will be closed automatically at the end of the request. You can use :class:`~werkzeug.local.LocalProxy` to make a new context local from ``get_db()``:: from werkzeug.local import LocalProxy db = LocalProxy(get_db) Accessing ``db`` will call ``get_db`` internally, in the same way that :data:`current_app` works. ---- If you're writing an extension, :data:`g` should be reserved for user code. You may store internal data on the context itself, but be sure to use a sufficiently unique name. The current context is accessed with :data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see :doc:`extensiondev`. Events and Signals ------------------ The application will call functions registered with :meth:`~Flask.teardown_appcontext` when the application context is popped. If :data:`~signals.signals_available` is true, the following signals are sent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and :data:`appcontext_popped`. Flask-1.1.1/docs/becomingbig.rst0000644000175000017500000001111313510701642016675 0ustar daviddavid00000000000000.. _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 mailing list 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-1.1.1/docs/blueprints.rst0000644000175000017500000002617513510701642016635 0ustar daviddavid00000000000000.. _blueprints: Modular Applications with Blueprints ==================================== .. currentmodule:: flask .. versionadded:: 0.7 Flask uses a concept of *blueprints* for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications. A :class:`Blueprint` object works similarly to a :class:`Flask` application object, but it is not actually an application. Rather it is a *blueprint* of how to construct or extend an application. Why Blueprints? --------------- Blueprints in Flask are intended for these cases: * Factor an application into a set of blueprints. This is ideal for larger applications; a project could instantiate an application object, initialize several extensions, and register a collection of blueprints. * Register a blueprint on an application at a URL prefix and/or subdomain. Parameters in the URL prefix/subdomain become common view arguments (with defaults) across all view functions in the blueprint. * Register a blueprint multiple times on an application with different URL rules. * Provide template filters, static files, templates, and other utilities through blueprints. A blueprint does not have to implement applications or view functions. * Register a blueprint on an application for any of these cases when initializing a Flask extension. A blueprint in Flask is not a pluggable app because it is not actually an application -- it's a set of operations which can be registered on an application, even multiple times. Why not have multiple application objects? You can do that (see :ref:`app-dispatch`), but your applications will have separate configs and will be managed at the WSGI layer. Blueprints instead provide separation at the Flask level, share application config, and can change an application object as necessary with being registered. The downside is that you cannot unregister a blueprint once an application was created without having to destroy the whole application object. The Concept of Blueprints ------------------------- The basic concept of blueprints is that they record operations to execute when registered on an application. Flask associates view functions with blueprints when dispatching requests and generating URLs from one endpoint to another. My First Blueprint ------------------ This is what a very basic blueprint looks like. In this case we want to implement a blueprint that does simple rendering of static templates:: from 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) When you bind a function with the help of the ``@simple_page.route`` decorator, the blueprint will record the intention of registering the function ``show`` on the application when it's later registered. Additionally it will prefix the endpoint of the function with the name of the blueprint which was given to the :class:`Blueprint` constructor (in this case also ``simple_page``). The blueprint's name does not modify the URL, only the endpoint. Registering Blueprints ---------------------- So how do you register that blueprint? Like this:: from flask import Flask from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page) If you check the rules registered on the application, you will find these:: >>> app.url_map Map([' (HEAD, OPTIONS, GET) -> static>, ' (HEAD, OPTIONS, GET) -> simple_page.show>, simple_page.show>]) The first one is obviously from the application itself for the static files. The other two are for the `show` function of the ``simple_page`` blueprint. As you can see, they are also prefixed with the name of the blueprint and separated by a dot (``.``). Blueprints however can also be mounted at different locations:: app.register_blueprint(simple_page, url_prefix='/pages') And sure enough, these are the generated rules:: >>> app.url_map Map([' (HEAD, OPTIONS, GET) -> static>, ' (HEAD, OPTIONS, GET) -> simple_page.show>, simple_page.show>]) On top of that you can register blueprints multiple times though not every blueprint might respond properly to that. In fact it depends on how the blueprint is implemented if it can be mounted more than once. Blueprint Resources ------------------- Blueprints can provide resources as well. Sometimes you might want to introduce a blueprint only for the resources it provides. Blueprint Resource Folder ````````````````````````` Like for regular applications, blueprints are considered to be contained in a folder. While multiple blueprints can originate from the same folder, it does not have to be the case and it's usually not recommended. The folder is inferred from the second argument to :class:`Blueprint` which is usually `__name__`. This argument specifies what logical Python module or package corresponds to the blueprint. If it points to an actual Python package that package (which is a folder on the filesystem) is the resource folder. If it's a module, the package the module is contained in will be the resource folder. You can access the :attr:`Blueprint.root_path` property to see what the resource folder is:: >>> simple_page.root_path '/Users/username/TestProject/yourapplication' To quickly open sources from this folder you can use the :meth:`~Blueprint.open_resource` function:: with simple_page.open_resource('static/style.css') as f: code = f.read() Static Files ```````````` A blueprint can expose a folder with static files by providing the path to the folder on the filesystem with the ``static_folder`` argument. It is either an absolute path or relative to the blueprint's location:: admin = Blueprint('admin', __name__, static_folder='static') By default the rightmost part of the path is where it is exposed on the web. This can be changed with the ``static_url_path`` argument. Because the folder is called ``static`` here it will be available at the ``url_prefix`` of the blueprint + ``/static``. If the blueprint has the prefix ``/admin``, the static URL will be ``/admin/static``. The endpoint is named ``blueprint_name.static``. You can generate URLs to it with :func:`url_for` like you would with the static folder of the application:: url_for('admin.static', filename='style.css') However, if the blueprint does not have a ``url_prefix``, it is not possible to access the blueprint's static folder. This is because the URL would be ``/static`` in this case, and the application's ``/static`` route takes precedence. Unlike template folders, blueprint static folders are not searched if the file does not exist in the application static folder. Templates ````````` If you want the blueprint to expose templates you can do that by providing the `template_folder` parameter to the :class:`Blueprint` constructor:: admin = Blueprint('admin', __name__, template_folder='templates') For static files, the path can be absolute or relative to the blueprint resource folder. The template folder is added to the search path of templates but with a lower priority than the actual application's template folder. That way you can easily override templates that a blueprint provides in the actual application. This also means that if you don't want a blueprint template to be accidentally overridden, make sure that no other blueprint or actual application template has the same relative path. When multiple blueprints provide the same relative template path the first blueprint registered takes precedence over the others. So if you have a blueprint in the folder ``yourapplication/admin`` and you want to render the template ``'admin/index.html'`` and you have provided ``templates`` as a `template_folder` you will have to create a file like this: :file:`yourapplication/admin/templates/admin/index.html`. The reason for the extra ``admin`` folder is to avoid getting our template overridden by a template named ``index.html`` in the actual application template folder. To further reiterate this: if you have a blueprint named ``admin`` and you want to render a template called :file:`index.html` which is specific to this blueprint, the best idea is to lay out your templates like this:: yourpackage/ blueprints/ admin/ templates/ admin/ index.html __init__.py And then when you want to render the template, use :file:`admin/index.html` as the name to look up the template by. If you encounter problems loading the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config variable which will instruct Flask to print out the steps it goes through to locate templates on every ``render_template`` call. Building URLs ------------- If you want to link from one page to another you can use the :func:`url_for` function just like you normally would do just that you prefix the URL endpoint with the name of the blueprint and a dot (``.``):: url_for('admin.index') Additionally if you are in a view function of a blueprint or a rendered template and you want to link to another endpoint of the same blueprint, you can use relative redirects by prefixing the endpoint with a dot only:: url_for('.index') This will link to ``admin.index`` for instance in case the current request was dispatched to any other admin blueprint endpoint. Error Handlers -------------- Blueprints support the ``errorhandler`` decorator just like the :class:`Flask` application object, so it is easy to make Blueprint-specific custom error pages. Here is an example for a "404 Page Not Found" exception:: @simple_page.errorhandler(404) def page_not_found(e): return render_template('pages/404.html') Most errorhandlers will simply work as expected; however, there is a caveat concerning handlers for 404 and 405 exceptions. These errorhandlers are only invoked from an appropriate ``raise`` statement or a call to ``abort`` in another of the blueprint's view functions; they are not invoked by, e.g., an invalid URL access. This is because the blueprint does not "own" a certain URL space, so the application instance has no way of knowing which blueprint error handler it should run if given an invalid URL. If you would like to execute different handling strategies for these errors based on URL prefixes, they may be defined at the application level using the ``request`` proxy object:: @app.errorhandler(404) @app.errorhandler(405) def _handle_api_error(ex): if request.path.startswith('/api/'): return jsonify_error(ex) else: return ex More information on error handling see :ref:`errorpages`. Flask-1.1.1/docs/changelog.rst0000644000175000017500000000006113510701642016357 0ustar daviddavid00000000000000Changelog ========= .. include:: ../CHANGES.rst Flask-1.1.1/docs/cli.rst0000644000175000017500000004064013510701642015206 0ustar daviddavid00000000000000.. currentmodule:: flask .. _cli: Command Line Interface ====================== Installing Flask installs the ``flask`` script, a `Click`_ command line interface, in your virtualenv. Executed from the terminal, this script gives access to built-in, extension, and application-defined commands. The ``--help`` option will give more information about any commands and options. .. _Click: https://click.palletsprojects.com/ Application Discovery --------------------- The ``flask`` command is installed by Flask, not your application; it must be told where to find your application in order to use it. The ``FLASK_APP`` environment variable is used to specify how to load the application. Unix Bash (Linux, Mac, etc.):: $ export FLASK_APP=hello $ flask run Windows CMD:: > set FLASK_APP=hello > flask run Windows PowerShell:: > $env:FLASK_APP = "hello" > flask run While ``FLASK_APP`` supports a variety of options for specifying your application, most use cases should be simple. Here are the typical values: (nothing) The file :file:`wsgi.py` is imported, automatically detecting an app (``app``). This provides an easy way to create an app from a factory with extra arguments. ``FLASK_APP=hello`` The name is imported, automatically detecting an app (``app``) or factory (``create_app``). ---- ``FLASK_APP`` has three parts: an optional path that sets the current working directory, a Python file or dotted import path, and an optional variable name of the instance or factory. If the name is a factory, it can optionally be followed by arguments in parentheses. The following values demonstrate these parts: ``FLASK_APP=src/hello`` Sets the current working directory to ``src`` then imports ``hello``. ``FLASK_APP=hello.web`` Imports the path ``hello.web``. ``FLASK_APP=hello:app2`` Uses the ``app2`` Flask instance in ``hello``. ``FLASK_APP="hello:create_app('dev')"`` The ``create_app`` factory in ``hello`` is called with the string ``'dev'`` as the argument. If ``FLASK_APP`` is not set, the command will try to import "app" or "wsgi" (as a ".py" file, or package) and try to detect an application instance or factory. Within the given import, the command looks for an application instance named ``app`` or ``application``, then any application instance. If no instance is found, the command looks for a factory function named ``create_app`` or ``make_app`` that returns an instance. When calling an application factory, if the factory takes an argument named ``script_info``, then the :class:`~cli.ScriptInfo` instance is passed as a keyword argument. If the application factory takes only one argument and no parentheses follow the factory name, the :class:`~cli.ScriptInfo` instance is passed as a positional argument. If parentheses follow the factory name, their contents are parsed as Python literals and passes as arguments to the function. This means that strings must still be in quotes. Run the Development Server -------------------------- The :func:`run ` command will start the development server. It replaces the :meth:`Flask.run` method in most cases. :: $ flask run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) .. warning:: Do not use this command to run your application in production. Only use the development server during development. The development server is provided for convenience, but is not designed to be particularly secure, stable, or efficient. See :ref:`deployment` for how to run in production. Open a Shell ------------ To explore the data in your application, you can start an interactive Python shell with the :func:`shell ` command. An application context will be active, and the app instance will be imported. :: $ flask shell Python 3.6.2 (default, Jul 20 2017, 03:52:27) [GCC 7.1.1 20170630] on linux App: example Instance: /home/user/Projects/hello/instance >>> Use :meth:`~Flask.shell_context_processor` to add other automatic imports. Environments ------------ .. versionadded:: 1.0 The environment in which the Flask app runs is set by the :envvar:`FLASK_ENV` environment variable. If not set it defaults to ``production``. The other recognized environment is ``development``. Flask and extensions may choose to enable behaviors based on the environment. If the env is set to ``development``, the ``flask`` command will enable debug mode and ``flask run`` will enable the interactive debugger and reloader. :: $ FLASK_ENV=development flask run * Serving Flask app "hello" * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with inotify reloader * Debugger is active! * Debugger PIN: 223-456-919 Watch Extra Files with the Reloader ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When using development mode, the reloader will trigger whenever your Python code or imported modules change. The reloader can watch additional files with the ``--extra-files`` option, or the ``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are separated with ``:``, or ``;`` on Windows. .. code-block:: none $ flask run --extra-files file1:dirA/file2:dirB/ # or $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/ $ flask run * Running on http://127.0.0.1:8000/ * Detected change in '/path/to/file1', reloading Debug Mode ---------- Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``, as described above. If you want to control debug mode separately, use :envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it. .. _dotenv: Environment Variables From dotenv --------------------------------- Rather than setting ``FLASK_APP`` each time you open a new terminal, you can use Flask's dotenv support to set environment variables automatically. If `python-dotenv`_ is installed, running the ``flask`` command will set environment variables defined in the files :file:`.env` and :file:`.flaskenv`. This can be used to avoid having to set ``FLASK_APP`` manually every time you open a new terminal, and to set configuration using environment variables similar to how some deployment services work. Variables set on the command line are used over those set in :file:`.env`, which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be used for public variables, such as ``FLASK_APP``, while :file:`.env` should not be committed to your repository so that it can set private variables. Directories are scanned upwards from the directory you call ``flask`` from to locate the files. The current working directory will be set to the location of the file, with the assumption that that is the top level project directory. The files are only loaded by the ``flask`` command or calling :meth:`~Flask.run`. If you would like to load these files when running in production, you should call :func:`~cli.load_dotenv` manually. .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme Setting Command Options ~~~~~~~~~~~~~~~~~~~~~~~ Click is configured to load default values for command options from environment variables. The variables use the pattern ``FLASK_COMMAND_OPTION``. For example, to set the port for the run command, instead of ``flask run --port 8000``: .. code-block:: bash $ export FLASK_RUN_PORT=8000 $ flask run * Running on http://127.0.0.1:8000/ These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to control default command options. Disable dotenv ~~~~~~~~~~~~~~ The ``flask`` command will show a message if it detects dotenv files but python-dotenv is not installed. .. code-block:: bash $ flask run * Tip: There are .env files present. Do "pip install python-dotenv" to use them. You can tell Flask not to load dotenv files even when python-dotenv is installed by setting the ``FLASK_SKIP_DOTENV`` environment variable. This can be useful if you want to load them manually, or if you're using a project runner that loads them already. Keep in mind that the environment variables must be set before the app loads or it won't configure as expected. .. code-block:: bash $ export FLASK_SKIP_DOTENV=1 $ flask run Environment Variables From virtualenv ------------------------------------- If you do not want to install dotenv support, you can still set environment variables by adding them to the end of the virtualenv's :file:`activate` script. Activating the virtualenv will set the variables. Unix Bash, :file:`venv/bin/activate`:: $ export FLASK_APP=hello Windows CMD, :file:`venv\\Scripts\\activate.bat`:: > set FLASK_APP=hello It is preferred to use dotenv support over this, since :file:`.flaskenv` can be committed to the repository so that it works automatically wherever the project is checked out. Custom Commands --------------- The ``flask`` command is implemented using `Click`_. See that project's documentation for full information about writing commands. This example adds the command ``create-user`` that takes the argument ``name``. :: import click from flask import Flask app = Flask(__name__) @app.cli.command("create-user") @click.argument("name") def create_user(name): ... :: $ flask create-user admin This example adds the same command, but as ``user create``, a command in a group. This is useful if you want to organize multiple related commands. :: import click from flask import Flask from flask.cli import AppGroup app = Flask(__name__) user_cli = AppGroup('user') @user_cli.command('create') @click.argument('name') def create_user(name): ... app.cli.add_command(user_cli) :: $ flask user create demo See :ref:`testing-cli` for an overview of how to test your custom commands. Registering Commands with Blueprints ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If your application uses blueprints, you can optionally register CLI commands directly onto them. When your blueprint is registered onto your application, the associated commands will be available to the ``flask`` command. By default, those commands will be nested in a group matching the name of the blueprint. .. code-block:: python from flask import Blueprint bp = Blueprint('students', __name__) @bp.cli.command('create') @click.argument('name') def create(name): ... app.register_blueprint(bp) .. code-block:: text $ flask students create alice You can alter the group name by specifying the ``cli_group`` parameter when creating the :class:`Blueprint` object, or later with :meth:`app.register_blueprint(bp, cli_group='...') `. The following are equivalent: .. code-block:: python bp = Blueprint('students', __name__, cli_group='other') # or app.register_blueprint(bp, cli_group='other') .. code-block:: text $ flask other create alice Specifying ``cli_group=None`` will remove the nesting and merge the commands directly to the application's level: .. code-block:: python bp = Blueprint('students', __name__, cli_group=None) # or app.register_blueprint(bp, cli_group=None) .. code-block:: text $ flask create alice Application Context ~~~~~~~~~~~~~~~~~~~ Commands added using the Flask app's :attr:`~Flask.cli` :meth:`~cli.AppGroup.command` decorator will be executed with an application context pushed, so your command and extensions have access to the app and its configuration. If you create a command using the Click :func:`~click.command` decorator instead of the Flask decorator, you can use :func:`~cli.with_appcontext` to get the same behavior. :: import click from flask.cli import with_appcontext @click.command() @with_appcontext def do_work(): ... app.cli.add_command(do_work) If you're sure a command doesn't need the context, you can disable it:: @app.cli.command(with_appcontext=False) def do_work(): ... Plugins ------- Flask will automatically load commands specified in the ``flask.commands`` `entry point`_. This is useful for extensions that want to add commands when they are installed. Entry points are specified in :file:`setup.py` :: from setuptools import setup setup( name='flask-my-extension', ..., entry_points={ 'flask.commands': [ 'my-command=flask_my_extension.commands:cli' ], }, ) .. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points Inside :file:`flask_my_extension/commands.py` you can then export a Click object:: import click @click.command() def cli(): ... Once that package is installed in the same virtualenv as your Flask project, you can run ``flask my-command`` to invoke the command. .. _custom-scripts: Custom Scripts -------------- When you are using the app factory pattern, it may be more convenient to define your own Click script. Instead of using ``FLASK_APP`` and letting Flask load your application, you can create your own Click object and export it as a `console script`_ entry point. Create an instance of :class:`~cli.FlaskGroup` and pass it the factory:: import click from flask import Flask from flask.cli import FlaskGroup def create_app(): app = Flask('wiki') # other setup return app @click.group(cls=FlaskGroup, create_app=create_app) def cli(): """Management script for the Wiki application.""" Define the entry point in :file:`setup.py`:: from setuptools import setup setup( name='flask-my-extension', ..., entry_points={ 'console_scripts': [ 'wiki=wiki:cli' ], }, ) Install the application in the virtualenv in editable mode and the custom script is available. Note that you don't need to set ``FLASK_APP``. :: $ pip install -e . $ wiki run .. admonition:: Errors in Custom Scripts When using a custom script, if you introduce an error in your module-level code, the reloader will fail because it can no longer load the entry point. The ``flask`` command, being separate from your code, does not have this issue and is recommended in most cases. .. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts PyCharm Integration ------------------- Prior to PyCharm 2018.1, the Flask CLI features weren't yet fully integrated into PyCharm. We have to do a few tweaks to get them working smoothly. These instructions should be similar for any other IDE you might want to use. In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit Configurations*. You'll be greeted by a screen similar to this: .. image:: _static/pycharm-runconfig.png :align: center :class: screenshot :alt: screenshot of pycharm's run configuration settings There's quite a few options to change, but once we've done it for one command, we can easily copy the entire configuration and make a single tweak to give us access to other commands, including any custom ones you may implement yourself. Click the + (*Add New Configuration*) button and select *Python*. Give the configuration a good descriptive name such as "Run Flask Server". For the ``flask run`` command, check "Single instance only" since you can't run the server more than once at the same time. Select *Module name* from the dropdown (**A**) then input ``flask``. The *Parameters* field (**B**) is set to the CLI command to execute (with any arguments). In this example we use ``run``, which will run the development server. You can skip this next step if you're using :ref:`dotenv`. We need to add an environment variable (**C**) to identify our application. Click on the browse button and add an entry with ``FLASK_APP`` on the left and the Python import or file on the right (``hello`` for example). Next we need to set the working directory (**D**) to be the folder where our application resides. If you have installed your project as a package in your virtualenv, you may untick the *PYTHONPATH* options (**E**). This will more accurately match how you deploy the app later. Click *Apply* to save the configuration, or *OK* to save and close the window. Select the configuration in the main PyCharm window and click the play button next to it to run the server. Now that we have a configuration which runs ``flask run`` from within PyCharm, we can copy that configuration and alter the *Script* argument to run a different CLI command, e.g. ``flask shell``. Flask-1.1.1/docs/conf.py0000644000175000017500000000612313510701642015202 0ustar daviddavid00000000000000from pallets_sphinx_themes import get_version from pallets_sphinx_themes import ProjectLink # Project -------------------------------------------------------------- project = "Flask" copyright = "2010 Pallets" author = "Pallets" release, version = get_version("Flask") # General -------------------------------------------------------------- master_doc = "index" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinxcontrib.log_cabinet", "pallets_sphinx_themes", "sphinx_issues", ] intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "werkzeug": ("https://werkzeug.palletsprojects.com/", None), "click": ("https://click.palletsprojects.com/", None), "jinja": ("http://jinja.pocoo.org/docs/", None), "itsdangerous": ("https://itsdangerous.palletsprojects.com/", None), "sqlalchemy": ("https://docs.sqlalchemy.org/", None), "wtforms": ("https://wtforms.readthedocs.io/en/stable/", None), "blinker": ("https://pythonhosted.org/blinker/", None), } issues_github_path = "pallets/flask" # HTML ----------------------------------------------------------------- html_theme = "flask" html_theme_options = {"index_sidebar_logo": False} html_context = { "project_links": [ ProjectLink("Donate to Pallets", "https://palletsprojects.com/donate"), ProjectLink("Flask Website", "https://palletsprojects.com/p/flask/"), ProjectLink("PyPI releases", "https://pypi.org/project/Flask/"), ProjectLink("Source Code", "https://github.com/pallets/flask/"), ProjectLink("Issue Tracker", "https://github.com/pallets/flask/issues/"), ] } html_sidebars = { "index": ["project.html", "localtoc.html", "searchbox.html"], "**": ["localtoc.html", "relations.html", "searchbox.html"], } singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]} html_static_path = ["_static"] html_favicon = "_static/flask-icon.png" html_logo = "_static/flask-icon.png" html_title = "Flask Documentation ({})".format(version) html_show_sourcelink = False # LaTeX ---------------------------------------------------------------- latex_documents = [ (master_doc, "Flask-{}.tex".format(version), html_title, author, "manual") ] # Local Extensions ----------------------------------------------------- def github_link(name, rawtext, text, lineno, inliner, options=None, content=None): app = inliner.document.settings.env.app release = app.config.release base_url = "https://github.com/pallets/flask/tree/" if text.endswith(">"): words, text = text[:-1].rsplit("<", 1) words = words.strip() else: words = None if release.endswith("dev"): url = "{0}master/{1}".format(base_url, text) else: url = "{0}{1}/{2}".format(base_url, release, text) if words is None: words = url from docutils.nodes import reference from docutils.parsers.rst.roles import set_classes options = options or {} set_classes(options) node = reference(rawtext, words, refuri=url, **options) return [node], [] def setup(app): app.add_role("gh", github_link) Flask-1.1.1/docs/config.rst0000644000175000017500000005763613510701642015721 0ustar daviddavid00000000000000.. _config: Configuration Handling ====================== Applications need some kind of configuration. There are different settings you might want to change depending on the application environment like toggling the debug mode, setting the secret key, and other such environment-specific things. The way Flask is designed usually requires the configuration to be available when the application starts up. You can hard code the configuration in the code, which for many small applications is not actually that bad, but there are better ways. Independent of how you load your config, there is a config object available which holds the loaded configuration values: The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask` object. This is the place where Flask itself puts certain configuration values and also where extensions can put their configuration values. But this is also where you can have your own configuration. Configuration Basics -------------------- The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and can be modified just like any dictionary:: app = Flask(__name__) app.config['TESTING'] = True Certain configuration values are also forwarded to the :attr:`~flask.Flask` object so you can read and write them from there:: app.testing = True To update multiple keys at once you can use the :meth:`dict.update` method:: app.config.update( TESTING=True, SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/' ) Environment and Debug Features ------------------------------ The :data:`ENV` and :data:`DEBUG` config values are special because they may behave inconsistently if changed after the app has begun setting up. In order to set the environment and debug mode reliably, Flask uses environment variables. The environment is used to indicate to Flask, extensions, and other programs, like Sentry, what context Flask is running in. It is controlled with the :envvar:`FLASK_ENV` environment variable and defaults to ``production``. Setting :envvar:`FLASK_ENV` to ``development`` will enable debug mode. ``flask run`` will use the interactive debugger and reloader by default in debug mode. To control this separately from the environment, use the :envvar:`FLASK_DEBUG` flag. .. versionchanged:: 1.0 Added :envvar:`FLASK_ENV` to control the environment separately from debug mode. The development environment enables debug mode. To switch Flask to the development environment and enable debug mode, set :envvar:`FLASK_ENV`:: $ export FLASK_ENV=development $ flask run (On Windows, use ``set`` instead of ``export``.) Using the environment variables as described above is recommended. While it is possible to set :data:`ENV` and :data:`DEBUG` in your config or code, this is strongly discouraged. They can't be read early by the ``flask`` command, and some systems or extensions may have already configured themselves based on a previous value. Builtin Configuration Values ---------------------------- The following configuration values are used internally by Flask: .. py:data:: ENV What environment the app is running in. Flask and extensions may enable behaviors based on the environment, such as enabling debug mode. The :attr:`~flask.Flask.env` attribute maps to this config key. This is set by the :envvar:`FLASK_ENV` environment variable and may not behave as expected if set in code. **Do not enable development when deploying in production.** Default: ``'production'`` .. versionadded:: 1.0 .. py:data:: DEBUG Whether debug mode is enabled. When using ``flask run`` to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. The :attr:`~flask.Flask.debug` attribute maps to this config key. This is enabled when :data:`ENV` is ``'development'`` and is overridden by the ``FLASK_DEBUG`` environment variable. It may not behave as expected if set in code. **Do not enable debug mode when deploying in production.** Default: ``True`` if :data:`ENV` is ``'development'``, or ``False`` otherwise. .. py:data:: TESTING Enable testing mode. Exceptions are propagated rather than handled by the the app's error handlers. Extensions may also change their behavior to facilitate easier testing. You should enable this in your own tests. Default: ``False`` .. py:data:: PROPAGATE_EXCEPTIONS Exceptions are re-raised rather than being handled by the app's error handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG`` is enabled. Default: ``None`` .. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION Don't pop the request context when an exception occurs. If not set, this is true if ``DEBUG`` is true. This allows debuggers to introspect the request data on errors, and should normally not need to be set directly. Default: ``None`` .. py:data:: TRAP_HTTP_EXCEPTIONS If there is no handler for an ``HTTPException``-type exception, re-raise it to be handled by the interactive debugger instead of returning it as a simple error response. Default: ``False`` .. py:data:: TRAP_BAD_REQUEST_ERRORS Trying to access a key that doesn't exist from request dicts like ``args`` and ``form`` will return a 400 Bad Request error page. Enable this to treat the error as an unhandled exception instead so that you get the interactive debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If unset, it is enabled in debug mode. Default: ``None`` .. py:data:: SECRET_KEY A secret key that will be used for securely signing the session cookie and can be used for any other security related needs by extensions or your application. It should be a long random string of bytes, although unicode is accepted too. For example, copy the output of this to your config:: $ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/' **Do not reveal the secret key when posting questions or committing code.** Default: ``None`` .. py:data:: SESSION_COOKIE_NAME The name of the session cookie. Can be changed in case you already have a cookie with the same name. Default: ``'session'`` .. py:data:: SESSION_COOKIE_DOMAIN The domain match rule that the session cookie will be valid for. If not set, the cookie will be valid for all subdomains of :data:`SERVER_NAME`. If ``False``, the cookie's domain will not be set. Default: ``None`` .. py:data:: SESSION_COOKIE_PATH The path that the session cookie will be valid for. If not set, the cookie will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set. Default: ``None`` .. py:data:: SESSION_COOKIE_HTTPONLY Browsers will not allow JavaScript access to cookies marked as "HTTP only" for security. Default: ``True`` .. py:data:: SESSION_COOKIE_SECURE Browsers will only send cookies with requests over HTTPS if the cookie is marked "secure". The application must be served over HTTPS for this to make sense. Default: ``False`` .. py:data:: SESSION_COOKIE_SAMESITE Restrict how cookies are sent with requests from external sites. Can be set to ``'Lax'`` (recommended) or ``'Strict'``. See :ref:`security-cookie`. Default: ``None`` .. versionadded:: 1.0 .. py:data:: PERMANENT_SESSION_LIFETIME If ``session.permanent`` is true, the cookie's expiration will be set this number of seconds in the future. Can either be a :class:`datetime.timedelta` or an ``int``. Flask's default cookie implementation validates that the cryptographic signature is not older than this value. Default: ``timedelta(days=31)`` (``2678400`` seconds) .. py:data:: SESSION_REFRESH_EACH_REQUEST Control whether the cookie is sent with every response when ``session.permanent`` is true. Sending the cookie every time (the default) can more reliably keep the session from expiring, but uses more bandwidth. Non-permanent sessions are not affected. Default: ``True`` .. py:data:: USE_X_SENDFILE When serving files, set the ``X-Sendfile`` header instead of serving the data with Flask. Some web servers, such as Apache, recognize this and serve the data more efficiently. This only makes sense when using such a server. Default: ``False`` .. py:data:: SEND_FILE_MAX_AGE_DEFAULT When serving files, set the cache control max age to this number of seconds. Can either be a :class:`datetime.timedelta` or an ``int``. Override this value on a per-file basis using :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint. Default: ``timedelta(hours=12)`` (``43200`` seconds) .. py:data:: SERVER_NAME Inform the application what host and port it is bound to. Required for subdomain route matching support. If set, will be used for the session cookie domain if :data:`SESSION_COOKIE_DOMAIN` is not set. Modern web browsers will not allow setting cookies for domains without a dot. To use a domain locally, add any names that should route to the app to your ``hosts`` file. :: 127.0.0.1 localhost.dev If set, ``url_for`` can generate external URLs with only an application context instead of a request context. Default: ``None`` .. py:data:: APPLICATION_ROOT Inform the application what path it is mounted under by the application / web server. This is used for generating URLs outside the context of a request (inside a request, the dispatcher is responsible for setting ``SCRIPT_NAME`` instead; see :ref:`Application Dispatching ` for examples of dispatch configuration). Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not set. Default: ``'/'`` .. py:data:: PREFERRED_URL_SCHEME Use this scheme for generating external URLs when not in a request context. Default: ``'http'`` .. py:data:: MAX_CONTENT_LENGTH Don't read more than this many bytes from the incoming request data. If not set and the request does not specify a ``CONTENT_LENGTH``, no data will be read for security. Default: ``None`` .. py:data:: JSON_AS_ASCII Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON will be returned as a Unicode string, or encoded as ``UTF-8`` by ``jsonify``. This has security implications when rendering the JSON into JavaScript in templates, and should typically remain enabled. Default: ``True`` .. py:data:: JSON_SORT_KEYS Sort the keys of JSON objects alphabetically. This is useful for caching because it ensures the data is serialized the same way no matter what Python's hash seed is. While not recommended, you can disable this for a possible performance improvement at the cost of caching. Default: ``True`` .. py:data:: JSONIFY_PRETTYPRINT_REGULAR ``jsonify`` responses will be output with newlines, spaces, and indentation for easier reading by humans. Always enabled in debug mode. Default: ``False`` .. py:data:: JSONIFY_MIMETYPE The mimetype of ``jsonify`` responses. Default: ``'application/json'`` .. py:data:: TEMPLATES_AUTO_RELOAD Reload templates when they are changed. If not set, it will be enabled in debug mode. Default: ``None`` .. py:data:: EXPLAIN_TEMPLATE_LOADING Log debugging information tracing how a template file was loaded. This can be useful to figure out why a template was not loaded or the wrong file appears to be loaded. Default: ``False`` .. py:data:: MAX_COOKIE_SIZE Warn if cookie headers are larger than this many bytes. Defaults to ``4093``. Larger cookies may be silently ignored by browsers. Set to ``0`` to disable the warning. .. versionadded:: 0.4 ``LOGGER_NAME`` .. versionadded:: 0.5 ``SERVER_NAME`` .. versionadded:: 0.6 ``MAX_CONTENT_LENGTH`` .. versionadded:: 0.7 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION`` .. versionadded:: 0.8 ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``, ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``, ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``, ``SESSION_COOKIE_SECURE`` .. versionadded:: 0.9 ``PREFERRED_URL_SCHEME`` .. versionadded:: 0.10 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR`` .. versionadded:: 0.11 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``, ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING`` .. versionchanged:: 1.0 ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See :doc:`/logging` for information about configuration. Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment variable. Added :data:`SESSION_COOKIE_SAMESITE` to control the session cookie's ``SameSite`` option. Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug. Configuring from Files ---------------------- Configuration becomes more useful if you can store it in a separate file, ideally located outside the actual application package. This makes packaging and distributing your application possible via various package handling tools (:ref:`distribute-deployment`) and finally modifying the configuration file afterwards. So a common pattern is this:: app = Flask(__name__) app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS') This first loads the configuration from the `yourapplication.default_settings` module and then overrides the values with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS` environment variable points to. This environment variable can be set on Linux or OS X with the export command in the shell before starting the server:: $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg $ python run-app.py * Running on http://127.0.0.1:5000/ * Restarting with reloader... On Windows systems use the `set` builtin instead:: > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg The configuration files themselves are actual Python files. Only values in uppercase are actually stored in the config object later on. So make sure to use uppercase letters for your config keys. Here is an example of a configuration file:: # Example configuration DEBUG = False SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/' Make sure to load the configuration very early on, so that extensions have the ability to access the configuration when starting up. There are other methods on the config object as well to load from individual files. For a complete reference, read the :class:`~flask.Config` object's documentation. Configuring from Environment Variables -------------------------------------- In addition to pointing to configuration files using environment variables, you may find it useful (or necessary) to control your configuration values directly from the environment. Environment variables can be set on Linux or OS X with the export command in the shell before starting the server:: $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f' $ export MAIL_ENABLED=false $ python run-app.py * Running on http://127.0.0.1:5000/ On Windows systems use the ``set`` builtin instead:: > set SECRET_KEY='5f352379324c22463451387a0aec5d2f' While this approach is straightforward to use, it is important to remember that environment variables are strings -- they are not automatically deserialized into Python types. Here is an example of a configuration file that uses environment variables:: import os _mail_enabled = os.environ.get("MAIL_ENABLED", default="true") MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"} SECRET_KEY = os.environ.get("SECRET_KEY") if not SECRET_KEY: raise ValueError("No SECRET_KEY set for Flask application") Notice that any value besides an empty string will be interpreted as a boolean ``True`` value in Python, which requires care if an environment explicitly sets values intended to be ``False``. Make sure to load the configuration very early on, so that extensions have the ability to access the configuration when starting up. There are other methods on the config object as well to load from individual files. For a complete reference, read the :class:`~flask.Config` class documentation. Configuration Best Practices ---------------------------- The downside with the approach mentioned earlier is that it makes testing a little harder. There is no single 100% solution for this problem in general, but there are a couple of things you can keep in mind to improve that experience: 1. Create your application in a function and register blueprints on it. That way you can create multiple instances of your application with different configurations attached which makes unit testing a lot easier. You can use this to pass in configuration as needed. 2. Do not write code that needs the configuration at import time. If you limit yourself to request-only accesses to the configuration you can reconfigure the object later on as needed. .. _config-dev-prod: Development / Production ------------------------ Most applications need more than one configuration. There should be at least separate configurations for the production server and the one used during development. The easiest way to handle this is to use a default configuration that is always loaded and part of the version control, and a separate configuration that overrides the values as necessary as mentioned in the example above:: app = Flask(__name__) app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS') Then you just have to add a separate :file:`config.py` file and export ``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However there are alternative ways as well. For example you could use imports or subclassing. What is very popular in the Django world is to make the import explicit in the config file by adding ``from yourapplication.default_settings import *`` to the top of the file and then overriding the changes by hand. You could also inspect an environment variable like ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc and import different hard-coded files based on that. An interesting pattern is also to use classes and inheritance for configuration:: class Config(object): DEBUG = False TESTING = False DATABASE_URI = 'sqlite:///:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True To enable such a config you just have to call into :meth:`~flask.Config.from_object`:: app.config.from_object('configmodule.ProductionConfig') Note that :meth:`~flask.Config.from_object` does not instantiate the class object. If you need to instantiate the class, such as to access a property, then you must do so before calling :meth:`~flask.Config.from_object`:: from configmodule import ProductionConfig app.config.from_object(ProductionConfig()) # Alternatively, import via string: from werkzeug.utils import import_string cfg = import_string('configmodule.ProductionConfig')() app.config.from_object(cfg) Instantiating the configuration object allows you to use ``@property`` in your configuration classes:: class Config(object): """Base config, uses staging database server.""" DEBUG = False TESTING = False DB_SERVER = '192.168.1.56' @property def DATABASE_URI(self): # Note: all caps return 'mysql://user@{}/foo'.format(self.DB_SERVER) class ProductionConfig(Config): """Uses production database server.""" DB_SERVER = '192.168.19.32' class DevelopmentConfig(Config): DB_SERVER = 'localhost' DEBUG = True class TestingConfig(Config): DB_SERVER = 'localhost' DEBUG = True DATABASE_URI = 'sqlite:///:memory:' There are many different ways and it's up to you how you want to manage your configuration files. However here a list of good recommendations: - Keep a default configuration in version control. Either populate the config with this default configuration or import it in your own configuration files before overriding values. - Use an environment variable to switch between the configurations. This can be done from outside the Python interpreter and makes development and deployment much easier because you can quickly and easily switch between different configs without having to touch the code at all. If you are working often on different projects you can even create your own script for sourcing that activates a virtualenv and exports the development configuration for you. - Use a tool like `fabric`_ in production to push code and configurations separately to the production server(s). For some details about how to do that, head over to the :ref:`fabric-deployment` pattern. .. _fabric: https://www.fabfile.org/ .. _instance-folders: Instance Folders ---------------- .. versionadded:: 0.8 Flask 0.8 introduces instance folders. Flask for a long time made it possible to refer to paths relative to the application's folder directly (via :attr:`Flask.root_path`). This was also how many developers loaded configurations stored next to the application. Unfortunately however this only works well if applications are not packages in which case the root path refers to the contents of the package. With Flask 0.8 a new attribute was introduced: :attr:`Flask.instance_path`. It refers to a new concept called the “instance folder”. The instance folder is designed to not be under version control and be deployment specific. It's the perfect place to drop things that either change at runtime or configuration files. You can either explicitly provide the path of the instance folder when creating the Flask application or you can let Flask autodetect the instance folder. For explicit configuration use the `instance_path` parameter:: app = Flask(__name__, instance_path='/path/to/instance/folder') Please keep in mind that this path *must* be absolute when provided. If the `instance_path` parameter is not provided the following default locations are used: - Uninstalled module:: /myapp.py /instance - Uninstalled package:: /myapp /__init__.py /instance - Installed module or package:: $PREFIX/lib/python2.X/site-packages/myapp $PREFIX/var/myapp-instance ``$PREFIX`` is the prefix of your Python installation. This can be ``/usr`` or the path to your virtualenv. You can print the value of ``sys.prefix`` to see what the prefix is set to. Since the config object provided loading of configuration files from relative filenames we made it possible to change the loading via filenames to be relative to the instance path if wanted. The behavior of relative paths in config files can be flipped between “relative to the application root” (the default) to “relative to instance folder” via the `instance_relative_config` switch to the application constructor:: app = Flask(__name__, instance_relative_config=True) Here is a full example of how to configure Flask to preload the config from a module and then override the config from a file in the instance folder if it exists:: app = Flask(__name__, instance_relative_config=True) app.config.from_object('yourapplication.default_settings') app.config.from_pyfile('application.cfg', silent=True) The path to the instance folder can be found via the :attr:`Flask.instance_path`. Flask also provides a shortcut to open a file from the instance folder with :meth:`Flask.open_instance_resource`. Example usage for both:: filename = os.path.join(app.instance_path, 'application.cfg') with open(filename) as f: config = f.read() # or via open_instance_resource: with app.open_instance_resource('application.cfg') as f: config = f.read() Flask-1.1.1/docs/contributing.rst0000644000175000017500000000004113510701642017135 0ustar daviddavid00000000000000.. include:: ../CONTRIBUTING.rst Flask-1.1.1/docs/deploying/0000755000175000017500000000000013510702200015662 5ustar daviddavid00000000000000Flask-1.1.1/docs/deploying/cgi.rst0000644000175000017500000000406313510701642017172 0ustar daviddavid00000000000000CGI === If all other deployment methods do not work, CGI will work for sure. CGI is supported by all major servers but usually has a sub-optimal performance. This is also the way you can use a Flask application on Google's `App Engine`_, where execution happens in a CGI-like environment. .. admonition:: Watch Out Please make sure in advance that any ``app.run()`` calls you might have in your application file are inside an ``if __name__ == '__main__':`` block or moved to a separate file. Just make sure it's not called because this will always start a local WSGI server which we do not want if we deploy that application to CGI / app engine. With CGI, you will also have to make sure that your code does not contain any ``print`` statements, or that ``sys.stdout`` is overridden by something that doesn't write into the HTTP response. Creating a `.cgi` file ---------------------- First you need to create the CGI application file. Let's call it :file:`yourapplication.cgi`:: #!/usr/bin/python from wsgiref.handlers import CGIHandler from yourapplication import app CGIHandler().run(app) Server Setup ------------ Usually there are two ways to configure the server. Either just copy the ``.cgi`` into a :file:`cgi-bin` (and use `mod_rewrite` or something similar to rewrite the URL) or let the server point to the file directly. In Apache for example you can put something like this into the config: .. sourcecode:: apache ScriptAlias /app /path/to/the/application.cgi On shared webhosting, though, you might not have access to your Apache config. In this case, a file called ``.htaccess``, sitting in the public directory you want your app to be available, works too but the ``ScriptAlias`` directive won't work in that case: .. sourcecode:: apache RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L] For more information consult the documentation of your webserver. .. _App Engine: https://cloud.google.com/appengine/docs/ Flask-1.1.1/docs/deploying/fastcgi.rst0000644000175000017500000002053713510701642020054 0ustar daviddavid00000000000000.. _deploying-fastcgi: FastCGI ======= FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and `cherokee`_; see :doc:`uwsgi` and :doc:`wsgi-standalone` for other options. To use your WSGI application with any of them you will need a FastCGI server first. The most popular one is `flup`_ which we will use for this guide. Make sure to have it installed to follow along. .. admonition:: Watch Out Please make sure in advance that any ``app.run()`` calls you might have in your application file are inside an ``if __name__ == '__main__':`` block or moved to a separate file. Just make sure it's not called because this will always start a local WSGI server which we do not want if we deploy that application to FastCGI. Creating a `.fcgi` file ----------------------- First you need to create the FastCGI server file. Let's call it `yourapplication.fcgi`:: #!/usr/bin/python from flup.server.fcgi import WSGIServer from yourapplication import app if __name__ == '__main__': WSGIServer(app).run() This is enough for Apache to work, however nginx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work you need to pass the path to the socket to the :class:`~flup.server.fcgi.WSGIServer`:: WSGIServer(application, bindAddress='/path/to/fcgi.sock').run() The path has to be the exact same path you define in the server config. Save the :file:`yourapplication.fcgi` file somewhere you will find it again. It makes sense to have that in :file:`/var/www/yourapplication` or something similar. Make sure to set the executable bit on that file so that the servers can execute it: .. sourcecode:: text $ chmod +x /var/www/yourapplication/yourapplication.fcgi Configuring Apache ------------------ The example above is good enough for a basic Apache deployment but your `.fcgi` file will appear in your application URL e.g. ``example.com/yourapplication.fcgi/news/``. There are few ways to configure your application so that yourapplication.fcgi does not appear in the URL. A preferable way is to use the ScriptAlias and SetHandler configuration directives to route requests to the FastCGI server. The following example uses FastCgiServer to start 5 instances of the application which will handle all incoming requests:: LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 5 ServerName webapp1.mydomain.com DocumentRoot /var/www/html/yourapplication AddHandler fastcgi-script fcgi ScriptAlias / /var/www/html/yourapplication/app.fcgi/ SetHandler fastcgi-script These processes will be managed by Apache. If you're using a standalone FastCGI server, you can use the FastCgiExternalServer directive instead. Note that in the following the path is not real, it's simply used as an identifier to other directives such as AliasMatch:: FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:3000 If you cannot set ScriptAlias, for example on a shared web host, you can use WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess:: AddHandler fcgid-script .fcgi SetHandler fcgid-script Options +FollowSymLinks +ExecCGI Options +FollowSymlinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L] Set yourapplication.fcgi:: #!/usr/bin/python #: optional path to your local python site-packages folder import sys sys.path.insert(0, '/lib/python/site-packages') from flup.server.fcgi import WSGIServer from yourapplication import app class ScriptNameStripper(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['SCRIPT_NAME'] = '' return self.app(environ, start_response) app = ScriptNameStripper(app) if __name__ == '__main__': WSGIServer(app).run() Configuring lighttpd -------------------- A basic FastCGI configuration for lighttpd looks like that:: fastcgi.server = ("/yourapplication.fcgi" => (( "socket" => "/tmp/yourapplication-fcgi.sock", "bin-path" => "/var/www/yourapplication/yourapplication.fcgi", "check-local" => "disable", "max-procs" => 1 )) ) alias.url = ( "/static/" => "/path/to/your/static/" ) url.rewrite-once = ( "^(/static($|/.*))$" => "$1", "^(/.*)$" => "/yourapplication.fcgi$1" ) Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to ``/yourapplication``. If you want the application to work in the URL root you have to work around a lighttpd bug with the :class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware. Make sure to apply it only if you are mounting the application the URL root. Also, see the Lighty docs for more information on `FastCGI and Python `_ (note that explicitly passing a socket to run() is no longer necessary). Configuring nginx ----------------- Installing FastCGI applications on nginx is a bit different because by default no FastCGI parameters are forwarded. A basic Flask FastCGI configuration for nginx looks like this:: location = /yourapplication { rewrite ^ /yourapplication/ last; } location /yourapplication { try_files $uri @yourapplication; } location @yourapplication { include fastcgi_params; fastcgi_split_path_info ^(/yourapplication)(.*)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; } This configuration binds the application to ``/yourapplication``. If you want to have it in the URL root it's a bit simpler because you don't have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``:: location / { try_files $uri @yourapplication; } location @yourapplication { include fastcgi_params; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param SCRIPT_NAME ""; fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; } Running FastCGI Processes ------------------------- Since nginx and others do not load FastCGI apps, you have to do it by yourself. `Supervisor can manage FastCGI processes. `_ You can look around for other FastCGI process managers or write a script to run your `.fcgi` file at boot, e.g. using a SysV ``init.d`` script. For a temporary solution, you can always run the ``.fcgi`` script inside GNU screen. See ``man screen`` for details, and note that this is a manual solution which does not persist across system restart:: $ screen $ /var/www/yourapplication/yourapplication.fcgi Debugging --------- FastCGI deployments tend to be hard to debug on most web servers. Very often the only thing the server log tells you is something along the lines of "premature end of headers". In order to debug the application the only thing that can really give you ideas why it breaks is switching to the correct user and executing the application by hand. This example assumes your application is called `application.fcgi` and that your web server user is `www-data`:: $ su www-data $ cd /var/www/yourapplication $ python application.fcgi Traceback (most recent call last): File "yourapplication.fcgi", line 4, in ImportError: No module named yourapplication In this case the error seems to be "yourapplication" not being on the python path. Common problems are: - Relative paths being used. Don't rely on the current working directory. - The code depending on environment variables that are not set by the web server. - Different python interpreters being used. .. _nginx: https://nginx.org/ .. _lighttpd: https://www.lighttpd.net/ .. _cherokee: http://cherokee-project.com/ .. _flup: https://pypi.org/project/flup/ Flask-1.1.1/docs/deploying/index.rst0000644000175000017500000000233113510701642017533 0ustar daviddavid00000000000000.. _deployment: Deployment Options ================== While lightweight and easy to use, **Flask's built-in server is not suitable for production** as it doesn't scale well. Some of the options available for properly running Flask in production are documented here. If you want to deploy your Flask application to a WSGI server not listed here, look up the server documentation about how to use a WSGI app with it. Just remember that your :class:`Flask` application object is the actual WSGI application. Hosted options -------------- - `Deploying Flask on Heroku `_ - `Deploying Flask on Google App Engine `_ - `Deploying Flask on AWS Elastic Beanstalk `_ - `Deploying on Azure (IIS) `_ - `Deploying on PythonAnywhere `_ Self-hosted options ------------------- .. toctree:: :maxdepth: 2 wsgi-standalone uwsgi mod_wsgi fastcgi cgi Flask-1.1.1/docs/deploying/mod_wsgi.rst0000644000175000017500000001663613510701642020251 0ustar daviddavid00000000000000.. _mod_wsgi-deployment: mod_wsgi (Apache) ================= If you are using the `Apache`_ webserver, consider using `mod_wsgi`_. .. admonition:: Watch Out Please make sure in advance that any ``app.run()`` calls you might have in your application file are inside an ``if __name__ == '__main__':`` block or moved to a separate file. Just make sure it's not called because this will always start a local WSGI server which we do not want if we deploy that application to mod_wsgi. .. _Apache: https://httpd.apache.org/ Installing `mod_wsgi` --------------------- If you don't have `mod_wsgi` installed yet you have to either install it using a package manager or compile it yourself. The mod_wsgi `installation instructions`_ cover source installations on UNIX systems. If you are using Ubuntu/Debian you can apt-get it and activate it as follows: .. sourcecode:: text $ apt-get install libapache2-mod-wsgi If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you can install it as follows: .. sourcecode:: text $ yum install mod_wsgi On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by using pkg_add: .. sourcecode:: text $ pkg install ap22-mod_wsgi2 If you are using pkgsrc you can install `mod_wsgi` by compiling the `www/ap2-wsgi` package. If you encounter segfaulting child processes after the first apache reload you can safely ignore them. Just restart the server. Creating a `.wsgi` file ----------------------- To run your application you need a :file:`yourapplication.wsgi` file. This file contains the code `mod_wsgi` is executing on startup to get the application object. The object called `application` in that file is then used as application. For most applications the following file should be sufficient:: from yourapplication import app as application If a factory function is used in a :file:`__init__.py` file, then the function should be imported:: from yourapplication import create_app application = create_app() If you don't have a factory function for application creation but a singleton instance you can directly import that one as `application`. Store that file somewhere that you will find it again (e.g.: :file:`/var/www/yourapplication`) and make sure that `yourapplication` and all the libraries that are in use are on the python load path. If you don't want to install it system wide consider using a `virtual python`_ instance. Keep in mind that you will have to actually install your application into the virtualenv as well. Alternatively there is the option to just patch the path in the ``.wsgi`` file before the import:: import sys sys.path.insert(0, '/path/to/the/application') Configuring Apache ------------------ The last thing you have to do is to create an Apache configuration file for your application. In this example we are telling `mod_wsgi` to execute the application under a different user for security reasons: .. sourcecode:: apache ServerName example.com WSGIDaemonProcess yourapplication user=user1 group=group1 threads=5 WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi WSGIProcessGroup yourapplication WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all Note: WSGIDaemonProcess isn't implemented in Windows and Apache will refuse to run with the above configuration. On a Windows system, eliminate those lines: .. sourcecode:: apache ServerName example.com WSGIScriptAlias / C:\yourdir\yourapp.wsgi Order deny,allow Allow from all Note: There have been some changes in access control configuration for `Apache 2.4`_. .. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html Most notably, the syntax for directory permissions has changed from httpd 2.2 .. sourcecode:: apache Order allow,deny Allow from all to httpd 2.4 syntax .. sourcecode:: apache Require all granted For more information consult the `mod_wsgi documentation`_. .. _mod_wsgi: https://github.com/GrahamDumpleton/mod_wsgi .. _installation instructions: https://modwsgi.readthedocs.io/en/develop/installation.html .. _virtual python: https://pypi.org/project/virtualenv/ .. _mod_wsgi documentation: https://modwsgi.readthedocs.io/en/develop/index.html Troubleshooting --------------- If your application does not run, follow this guide to troubleshoot: **Problem:** application does not run, errorlog shows SystemExit ignored You have an ``app.run()`` call in your application file that is not guarded by an ``if __name__ == '__main__':`` condition. Either remove that :meth:`~flask.Flask.run` call from the file and move it into a separate :file:`run.py` file or put it into such an if block. **Problem:** application gives permission errors Probably caused by your application running as the wrong user. Make sure the folders the application needs access to have the proper privileges set and the application runs as the correct user (``user`` and ``group`` parameter to the `WSGIDaemonProcess` directive) **Problem:** application dies with an error on print Keep in mind that mod_wsgi disallows doing anything with :data:`sys.stdout` and :data:`sys.stderr`. You can disable this protection from the config by setting the `WSGIRestrictStdout` to ``off``: .. sourcecode:: apache WSGIRestrictStdout Off Alternatively you can also replace the standard out in the .wsgi file with a different stream:: import sys sys.stdout = sys.stderr **Problem:** accessing resources gives IO errors Your application probably is a single .py file you symlinked into the site-packages folder. Please be aware that this does not work, instead you either have to put the folder into the pythonpath the file is stored in, or convert your application into a package. The reason for this is that for non-installed packages, the module filename is used to locate the resources and for symlinks the wrong filename is picked up. Support for Automatic Reloading ------------------------------- To help deployment tools you can activate support for automatic reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will reload all the daemon processes for us. For that, just add the following directive to your `Directory` section: .. sourcecode:: apache WSGIScriptReloading On Working with Virtual Environments --------------------------------- Virtual environments have the advantage that they never install the required dependencies system wide so you have a better control over what is used where. If you want to use a virtual environment with mod_wsgi you have to modify your ``.wsgi`` file slightly. Add the following lines to the top of your ``.wsgi`` file:: activate_this = '/path/to/env/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) For Python 3 add the following lines to the top of your ``.wsgi`` file:: activate_this = '/path/to/env/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) This sets up the load paths according to the settings of the virtual environment. Keep in mind that the path has to be absolute. Flask-1.1.1/docs/deploying/uwsgi.rst0000644000175000017500000000546313510701642017573 0ustar daviddavid00000000000000.. _deploying-uwsgi: uWSGI ===== uWSGI is a deployment option on servers like `nginx`_, `lighttpd`_, and `cherokee`_; see :doc:`fastcgi` and :doc:`wsgi-standalone` for other options. To use your WSGI application with uWSGI protocol you will need a uWSGI server first. uWSGI is both a protocol and an application server; the application server can serve uWSGI, FastCGI, and HTTP protocols. The most popular uWSGI server is `uwsgi`_, which we will use for this guide. Make sure to have it installed to follow along. .. admonition:: Watch Out Please make sure in advance that any ``app.run()`` calls you might have in your application file are inside an ``if __name__ == '__main__':`` block or moved to a separate file. Just make sure it's not called because this will always start a local WSGI server which we do not want if we deploy that application to uWSGI. Starting your app with uwsgi ---------------------------- `uwsgi` is designed to operate on WSGI callables found in python modules. Given a flask application in myapp.py, use the following command: .. sourcecode:: text $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` to uwsgi, since it is smarter about that. It is used together with the ``--mount`` directive which will make requests to ``/yourapplication`` be directed to ``myapp:app``. If your application is accessible at root level, you can use a single ``/`` instead of ``/yourapplication``. ``myapp`` refers to the name of the file of your flask application (without extension) or the module which provides ``app``. ``app`` is the callable inside of your application (usually the line reads ``app = Flask(__name__)``. If you want to deploy your flask application inside of a virtual environment, you need to also add ``--virtualenv /path/to/virtual/environment``. You might also need to add ``--plugin python`` or ``--plugin python3`` depending on which python version you use for your project. Configuring nginx ----------------- A basic flask nginx configuration looks like this:: location = /yourapplication { rewrite ^ /yourapplication/; } location /yourapplication { try_files $uri @yourapplication; } location @yourapplication { include uwsgi_params; uwsgi_pass unix:/tmp/yourapplication.sock; } This configuration binds the application to ``/yourapplication``. If you want to have it in the URL root its a bit simpler:: location / { try_files $uri @yourapplication; } location @yourapplication { include uwsgi_params; uwsgi_pass unix:/tmp/yourapplication.sock; } .. _nginx: https://nginx.org/ .. _lighttpd: https://www.lighttpd.net/ .. _cherokee: http://cherokee-project.com/ .. _uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/ Flask-1.1.1/docs/deploying/wsgi-standalone.rst0000644000175000017500000001212113510701642021521 0ustar daviddavid00000000000000.. _deploying-wsgi-standalone: Standalone WSGI Containers ========================== There are popular servers written in Python that contain WSGI applications and serve HTTP. These servers stand alone when they run; you can proxy to them from your web server. Note the section on :ref:`deploying-proxy-setups` if you run into issues. Gunicorn -------- `Gunicorn`_ 'Green Unicorn' is a WSGI HTTP Server for UNIX. It's a pre-fork worker model ported from Ruby's Unicorn project. It supports both `eventlet`_ and `greenlet`_. Running a Flask application on this server is quite simple:: $ gunicorn myproject:app `Gunicorn`_ provides many command-line options -- see ``gunicorn -h``. For example, to run a Flask application with 4 worker processes (``-w 4``) binding to localhost port 4000 (``-b 127.0.0.1:4000``):: $ gunicorn -w 4 -b 127.0.0.1:4000 myproject:app The ``gunicorn`` command expects the names of your application module or package and the application instance within the module. If you use the application factory pattern, you can pass a call to that:: $ gunicorn "myproject:create_app()" .. _Gunicorn: https://gunicorn.org/ .. _eventlet: https://eventlet.net/ uWSGI -------- `uWSGI`_ is a fast application server written in C. It is very configurable which makes it more complicated to setup than gunicorn. Running `uWSGI HTTP Router`_:: $ uwsgi --http 127.0.0.1:5000 --module myproject:app For a more optimized setup, see :doc:`configuring uWSGI and NGINX `. .. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/ .. _uWSGI HTTP Router: https://uwsgi-docs.readthedocs.io/en/latest/HTTP.html#the-uwsgi-http-https-router Gevent ------- `Gevent`_ is a coroutine-based Python networking library that uses `greenlet`_ to provide a high-level synchronous API on top of `libev`_ event loop:: from gevent.pywsgi import WSGIServer from yourapplication import app http_server = WSGIServer(('', 5000), app) http_server.serve_forever() .. _Gevent: http://www.gevent.org/ .. _greenlet: https://greenlet.readthedocs.io/en/latest/ .. _libev: http://software.schmorp.de/pkg/libev.html Twisted Web ----------- `Twisted Web`_ is the web server shipped with `Twisted`_, a mature, non-blocking event-driven networking library. Twisted Web comes with a standard WSGI container which can be controlled from the command line using the ``twistd`` utility:: $ twistd web --wsgi myproject.app This example will run a Flask application called ``app`` from a module named ``myproject``. Twisted Web supports many flags and options, and the ``twistd`` utility does as well; see ``twistd -h`` and ``twistd web -h`` for more information. For example, to run a Twisted Web server in the foreground, on port 8080, with an application from ``myproject``:: $ twistd -n web --port tcp:8080 --wsgi myproject.app .. _Twisted: https://twistedmatrix.com/trac/ .. _Twisted Web: https://twistedmatrix.com/trac/wiki/TwistedWeb .. _deploying-proxy-setups: Proxy Setups ------------ If you deploy your application using one of these servers behind an HTTP proxy you will need to rewrite a few headers in order for the application to work. The two problematic values in the WSGI environment usually are ``REMOTE_ADDR`` and ``HTTP_HOST``. You can configure your httpd to pass these headers, or you can fix them in middleware. Werkzeug ships a fixer that will solve some common setups, but you might want to write your own WSGI middleware for specific setups. Here's a simple nginx configuration which proxies to an application served on localhost at port 8000, setting appropriate headers: .. sourcecode:: nginx server { listen 80; server_name _; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { proxy_pass http://127.0.0.1:8000/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } If your httpd is not providing these headers, the most common setup invokes the host being set from ``X-Forwarded-Host`` and the remote address from ``X-Forwarded-For``:: from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1) .. admonition:: Trusting Headers Please keep in mind that it is a security issue to use such a middleware in a non-proxy setup because it will blindly trust the incoming headers which might be forged by malicious clients. If you want to rewrite the headers from another header, you might want to use a fixer like this:: class CustomProxyFix(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): host = environ.get('HTTP_X_FHOST', '') if host: environ['HTTP_HOST'] = host return self.app(environ, start_response) app.wsgi_app = CustomProxyFix(app.wsgi_app) Flask-1.1.1/docs/design.rst0000644000175000017500000002142613510701642015711 0ustar daviddavid00000000000000.. _design: Design Decisions in Flask ========================= If you are curious why Flask does certain things the way it does and not differently, this section is for you. This should give you an idea about some of the design decisions that may appear arbitrary and surprising at first, especially in direct comparison with other frameworks. The Explicit Application Object ------------------------------- A Python web application based on WSGI has to have one central callable object that implements the actual application. In Flask this is an instance of the :class:`~flask.Flask` class. Each Flask application has to create an instance of this class itself and pass it the name of the module, but why can't Flask do that itself? Without such an explicit application object the following code:: from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello World!' Would look like this instead:: from hypothetical_flask import route @route('/') def index(): return 'Hello World!' There are three major reasons for this. The most important one is that implicit application objects require that there may only be one instance at the time. There are ways to fake multiple applications with a single application object, like maintaining a stack of applications, but this causes some problems I won't outline here in detail. Now the question is: when does a microframework need more than one application at the same time? A good example for this is unit testing. When you want to test something it can be very helpful to create a minimal application to test specific behavior. When the application object is deleted everything it allocated will be freed again. Another thing that becomes possible when you have an explicit object lying around in your code is that you can subclass the base class (:class:`~flask.Flask`) to alter specific behavior. This would not be possible without hacks if the object were created ahead of time for you based on a class that is not exposed to you. But there is another very important reason why Flask depends on an explicit instantiation of that class: the package name. Whenever you create a Flask instance you usually pass it `__name__` as package name. Flask depends on that information to properly load resources relative to your module. With Python's outstanding support for reflection it can then access the package to figure out where the templates and static files are stored (see :meth:`~flask.Flask.open_resource`). Now obviously there are frameworks around that do not need any configuration and will still be able to load templates relative to your application module. But they have to use the current working directory for that, which is a very unreliable way to determine where the application is. The current working directory is process-wide and if you are running multiple applications in one process (which could happen in a webserver without you knowing) the paths will be off. Worse: many webservers do not set the working directory to the directory of your application but to the document root which does not have to be the same folder. The third reason is "explicit is better than implicit". That object is your WSGI application, you don't have to remember anything else. If you want to apply a WSGI middleware, just wrap it and you're done (though there are better ways to do that so that you do not lose the reference to the application object :meth:`~flask.Flask.wsgi_app`). Furthermore this design makes it possible to use a factory function to create the application which is very helpful for unit testing and similar things (:ref:`app-factories`). The Routing System ------------------ Flask uses the Werkzeug routing system which was designed to automatically order routes by complexity. This means that you can declare routes in arbitrary order and they will still work as expected. This is a requirement if you want to properly implement decorator based routing since decorators could be fired in undefined order when the application is split into multiple modules. Another design decision with the Werkzeug routing system is that routes in Werkzeug try to ensure that URLs are unique. Werkzeug will go quite far with that in that it will automatically redirect to a canonical URL if a route is ambiguous. One Template Engine ------------------- Flask decides on one template engine: Jinja2. Why doesn't Flask have a pluggable template engine interface? You can obviously use a different template engine, but Flask will still configure Jinja2 for you. While that limitation that Jinja2 is *always* configured will probably go away, the decision to bundle one template engine and use that will not. Template engines are like programming languages and each of those engines has a certain understanding about how things work. On the surface they all work the same: you tell the engine to evaluate a template with a set of variables and take the return value as string. But that's about where similarities end. Jinja2 for example has an extensive filter system, a certain way to do template inheritance, support for reusable blocks (macros) that can be used from inside templates and also from Python code, uses Unicode for all operations, supports iterative template rendering, configurable syntax and more. On the other hand an engine like Genshi is based on XML stream evaluation, template inheritance by taking the availability of XPath into account and more. Mako on the other hand treats templates similar to Python modules. When it comes to connecting a template engine with an application or framework there is more than just rendering templates. For instance, Flask uses Jinja2's extensive autoescaping support. Also it provides ways to access macros from Jinja2 templates. A template abstraction layer that would not take the unique features of the template engines away is a science on its own and a too large undertaking for a microframework like Flask. Furthermore extensions can then easily depend on one template language being present. You can easily use your own templating language, but an extension could still depend on Jinja itself. Micro with Dependencies ----------------------- Why does Flask call itself a microframework and yet it depends on two libraries (namely Werkzeug and Jinja2). Why shouldn't it? If we look over to the Ruby side of web development there we have a protocol very similar to WSGI. Just that it's called Rack there, but besides that it looks very much like a WSGI rendition for Ruby. But nearly all applications in Ruby land do not work with Rack directly, but on top of a library with the same name. This Rack library has two equivalents in Python: WebOb (formerly Paste) and Werkzeug. Paste is still around but from my understanding it's sort of deprecated in favour of WebOb. The development of WebOb and Werkzeug started side by side with similar ideas in mind: be a good implementation of WSGI for other applications to take advantage. Flask is a framework that takes advantage of the work already done by Werkzeug to properly interface WSGI (which can be a complex task at times). Thanks to recent developments in the Python package infrastructure, packages with dependencies are no longer an issue and there are very few reasons against having libraries that depend on others. Thread Locals ------------- Flask uses thread local objects (context local objects in fact, they support greenlet contexts as well) for request, session and an extra object you can put your own things on (:data:`~flask.g`). Why is that and isn't that a bad idea? Yes it is usually not such a bright idea to use thread locals. They cause troubles for servers that are not based on the concept of threads and make large applications harder to maintain. However Flask is just not designed for large applications or asynchronous servers. Flask wants to make it quick and easy to write a traditional web application. Also see the :ref:`becomingbig` section of the documentation for some inspiration for larger applications based on Flask. What Flask is, What Flask is Not -------------------------------- Flask will never have a database layer. It will not have a form library or anything else in that direction. Flask itself just bridges to Werkzeug to implement a proper WSGI application and to Jinja2 to handle templating. It also binds to a few common standard library packages such as logging. Everything else is up for extensions. Why is this the case? Because people have different preferences and requirements and Flask could not meet those if it would force any of this into the core. The majority of web applications will need a template engine in some sort. However not every application needs a SQL database. The idea of Flask is to build a good foundation for all applications. Everything else is up to you or extensions. Flask-1.1.1/docs/errorhandling.rst0000644000175000017500000002613413510701642017277 0ustar daviddavid00000000000000.. _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 `sentry-sdk` client with extra `flask` dependencies:: $ pip install sentry-sdk[flask] And then add this to your Flask app:: import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()]) The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get from your Sentry installation. After installation, failures leading to an Internal Server Error are automatically reported to Sentry and from there you can receive error notifications. Follow-up reads: * Sentry also supports catching errors from your worker queue (RQ, Celery) in a similar fashion. See the `Python SDK docs `_ for more information. * `Getting started with Sentry `_ * `Flask-specific documentation `_. .. _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. An error handler is a normal view function that returns a response, but instead of being registered for a route, it is registered for an exception or HTTP status code that would be raised while trying to handle a request. Registering ``````````` Register handlers by decorating a function with :meth:`~flask.Flask.errorhandler`. Or use :meth:`~flask.Flask.register_error_handler` to register the function later. Remember to set the error code when returning the response. :: @app.errorhandler(werkzeug.exceptions.BadRequest) def handle_bad_request(e): return 'bad request!', 400 # or, without the decorator app.register_error_handler(400, handle_bad_request) :exc:`werkzeug.exceptions.HTTPException` subclasses like :exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable when registering handlers. (``BadRequest.code == 400``) Non-standard HTTP codes cannot be registered by code because they are not known by Werkzeug. Instead, define a subclass of :class:`~werkzeug.exceptions.HTTPException` with the appropriate code and register and raise that exception class. :: class InsufficientStorage(werkzeug.exceptions.HTTPException): code = 507 description = 'Not enough storage space.' app.register_error_handler(InsufficientStorage, handle_507) raise InsufficientStorage() Handlers can be registered for any exception class, not just :exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status codes. Handlers can be registered for a specific class, or for all subclasses of a parent class. Handling ```````` When an exception is caught by Flask while handling a request, it is first looked up by code. If no handler is registered for the code, it is looked up by its class hierarchy; the most specific handler is chosen. If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a generic message about their code, while other exceptions are converted to a generic 500 Internal Server Error. For example, 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 with the exception instance to generate the response. Handlers registered on the blueprint take precedence over those registered globally on the application, assuming a blueprint is handling the request that raises the exception. However, the blueprint cannot handle 404 routing errors because the 404 occurs at the routing level before the blueprint can be determined. Generic Exception Handlers `````````````````````````` It is possible to register error handlers for very generic base classes such as ``HTTPException`` or even ``Exception``. However, be aware that these will catch more than you might expect. An error handler for ``HTTPException`` might be useful for turning the default HTML errors pages into JSON, for example. However, this handler will trigger for things you don't cause directly, such as 404 and 405 errors during routing. Be sure to craft your handler carefully so you don't lose information about the HTTP error. .. code-block:: python from flask import json from werkzeug.exceptions import HTTPException @app.errorhandler(HTTPException) def handle_exception(e): """Return JSON instead of HTML for HTTP errors.""" # start with the correct headers and status code from the error response = e.get_response() # replace the body with JSON response.data = json.dumps({ "code": e.code, "name": e.name, "description": e.description, }) response.content_type = "application/json" return response An error handler for ``Exception`` might seem useful for changing how all errors, even unhandled ones, are presented to the user. However, this is similar to doing ``except Exception:`` in Python, it will capture *all* otherwise unhandled errors, including all HTTP status codes. In most cases it will be safer to register handlers for more specific exceptions. Since ``HTTPException`` instances are valid WSGI responses, you could also pass them through directly. .. code-block:: python from werkzeug.exceptions import HTTPException @app.errorhandler(Exception) def handle_exception(e): # pass through HTTP errors if isinstance(e, HTTPException): return e # now you're handling non-HTTP exceptions only return render_template("500_generic.html", e=e), 500 Error handlers still respect the exception class hierarchy. If you register handlers for both ``HTTPException`` and ``Exception``, the ``Exception`` handler will not handle ``HTTPException`` subclasses because it the ``HTTPException`` handler is more specific. Unhandled Exceptions ```````````````````` When there is no error handler registered for an exception, a 500 Internal Server Error will be returned instead. See :meth:`flask.Flask.handle_exception` for information about this behavior. If there is an error handler registered for ``InternalServerError``, this will be invoked. As of Flask 1.1.0, this error handler will always be passed an instance of ``InternalServerError``, not the original unhandled error. The original error is available as ``e.original_error``. Until Werkzeug 1.0.0, this attribute will only exist during unhandled errors, use ``getattr`` to get access it for compatibility. .. code-block:: python @app.errorhandler(InternalServerError) def handle_500(e): original = getattr(e, "original_exception", None) if original is None: # direct 500 error, such as abort(500) return render_template("500.html"), 500 # wrapped unhandled error return render_template("500_unhandled.html", e=original), 500 Logging ------- See :doc:`/logging` for information on how to log exceptions, such as by emailing them to admins. 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 if modules were changed ``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") use_debugger = app.debug and not(app.config.get('DEBUG_WITH_APTANA')) app.run(use_debugger=use_debugger, debug=app.debug, use_reloader=use_debugger, host='0.0.0.0') Flask-1.1.1/docs/extensiondev.rst0000644000175000017500000003216113510701642017151 0ustar daviddavid00000000000000.. _extension-dev: Flask Extension Development =========================== Flask, being a microframework, often requires some repetitive steps to get a third party library working. Many such extensions are already available on `PyPI `_. 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. 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 in order to be listed 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. When designing your classes, it's important to make them easily reusable at the module level. This means the object itself must not under any circumstances store any application specific state and must be shareable between different applications. The Extension Code ------------------ Here's the contents of the `flask_sqlite3.py` for copy/paste:: import sqlite3 from flask import current_app, _app_ctx_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:') app.teardown_appcontext(self.teardown) def connect(self): return sqlite3.connect(current_app.config['SQLITE3_DATABASE']) def teardown(self, exception): ctx = _app_ctx_stack.top if hasattr(ctx, 'sqlite3_db'): ctx.sqlite3_db.close() @property def connection(self): ctx = _app_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. 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. 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 you can use the database by pushing an app context:: 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. 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 generates useful feedback on what people might want from an extension, but also avoids having multiple developers working in isolation on pretty much the same problem. Remember: good API design is hard, so introduce your project on the mailing list, 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 documentation must use the ``flask`` theme from the `Official Pallets Themes`_. 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 3.4 and newer and 2.7. .. _OAuth extension: https://pythonhosted.org/Flask-OAuth/ .. _mailinglist: http://flask.pocoo.org/mailinglist/ .. _IRC channel: http://flask.pocoo.org/community/irc/ .. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/ Flask-1.1.1/docs/extensions.rst0000644000175000017500000000276513510701642016644 0ustar daviddavid00000000000000.. _extensions: Extensions ========== Extensions are extra packages that add functionality to a Flask application. For example, an extension might add support for sending email or connecting to a database. Some extensions add entire new frameworks to help build certain types of applications, like a REST API. Finding Extensions ------------------ Flask extensions are usually named "Flask-Foo" or "Foo-Flask". Many extensions are listed in the `Extension Registry`_, which can be updated by extension developers. You can also search PyPI for packages tagged with `Framework :: Flask `_. Using Extensions ---------------- Consult each extension's documentation for installation, configuration, and usage instructions. Generally, extensions pull their own configuration from :attr:`app.config ` and are passed an application instance during initialization. For example, an extension called "Flask-Foo" might be used like this:: from flask_foo import Foo foo = Foo() app = Flask(__name__) app.config.update( FOO_BAR='baz', FOO_SPAM='eggs', ) foo.init_app(app) Building Extensions ------------------- While the `Extension Registry`_ contains many Flask extensions, you may not find an extension that fits your need. If this is the case, you can create your own. Read :ref:`extension-dev` to develop your own Flask extension. .. _Extension Registry: http://flask.pocoo.org/extensions/ .. _pypi: https://pypi.org/search/?c=Framework+%3A%3A+Flask Flask-1.1.1/docs/foreword.rst0000644000175000017500000000536713510701642016275 0ustar daviddavid00000000000000Foreword ======== 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-1.1.1/docs/htmlfaq.rst0000644000175000017500000002271713510701642016100 0ustar daviddavid00000000000000HTML/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 where 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

+ = ?

{% block content %}{% endblock %}
In this example, the ``{% block %}`` tags define four blocks that child templates can fill in. All the `block` tag does is tell the template engine that a child template may override those portions of the template. Child Template -------------- A child template might look like this: .. sourcecode:: html+jinja {% extends "layout.html" %} {% block title %}Index{% endblock %} {% block head %} {{ super() }} {% endblock %} {% block content %}

Index

Welcome on my awesome homepage. {% endblock %} The ``{% extends %}`` tag is the key here. It tells the template engine that this template "extends" another template. When the template system evaluates this template, first it locates the parent. The extends tag must be the first tag in the template. To render the contents of a block defined in the parent template, use ``{{ super() }}``. Flask-1.1.1/docs/patterns/urlprocessors.rst0000644000175000017500000001034113510701642021217 0ustar daviddavid00000000000000Using URL Processors ==================== .. versionadded:: 0.7 Flask 0.7 introduces the concept of URL processors. The idea is that you might have a bunch of resources with common parts in the URL that you don't always explicitly want to provide. For instance you might have a bunch of URLs that have the language code in it but you don't want to have to handle it in every single function yourself. URL processors are especially helpful when combined with blueprints. We will handle both application specific URL processors here as well as blueprint specifics. Internationalized Application URLs ---------------------------------- Consider an application like this:: from flask import Flask, g app = Flask(__name__) @app.route('//') def index(lang_code): g.lang_code = lang_code ... @app.route('//about') def about(lang_code): g.lang_code = lang_code ... This is an awful lot of repetition as you have to handle the language code setting on the :data:`~flask.g` object yourself in every single function. Sure, a decorator could be used to simplify this, but if you want to generate URLs from one function to another you would have to still provide the language code explicitly which can be annoying. For the latter, this is where :func:`~flask.Flask.url_defaults` functions come in. They can automatically inject values into a call for :func:`~flask.url_for` automatically. The code below checks if the language code is not yet in the dictionary of URL values and if the endpoint wants a value named ``'lang_code'``:: @app.url_defaults def add_language_code(endpoint, values): if 'lang_code' in values or not g.lang_code: return if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): values['lang_code'] = g.lang_code The method :meth:`~werkzeug.routing.Map.is_endpoint_expecting` of the URL map can be used to figure out if it would make sense to provide a language code for the given endpoint. The reverse of that function are :meth:`~flask.Flask.url_value_preprocessor`\s. They are executed right after the request was matched and can execute code based on the URL values. The idea is that they pull information out of the values dictionary and put it somewhere else:: @app.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code = values.pop('lang_code', None) That way you no longer have to do the `lang_code` assignment to :data:`~flask.g` in every function. You can further improve that by writing your own decorator that prefixes URLs with the language code, but the more beautiful solution is using a blueprint. Once the ``'lang_code'`` is popped from the values dictionary and it will no longer be forwarded to the view function reducing the code to this:: from flask import Flask, g app = Flask(__name__) @app.url_defaults def add_language_code(endpoint, values): if 'lang_code' in values or not g.lang_code: return if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): values['lang_code'] = g.lang_code @app.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code = values.pop('lang_code', None) @app.route('//') def index(): ... @app.route('//about') def about(): ... Internationalized Blueprint URLs -------------------------------- Because blueprints can automatically prefix all URLs with a common string it's easy to automatically do that for every function. Furthermore blueprints can have per-blueprint URL processors which removes a whole lot of logic from the :meth:`~flask.Flask.url_defaults` function because it no longer has to check if the URL is really interested in a ``'lang_code'`` parameter:: from flask import Blueprint, g bp = Blueprint('frontend', __name__, url_prefix='/') @bp.url_defaults def add_language_code(endpoint, values): values.setdefault('lang_code', g.lang_code) @bp.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code = values.pop('lang_code') @bp.route('/') def index(): ... @bp.route('/about') def about(): ... Flask-1.1.1/docs/patterns/viewdecorators.rst0000644000175000017500000001434513510701642021342 0ustar daviddavid00000000000000View 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-1.1.1/docs/patterns/wtforms.rst0000644000175000017500000001121213510701642017771 0ustar daviddavid00000000000000Form Validation with WTForms ============================ When you have to work with form data submitted by a browser view, code quickly becomes very hard to read. There are libraries out there designed to make this process easier to manage. One of them is `WTForms`_ which we will handle here. If you find yourself in the situation of having many forms, you might want to give it a try. When you are working with WTForms you have to define your forms as classes first. I recommend breaking up the application into multiple modules (:ref:`larger-applications`) for that and adding a separate module for the forms. .. admonition:: Getting the most out of WTForms with an Extension The `Flask-WTF`_ extension expands on this pattern and adds a few little helpers that make working with forms and Flask more fun. You can get it from `PyPI `_. .. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/ The Forms --------- This is an example form for a typical registration page:: from wtforms import Form, BooleanField, StringField, PasswordField, validators class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password') accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()]) In the View ----------- In the view function, the usage of this form looks like this:: @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): user = User(form.username.data, form.email.data, form.password.data) db_session.add(user) flash('Thanks for registering') return redirect(url_for('login')) return render_template('register.html', form=form) Notice we're implying that the view is using SQLAlchemy here (:ref:`sqlalchemy-pattern`), but that's not a requirement, of course. Adapt the code as necessary. Things to remember: 1. create the form from the request :attr:`~flask.request.form` value if the data is submitted via the HTTP ``POST`` method and :attr:`~flask.request.args` if the data is submitted as ``GET``. 2. to validate the data, call the :func:`~wtforms.form.Form.validate` method, which will return ``True`` if the data validates, ``False`` otherwise. 3. to access individual values from the form, access `form..data`. Forms in Templates ------------------ Now to the template side. When you pass the form to the templates, you can easily render them there. Look at the following example template to see how easy this is. WTForms does half the form generation for us already. To make it even nicer, we can write a macro that renders a field with label and a list of errors if there are any. Here's an example :file:`_formhelpers.html` template with such a macro: .. sourcecode:: html+jinja {% macro render_field(field) %}

{{ field.label }}
{{ field(**kwargs)|safe }} {% if field.errors %}
    {% for error in field.errors %}
  • {{ error }}
  • {% endfor %}
{% endif %}
{% endmacro %} This macro accepts a couple of keyword arguments that are forwarded to WTForm's field function, which renders the field for us. The keyword arguments will be inserted as HTML attributes. So, for example, you can call ``render_field(form.username, class='username')`` to add a class to the input element. Note that WTForms returns standard Python unicode strings, so we have to tell Jinja2 that this data is already HTML-escaped with the ``|safe`` filter. Here is the :file:`register.html` template for the function we used above, which takes advantage of the :file:`_formhelpers.html` template: .. sourcecode:: html+jinja {% from "_formhelpers.html" import render_field %}
{{ render_field(form.username) }} {{ render_field(form.email) }} {{ render_field(form.password) }} {{ render_field(form.confirm) }} {{ render_field(form.accept_tos) }}

For more information about WTForms, head over to the `WTForms website`_. .. _WTForms: https://wtforms.readthedocs.io/ .. _WTForms website: https://wtforms.readthedocs.io/ Flask-1.1.1/docs/quickstart.rst0000644000175000017500000007660013510701642016636 0ustar daviddavid00000000000000.. _quickstart: Quickstart ========== Eager to get started? This page gives a good introduction to Flask. It assumes you already have Flask installed. If you do not, head over to the :ref:`installation` section. A Minimal Application --------------------- A minimal Flask application looks something like this:: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' So what did that code do? 1. First we imported the :class:`~flask.Flask` class. An instance of this class will be our WSGI application. 2. Next we create an instance of this class. The first argument is the name of the application's module or package. If you are using a single module (as in this example), you should use ``__name__`` because depending on if it's started as application or imported as module the name will be different (``'__main__'`` versus the actual import name). This is needed so that Flask knows where to look for templates, static files, and so on. For more information have a look at the :class:`~flask.Flask` documentation. 3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL should trigger our function. 4. The function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user's browser. Just save it as :file:`hello.py` or something similar. Make sure to not call your application :file:`flask.py` because this would conflict with Flask itself. To run the application you can either use the :command:`flask` command or python's ``-m`` switch with Flask. Before you can do that you need to tell your terminal the application to work with by exporting the ``FLASK_APP`` environment variable:: $ export FLASK_APP=hello.py $ flask run * Running on http://127.0.0.1:5000/ If you are on Windows, the environment variable syntax depends on command line interpreter. On Command Prompt:: C:\path\to\app>set FLASK_APP=hello.py And on PowerShell:: PS C:\path\to\app> $env:FLASK_APP = "hello.py" Alternatively you can use :command:`python -m flask`:: $ export FLASK_APP=hello.py $ python -m flask run * Running on http://127.0.0.1:5000/ This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see :ref:`deployment`. Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting. .. _public-server: .. admonition:: Externally Visible Server If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding ``--host=0.0.0.0`` to the command line:: $ flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs. What to do if the Server does not Start --------------------------------------- In case the :command:`python -m flask` fails or :command:`flask` does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message. Old Version of Flask ```````````````````` Versions of Flask older than 0.11 use to have different ways to start the application. In short, the :command:`flask` command did not exist, and neither did :command:`python -m flask`. In that case you have two options: either upgrade to newer Flask versions or have a look at the :ref:`server` docs to see the alternative method for running a server. Invalid Import Name ``````````````````` The ``FLASK_APP`` environment variable is the name of the module to import at :command:`flask run`. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application). It will tell you what it tried to import and why it failed. The most common reason is a typo or because you did not actually create an ``app`` object. .. _debug-mode: Debug Mode ---------- (Want to just log errors and stack traces? See :ref:`application-errors`) The :command:`flask` script is nice to start a local development server, but you would have to restart it manually after each change to your code. That is not very nice and Flask can do better. If you enable debug support the server will reload itself on code changes, and it will also provide you with a helpful debugger if things go wrong. To enable all development features (including debug mode) you can export the ``FLASK_ENV`` environment variable and set it to ``development`` before running the server:: $ export FLASK_ENV=development $ flask run (On Windows you need to use ``set`` instead of ``export``.) This does the following things: 1. it activates the debugger 2. it activates the automatic reloader 3. it enables the debug mode on the Flask application. You can also control debug mode separately from the environment by exporting ``FLASK_DEBUG=1``. There are more parameters that are explained in the :ref:`server` docs. .. admonition:: Attention Even though the interactive debugger does not work in forking environments (which makes it nearly impossible to use on production servers), it still allows the execution of arbitrary code. This makes it a major security risk and therefore it **must never be used on production machines**. Screenshot of the debugger in action: .. image:: _static/debugger.png :align: center :class: screenshot :alt: screenshot of debugger in action More information on using the debugger can be found in the `Werkzeug documentation`_. .. _Werkzeug documentation: https://werkzeug.palletsprojects.com/debug/#using-the-debugger Have another debugger in mind? See :ref:`working-with-debuggers`. Routing ------- Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page. Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. :: @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello, World' You can do more! You can make parts of the URL dynamic and attach multiple rules to a function. Variable Rules `````````````` You can add variable sections to a URL by marking sections with ````. Your function then receives the ```` as a keyword argument. Optionally, you can use a converter to specify the type of the argument like ````. :: @app.route('/user/') def show_user_profile(username): # show the user profile for that user return 'User %s' % escape(username) @app.route('/post/') def show_post(post_id): # show the post with the given id, the id is an integer return 'Post %d' % post_id @app.route('/path/') def show_subpath(subpath): # show the subpath after /path/ return 'Subpath %s' % escape(subpath) Converter types: ========== ========================================== ``string`` (default) accepts any text without a slash ``int`` accepts positive integers ``float`` accepts positive floating point values ``path`` like ``string`` but also accepts slashes ``uuid`` accepts UUID strings ========== ========================================== Unique URLs / Redirection Behavior `````````````````````````````````` The following two rules differ in their use of a trailing slash. :: @app.route('/projects/') def projects(): return 'The project page' @app.route('/about') def about(): return 'The about page' The canonical URL for the ``projects`` endpoint has a trailing slash. It's similar to a folder in a file system. If you access the URL without a trailing slash, Flask redirects you to the canonical URL with the trailing slash. The canonical URL for the ``about`` endpoint does not have a trailing slash. It's similar to the pathname of a file. Accessing the URL with a trailing slash produces a 404 "Not Found" error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice. .. _url-building: URL Building ```````````` To build a URL to a specific function, use the :func:`~flask.url_for` function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters. Why would you want to build URLs using the URL reversing function :func:`~flask.url_for` instead of hard-coding them into your templates? 1. Reversing is often more descriptive than hard-coding the URLs. 2. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs. 3. URL building handles escaping of special characters and Unicode data transparently. 4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers. 5. If your application is placed outside the URL root, for example, in ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly handles that for you. For example, here we use the :meth:`~flask.Flask.test_request_context` method to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context` tells Flask to behave as though it's handling a request even while we use a Python shell. See :ref:`context-locals`. .. code-block:: python from flask import Flask, escape, url_for app = Flask(__name__) @app.route('/') def index(): return 'index' @app.route('/login') def login(): return 'login' @app.route('/user/') def profile(username): return '{}\'s profile'.format(escape(username)) with app.test_request_context(): print(url_for('index')) print(url_for('login')) print(url_for('login', next='/')) print(url_for('profile', username='John Doe')) .. code-block:: text / /login /login?next=/ /user/John%20Doe HTTP Methods ```````````` Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to ``GET`` requests. You can use the ``methods`` argument of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods. :: from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() else: return show_the_login_form() If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method and handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise, ``OPTIONS`` is automatically implemented for you. .. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt Static Files ------------ Dynamic web applications also need static files. That's usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called :file:`static` in your package or next to your module and it will be available at ``/static`` on the application. To generate URLs for static files, use the special ``'static'`` endpoint name:: url_for('static', filename='style.css') The file has to be stored on the filesystem as :file:`static/style.css`. Rendering Templates ------------------- Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the `Jinja2 `_ template engine for you automatically. To render a template you can use the :func:`~flask.render_template` method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here's a simple example of how to render a template:: from flask import render_template @app.route('/hello/') @app.route('/hello/') def hello(name=None): return render_template('hello.html', name=name) Flask will look for templates in the :file:`templates` folder. So if your application is a module, this folder is next to that module, if it's a package it's actually inside your package: **Case 1**: a module:: /application.py /templates /hello.html **Case 2**: a package:: /application /__init__.py /templates /hello.html For templates you can use the full power of Jinja2 templates. Head over to the official `Jinja2 Template Documentation `_ for more information. Here is an example template: .. sourcecode:: html+jinja Hello from Flask {% if name %}

Hello {{ name }}!

{% else %}

Hello, World!

{% endif %} Inside templates you also have access to the :class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects as well as the :func:`~flask.get_flashed_messages` function. Templates are especially useful if inheritance is used. If you want to know how that works, head over to the :ref:`template-inheritance` pattern documentation. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer). Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the :class:`~jinja2.Markup` class or by using the ``|safe`` filter in the template. Head over to the Jinja 2 documentation for more examples. Here is a basic introduction to how the :class:`~jinja2.Markup` class works:: >>> from flask import Markup >>> Markup('Hello %s!') % 'hacker' Markup(u'Hello <blink>hacker</blink>!') >>> Markup.escape('hacker') Markup(u'<blink>hacker</blink>') >>> Markup('Marked up » HTML').striptags() u'Marked up \xbb HTML' .. versionchanged:: 0.5 Autoescaping is no longer enabled for all templates. The following extensions for templates trigger autoescaping: ``.html``, ``.htm``, ``.xml``, ``.xhtml``. Templates loaded from a string will have autoescaping disabled. .. [#] Unsure what that :class:`~flask.g` object is? It's something in which you can store information for your own needs, check the documentation of that object (:class:`~flask.g`) and the :ref:`sqlite3` for more information. Accessing Request Data ---------------------- For web applications it's crucial to react to the data a client sends to the server. In Flask this information is provided by the global :class:`~flask.request` object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals: .. _context-locals: Context Locals `````````````` .. admonition:: Insider Information If you want to understand how that works and how you can implement tests with context locals, read this section, otherwise just skip it. Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand. Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking. So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use the :meth:`~flask.Flask.test_request_context` context manager. In combination with the ``with`` statement it will bind a test request so that you can interact with it. Here is an example:: from flask import request with app.test_request_context('/hello', method='POST'): # now you can do something with the request until the # end of the with block, such as basic assertions: assert request.path == '/hello' assert request.method == 'POST' The other possibility is passing a whole WSGI environment to the :meth:`~flask.Flask.request_context` method:: from flask import request with app.request_context(environ): assert request.method == 'POST' The Request Object `````````````````` The request object is documented in the API section and we will not cover it here in detail (see :class:`~flask.Request`). Here is a broad overview of some of the most common operations. First of all you have to import it from the ``flask`` module:: from flask import request The current request method is available by using the :attr:`~flask.Request.method` attribute. To access form data (data transmitted in a ``POST`` or ``PUT`` request) you can use the :attr:`~flask.Request.form` attribute. Here is a full example of the two attributes mentioned above:: @app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error) What happens if the key does not exist in the ``form`` attribute? In that case a special :exc:`KeyError` is raised. You can catch it like a standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don't have to deal with that problem. To access parameters submitted in the URL (``?key=value``) you can use the :attr:`~flask.Request.args` attribute:: searchword = request.args.get('key', '') We recommend accessing URL parameters with `get` or by catching the :exc:`KeyError` because users might change the URL and presenting them a 400 bad request page in that case is not user friendly. For a full list of methods and attributes of the request object, head over to the :class:`~flask.Request` documentation. File Uploads ```````````` You can handle uploaded files with Flask easily. Just make sure not to forget to set the ``enctype="multipart/form-data"`` attribute on your HTML form, otherwise the browser will not transmit your files at all. Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the :attr:`~flask.request.files` attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python :class:`file` object, but it also has a :meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works:: from flask import request @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') ... If you want to know how the file was named on the client before it was uploaded to your application, you can access the :attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through the :func:`~werkzeug.utils.secure_filename` function that Werkzeug provides for you:: from flask import request from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/' + secure_filename(f.filename)) ... For some better examples, checkout the :ref:`uploading-files` pattern. Cookies ``````` To access cookies you can use the :attr:`~flask.Request.cookies` attribute. To set cookies you can use the :attr:`~flask.Response.set_cookie` method of response objects. The :attr:`~flask.Request.cookies` attribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use the :ref:`sessions` in Flask that add some security on top of cookies for you. Reading cookies:: from flask import request @app.route('/') def index(): username = request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing. Storing cookies:: from flask import make_response @app.route('/') def index(): resp = make_response(render_template(...)) resp.set_cookie('username', 'the username') return resp Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the :meth:`~flask.make_response` function and then modify it. Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the :ref:`deferred-callbacks` pattern. For this also see :ref:`about-responses`. Redirects and Errors -------------------- To redirect a user to another endpoint, use the :func:`~flask.redirect` function; to abort a request early with an error code, use the :func:`~flask.abort` function:: from flask import abort, redirect, url_for @app.route('/') def index(): return redirect(url_for('login')) @app.route('/login') def login(): abort(401) this_is_never_executed() This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works. By default a black and white error page is shown for each error code. If you want to customize the error page, you can use the :meth:`~flask.Flask.errorhandler` decorator:: from flask import render_template @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404 Note the ``404`` after the :func:`~flask.render_template` call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well. See :ref:`error-handlers` for more details. .. _about-responses: About Responses --------------- The return value from a view function is automatically converted into a response object for you. If the return value is a string it's converted into a response object with the string as response body, a ``200 OK`` status code and a :mimetype:`text/html` mimetype. If the return value is a dict, :func:`jsonify` is called to produce a response. The logic that Flask applies to converting return values into response objects is as follows: 1. If a response object of the correct type is returned it's directly returned from the view. 2. If it's a string, a response object is created with that data and the default parameters. 3. If it's a dict, a response object is created using ``jsonify``. 4. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form ``(response, status)``, ``(response, headers)``, or ``(response, status, headers)``. The ``status`` value will override the status code and ``headers`` can be a list or dictionary of additional header values. 5. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object. If you want to get hold of the resulting response object inside the view you can use the :func:`~flask.make_response` function. Imagine you have a view like this:: @app.errorhandler(404) def not_found(error): return render_template('error.html'), 404 You just need to wrap the return expression with :func:`~flask.make_response` and get the response object to modify it, then return it:: @app.errorhandler(404) def not_found(error): resp = make_response(render_template('error.html'), 404) resp.headers['X-Something'] = 'A value' return resp APIs with JSON `````````````` A common response format when writing an API is JSON. It's easy to get started writing such an API with Flask. If you return a ``dict`` from a view, it will be converted to a JSON response. .. code-block:: python @app.route("/me") def me_api(): user = get_current_user() return { "username": user.username, "theme": user.theme, "image": url_for("user_image", filename=user.image), } Depending on your API design, you may want to create JSON responses for types other than ``dict``. In that case, use the :func:`~flask.json.jsonify` function, which will serialize any supported JSON data type. Or look into Flask community extensions that support more complex applications. .. code-block:: python @app.route("/users") def users_api(): users = get_all_users() return jsonify([user.to_json() for user in users]) .. _sessions: Sessions -------- In addition to the request object there is also a second object called :class:`~flask.session` which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing. In order to use sessions you have to set a secret key. Here is how sessions work:: from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return '''

''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) The :func:`~flask.escape` mentioned here does escaping for you if you are not using the template engine (as in this example). .. admonition:: How to generate good secret keys A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for :attr:`Flask.secret_key` (or :data:`SECRET_KEY`):: $ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/' A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers. Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this. Message Flashing ---------------- Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message. To flash a message use the :func:`~flask.flash` method, to get hold of the messages you can use :func:`~flask.get_flashed_messages` which is also available in the templates. Check out the :ref:`message-flashing-pattern` for a full example. Logging ------- .. versionadded:: 0.3 Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it's obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it's okay to reply with ``400 Bad Request`` in that situation, but sometimes that won't do and the code has to continue working. You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use. Here are some example log calls:: app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred') The attached :attr:`~flask.Flask.logger` is a standard logging :class:`~logging.Logger`, so head over to the official :mod:`logging` docs for more information. Read more on :ref:`application-errors`. Hooking in WSGI Middlewares --------------------------- If you want to add a WSGI middleware to your application you can wrap the internal WSGI application. For example if you want to use one of the middlewares from the Werkzeug package to work around bugs in lighttpd, you can do it like this:: from werkzeug.contrib.fixers import LighttpdCGIRootFix app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app) Using Flask Extensions ---------------------- Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask. For more on Flask extensions, have a look at :ref:`extensions`. Deploying to a Web Server ------------------------- Ready to deploy your new Flask app? Go to :ref:`deployment`. Flask-1.1.1/docs/reqcontext.rst0000644000175000017500000002362413510701642016636 0ustar daviddavid00000000000000.. currentmodule:: flask .. _request-context: The Request Context =================== The request context keeps track of the request-level data during a request. Rather than passing the request object to each function that runs during a request, the :data:`request` and :data:`session` proxies are accessed instead. This is similar to the :doc:`/appcontext`, which keeps track of the application-level data independent of a request. A corresponding application context is pushed when a request context is pushed. Purpose of the Context ---------------------- When the :class:`Flask` application handles a request, it creates a :class:`Request` object based on the environment it received from the WSGI server. Because a *worker* (thread, process, or coroutine depending on the server) handles only one request at a time, the request data can be considered global to that worker during that request. Flask uses the term *context local* for this. Flask automatically *pushes* a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the :data:`request` proxy, which points to the request object for the current request. Lifetime of the Context ----------------------- When a Flask application begins handling a request, it pushes a request context, which also pushes an :doc:`/appcontext`. When the request ends it pops the request context then the application context. The context is unique to each thread (or other worker type). :data:`request` cannot be passed to another thread, the other thread will have a different context stack and will not know about the request the parent thread was pointing to. Context locals are implemented in Werkzeug. See :doc:`werkzeug:local` for more information on how this works internally. Manually Push a Context ----------------------- If you try to access :data:`request`, or anything that uses it, outside a request context, you'll get this error message: .. code-block:: pytb RuntimeError: 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. This should typically only happen when testing code that expects an active request. One option is to use the :meth:`test client ` to simulate a full request. Or you can use :meth:`~Flask.test_request_context` in a ``with`` block, and everything that runs in the block will have access to :data:`request`, populated with your test data. :: def generate_report(year): format = request.args.get('format') ... with app.test_request_context( '/make_report/2017', data={'format': 'short'}): generate_report() If you see that error somewhere else in your code not related to testing, it most likely indicates that you should move that code into a view function. For information on how to use the request context from the interactive Python shell, see :doc:`/shell`. How the Context Works --------------------- The :meth:`Flask.wsgi_app` method is called to handle each request. It manages the contexts during the request. Internally, the request and application contexts work as stacks, :data:`_request_ctx_stack` and :data:`_app_ctx_stack`. When contexts are pushed onto the stack, the proxies that depend on them are available and point at information from the top context on the stack. When the request starts, a :class:`~ctx.RequestContext` is created and pushed, which creates and pushes an :class:`~ctx.AppContext` first if a context for that application is not already the top context. While these contexts are pushed, the :data:`current_app`, :data:`g`, :data:`request`, and :data:`session` proxies are available to the original thread handling the request. Because the contexts are stacks, other contexts may be pushed to change the proxies during a request. While this is not a common pattern, it can be used in advanced applications to, for example, do internal redirects or chain different applications together. After the request is dispatched and a response is generated and sent, the request context is popped, which then pops the application context. Immediately before they are popped, the :meth:`~Flask.teardown_request` and :meth:`~Flask.teardown_appcontext` functions are are executed. These execute even if an unhandled exception occurred during dispatch. .. _callbacks-and-errors: Callbacks and Errors -------------------- Flask dispatches a request in multiple stages which can affect the request, response, and how errors are handled. The contexts are active during all of these stages. A :class:`Blueprint` can add handlers for these events that are specific to the blueprint. The handlers for a blueprint will run if the blueprint owns the route that matches the request. #. Before each request, :meth:`~Flask.before_request` functions are called. If one of these functions return a value, the other functions are skipped. The return value is treated as the response and the view function is not called. #. If the :meth:`~Flask.before_request` functions did not return a response, the view function for the matched route is called and returns a response. #. The return value of the view is converted into an actual response object and passed to the :meth:`~Flask.after_request` functions. Each function returns a modified or new response object. #. After the response is returned, the contexts are popped, which calls the :meth:`~Flask.teardown_request` and :meth:`~Flask.teardown_appcontext` functions. These functions are called even if an unhandled exception was raised at any point above. If an exception is raised before the teardown functions, Flask tries to match it with an :meth:`~Flask.errorhandler` function to handle the exception and return a response. If no error handler is found, or the handler itself raises an exception, Flask returns a generic ``500 Internal Server Error`` response. The teardown functions are still called, and are passed the exception object. If debug mode is enabled, unhandled exceptions are not converted to a ``500`` response and instead are propagated to the WSGI server. This allows the development server to present the interactive debugger with the traceback. Teardown Callbacks ~~~~~~~~~~~~~~~~~~ The teardown callbacks are independent of the request dispatch, and are instead called by the contexts when they are popped. The functions are called even if there is an unhandled exception during dispatch, and for manually pushed contexts. This means there is no guarantee that any other parts of the request dispatch have run first. Be sure to write these functions in a way that does not depend on other callbacks and will not fail. During testing, it can be useful to defer popping the contexts after the request ends, so that their data can be accessed in the test function. Using the :meth:`~Flask.test_client` as a ``with`` block to preserve the contexts until the with block exits. .. code-block:: python from flask import Flask, request app = Flask(__name__) @app.route('/') def hello(): print('during view') return 'Hello, World!' @app.teardown_request def show_teardown(exception): print('after with block') with app.test_request_context(): print('during with block') # teardown functions are called after the context with block exits with app.test_client() as client: client.get('/') # the contexts are not popped even though the request ended print(request.path) # the contexts are popped and teardown functions are called after # the client with block exists Signals ~~~~~~~ If :data:`~signals.signals_available` is true, the following signals are sent: #. :data:`request_started` is sent before the :meth:`~Flask.before_request` functions are called. #. :data:`request_finished` is sent after the :meth:`~Flask.after_request` functions are called. #. :data:`got_request_exception` is sent when an exception begins to be handled, but before an :meth:`~Flask.errorhandler` is looked up or called. #. :data:`request_tearing_down` is sent after the :meth:`~Flask.teardown_request` functions are called. Context Preservation on Error ----------------------------- At the end of a request, the request context is popped and all data associated with it is destroyed. If an error occurs during development, it is useful to delay destroying the data for debugging purposes. When the development server is running in development mode (the ``FLASK_ENV`` environment variable is set to ``'development'``), the error and data will be preserved and shown in the interactive debugger. This behavior can be controlled with the :data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it defaults to ``True`` in the development environment. Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it will cause your application to leak memory on exceptions. .. _notes-on-proxies: Notes On Proxies ---------------- Some of the objects provided by Flask are proxies to other objects. The proxies are accessed in the same way for each worker thread, but point to the unique object bound to each worker behind the scenes as described on this page. 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 cannot fake their type as the actual object types. If you want to perform instance checks, you have to do that on the object being proxied. - If the specific object reference is important, for example for sending :ref:`signals` or passing data to a background thread. If you need to access the underlying object that is proxied, use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method:: app = current_app._get_current_object() my_signal.send(app) Flask-1.1.1/docs/requirements.txt0000644000175000017500000000014113510701642017161 0ustar daviddavid00000000000000Sphinx~=2.1.2 Pallets-Sphinx-Themes~=1.1.4 sphinxcontrib-log-cabinet~=1.0.0 sphinx-issues~=1.2.0 Flask-1.1.1/docs/security.rst0000644000175000017500000002352513510701642016311 0ustar daviddavid00000000000000Security 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 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 input, 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. There is one class of XSS issues that Jinja's escaping does not protect against. The ``a`` tag's ``href`` attribute can contain a `javascript:` URI, which the browser will execute when clicked if not secured properly. .. sourcecode:: html click here click here To prevent this, you'll need to set the :ref:`security-csp` response header. 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. Security Headers ---------------- Browsers recognize various response headers in order to control security. We recommend reviewing each of the headers below for use in your application. The `Flask-Talisman`_ extension can be used to manage HTTPS and the security headers for you. .. _Flask-Talisman: https://github.com/GoogleCloudPlatform/flask-talisman HTTP Strict Transport Security (HSTS) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tells the browser to convert all HTTP requests to HTTPS, preventing man-in-the-middle (MITM) attacks. :: response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security .. _security-csp: Content Security Policy (CSP) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tell the browser where it can load various types of resource from. This header should be used whenever possible, but requires some work to define the correct policy for your site. A very strict policy would be:: response.headers['Content-Security-Policy'] = "default-src 'self'" - https://csp.withgoogle.com/docs/index.html - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy X-Content-Type-Options ~~~~~~~~~~~~~~~~~~~~~~ Forces the browser to honor the response content type instead of trying to detect it, which can be abused to generate a cross-site scripting (XSS) attack. :: response.headers['X-Content-Type-Options'] = 'nosniff' - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options X-Frame-Options ~~~~~~~~~~~~~~~ Prevents external sites from embedding your site in an ``iframe``. This prevents a class of attacks where clicks in the outer frame can be translated invisibly to clicks on your page's elements. This is also known as "clickjacking". :: response.headers['X-Frame-Options'] = 'SAMEORIGIN' - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options X-XSS-Protection ~~~~~~~~~~~~~~~~ The browser will try to prevent reflected XSS attacks by not loading the page if the request contains something that looks like JavaScript and the response contains the same data. :: response.headers['X-XSS-Protection'] = '1; mode=block' - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection .. _security-cookie: Set-Cookie options ~~~~~~~~~~~~~~~~~~ These options can be added to a ``Set-Cookie`` header to improve their security. Flask has configuration options to set these on the session cookie. They can be set on other cookies too. - ``Secure`` limits cookies to HTTPS traffic only. - ``HttpOnly`` protects the contents of cookies from being read with JavaScript. - ``SameSite`` restricts how cookies are sent with requests from external sites. Can be set to ``'Lax'`` (recommended) or ``'Strict'``. ``Lax`` prevents sending cookies with CSRF-prone requests from external sites, such as submitting a form. ``Strict`` prevents sending cookies with all external requests, including following regular links. :: app.config.update( SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Lax', ) response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax') Specifying ``Expires`` or ``Max-Age`` options, will remove the cookie after the given time, or the current time plus the age, respectively. If neither option is set, the cookie will be removed when the browser is closed. :: # cookie expires after 10 minutes response.set_cookie('snakes', '3', max_age=600) For the session cookie, if :attr:`session.permanent ` is set, then :data:`PERMANENT_SESSION_LIFETIME` is used to set the expiration. Flask's default cookie implementation validates that the cryptographic signature is not older than this value. Lowering this value may help mitigate replay attacks, where intercepted cookies can be sent at a later time. :: app.config.update( PERMANENT_SESSION_LIFETIME=600 ) @app.route('/login', methods=['POST']) def login(): ... session.clear() session['user_id'] = user.id session.permanent = True ... Use :class:`itsdangerous.TimedSerializer` to sign and validate other cookie values (or any values that need secure signatures). - https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie .. _samesite_support: https://caniuse.com/#feat=same-site-cookie-attribute HTTP Public Key Pinning (HPKP) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This tells the browser to authenticate with the server using only the specific certificate key to prevent MITM attacks. .. warning:: Be careful when enabling this, as it is very difficult to undo if you set up or upgrade your key incorrectly. - https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning Flask-1.1.1/docs/server.rst0000644000175000017500000000370713510701642015750 0ustar daviddavid00000000000000.. _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_ENV=development $ flask run This enables the development environment, including the interactive debugger and reloader, and then starts 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 .. note:: Prior to Flask 1.0 the :envvar:`FLASK_ENV` environment variable was not supported and you needed to enable debug mode by exporting ``FLASK_DEBUG=1``. This can still be used to control debug mode, but you should prefer setting the development environment as shown above. 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-1.1.1/docs/shell.rst0000644000175000017500000000715713510701642015554 0ustar daviddavid00000000000000.. _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 unit testing 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-1.1.1/docs/signals.rst0000644000175000017500000001566313510701642016106 0ustar daviddavid00000000000000.. _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 unit testing 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 unit test 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.org/project/blinker/ Flask-1.1.1/docs/styleguide.rst0000644000175000017500000001341013510701642016610 0ustar daviddavid00000000000000Pocoo Styleguide ================ The Pocoo styleguide is the styleguide for all Pocoo Projects, including Flask. This styleguide is a requirement for Patches to Flask and a recommendation for Flask extensions. In general the Pocoo Styleguide closely follows :pep:`8` with some small differences and extensions. General Layout -------------- Indentation: 4 real spaces. No tabs, no exceptions. Maximum line length: 79 characters with a soft limit for 84 if absolutely necessary. Try to avoid too nested code by cleverly placing `break`, `continue` and `return` statements. Continuing long statements: To continue a statement you can use backslashes in which case you should align the next line with the last dot or equal sign, or indent four spaces:: this_is_a_very_long(function_call, 'with many parameters') \ .that_returns_an_object_with_an_attribute MyModel.query.filter(MyModel.scalar > 120) \ .order_by(MyModel.name.desc()) \ .limit(10) If you break in a statement with parentheses or braces, align to the braces:: this_is_a_very_long(function_call, 'with many parameters', 23, 42, 'and even more') For lists or tuples with many items, break immediately after the opening brace:: items = [ 'this is the first', 'set of items', 'with more items', 'to come in this line', 'like this' ] Blank lines: Top level functions and classes are separated by two lines, everything else by one. Do not use too many blank lines to separate logical segments in code. Example:: def hello(name): print 'Hello %s!' % name def goodbye(name): print 'See you %s.' % name class MyClass(object): """This is a simple docstring""" def __init__(self, name): self.name = name def get_annoying_name(self): return self.name.upper() + '!!!!111' Expressions and Statements -------------------------- General whitespace rules: - No whitespace for unary operators that are not words (e.g.: ``-``, ``~`` etc.) as well on the inner side of parentheses. - Whitespace is placed between binary operators. Good:: exp = -1.05 value = (item_value / item_count) * offset / exp value = my_list[index] value = my_dict['key'] Bad:: exp = - 1.05 value = ( item_value / item_count ) * offset / exp value = (item_value/item_count)*offset/exp value=( item_value/item_count ) * offset/exp value = my_list[ index ] value = my_dict ['key'] Yoda statements are a no-go: Never compare constant with variable, always variable with constant: Good:: if method == 'md5': pass Bad:: if 'md5' == method: pass Comparisons: - against arbitrary types: ``==`` and ``!=`` - against singletons with ``is`` and ``is not`` (eg: ``foo is not None``) - never compare something with ``True`` or ``False`` (for example never do ``foo == False``, do ``not foo`` instead) Negated containment checks: use ``foo not in bar`` instead of ``not foo in bar`` Instance checks: ``isinstance(a, C)`` instead of ``type(A) is C``, but try to avoid instance checks in general. Check for features. Naming Conventions ------------------ - Class names: ``CamelCase``, with acronyms kept uppercase (``HTTPWriter`` and not ``HttpWriter``) - Variable names: ``lowercase_with_underscores`` - Method and function names: ``lowercase_with_underscores`` - Constants: ``UPPERCASE_WITH_UNDERSCORES`` - precompiled regular expressions: ``name_re`` Protected members are prefixed with a single underscore. Double underscores are reserved for mixin classes. On classes with keywords, trailing underscores are appended. Clashes with builtins are allowed and **must not** be resolved by appending an underline to the variable name. If the function needs to access a shadowed builtin, rebind the builtin to a different name instead. Function and method arguments: - class methods: ``cls`` as first parameter - instance methods: ``self`` as first parameter - lambdas for properties might have the first parameter replaced with ``x`` like in ``display_name = property(lambda x: x.real_name or x.username)`` Docstrings ---------- Docstring conventions: All docstrings are formatted with reStructuredText as understood by Sphinx. Depending on the number of lines in the docstring, they are laid out differently. If it's just one line, the closing triple quote is on the same line as the opening, otherwise the text is on the same line as the opening quote and the triple quote that closes the string on its own line:: def foo(): """This is a simple docstring""" def bar(): """This is a longer docstring with so much information in there that it spans three lines. In this case the closing triple quote is on its own line. """ Module header: The module header consists of a utf-8 encoding declaration (if non ASCII letters are used, but it is recommended all the time) and a standard docstring:: # -*- coding: utf-8 -*- """ package.module ~~~~~~~~~~~~~~ A brief description goes here. :copyright: (c) YEAR by AUTHOR. :license: LICENSE_NAME, see LICENSE_FILE for more details. """ Please keep in mind that proper copyrights and license files are a requirement for approved Flask extensions. Comments -------- Rules for comments are similar to docstrings. Both are formatted with reStructuredText. If a comment is used to document an attribute, put a colon after the opening pound sign (``#``):: class User(object): #: the name of the user as unicode string name = Column(String) #: the sha1 hash of the password + inline salt pw_hash = Column(String) Flask-1.1.1/docs/templating.rst0000644000175000017500000001722413510701642016605 0ustar daviddavid00000000000000.. _templates: Templates ========= 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. .. sourcecode:: html+jinja It is also safe to use the output of `|tojson` in a *single-quoted* HTML attribute: .. sourcecode:: html+jinja Note that in versions of Flask prior to 0.10, if using the output of ``|tojson`` inside ``script``, make sure to disable escaping with ``|safe``. In Flask 0.10 and above, this happens automatically. 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-1.1.1/docs/testing.rst0000644000175000017500000003666713510701642016132 0ustar daviddavid00000000000000.. _testing: Testing Flask Applications ========================== **Something that is untested is broken.** The origin of this quote is unknown and while it is not entirely correct, it is also not far from the truth. Untested applications make it hard to improve existing code and developers of untested applications tend to become pretty paranoid. If an application has automated tests, you can safely make changes and instantly know if anything breaks. Flask provides a way to test your application by exposing the Werkzeug test :class:`~werkzeug.test.Client` and handling the context locals for you. You can then use that with your favourite testing solution. In this documentation we will use the `pytest`_ package as the base framework for our tests. You can install it with ``pip``, like so:: $ pip install pytest .. _pytest: https://docs.pytest.org/ The Application --------------- First, we need an application to test; we will use the application from the :ref:`tutorial`. If you don't have that application yet, get the source code from :gh:`the examples `. The Testing Skeleton -------------------- We begin by adding a tests directory under the application root. Then create a Python file to store our tests (:file:`test_flaskr.py`). When we format the filename like ``test_*.py``, it will be auto-discoverable by pytest. Next, we create a `pytest fixture`_ called :func:`client` that configures the application for testing and initializes a new database:: import os import tempfile import pytest from flaskr import flaskr @pytest.fixture def client(): db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp() flaskr.app.config['TESTING'] = True with flaskr.app.test_client() as client: with flaskr.app.app_context(): flaskr.init_db() yield client os.close(db_fd) os.unlink(flaskr.app.config['DATABASE']) This client fixture will be called by each individual test. It gives us a simple interface to the application, where we can trigger test requests to the application. The client will also keep track of cookies for us. During setup, the ``TESTING`` config flag is activated. What this does is disable error catching during request handling, so that you get better error reports when performing test requests against the application. Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module to create a temporary database and initialize it. The :func:`~tempfile.mkstemp` function does two things for us: it returns a low-level file handle and a random file name, the latter we use as database name. We just have to keep the `db_fd` around so that we can use the :func:`os.close` function to close the file. To delete the database after the test, the fixture closes the file and removes it from the filesystem. If we now run the test suite, we should see the following output:: $ pytest ================ test session starts ================ rootdir: ./flask/examples/flaskr, inifile: setup.cfg collected 0 items =========== no tests ran in 0.07 seconds ============ Even though it did not run any actual tests, we already know that our ``flaskr`` application is syntactically valid, otherwise the import would have died with an exception. .. _pytest fixture: https://docs.pytest.org/en/latest/fixture.html The First Test -------------- Now it's time to start testing the functionality of the application. Let's check that the application shows "No entries here so far" if we access the root of the application (``/``). To do this, we add a new test function to :file:`test_flaskr.py`, like this:: def test_empty_db(client): """Start with a blank database.""" rv = client.get('/') assert b'No entries here so far' in rv.data Notice that our test functions begin with the word `test`; this allows `pytest`_ to automatically identify the function as a test to run. By using ``client.get`` we can send an HTTP ``GET`` request to the application with the given path. The return value will be a :class:`~flask.Flask.response_class` object. We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect the return value (as string) from the application. In this case, we ensure that ``'No entries here so far'`` is part of the output. Run it again and you should see one passing test:: $ pytest -v ================ test session starts ================ rootdir: ./flask/examples/flaskr, inifile: setup.cfg collected 1 items tests/test_flaskr.py::test_empty_db PASSED ============= 1 passed in 0.10 seconds ============== Logging In and Out ------------------ The majority of the functionality of our application is only available for the administrative user, so we need a way to log our test client in and out of the application. To do this, we fire some requests to the login and logout pages with the required form data (username and password). And because the login and logout pages redirect, we tell the client to `follow_redirects`. Add the following two functions to your :file:`test_flaskr.py` file:: def login(client, username, password): return client.post('/login', data=dict( username=username, password=password ), follow_redirects=True) def logout(client): return client.get('/logout', follow_redirects=True) Now we can easily test that logging in and out works and that it fails with invalid credentials. Add this new test function:: def test_login_logout(client): """Make sure login and logout works.""" rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']) assert b'You were logged in' in rv.data rv = logout(client) assert b'You were logged out' in rv.data rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD']) assert b'Invalid username' in rv.data rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x') assert b'Invalid password' in rv.data Test Adding Messages -------------------- We should also test that adding messages works. Add a new test function like this:: def test_messages(client): """Test that messages work.""" login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']) rv = client.post('/add', data=dict( title='', text='HTML allowed here' ), follow_redirects=True) assert b'No entries here so far' not in rv.data assert b'<Hello>' in rv.data assert b'HTML allowed here' in rv.data Here we check that HTML is allowed in the text but not in the title, which is the intended behavior. Running that should now give us three passing tests:: $ pytest -v ================ test session starts ================ rootdir: ./flask/examples/flaskr, inifile: setup.cfg collected 3 items tests/test_flaskr.py::test_empty_db PASSED tests/test_flaskr.py::test_login_logout PASSED tests/test_flaskr.py::test_messages PASSED ============= 3 passed in 0.23 seconds ============== Other Testing Tricks -------------------- Besides using the test client as shown above, there is also the :meth:`~flask.Flask.test_request_context` method that can be used in combination with the ``with`` statement to activate a request context temporarily. With this you can access the :class:`~flask.request`, :class:`~flask.g` and :class:`~flask.session` objects like in view functions. Here is a full example that demonstrates this approach:: import flask app = flask.Flask(__name__) with app.test_request_context('/?name=Peter'): assert flask.request.path == '/' assert flask.request.args['name'] == 'Peter' All the other objects that are context bound can be used in the same way. If you want to test your application with different configurations and there does not seem to be a good way to do that, consider switching to application factories (see :ref:`app-factories`). Note however that if you are using a test request context, the :meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request` functions are not called automatically. However :meth:`~flask.Flask.teardown_request` functions are indeed executed when the test request context leaves the ``with`` block. If you do want the :meth:`~flask.Flask.before_request` functions to be called as well, you need to call :meth:`~flask.Flask.preprocess_request` yourself:: app = flask.Flask(__name__) with app.test_request_context('/?name=Peter'): app.preprocess_request() ... This can be necessary to open database connections or something similar depending on how your application was designed. If you want to call the :meth:`~flask.Flask.after_request` functions you need to call into :meth:`~flask.Flask.process_response` which however requires that you pass it a response object:: app = flask.Flask(__name__) with app.test_request_context('/?name=Peter'): resp = Response('...') resp = app.process_response(resp) ... This in general is less useful because at that point you can directly start using the test client. .. _faking-resources: Faking Resources and Context ---------------------------- .. versionadded:: 0.10 A very common pattern is to store user authorization information and database connections on the application context or the :attr:`flask.g` object. The general pattern for this is to put the object on there on first usage and then to remove it on a teardown. Imagine for instance this code to get the current user:: def get_user(): user = getattr(g, 'user', None) if user is None: user = fetch_current_user_from_database() g.user = user return user For a test it would be nice to override this user from the outside without having to change some code. This can be accomplished with hooking the :data:`flask.appcontext_pushed` signal:: from contextlib import contextmanager from flask import appcontext_pushed, g @contextmanager def user_set(app, user): def handler(sender, **kwargs): g.user = user with appcontext_pushed.connected_to(handler, app): yield And then to use it:: from flask import json, jsonify @app.route('/users/me') def users_me(): return jsonify(username=g.user.username) with user_set(app, my_user): with app.test_client() as c: resp = c.get('/users/me') data = json.loads(resp.data) self.assert_equal(data['username'], my_user.username) Keeping the Context Around -------------------------- .. versionadded:: 0.4 Sometimes it is helpful to trigger a regular request but still keep the context around for a little longer so that additional introspection can happen. With Flask 0.4 this is possible by using the :meth:`~flask.Flask.test_client` with a ``with`` block:: app = flask.Flask(__name__) with app.test_client() as c: rv = c.get('/?tequila=42') assert request.args['tequila'] == '42' If you were to use just the :meth:`~flask.Flask.test_client` without the ``with`` block, the ``assert`` would fail with an error because `request` is no longer available (because you are trying to use it outside of the actual request). Accessing and Modifying Sessions -------------------------------- .. versionadded:: 0.8 Sometimes it can be very helpful to access or modify the sessions from the test client. Generally there are two ways for this. If you just want to ensure that a session has certain keys set to certain values you can just keep the context around and access :data:`flask.session`:: with app.test_client() as c: rv = c.get('/') assert flask.session['foo'] == 42 This however does not make it possible to also modify the session or to access the session before a request was fired. Starting with Flask 0.8 we provide a so called “session transaction” which simulates the appropriate calls to open a session in the context of the test client and to modify it. At the end of the transaction the session is stored and ready to be used by the test client. This works independently of the session backend used:: with app.test_client() as c: with c.session_transaction() as sess: sess['a_key'] = 'a value' # once this is reached the session was stored and ready to be used by the client c.get(...) Note that in this case you have to use the ``sess`` object instead of the :data:`flask.session` proxy. The object however itself will provide the same interface. Testing JSON APIs ----------------- .. versionadded:: 1.0 Flask has great support for JSON, and is a popular choice for building JSON APIs. Making requests with JSON data and examining JSON data in responses is very convenient:: from flask import request, jsonify @app.route('/api/auth') def auth(): json_data = request.get_json() email = json_data['email'] password = json_data['password'] return jsonify(token=generate_token(email, password)) with app.test_client() as c: rv = c.post('/api/auth', json={ 'email': 'flask@example.com', 'password': 'secret' }) json_data = rv.get_json() assert verify_token(email, json_data['token']) Passing the ``json`` argument in the test client methods sets the request data to the JSON-serialized object and sets the content type to ``application/json``. You can get the JSON data from the request or response with ``get_json``. .. _testing-cli: Testing CLI Commands -------------------- Click comes with `utilities for testing`_ your CLI commands. A :class:`~click.testing.CliRunner` runs commands in isolation and captures the output in a :class:`~click.testing.Result` object. Flask provides :meth:`~flask.Flask.test_cli_runner` to create a :class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke` method to call commands in the same way they would be called from the command line. :: import click @app.cli.command('hello') @click.option('--name', default='World') def hello_command(name) click.echo(f'Hello, {name}!') def test_hello(): runner = app.test_cli_runner() # invoke the command directly result = runner.invoke(hello_command, ['--name', 'Flask']) assert 'Hello, Flask' in result.output # or by name result = runner.invoke(args=['hello']) assert 'World' in result.output In the example above, invoking the command by name is useful because it verifies that the command was correctly registered with the app. If you want to test how your command parses parameters, without running the command, use its :meth:`~click.BaseCommand.make_context` method. This is useful for testing complex validation rules and custom types. :: def upper(ctx, param, value): if value is not None: return value.upper() @app.cli.command('hello') @click.option('--name', default='World', callback=upper) def hello_command(name) click.echo(f'Hello, {name}!') def test_hello_params(): context = hello_command.make_context('hello', ['--name', 'flask']) assert context.params['name'] == 'FLASK' .. _click: https://click.palletsprojects.com/ .. _utilities for testing: https://click.palletsprojects.com/testing/ Flask-1.1.1/docs/tutorial/0000755000175000017500000000000013510702200015533 5ustar daviddavid00000000000000Flask-1.1.1/docs/tutorial/blog.rst0000644000175000017500000002617613510701642017235 0ustar daviddavid00000000000000.. currentmodule:: flask Blog Blueprint ============== You'll use the same techniques you learned about when writing the authentication blueprint to write the blog blueprint. The blog should list all posts, allow logged in users to create posts, and allow the author of a post to edit or delete it. As you implement each view, keep the development server running. As you save your changes, try going to the URL in your browser and testing them out. The Blueprint ------------- Define the blueprint and register it in the application factory. .. code-block:: python :caption: ``flaskr/blog.py`` from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort from flaskr.auth import login_required from flaskr.db import get_db bp = Blueprint('blog', __name__) Import and register the blueprint from the factory using :meth:`app.register_blueprint() `. Place the new code at the end of the factory function before returning the app. .. code-block:: python :caption: ``flaskr/__init__.py`` def create_app(): app = ... # existing code omitted from . import blog app.register_blueprint(blog.bp) app.add_url_rule('/', endpoint='index') return app Unlike the auth blueprint, the blog blueprint does not have a ``url_prefix``. So the ``index`` view will be at ``/``, the ``create`` view at ``/create``, and so on. The blog is the main feature of Flaskr, so it makes sense that the blog index will be the main index. However, the endpoint for the ``index`` view defined below will be ``blog.index``. Some of the authentication views referred to a plain ``index`` endpoint. :meth:`app.add_url_rule() ` associates the endpoint name ``'index'`` with the ``/`` url so that ``url_for('index')`` or ``url_for('blog.index')`` will both work, generating the same ``/`` URL either way. In another application you might give the blog blueprint a ``url_prefix`` and define a separate ``index`` view in the application factory, similar to the ``hello`` view. Then the ``index`` and ``blog.index`` endpoints and URLs would be different. Index ----- The index will show all of the posts, most recent first. A ``JOIN`` is used so that the author information from the ``user`` table is available in the result. .. code-block:: python :caption: ``flaskr/blog.py`` @bp.route('/') def index(): db = get_db() posts = db.execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC' ).fetchall() return render_template('blog/index.html', posts=posts) .. code-block:: html+jinja :caption: ``flaskr/templates/blog/index.html`` {% extends 'base.html' %} {% block header %}

{% block title %}Posts{% endblock %}

{% if g.user %} New {% endif %} {% endblock %} {% block content %} {% for post in posts %}

{{ post['title'] }}

by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}
{% if g.user['id'] == post['author_id'] %} Edit {% endif %}

{{ post['body'] }}

{% if not loop.last %}
{% endif %} {% endfor %} {% endblock %} When a user is logged in, the ``header`` block adds a link to the ``create`` view. When the user is the author of a post, they'll see an "Edit" link to the ``update`` view for that post. ``loop.last`` is a special variable available inside `Jinja for loops`_. It's used to display a line after each post except the last one, to visually separate them. .. _Jinja for loops: http://jinja.pocoo.org/docs/templates/#for Create ------ The ``create`` view works the same as the auth ``register`` view. Either the form is displayed, or the posted data is validated and the post is added to the database or an error is shown. The ``login_required`` decorator you wrote earlier is used on the blog views. A user must be logged in to visit these views, otherwise they will be redirected to the login page. .. code-block:: python :caption: ``flaskr/blog.py`` @bp.route('/create', methods=('GET', 'POST')) @login_required def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', (title, body, g.user['id']) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/create.html') .. code-block:: html+jinja :caption: ``flaskr/templates/blog/create.html`` {% extends 'base.html' %} {% block header %}

{% block title %}New Post{% endblock %}

{% endblock %} {% block content %}
{% endblock %} Update ------ Both the ``update`` and ``delete`` views will need to fetch a ``post`` by ``id`` and check if the author matches the logged in user. To avoid duplicating code, you can write a function to get the ``post`` and call it from each view. .. code-block:: python :caption: ``flaskr/blog.py`` def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone() if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post['author_id'] != g.user['id']: abort(403) return post :func:`abort` will raise a special exception that returns an HTTP status code. It takes an optional message to show with the error, otherwise a default message is used. ``404`` means "Not Found", and ``403`` means "Forbidden". (``401`` means "Unauthorized", but you redirect to the login page instead of returning that status.) The ``check_author`` argument is defined so that the function can be used to get a ``post`` without checking the author. This would be useful if you wrote a view to show an individual post on a page, where the user doesn't matter because they're not modifying the post. .. code-block:: python :caption: ``flaskr/blog.py`` @bp.route('//update', methods=('GET', 'POST')) @login_required def update(id): post = get_post(id) if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'UPDATE post SET title = ?, body = ?' ' WHERE id = ?', (title, body, id) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post) Unlike the views you've written so far, the ``update`` function takes an argument, ``id``. That corresponds to the ```` in the route. A real URL will look like ``/1/update``. Flask will capture the ``1``, ensure it's an :class:`int`, and pass it as the ``id`` argument. If you don't specify ``int:`` and instead do ````, it will be a string. To generate a URL to the update page, :func:`url_for` needs to be passed the ``id`` so it knows what to fill in: ``url_for('blog.update', id=post['id'])``. This is also in the ``index.html`` file above. The ``create`` and ``update`` views look very similar. The main difference is that the ``update`` view uses a ``post`` object and an ``UPDATE`` query instead of an ``INSERT``. With some clever refactoring, you could use one view and template for both actions, but for the tutorial it's clearer to keep them separate. .. code-block:: html+jinja :caption: ``flaskr/templates/blog/update.html`` {% extends 'base.html' %} {% block header %}

{% block title %}Edit "{{ post['title'] }}"{% endblock %}

{% endblock %} {% block content %}

{% endblock %} This template has two forms. The first posts the edited data to the current page (``//update``). The other form contains only a button and specifies an ``action`` attribute that posts to the delete view instead. The button uses some JavaScript to show a confirmation dialog before submitting. The pattern ``{{ request.form['title'] or post['title'] }}`` is used to choose what data appears in the form. When the form hasn't been submitted, the original ``post`` data appears, but if invalid form data was posted you want to display that so the user can fix the error, so ``request.form`` is used instead. :data:`request` is another variable that's automatically available in templates. Delete ------ The delete view doesn't have its own template, the delete button is part of ``update.html`` and posts to the ``//delete`` URL. Since there is no template, it will only handle the ``POST`` method and then redirect to the ``index`` view. .. code-block:: python :caption: ``flaskr/blog.py`` @bp.route('//delete', methods=('POST',)) @login_required def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id,)) db.commit() return redirect(url_for('blog.index')) Congratulations, you've now finished writing your application! Take some time to try out everything in the browser. However, there's still more to do before the project is complete. Continue to :doc:`install`. Flask-1.1.1/docs/tutorial/database.rst0000644000175000017500000001532613510701642020051 0ustar daviddavid00000000000000.. currentmodule:: flask Define and Access the Database ============================== The application will use a `SQLite`_ database to store users and posts. Python comes with built-in support for SQLite in the :mod:`sqlite3` module. SQLite is convenient because it doesn't require setting up a separate database server and is built-in to Python. However, if concurrent requests try to write to the database at the same time, they will slow down as each write happens sequentially. Small applications won't notice this. Once you become big, you may want to switch to a different database. The tutorial doesn't go into detail about SQL. If you are not familiar with it, the SQLite docs describe the `language`_. .. _SQLite: https://sqlite.org/about.html .. _language: https://sqlite.org/lang.html Connect to the Database ----------------------- The first thing to do when working with a SQLite database (and most other Python database libraries) is to create a connection to it. Any queries and operations are performed using the connection, which is closed after the work is finished. In web applications this connection is typically tied to the request. It is created at some point when handling a request, and closed before the response is sent. .. code-block:: python :caption: ``flaskr/db.py`` import sqlite3 import click from flask import current_app, g from flask.cli import with_appcontext def get_db(): if 'db' not in g: g.db = sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sqlite3.Row return g.db def close_db(e=None): db = g.pop('db', None) if db is not None: db.close() :data:`g` is a special object that is unique for each request. It is used to store data that might be accessed by multiple functions during the request. The connection is stored and reused instead of creating a new connection if ``get_db`` is called a second time in the same request. :data:`current_app` is another special object that points to the Flask application handling the request. Since you used an application factory, there is no application object when writing the rest of your code. ``get_db`` will be called when the application has been created and is handling a request, so :data:`current_app` can be used. :func:`sqlite3.connect` establishes a connection to the file pointed at by the ``DATABASE`` configuration key. This file doesn't have to exist yet, and won't until you initialize the database later. :class:`sqlite3.Row` tells the connection to return rows that behave like dicts. This allows accessing the columns by name. ``close_db`` checks if a connection was created by checking if ``g.db`` was set. If the connection exists, it is closed. Further down you will tell your application about the ``close_db`` function in the application factory so that it is called after each request. Create the Tables ----------------- In SQLite, data is stored in *tables* and *columns*. These need to be created before you can store and retrieve data. Flaskr will store users in the ``user`` table, and posts in the ``post`` table. Create a file with the SQL commands needed to create empty tables: .. code-block:: sql :caption: ``flaskr/schema.sql`` DROP TABLE IF EXISTS user; DROP TABLE IF EXISTS post; CREATE TABLE user ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL ); CREATE TABLE post ( id INTEGER PRIMARY KEY AUTOINCREMENT, author_id INTEGER NOT NULL, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, title TEXT NOT NULL, body TEXT NOT NULL, FOREIGN KEY (author_id) REFERENCES user (id) ); Add the Python functions that will run these SQL commands to the ``db.py`` file: .. code-block:: python :caption: ``flaskr/db.py`` def init_db(): db = get_db() with current_app.open_resource('schema.sql') as f: db.executescript(f.read().decode('utf8')) @click.command('init-db') @with_appcontext def init_db_command(): """Clear the existing data and create new tables.""" init_db() click.echo('Initialized the database.') :meth:`open_resource() ` opens a file relative to the ``flaskr`` package, which is useful since you won't necessarily know where that location is when deploying the application later. ``get_db`` returns a database connection, which is used to execute the commands read from the file. :func:`click.command` defines a command line command called ``init-db`` that calls the ``init_db`` function and shows a success message to the user. You can read :ref:`cli` to learn more about writing commands. Register with the Application ----------------------------- The ``close_db`` and ``init_db_command`` functions need to be registered with the application instance; otherwise, they won't be used by the application. However, since you're using a factory function, that instance isn't available when writing the functions. Instead, write a function that takes an application and does the registration. .. code-block:: python :caption: ``flaskr/db.py`` def init_app(app): app.teardown_appcontext(close_db) app.cli.add_command(init_db_command) :meth:`app.teardown_appcontext() ` tells Flask to call that function when cleaning up after returning the response. :meth:`app.cli.add_command() ` adds a new command that can be called with the ``flask`` command. Import and call this function from the factory. Place the new code at the end of the factory function before returning the app. .. code-block:: python :caption: ``flaskr/__init__.py`` def create_app(): app = ... # existing code omitted from . import db db.init_app(app) return app Initialize the Database File ---------------------------- Now that ``init-db`` has been registered with the app, it can be called using the ``flask`` command, similar to the ``run`` command from the previous page. .. note:: If you're still running the server from the previous page, you can either stop the server, or run this command in a new terminal. If you use a new terminal, remember to change to your project directory and activate the env as described in :ref:`install-activate-env`. You'll also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on the previous page. Run the ``init-db`` command: .. code-block:: none $ flask init-db Initialized the database. There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in your project. Continue to :doc:`views`. Flask-1.1.1/docs/tutorial/deploy.rst0000644000175000017500000000746613510701642017607 0ustar daviddavid00000000000000Deploy to Production ==================== This part of the tutorial assumes you have a server that you want to deploy your application to. It gives an overview of how to create the distribution file and install it, but won't go into specifics about what server or software to use. You can set up a new environment on your development computer to try out the instructions below, but probably shouldn't use it for hosting a real public application. See :doc:`/deploying/index` for a list of many different ways to host your application. Build and Install ----------------- When you want to deploy your application elsewhere, you build a distribution file. The current standard for Python distribution is the *wheel* format, with the ``.whl`` extension. Make sure the wheel library is installed first: .. code-block:: none $ pip install wheel Running ``setup.py`` with Python gives you a command line tool to issue build-related commands. The ``bdist_wheel`` command will build a wheel distribution file. .. code-block:: none $ python setup.py bdist_wheel You can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The file name is the name of the project, the version, and some tags about the file can install. Copy this file to another machine, :ref:`set up a new virtualenv `, then install the file with ``pip``. .. code-block:: none $ pip install flaskr-1.0.0-py3-none-any.whl Pip will install your project along with its dependencies. Since this is a different machine, you need to run ``init-db`` again to create the database in the instance folder. .. code-block:: none $ export FLASK_APP=flaskr $ flask init-db When Flask detects that it's installed (not in editable mode), it uses a different directory for the instance folder. You can find it at ``venv/var/flaskr-instance`` instead. Configure the Secret Key ------------------------ In the beginning of the tutorial that you gave a default value for :data:`SECRET_KEY`. This should be changed to some random bytes in production. Otherwise, attackers could use the public ``'dev'`` key to modify the session cookie, or anything else that uses the secret key. You can use the following command to output a random secret key: .. code-block:: none $ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/' Create the ``config.py`` file in the instance folder, which the factory will read from if it exists. Copy the generated value into it. .. code-block:: python :caption: ``venv/var/flaskr-instance/config.py`` SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/' You can also set any other necessary configuration here, although ``SECRET_KEY`` is the only one needed for Flaskr. Run with a Production Server ---------------------------- When running publicly rather than in development, you should not use the built-in development server (``flask run``). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure. Instead, use a production WSGI server. For example, to use `Waitress`_, first install it in the virtual environment: .. code-block:: none $ pip install waitress You need to tell Waitress about your application, but it doesn't use ``FLASK_APP`` like ``flask run`` does. You need to tell it to import and call the application factory to get an application object. .. code-block:: none $ waitress-serve --call 'flaskr:create_app' Serving on http://0.0.0.0:8080 See :doc:`/deploying/index` for a list of many different ways to host your application. Waitress is just an example, chosen for the tutorial because it supports both Windows and Linux. There are many more WSGI servers and deployment options that you may choose for your project. .. _Waitress: https://docs.pylonsproject.org/projects/waitress/en/stable/ Continue to :doc:`next`. Flask-1.1.1/docs/tutorial/factory.rst0000644000175000017500000001400013510701642017740 0ustar daviddavid00000000000000.. currentmodule:: flask Application Setup ================= A Flask application is an instance of the :class:`Flask` class. Everything about the application, such as configuration and URLs, will be registered with this class. The most straightforward way to create a Flask application is to create a global :class:`Flask` instance directly at the top of your code, like how the "Hello, World!" example did on the previous page. While this is simple and useful in some cases, it can cause some tricky issues as the project grows. Instead of creating a :class:`Flask` instance globally, you will create it inside a function. This function is known as the *application factory*. Any configuration, registration, and other setup the application needs will happen inside the function, then the application will be returned. The Application Factory ----------------------- It's time to start coding! Create the ``flaskr`` directory and add the ``__init__.py`` file. The ``__init__.py`` serves double duty: it will contain the application factory, and it tells Python that the ``flaskr`` directory should be treated as a package. .. code-block:: none $ mkdir flaskr .. code-block:: python :caption: ``flaskr/__init__.py`` import os from flask import Flask def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' return app ``create_app`` is the application factory function. You'll add to it later in the tutorial, but it already does a lot. #. ``app = Flask(__name__, instance_relative_config=True)`` creates the :class:`Flask` instance. * ``__name__`` is the name of the current Python module. The app needs to know where it's located to set up some paths, and ``__name__`` is a convenient way to tell it that. * ``instance_relative_config=True`` tells the app that configuration files are relative to the :ref:`instance folder `. The instance folder is located outside the ``flaskr`` package and can hold local data that shouldn't be committed to version control, such as configuration secrets and the database file. #. :meth:`app.config.from_mapping() ` sets some default configuration that the app will use: * :data:`SECRET_KEY` is used by Flask and extensions to keep data safe. It's set to ``'dev'`` to provide a convenient value during development, but it should be overridden with a random value when deploying. * ``DATABASE`` is the path where the SQLite database file will be saved. It's under :attr:`app.instance_path `, which is the path that Flask has chosen for the instance folder. You'll learn more about the database in the next section. #. :meth:`app.config.from_pyfile() ` overrides the default configuration with values taken from the ``config.py`` file in the instance folder if it exists. For example, when deploying, this can be used to set a real ``SECRET_KEY``. * ``test_config`` can also be passed to the factory, and will be used instead of the instance configuration. This is so the tests you'll write later in the tutorial can be configured independently of any development values you have configured. #. :func:`os.makedirs` ensures that :attr:`app.instance_path ` exists. Flask doesn't create the instance folder automatically, but it needs to be created because your project will create the SQLite database file there. #. :meth:`@app.route() ` creates a simple route so you can see the application working before getting into the rest of the tutorial. It creates a connection between the URL ``/hello`` and a function that returns a response, the string ``'Hello, World!'`` in this case. Run The Application ------------------- Now you can run your application using the ``flask`` command. From the terminal, tell Flask where to find your application, then run it in development mode. Remember, you should still be in the top-level ``flask-tutorial`` directory, not the ``flaskr`` package. Development mode shows an interactive debugger whenever a page raises an exception, and restarts the server whenever you make changes to the code. You can leave it running and just reload the browser page as you follow the tutorial. For Linux and Mac: .. code-block:: none $ export FLASK_APP=flaskr $ export FLASK_ENV=development $ flask run For Windows cmd, use ``set`` instead of ``export``: .. code-block:: none > set FLASK_APP=flaskr > set FLASK_ENV=development > flask run For Windows PowerShell, use ``$env:`` instead of ``export``: .. code-block:: none > $env:FLASK_APP = "flaskr" > $env:FLASK_ENV = "development" > flask run You'll see output similar to this: .. code-block:: none * Serving Flask app "flaskr" * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 855-212-761 Visit http://127.0.0.1:5000/hello in a browser and you should see the "Hello, World!" message. Congratulations, you're now running your Flask web application! Continue to :doc:`database`. Flask-1.1.1/docs/tutorial/flaskr_edit.png0000644000175000017500000003171313510701642020546 0ustar daviddavid00000000000000PNG  IHDR ) IDATx]LTwqUӋ0{]dIiB; ?HҐ%%%1j5J.sZP)CeAʈ-}u;.-X_Ü+$-9pHu!x+@!dq!b BQ(B!F@!!b BQ(B!F@!!b BQ(B!F@!!b BQ\ Ba(B!F@!!b BQ(B!F@!!b$()0wuZ; Fu@fɟve'vyo!kZv'Fg( Bb N"y 4dXi=Fu%xsSejQnyJV֨\u  /w҉n?(oՑ>9/BP+m+GzfΖě#+uKXOy'FH`(87)Ѕ%qsFOĐX :nB!NB9iSfn?-uJ-seӪk:~1^ZZ#r\TPYS{$*3v"hg}N2)<%Nc)_>u+*~)ǔiT.NO[_2M))OiKEc\8LY[ꔺA=Ǵdor_M%QZi^o -J-=OK> mN|ؠԝS{f#!>-:b; C)uK6^P{eS߫}ܖf~2 *?=Sg9v}zj_WRc{~Sެu.tUqBbOdcZR>mퟪBSVO/36Öv]إ驍-j/Rj^][JQJZ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7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7EvCX4`7Evr D@ jkk@$ b5666?~(ؘN86OD@4!1n @ UL{Q Z`B(ו;|ViU7|sS\Չ7TUIm@EIx@r6UW|T8uC=Rwկ*mPG'6)gç]ݹ󃺪J_݂o;,6HeĩʭZR2ZYR?v)PWW<ԃwվ١Bu>*J_F#nmyw P ;?g[]=_~~1s*+-}NLtRaUyU| 9կ]mi)9\#( _m@d@$RFkˆ?WsG]n-WNzv}PF>תWypW7:6Oi~PWMk߄ttJmz)`ѡ@*wuS}U9/:|VI{O^΁ՕUPZC/]u{=G7,wD&}:ieB*0(T@C  $U(`,/ D'BX255%׈[C#4"6Ј\#nMMMYE_ AP #0BP #0BP #0BP #0BP #0BP #0BP #0B,'b`aP #0BP #0BP #0BP #0 djjJ?50o]tf`hD?555e@,}0wtOuYP @}( XȂFi9_G?Su륧gw`)`@@~לqrзMP @B@@f>V{gk?UW0au>G<+ŗn_\@C$\<ԃ˹oq[}HhT і u1+0(D,kv>ԃ4ⷺwDСoHeCH,P @@@=\pɛoHeCH,P @@@nW5r+D_6$cW(`P S w4*,9qM<;u;5X QW?;YhY\@C,p̞2zZ7} ?wh_W_g{K UXa}IZWaExb  $U(`P $B!I ?IP Y_$$/kN7с djjJFtiElFܚc @ @F( `@F( `@F( `@F( `@F( `@F( `@F( `@F( `@F( `@F( `@F( `d B=CB1 B!(!P BBB1 B!(!P BBB1 B!(!P BBB1 B!(!jPM6UTIENDB`Flask-1.1.1/docs/tutorial/flaskr_index.png0000644000175000017500000002663313510701642020735 0ustar daviddavid00000000000000PNG  IHDR+z IDATxMLg*/ ݱ+J^D[E8{*EEb*] *Bqc)N'r))GĄ\j'#U+ӂFHa`'=R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1.1.1/docs/tutorial/index.rst0000644000175000017500000000403313510701642017405 0ustar daviddavid00000000000000.. _tutorial: Tutorial ======== .. toctree:: :caption: Contents: :maxdepth: 1 layout factory database views templates static blog install tests deploy next This tutorial will walk you through creating a basic blog application called Flaskr. Users will be able to register, log in, create posts, and edit or delete their own posts. You will be able to package and install the application on other computers. .. image:: flaskr_index.png :align: center :class: screenshot :alt: screenshot of index page It's assumed that you're already familiar with Python. The `official tutorial`_ in the Python docs is a great way to learn or review first. .. _official tutorial: https://docs.python.org/3/tutorial/ While it's designed to give a good starting point, the tutorial doesn't cover all of Flask's features. Check out the :ref:`quickstart` for an overview of what Flask can do, then dive into the docs to find out more. The tutorial only uses what's provided by Flask and Python. In another project, you might decide to use :ref:`extensions` or other libraries to make some tasks simpler. .. image:: flaskr_login.png :align: center :class: screenshot :alt: screenshot of login page Flask is flexible. It doesn't require you to use any particular project or code layout. However, when first starting, it's helpful to use a more structured approach. This means that the tutorial will require a bit of boilerplate up front, but it's done to avoid many common pitfalls that new developers encounter, and it creates a project that's easy to expand on. Once you become more comfortable with Flask, you can step out of this structure and take full advantage of Flask's flexibility. .. image:: flaskr_edit.png :align: center :class: screenshot :alt: screenshot of login page :gh:`The tutorial project is available as an example in the Flask repository `, if you want to compare your project with the final product as you follow the tutorial. Continue to :doc:`layout`. Flask-1.1.1/docs/tutorial/install.rst0000644000175000017500000000675713510701642017763 0ustar daviddavid00000000000000Make the Project Installable ============================ Making your project installable means that you can build a *distribution* file and install that in another environment, just like you installed Flask in your project's environment. This makes deploying your project the same as installing any other library, so you're using all the standard Python tools to manage everything. Installing also comes with other benefits that might not be obvious from the tutorial or as a new Python user, including: * Currently, Python and Flask understand how to use the ``flaskr`` package only because you're running from your project's directory. Installing means you can import it no matter where you run from. * You can manage your project's dependencies just like other packages do, so ``pip install yourproject.whl`` installs them. * Test tools can isolate your test environment from your development environment. .. note:: This is being introduced late in the tutorial, but in your future projects you should always start with this. Describe the Project -------------------- The ``setup.py`` file describes your project and the files that belong to it. .. code-block:: python :caption: ``setup.py`` from setuptools import find_packages, setup setup( name='flaskr', version='1.0.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'flask', ], ) ``packages`` tells Python what package directories (and the Python files they contain) to include. ``find_packages()`` finds these directories automatically so you don't have to type them out. To include other files, such as the static and templates directories, ``include_package_data`` is set. Python needs another file named ``MANIFEST.in`` to tell what this other data is. .. code-block:: none :caption: ``MANIFEST.in`` include flaskr/schema.sql graft flaskr/static graft flaskr/templates global-exclude *.pyc This tells Python to copy everything in the ``static`` and ``templates`` directories, and the ``schema.sql`` file, but to exclude all bytecode files. See the `official packaging guide`_ for another explanation of the files and options used. .. _official packaging guide: https://packaging.python.org/tutorials/packaging-projects/ Install the Project ------------------- Use ``pip`` to install your project in the virtual environment. .. code-block:: none $ pip install -e . This tells pip to find ``setup.py`` in the current directory and install it in *editable* or *development* mode. Editable mode means that as you make changes to your local code, you'll only need to re-install if you change the metadata about the project, such as its dependencies. You can observe that the project is now installed with ``pip list``. .. code-block:: none $ pip list Package Version Location -------------- --------- ---------------------------------- click 6.7 Flask 1.0 flaskr 1.0.0 /home/user/Projects/flask-tutorial itsdangerous 0.24 Jinja2 2.10 MarkupSafe 1.0 pip 9.0.3 setuptools 39.0.1 Werkzeug 0.14.1 wheel 0.30.0 Nothing changes from how you've been running your project so far. ``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs the application, but you can call it from anywhere, not just the ``flask-tutorial`` directory. Continue to :doc:`tests`. Flask-1.1.1/docs/tutorial/layout.rst0000644000175000017500000000564413510701642017624 0ustar daviddavid00000000000000Project Layout ============== Create a project directory and enter it: .. code-block:: none $ mkdir flask-tutorial $ cd flask-tutorial Then follow the :doc:`installation instructions ` to set up a Python virtual environment and install Flask for your project. The tutorial will assume you're working from the ``flask-tutorial`` directory from now on. The file names at the top of each code block are relative to this directory. ---- A Flask application can be as simple as a single file. .. code-block:: python :caption: ``hello.py`` from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' However, as a project gets bigger, it becomes overwhelming to keep all the code in one file. Python projects use *packages* to organize code into multiple modules that can be imported where needed, and the tutorial will do this as well. The project directory will contain: * ``flaskr/``, a Python package containing your application code and files. * ``tests/``, a directory containing test modules. * ``venv/``, a Python virtual environment where Flask and other dependencies are installed. * Installation files telling Python how to install your project. * Version control config, such as `git`_. You should make a habit of using some type of version control for all your projects, no matter the size. * Any other project files you might add in the future. .. _git: https://git-scm.com/ By the end, your project layout will look like this: .. code-block:: none /home/user/Projects/flask-tutorial ├── flaskr/ │   ├── __init__.py │   ├── db.py │   ├── schema.sql │   ├── auth.py │   ├── blog.py │   ├── templates/ │   │ ├── base.html │   │ ├── auth/ │   │ │   ├── login.html │   │ │   └── register.html │   │ └── blog/ │   │ ├── create.html │   │ ├── index.html │   │ └── update.html │   └── static/ │      └── style.css ├── tests/ │   ├── conftest.py │   ├── data.sql │   ├── test_factory.py │   ├── test_db.py │  ├── test_auth.py │  └── test_blog.py ├── venv/ ├── setup.py └── MANIFEST.in If you're using version control, the following files that are generated while running your project should be ignored. There may be other files based on the editor you use. In general, ignore files that you didn't write. For example, with git: .. code-block:: none :caption: ``.gitignore`` venv/ *.pyc __pycache__/ instance/ .pytest_cache/ .coverage htmlcov/ dist/ build/ *.egg-info/ Continue to :doc:`factory`. Flask-1.1.1/docs/tutorial/next.rst0000644000175000017500000000313513510701642017256 0ustar daviddavid00000000000000Keep Developing! ================ You've learned about quite a few Flask and Python concepts throughout the tutorial. Go back and review the tutorial and compare your code with the steps you took to get there. Compare your project to the :gh:`example project `, which might look a bit different due to the step-by-step nature of the tutorial. There's a lot more to Flask than what you've seen so far. Even so, you're now equipped to start developing your own web applications. Check out the :ref:`quickstart` for an overview of what Flask can do, then dive into the docs to keep learning. Flask uses `Jinja`_, `Click`_, `Werkzeug`_, and `ItsDangerous`_ behind the scenes, and they all have their own documentation too. You'll also be interested in :ref:`extensions` which make tasks like working with the database or validating form data easier and more powerful. If you want to keep developing your Flaskr project, here are some ideas for what to try next: * A detail view to show a single post. Click a post's title to go to its page. * Like / unlike a post. * Comments. * Tags. Clicking a tag shows all the posts with that tag. * A search box that filters the index page by name. * Paged display. Only show 5 posts per page. * Upload an image to go along with a post. * Format posts using Markdown. * An RSS feed of new posts. Have fun and make awesome applications! .. _Jinja: https://palletsprojects.com/p/jinja/ .. _Click: https://palletsprojects.com/p/click/ .. _Werkzeug: https://palletsprojects.com/p/werkzeug/ .. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/ Flask-1.1.1/docs/tutorial/static.rst0000644000175000017500000000614213510701642017570 0ustar daviddavid00000000000000Static Files ============ The authentication views and templates work, but they look very plain right now. Some `CSS`_ can be added to add style to the HTML layout you constructed. The style won't change, so it's a *static* file rather than a template. Flask automatically adds a ``static`` view that takes a path relative to the ``flaskr/static`` directory and serves it. The ``base.html`` template already has a link to the ``style.css`` file: .. code-block:: html+jinja {{ url_for('static', filename='style.css') }} Besides CSS, other types of static files might be files with JavaScript functions, or a logo image. They are all placed under the ``flaskr/static`` directory and referenced with ``url_for('static', filename='...')``. This tutorial isn't focused on how to write CSS, so you can just copy the following into the ``flaskr/static/style.css`` file: .. code-block:: css :caption: ``flaskr/static/style.css`` html { font-family: sans-serif; background: #eee; padding: 1rem; } body { max-width: 960px; margin: 0 auto; background: white; } h1 { font-family: serif; color: #377ba8; margin: 1rem 0; } a { color: #377ba8; } hr { border: none; border-top: 1px solid lightgray; } nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; } nav h1 { flex: auto; margin: 0; } nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; } nav ul { display: flex; list-style: none; margin: 0; padding: 0; } nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; } .content { padding: 0 1rem 1rem; } .content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; } .content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; } .flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; } .post > header { display: flex; align-items: flex-end; font-size: 0.85em; } .post > header > div:first-of-type { flex: auto; } .post > header h1 { font-size: 1.5em; margin-bottom: 0; } .post .about { color: slategray; font-style: italic; } .post .body { white-space: pre-line; } .content:last-child { margin-bottom: 0; } .content form { margin: 1em 0; display: flex; flex-direction: column; } .content label { font-weight: bold; margin-bottom: 0.5em; } .content input, .content textarea { margin-bottom: 1em; } .content textarea { min-height: 12em; resize: vertical; } input.danger { color: #cc2f2e; } input[type=submit] { align-self: start; min-width: 10em; } You can find a less compact version of ``style.css`` in the :gh:`example code `. Go to http://127.0.0.1:5000/auth/login and the page should look like the screenshot below. .. image:: flaskr_login.png :align: center :class: screenshot :alt: screenshot of login page You can read more about CSS from `Mozilla's documentation `_. If you change a static file, refresh the browser page. If the change doesn't show up, try clearing your browser's cache. .. _CSS: https://developer.mozilla.org/docs/Web/CSS Continue to :doc:`blog`. Flask-1.1.1/docs/tutorial/templates.rst0000644000175000017500000001545313510701642020304 0ustar daviddavid00000000000000.. currentmodule:: flask Templates ========= You've written the authentication views for your application, but if you're running the server and try to go to any of the URLs, you'll see a ``TemplateNotFound`` error. That's because the views are calling :func:`render_template`, but you haven't written the templates yet. The template files will be stored in the ``templates`` directory inside the ``flaskr`` package. Templates are files that contain static data as well as placeholders for dynamic data. A template is rendered with specific data to produce a final document. Flask uses the `Jinja`_ template library to render templates. In your application, you will use templates to render `HTML`_ which will display in the user's browser. In Flask, Jinja is configured to *autoescape* any data that is rendered in HTML templates. This means that it's safe to render user input; any characters they've entered that could mess with the HTML, such as ``<`` and ``>`` will be *escaped* with *safe* values that look the same in the browser but don't cause unwanted effects. Jinja looks and behaves mostly like Python. Special delimiters are used to distinguish Jinja syntax from the static data in the template. Anything between ``{{`` and ``}}`` is an expression that will be output to the final document. ``{%`` and ``%}`` denotes a control flow statement like ``if`` and ``for``. Unlike Python, blocks are denoted by start and end tags rather than indentation since static text within a block could change indentation. .. _Jinja: http://jinja.pocoo.org/docs/templates/ .. _HTML: https://developer.mozilla.org/docs/Web/HTML The Base Layout --------------- Each page in the application will have the same basic layout around a different body. Instead of writing the entire HTML structure in each template, each template will *extend* a base template and override specific sections. .. code-block:: html+jinja :caption: ``flaskr/templates/base.html`` {% block title %}{% endblock %} - Flaskr
{% block header %}{% endblock %}
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %} {% block content %}{% endblock %}
:data:`g` is automatically available in templates. Based on if ``g.user`` is set (from ``load_logged_in_user``), either the username and a log out link are displayed, or links to register and log in are displayed. :func:`url_for` is also automatically available, and is used to generate URLs to views instead of writing them out manually. After the page title, and before the content, the template loops over each message returned by :func:`get_flashed_messages`. You used :func:`flash` in the views to show error messages, and this is the code that will display them. There are three blocks defined here that will be overridden in the other templates: #. ``{% block title %}`` will change the title displayed in the browser's tab and window title. #. ``{% block header %}`` is similar to ``title`` but will change the title displayed on the page. #. ``{% block content %}`` is where the content of each page goes, such as the login form or a blog post. The base template is directly in the ``templates`` directory. To keep the others organized, the templates for a blueprint will be placed in a directory with the same name as the blueprint. Register -------- .. code-block:: html+jinja :caption: ``flaskr/templates/auth/register.html`` {% extends 'base.html' %} {% block header %}

{% block title %}Register{% endblock %}

{% endblock %} {% block content %}
{% endblock %} ``{% extends 'base.html' %}`` tells Jinja that this template should replace the blocks from the base template. All the rendered content must appear inside ``{% block %}`` tags that override blocks from the base template. A useful pattern used here is to place ``{% block title %}`` inside ``{% block header %}``. This will set the title block and then output the value of it into the header block, so that both the window and page share the same title without writing it twice. The ``input`` tags are using the ``required`` attribute here. This tells the browser not to submit the form until those fields are filled in. If the user is using an older browser that doesn't support that attribute, or if they are using something besides a browser to make requests, you still want to validate the data in the Flask view. It's important to always fully validate the data on the server, even if the client does some validation as well. Log In ------ This is identical to the register template except for the title and submit button. .. code-block:: html+jinja :caption: ``flaskr/templates/auth/login.html`` {% extends 'base.html' %} {% block header %}

{% block title %}Log In{% endblock %}

{% endblock %} {% block content %}
{% endblock %} Register A User --------------- Now that the authentication templates are written, you can register a user. Make sure the server is still running (``flask run`` if it's not), then go to http://127.0.0.1:5000/auth/register. Try clicking the "Register" button without filling out the form and see that the browser shows an error message. Try removing the ``required`` attributes from the ``register.html`` template and click "Register" again. Instead of the browser showing an error, the page will reload and the error from :func:`flash` in the view will be shown. Fill out a username and password and you'll be redirected to the login page. Try entering an incorrect username, or the correct username and incorrect password. If you log in you'll get an error because there's no ``index`` view to redirect to yet. Continue to :doc:`static`. Flask-1.1.1/docs/tutorial/tests.rst0000644000175000017500000004363213510701642017450 0ustar daviddavid00000000000000.. currentmodule:: flask Test Coverage ============= Writing unit tests for your application lets you check that the code you wrote works the way you expect. Flask provides a test client that simulates requests to the application and returns the response data. You should test as much of your code as possible. Code in functions only runs when the function is called, and code in branches, such as ``if`` blocks, only runs when the condition is met. You want to make sure that each function is tested with data that covers each branch. The closer you get to 100% coverage, the more comfortable you can be that making a change won't unexpectedly change other behavior. However, 100% coverage doesn't guarantee that your application doesn't have bugs. In particular, it doesn't test how the user interacts with the application in the browser. Despite this, test coverage is an important tool to use during development. .. note:: This is being introduced late in the tutorial, but in your future projects you should test as you develop. You'll use `pytest`_ and `coverage`_ to test and measure your code. Install them both: .. code-block:: none $ pip install pytest coverage .. _pytest: https://pytest.readthedocs.io/ .. _coverage: https://coverage.readthedocs.io/ Setup and Fixtures ------------------ The test code is located in the ``tests`` directory. This directory is *next to* the ``flaskr`` package, not inside it. The ``tests/conftest.py`` file contains setup functions called *fixtures* that each test will use. Tests are in Python modules that start with ``test_``, and each test function in those modules also starts with ``test_``. Each test will create a new temporary database file and populate some data that will be used in the tests. Write a SQL file to insert that data. .. code-block:: sql :caption: ``tests/data.sql`` INSERT INTO user (username, password) VALUES ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'), ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79'); INSERT INTO post (title, body, author_id, created) VALUES ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00'); The ``app`` fixture will call the factory and pass ``test_config`` to configure the application and database for testing instead of using your local development configuration. .. code-block:: python :caption: ``tests/conftest.py`` import os import tempfile import pytest from flaskr import create_app from flaskr.db import get_db, init_db with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f: _data_sql = f.read().decode('utf8') @pytest.fixture def app(): db_fd, db_path = tempfile.mkstemp() app = create_app({ 'TESTING': True, 'DATABASE': db_path, }) with app.app_context(): init_db() get_db().executescript(_data_sql) yield app os.close(db_fd) os.unlink(db_path) @pytest.fixture def client(app): return app.test_client() @pytest.fixture def runner(app): return app.test_cli_runner() :func:`tempfile.mkstemp` creates and opens a temporary file, returning the file object and the path to it. The ``DATABASE`` path is overridden so it points to this temporary path instead of the instance folder. After setting the path, the database tables are created and the test data is inserted. After the test is over, the temporary file is closed and removed. :data:`TESTING` tells Flask that the app is in test mode. Flask changes some internal behavior so it's easier to test, and other extensions can also use the flag to make testing them easier. The ``client`` fixture calls :meth:`app.test_client() ` with the application object created by the ``app`` fixture. Tests will use the client to make requests to the application without running the server. The ``runner`` fixture is similar to ``client``. :meth:`app.test_cli_runner() ` creates a runner that can call the Click commands registered with the application. Pytest uses fixtures by matching their function names with the names of arguments in the test functions. For example, the ``test_hello`` function you'll write next takes a ``client`` argument. Pytest matches that with the ``client`` fixture function, calls it, and passes the returned value to the test function. Factory ------- There's not much to test about the factory itself. Most of the code will be executed for each test already, so if something fails the other tests will notice. The only behavior that can change is passing test config. If config is not passed, there should be some default configuration, otherwise the configuration should be overridden. .. code-block:: python :caption: ``tests/test_factory.py`` from flaskr import create_app def test_config(): assert not create_app().testing assert create_app({'TESTING': True}).testing def test_hello(client): response = client.get('/hello') assert response.data == b'Hello, World!' You added the ``hello`` route as an example when writing the factory at the beginning of the tutorial. It returns "Hello, World!", so the test checks that the response data matches. Database -------- Within an application context, ``get_db`` should return the same connection each time it's called. After the context, the connection should be closed. .. code-block:: python :caption: ``tests/test_db.py`` import sqlite3 import pytest from flaskr.db import get_db def test_get_close_db(app): with app.app_context(): db = get_db() assert db is get_db() with pytest.raises(sqlite3.ProgrammingError) as e: db.execute('SELECT 1') assert 'closed' in str(e.value) The ``init-db`` command should call the ``init_db`` function and output a message. .. code-block:: python :caption: ``tests/test_db.py`` def test_init_db_command(runner, monkeypatch): class Recorder(object): called = False def fake_init_db(): Recorder.called = True monkeypatch.setattr('flaskr.db.init_db', fake_init_db) result = runner.invoke(args=['init-db']) assert 'Initialized' in result.output assert Recorder.called This test uses Pytest's ``monkeypatch`` fixture to replace the ``init_db`` function with one that records that it's been called. The ``runner`` fixture you wrote above is used to call the ``init-db`` command by name. Authentication -------------- For most of the views, a user needs to be logged in. The easiest way to do this in tests is to make a ``POST`` request to the ``login`` view with the client. Rather than writing that out every time, you can write a class with methods to do that, and use a fixture to pass it the client for each test. .. code-block:: python :caption: ``tests/conftest.py`` class AuthActions(object): def __init__(self, client): self._client = client def login(self, username='test', password='test'): return self._client.post( '/auth/login', data={'username': username, 'password': password} ) def logout(self): return self._client.get('/auth/logout') @pytest.fixture def auth(client): return AuthActions(client) With the ``auth`` fixture, you can call ``auth.login()`` in a test to log in as the ``test`` user, which was inserted as part of the test data in the ``app`` fixture. The ``register`` view should render successfully on ``GET``. On ``POST`` with valid form data, it should redirect to the login URL and the user's data should be in the database. Invalid data should display error messages. .. code-block:: python :caption: ``tests/test_auth.py`` import pytest from flask import g, session from flaskr.db import get_db def test_register(client, app): assert client.get('/auth/register').status_code == 200 response = client.post( '/auth/register', data={'username': 'a', 'password': 'a'} ) assert 'http://localhost/auth/login' == response.headers['Location'] with app.app_context(): assert get_db().execute( "select * from user where username = 'a'", ).fetchone() is not None @pytest.mark.parametrize(('username', 'password', 'message'), ( ('', '', b'Username is required.'), ('a', '', b'Password is required.'), ('test', 'test', b'already registered'), )) def test_register_validate_input(client, username, password, message): response = client.post( '/auth/register', data={'username': username, 'password': password} ) assert message in response.data :meth:`client.get() ` makes a ``GET`` request and returns the :class:`Response` object returned by Flask. Similarly, :meth:`client.post() ` makes a ``POST`` request, converting the ``data`` dict into form data. To test that the page renders successfully, a simple request is made and checked for a ``200 OK`` :attr:`~Response.status_code`. If rendering failed, Flask would return a ``500 Internal Server Error`` code. :attr:`~Response.headers` will have a ``Location`` header with the login URL when the register view redirects to the login view. :attr:`~Response.data` contains the body of the response as bytes. If you expect a certain value to render on the page, check that it's in ``data``. Bytes must be compared to bytes. If you want to compare Unicode text, use :meth:`get_data(as_text=True) ` instead. ``pytest.mark.parametrize`` tells Pytest to run the same test function with different arguments. You use it here to test different invalid input and error messages without writing the same code three times. The tests for the ``login`` view are very similar to those for ``register``. Rather than testing the data in the database, :data:`session` should have ``user_id`` set after logging in. .. code-block:: python :caption: ``tests/test_auth.py`` def test_login(client, auth): assert client.get('/auth/login').status_code == 200 response = auth.login() assert response.headers['Location'] == 'http://localhost/' with client: client.get('/') assert session['user_id'] == 1 assert g.user['username'] == 'test' @pytest.mark.parametrize(('username', 'password', 'message'), ( ('a', 'test', b'Incorrect username.'), ('test', 'a', b'Incorrect password.'), )) def test_login_validate_input(auth, username, password, message): response = auth.login(username, password) assert message in response.data Using ``client`` in a ``with`` block allows accessing context variables such as :data:`session` after the response is returned. Normally, accessing ``session`` outside of a request would raise an error. Testing ``logout`` is the opposite of ``login``. :data:`session` should not contain ``user_id`` after logging out. .. code-block:: python :caption: ``tests/test_auth.py`` def test_logout(client, auth): auth.login() with client: auth.logout() assert 'user_id' not in session Blog ---- All the blog views use the ``auth`` fixture you wrote earlier. Call ``auth.login()`` and subsequent requests from the client will be logged in as the ``test`` user. The ``index`` view should display information about the post that was added with the test data. When logged in as the author, there should be a link to edit the post. You can also test some more authentication behavior while testing the ``index`` view. When not logged in, each page shows links to log in or register. When logged in, there's a link to log out. .. code-block:: python :caption: ``tests/test_blog.py`` import pytest from flaskr.db import get_db def test_index(client, auth): response = client.get('/') assert b"Log In" in response.data assert b"Register" in response.data auth.login() response = client.get('/') assert b'Log Out' in response.data assert b'test title' in response.data assert b'by test on 2018-01-01' in response.data assert b'test\nbody' in response.data assert b'href="/1/update"' in response.data A user must be logged in to access the ``create``, ``update``, and ``delete`` views. The logged in user must be the author of the post to access ``update`` and ``delete``, otherwise a ``403 Forbidden`` status is returned. If a ``post`` with the given ``id`` doesn't exist, ``update`` and ``delete`` should return ``404 Not Found``. .. code-block:: python :caption: ``tests/test_blog.py`` @pytest.mark.parametrize('path', ( '/create', '/1/update', '/1/delete', )) def test_login_required(client, path): response = client.post(path) assert response.headers['Location'] == 'http://localhost/auth/login' def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db = get_db() db.execute('UPDATE post SET author_id = 2 WHERE id = 1') db.commit() auth.login() # current user can't modify other user's post assert client.post('/1/update').status_code == 403 assert client.post('/1/delete').status_code == 403 # current user doesn't see edit link assert b'href="/1/update"' not in client.get('/').data @pytest.mark.parametrize('path', ( '/2/update', '/2/delete', )) def test_exists_required(client, auth, path): auth.login() assert client.post(path).status_code == 404 The ``create`` and ``update`` views should render and return a ``200 OK`` status for a ``GET`` request. When valid data is sent in a ``POST`` request, ``create`` should insert the new post data into the database, and ``update`` should modify the existing data. Both pages should show an error message on invalid data. .. code-block:: python :caption: ``tests/test_blog.py`` def test_create(client, auth, app): auth.login() assert client.get('/create').status_code == 200 client.post('/create', data={'title': 'created', 'body': ''}) with app.app_context(): db = get_db() count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0] assert count == 2 def test_update(client, auth, app): auth.login() assert client.get('/1/update').status_code == 200 client.post('/1/update', data={'title': 'updated', 'body': ''}) with app.app_context(): db = get_db() post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post['title'] == 'updated' @pytest.mark.parametrize('path', ( '/create', '/1/update', )) def test_create_update_validate(client, auth, path): auth.login() response = client.post(path, data={'title': '', 'body': ''}) assert b'Title is required.' in response.data The ``delete`` view should redirect to the index URL and the post should no longer exist in the database. .. code-block:: python :caption: ``tests/test_blog.py`` def test_delete(client, auth, app): auth.login() response = client.post('/1/delete') assert response.headers['Location'] == 'http://localhost/' with app.app_context(): db = get_db() post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post is None Running the Tests ----------------- Some extra configuration, which is not required but makes running tests with coverage less verbose, can be added to the project's ``setup.cfg`` file. .. code-block:: none :caption: ``setup.cfg`` [tool:pytest] testpaths = tests [coverage:run] branch = True source = flaskr To run the tests, use the ``pytest`` command. It will find and run all the test functions you've written. .. code-block:: none $ pytest ========================= test session starts ========================== platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0 rootdir: /home/user/Projects/flask-tutorial, inifile: setup.cfg collected 23 items tests/test_auth.py ........ [ 34%] tests/test_blog.py ............ [ 86%] tests/test_db.py .. [ 95%] tests/test_factory.py .. [100%] ====================== 24 passed in 0.64 seconds ======================= If any tests fail, pytest will show the error that was raised. You can run ``pytest -v`` to get a list of each test function rather than dots. To measure the code coverage of your tests, use the ``coverage`` command to run pytest instead of running it directly. .. code-block:: none $ coverage run -m pytest You can either view a simple coverage report in the terminal: .. code-block:: none $ coverage report Name Stmts Miss Branch BrPart Cover ------------------------------------------------------ flaskr/__init__.py 21 0 2 0 100% flaskr/auth.py 54 0 22 0 100% flaskr/blog.py 54 0 16 0 100% flaskr/db.py 24 0 4 0 100% ------------------------------------------------------ TOTAL 153 0 44 0 100% An HTML report allows you to see which lines were covered in each file: .. code-block:: none $ coverage html This generates files in the ``htmlcov`` directory. Open ``htmlcov/index.html`` in your browser to see the report. Continue to :doc:`deploy`. Flask-1.1.1/docs/tutorial/views.rst0000644000175000017500000002514513510701642017442 0ustar daviddavid00000000000000.. currentmodule:: flask Blueprints and Views ==================== A view function is the code you write to respond to requests to your application. Flask uses patterns to match the incoming request URL to the view that should handle it. The view returns data that Flask turns into an outgoing response. Flask can also go the other direction and generate a URL to a view based on its name and arguments. Create a Blueprint ------------------ A :class:`Blueprint` is a way to organize a group of related views and other code. Rather than registering views and other code directly with an application, they are registered with a blueprint. Then the blueprint is registered with the application when it is available in the factory function. Flaskr will have two blueprints, one for authentication functions and one for the blog posts functions. The code for each blueprint will go in a separate module. Since the blog needs to know about authentication, you'll write the authentication one first. .. code-block:: python :caption: ``flaskr/auth.py`` import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for ) from werkzeug.security import check_password_hash, generate_password_hash from flaskr.db import get_db bp = Blueprint('auth', __name__, url_prefix='/auth') This creates a :class:`Blueprint` named ``'auth'``. Like the application object, the blueprint needs to know where it's defined, so ``__name__`` is passed as the second argument. The ``url_prefix`` will be prepended to all the URLs associated with the blueprint. Import and register the blueprint from the factory using :meth:`app.register_blueprint() `. Place the new code at the end of the factory function before returning the app. .. code-block:: python :caption: ``flaskr/__init__.py`` def create_app(): app = ... # existing code omitted from . import auth app.register_blueprint(auth.bp) return app The authentication blueprint will have views to register new users and to log in and log out. The First View: Register ------------------------ When the user visits the ``/auth/register`` URL, the ``register`` view will return `HTML`_ with a form for them to fill out. When they submit the form, it will validate their input and either show the form again with an error message or create the new user and go to the login page. .. _HTML: https://developer.mozilla.org/docs/Web/HTML For now you will just write the view code. On the next page, you'll write templates to generate the HTML form. .. code-block:: python :caption: ``flaskr/auth.py`` @bp.route('/register', methods=('GET', 'POST')) def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif db.execute( 'SELECT id FROM user WHERE username = ?', (username,) ).fetchone() is not None: error = 'User {} is already registered.'.format(username) if error is None: db.execute( 'INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password)) ) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html') Here's what the ``register`` view function is doing: #. :meth:`@bp.route ` associates the URL ``/register`` with the ``register`` view function. When Flask receives a request to ``/auth/register``, it will call the ``register`` view and use the return value as the response. #. If the user submitted the form, :attr:`request.method ` will be ``'POST'``. In this case, start validating the input. #. :attr:`request.form ` is a special type of :class:`dict` mapping submitted form keys and values. The user will input their ``username`` and ``password``. #. Validate that ``username`` and ``password`` are not empty. #. Validate that ``username`` is not already registered by querying the database and checking if a result is returned. :meth:`db.execute ` takes a SQL query with ``?`` placeholders for any user input, and a tuple of values to replace the placeholders with. The database library will take care of escaping the values so you are not vulnerable to a *SQL injection attack*. :meth:`~sqlite3.Cursor.fetchone` returns one row from the query. If the query returned no results, it returns ``None``. Later, :meth:`~sqlite3.Cursor.fetchall` is used, which returns a list of all results. #. If validation succeeds, insert the new user data into the database. For security, passwords should never be stored in the database directly. Instead, :func:`~werkzeug.security.generate_password_hash` is used to securely hash the password, and that hash is stored. Since this query modifies data, :meth:`db.commit() ` needs to be called afterwards to save the changes. #. After storing the user, they are redirected to the login page. :func:`url_for` generates the URL for the login view based on its name. This is preferable to writing the URL directly as it allows you to change the URL later without changing all code that links to it. :func:`redirect` generates a redirect response to the generated URL. #. If validation fails, the error is shown to the user. :func:`flash` stores messages that can be retrieved when rendering the template. #. When the user initially navigates to ``auth/register``, or there was a validation error, an HTML page with the registration form should be shown. :func:`render_template` will render a template containing the HTML, which you'll write in the next step of the tutorial. Login ----- This view follows the same pattern as the ``register`` view above. .. code-block:: python :caption: ``flaskr/auth.py`` @bp.route('/login', methods=('GET', 'POST')) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone() if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html') There are a few differences from the ``register`` view: #. The user is queried first and stored in a variable for later use. #. :func:`~werkzeug.security.check_password_hash` hashes the submitted password in the same way as the stored hash and securely compares them. If they match, the password is valid. #. :data:`session` is a :class:`dict` that stores data across requests. When validation succeeds, the user's ``id`` is stored in a new session. The data is stored in a *cookie* that is sent to the browser, and the browser then sends it back with subsequent requests. Flask securely *signs* the data so that it can't be tampered with. Now that the user's ``id`` is stored in the :data:`session`, it will be available on subsequent requests. At the beginning of each request, if a user is logged in their information should be loaded and made available to other views. .. code-block:: python :caption: ``flaskr/auth.py`` @bp.before_app_request def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute( 'SELECT * FROM user WHERE id = ?', (user_id,) ).fetchone() :meth:`bp.before_app_request() ` registers a function that runs before the view function, no matter what URL is requested. ``load_logged_in_user`` checks if a user id is stored in the :data:`session` and gets that user's data from the database, storing it on :data:`g.user `, which lasts for the length of the request. If there is no user id, or if the id doesn't exist, ``g.user`` will be ``None``. Logout ------ To log out, you need to remove the user id from the :data:`session`. Then ``load_logged_in_user`` won't load a user on subsequent requests. .. code-block:: python :caption: ``flaskr/auth.py`` @bp.route('/logout') def logout(): session.clear() return redirect(url_for('index')) Require Authentication in Other Views ------------------------------------- Creating, editing, and deleting blog posts will require a user to be logged in. A *decorator* can be used to check this for each view it's applied to. .. code-block:: python :caption: ``flaskr/auth.py`` def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for('auth.login')) return view(**kwargs) return wrapped_view This decorator returns a new view function that wraps the original view it's applied to. The new function checks if a user is loaded and redirects to the login page otherwise. If a user is loaded the original view is called and continues normally. You'll use this decorator when writing the blog views. Endpoints and URLs ------------------ The :func:`url_for` function generates the URL to a view based on a name and arguments. The name associated with a view is also called the *endpoint*, and by default it's the same as the name of the view function. For example, the ``hello()`` view that was added to the app factory earlier in the tutorial has the name ``'hello'`` and can be linked to with ``url_for('hello')``. If it took an argument, which you'll see later, it would be linked to using ``url_for('hello', who='World')``. When using a blueprint, the name of the blueprint is prepended to the name of the function, so the endpoint for the ``login`` function you wrote above is ``'auth.login'`` because you added it to the ``'auth'`` blueprint. Continue to :doc:`templates`. Flask-1.1.1/docs/unicode.rst0000644000175000017500000001120013510701642016053 0ustar daviddavid00000000000000Unicode in Flask ================ Flask, like Jinja2 and Werkzeug, is totally Unicode based when it comes to text. Not only these libraries, also the majority of web related Python libraries that deal with text. If you don't know Unicode so far, you should probably read `The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets `_. This part of the documentation just tries to cover the very basics so that you have a pleasant experience with Unicode related things. Automatic Conversion -------------------- Flask has a few assumptions about your application (which you can change of course) that give you basic and painless Unicode support: - the encoding for text on your website is UTF-8 - internally you will always use Unicode exclusively for text except for literal strings with only ASCII character points. - encoding and decoding happens whenever you are talking over a protocol that requires bytes to be transmitted. So what does this mean to you? HTTP is based on bytes. Not only the protocol, also the system used to address documents on servers (so called URIs or URLs). However HTML which is usually transmitted on top of HTTP supports a large variety of character sets and which ones are used, are transmitted in an HTTP header. To not make this too complex Flask just assumes that if you are sending Unicode out you want it to be UTF-8 encoded. Flask will do the encoding and setting of the appropriate headers for you. The same is true if you are talking to databases with the help of SQLAlchemy or a similar ORM system. Some databases have a protocol that already transmits Unicode and if they do not, SQLAlchemy or your other ORM should take care of that. The Golden Rule --------------- So the rule of thumb: if you are not dealing with binary data, work with Unicode. What does working with Unicode in Python 2.x mean? - as long as you are using ASCII code points only (basically numbers, some special characters of Latin letters without umlauts or anything fancy) you can use regular string literals (``'Hello World'``). - if you need anything else than ASCII in a string you have to mark this string as Unicode string by prefixing it with a lowercase `u`. (like ``u'Hänsel und Gretel'``) - if you are using non-Unicode characters in your Python files you have to tell Python which encoding your file uses. Again, I recommend UTF-8 for this purpose. To tell the interpreter your encoding you can put the ``# -*- coding: utf-8 -*-`` into the first or second line of your Python source file. - Jinja is configured to decode the template files from UTF-8. So make sure to tell your editor to save the file as UTF-8 there as well. Encoding and Decoding Yourself ------------------------------ If you are talking with a filesystem or something that is not really based on Unicode you will have to ensure that you decode properly when working with Unicode interface. So for example if you want to load a file on the filesystem and embed it into a Jinja2 template you will have to decode it from the encoding of that file. Here the old problem that text files do not specify their encoding comes into play. So do yourself a favour and limit yourself to UTF-8 for text files as well. Anyways. To load such a file with Unicode you can use the built-in :meth:`str.decode` method:: def read_file(filename, charset='utf-8'): with open(filename, 'r') as f: return f.read().decode(charset) To go from Unicode into a specific charset such as UTF-8 you can use the :meth:`unicode.encode` method:: def write_file(filename, contents, charset='utf-8'): with open(filename, 'w') as f: f.write(contents.encode(charset)) Configuring Editors ------------------- Most editors save as UTF-8 by default nowadays but in case your editor is not configured to do this you have to change it. Here some common ways to set your editor to store as UTF-8: - Vim: put ``set enc=utf-8`` to your ``.vimrc`` file. - Emacs: either use an encoding cookie or put this into your ``.emacs`` file:: (prefer-coding-system 'utf-8) (setq default-buffer-file-coding-system 'utf-8) - Notepad++: 1. Go to *Settings -> Preferences ...* 2. Select the "New Document/Default Directory" tab 3. Select "UTF-8 without BOM" as encoding It is also recommended to use the Unix newline format, you can select it in the same panel but this is not a requirement. Flask-1.1.1/docs/upgrading.rst0000644000175000017500000004610713510701642016423 0ustar daviddavid00000000000000Upgrading 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 an 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: https://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 a 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-1.1.1/docs/views.rst0000644000175000017500000002017013510701642015570 0ustar daviddavid00000000000000.. _views: Pluggable Views =============== .. versionadded:: 0.7 Flask 0.7 introduces pluggable views inspired by the generic views from Django which are based on classes instead of functions. The main intention is that you can replace parts of the implementations and this way have customizable pluggable views. Basic Principle --------------- Consider you have a function that loads a list of objects from the database and renders into a template:: @app.route('/users/') def show_users(page): users = User.query.all() return render_template('users.html', users=users) This is simple and flexible, but if you want to provide this view in a generic fashion that can be adapted to other models and templates as well you might want more flexibility. This is where pluggable class-based views come into place. As the first step to convert this into a class based view you would do this:: from flask.views import View class ShowUsers(View): def dispatch_request(self): users = User.query.all() return render_template('users.html', objects=users) app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users')) As you can see what you have to do is to create a subclass of :class:`flask.views.View` and implement :meth:`~flask.views.View.dispatch_request`. Then we have to convert that class into an actual view function by using the :meth:`~flask.views.View.as_view` class method. The string you pass to that function is the name of the endpoint that view will then have. But this by itself is not helpful, so let's refactor the code a bit:: from flask.views import View class ListView(View): def get_template_name(self): raise NotImplementedError() def render_template(self, context): return render_template(self.get_template_name(), **context) def dispatch_request(self): context = {'objects': self.get_objects()} return self.render_template(context) class UserView(ListView): def get_template_name(self): return 'users.html' def get_objects(self): return User.query.all() This of course is not that helpful for such a small example, but it's good enough to explain the basic principle. When you have a class-based view the question comes up what ``self`` points to. The way this works is that whenever the request is dispatched a new instance of the class is created and the :meth:`~flask.views.View.dispatch_request` method is called with the parameters from the URL rule. The class itself is instantiated with the parameters passed to the :meth:`~flask.views.View.as_view` function. For instance you can write a class like this:: class RenderTemplateView(View): def __init__(self, template_name): self.template_name = template_name def dispatch_request(self): return render_template(self.template_name) And then you can register it like this:: app.add_url_rule('/about', view_func=RenderTemplateView.as_view( 'about_page', template_name='about.html')) Method Hints ------------ Pluggable views are attached to the application like a regular function by either using :func:`~flask.Flask.route` or better :meth:`~flask.Flask.add_url_rule`. That however also means that you would have to provide the names of the HTTP methods the view supports when you attach this. In order to move that information to the class you can provide a :attr:`~flask.views.View.methods` attribute that has this information:: class MyView(View): methods = ['GET', 'POST'] def dispatch_request(self): if request.method == 'POST': ... ... app.add_url_rule('/myview', view_func=MyView.as_view('myview')) Method Based Dispatching ------------------------ For RESTful APIs it's especially helpful to execute a different function for each HTTP method. With the :class:`flask.views.MethodView` you can easily do that. Each HTTP method maps to a function with the same name (just in lowercase):: from flask.views import MethodView class UserAPI(MethodView): def get(self): users = User.query.all() ... def post(self): user = User.from_form_data(request.form) ... app.add_url_rule('/users/', view_func=UserAPI.as_view('users')) That way you also don't have to provide the :attr:`~flask.views.View.methods` attribute. It's automatically set based on the methods defined in the class. Decorating Views ---------------- Since the view class itself is not the view function that is added to the routing system it does not make much sense to decorate the class itself. Instead you either have to decorate the return value of :meth:`~flask.views.View.as_view` by hand:: def user_required(f): """Checks whether user is logged in or raises error 401.""" def decorator(*args, **kwargs): if not g.user: abort(401) return f(*args, **kwargs) return decorator view = user_required(UserAPI.as_view('users')) app.add_url_rule('/users/', view_func=view) Starting with Flask 0.8 there is also an alternative way where you can specify a list of decorators to apply in the class declaration:: class UserAPI(MethodView): decorators = [user_required] Due to the implicit self from the caller's perspective you cannot use regular view decorators on the individual methods of the view however, keep this in mind. Method Views for APIs --------------------- Web APIs are often working very closely with HTTP verbs so it makes a lot of sense to implement such an API based on the :class:`~flask.views.MethodView`. That said, you will notice that the API will require different URL rules that go to the same method view most of the time. For instance consider that you are exposing a user object on the web: =============== =============== ====================================== URL Method Description --------------- --------------- -------------------------------------- ``/users/`` ``GET`` Gives a list of all users ``/users/`` ``POST`` Creates a new user ``/users/`` ``GET`` Shows a single user ``/users/`` ``PUT`` Updates a single user ``/users/`` ``DELETE`` Deletes a single user =============== =============== ====================================== So how would you go about doing that with the :class:`~flask.views.MethodView`? The trick is to take advantage of the fact that you can provide multiple rules to the same view. Let's assume for the moment the view would look like this:: class UserAPI(MethodView): def get(self, user_id): if user_id is None: # return a list of users pass else: # expose a single user pass def post(self): # create a new user pass def delete(self, user_id): # delete a single user pass def put(self, user_id): # update a single user pass So how do we hook this up with the routing system? By adding two rules and explicitly mentioning the methods for each:: user_view = UserAPI.as_view('user_api') app.add_url_rule('/users/', defaults={'user_id': None}, view_func=user_view, methods=['GET',]) app.add_url_rule('/users/', view_func=user_view, methods=['POST',]) app.add_url_rule('/users/', view_func=user_view, methods=['GET', 'PUT', 'DELETE']) If you have a lot of APIs that look similar you can refactor that registration code:: def register_api(view, endpoint, url, pk='id', pk_type='int'): view_func = view.as_view(endpoint) app.add_url_rule(url, defaults={pk: None}, view_func=view_func, methods=['GET',]) app.add_url_rule(url, view_func=view_func, methods=['POST',]) app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func, methods=['GET', 'PUT', 'DELETE']) register_api(UserAPI, 'user_api', '/users/', pk='user_id') Flask-1.1.1/examples/0000755000175000017500000000000013510702200014556 5ustar daviddavid00000000000000Flask-1.1.1/examples/javascript/0000755000175000017500000000000013510702200016724 5ustar daviddavid00000000000000Flask-1.1.1/examples/javascript/.gitignore0000644000175000017500000000016613510701642020730 0ustar daviddavid00000000000000venv/ *.pyc __pycache__/ instance/ .cache/ .pytest_cache/ .coverage htmlcov/ dist/ build/ *.egg-info/ .idea/ *.swp *~ Flask-1.1.1/examples/javascript/LICENSE0000644000175000017500000000304713510701642017746 0ustar daviddavid00000000000000Copyright © 2010 by the Pallets team. 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. * Neither the name of the copyright holder nor the names of its contributors may 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 HOLDER 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-1.1.1/examples/javascript/MANIFEST.in0000644000175000017500000000011413510701642020467 0ustar daviddavid00000000000000include LICENSE graft js_example/templates graft tests global-exclude *.pyc Flask-1.1.1/examples/javascript/README.rst0000644000175000017500000000201013510701642020415 0ustar daviddavid00000000000000JavaScript Ajax Example ======================= Demonstrates how to post form data and process a JSON response using JavaScript. This allows making requests without navigating away from the page. Demonstrates using |XMLHttpRequest|_, |fetch|_, and |jQuery.ajax|_. See the `Flask docs`_ about jQuery and Ajax. .. |XMLHttpRequest| replace:: ``XMLHttpRequest`` .. _XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest .. |fetch| replace:: ``fetch`` .. _fetch: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch .. |jQuery.ajax| replace:: ``jQuery.ajax`` .. _jQuery.ajax: https://api.jquery.com/jQuery.ajax/ .. _Flask docs: http://flask.pocoo.org/docs/patterns/jquery/ Install ------- :: $ python3 -m venv venv $ . venv/bin/activate $ pip install -e . Run --- :: $ export FLASK_APP=js_example $ flask run Open http://127.0.0.1:5000 in a browser. Test ---- :: $ pip install -e '.[test]' $ coverage run -m pytest $ coverage report Flask-1.1.1/examples/javascript/js_example/0000755000175000017500000000000013510702200021053 5ustar daviddavid00000000000000Flask-1.1.1/examples/javascript/js_example/__init__.py0000644000175000017500000000011513510701642023172 0ustar daviddavid00000000000000from flask import Flask app = Flask(__name__) from js_example import views Flask-1.1.1/examples/javascript/js_example/templates/0000755000175000017500000000000013510702200023051 5ustar daviddavid00000000000000Flask-1.1.1/examples/javascript/js_example/templates/base.html0000644000175000017500000000225113510701642024662 0ustar daviddavid00000000000000 JavaScript Example

{% block intro %}{% endblock %}


+
= {% block script %}{% endblock %} Flask-1.1.1/examples/javascript/js_example/templates/fetch.html0000644000175000017500000000210613510701642025040 0ustar daviddavid00000000000000{% extends 'base.html' %} {% block intro %} fetch is the new plain JavaScript way to make requests. It's supported in all modern browsers except IE, which requires a polyfill. {% endblock %} {% block script %} {% endblock %} Flask-1.1.1/examples/javascript/js_example/templates/jquery.html0000644000175000017500000000123213510701642025265 0ustar daviddavid00000000000000{% extends 'base.html' %} {% block intro %} jQuery is a popular library that adds cross browser APIs for common tasks. However, it requires loading an extra library. {% endblock %} {% block script %} {% endblock %} Flask-1.1.1/examples/javascript/js_example/templates/plain.html0000644000175000017500000000150013510701642025047 0ustar daviddavid00000000000000{% extends 'base.html' %} {% block intro %} XMLHttpRequest is the plain JavaScript way to make requests. It's natively supported by all browsers. {% endblock %} {% block script %} {% endblock %} Flask-1.1.1/examples/javascript/js_example/views.py0000644000175000017500000000070113510701642022571 0ustar daviddavid00000000000000from flask import jsonify from flask import render_template from flask import request from js_example import app @app.route("/", defaults={"js": "plain"}) @app.route("/") def index(js): return render_template("{0}.html".format(js), js=js) @app.route("/add", methods=["POST"]) def add(): a = request.form.get("a", 0, type=float) b = request.form.get("b", 0, type=float) return jsonify(result=a + b) Flask-1.1.1/examples/javascript/setup.cfg0000644000175000017500000000023113510701642020552 0ustar daviddavid00000000000000[metadata] license_file = LICENSE [bdist_wheel] universal = True [tool:pytest] testpaths = tests [coverage:run] branch = True source = js_example Flask-1.1.1/examples/javascript/setup.py0000644000175000017500000000117513510701642020453 0ustar daviddavid00000000000000import io from setuptools import find_packages from setuptools import setup with io.open("README.rst", "rt", encoding="utf8") as f: readme = f.read() setup( name="js_example", version="1.0.0", url="http://flask.pocoo.org/docs/patterns/jquery/", license="BSD", maintainer="Pallets team", maintainer_email="contact@palletsprojects.com", description="Demonstrates making Ajax requests to Flask.", long_description=readme, packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=["flask"], extras_require={"test": ["pytest", "coverage", "blinker"]}, ) Flask-1.1.1/examples/javascript/tests/0000755000175000017500000000000013510702200020066 5ustar daviddavid00000000000000Flask-1.1.1/examples/javascript/tests/conftest.py0000644000175000017500000000033013510701642022272 0ustar daviddavid00000000000000import pytest from js_example import app @pytest.fixture(name="app") def fixture_app(): app.testing = True yield app app.testing = False @pytest.fixture def client(app): return app.test_client() Flask-1.1.1/examples/javascript/tests/test_js_example.py0000644000175000017500000000133113510701642023635 0ustar daviddavid00000000000000import pytest from flask import template_rendered @pytest.mark.parametrize( ("path", "template_name"), ( ("/", "plain.html"), ("/plain", "plain.html"), ("/fetch", "fetch.html"), ("/jquery", "jquery.html"), ), ) def test_index(app, client, path, template_name): def check(sender, template, context): assert template.name == template_name with template_rendered.connected_to(check, app): client.get(path) @pytest.mark.parametrize( ("a", "b", "result"), ((2, 3, 5), (2.5, 3, 5.5), (2, None, 2), (2, "b", 2)) ) def test_add(client, a, b, result): response = client.post("/add", data={"a": a, "b": b}) assert response.get_json()["result"] == result Flask-1.1.1/examples/tutorial/0000755000175000017500000000000013510702200016421 5ustar daviddavid00000000000000Flask-1.1.1/examples/tutorial/.gitignore0000644000175000017500000000016613510701642020425 0ustar daviddavid00000000000000venv/ *.pyc __pycache__/ instance/ .cache/ .pytest_cache/ .coverage htmlcov/ dist/ build/ *.egg-info/ .idea/ *.swp *~ Flask-1.1.1/examples/tutorial/LICENSE0000644000175000017500000000304713510701642017443 0ustar daviddavid00000000000000Copyright © 2010 by the Pallets team. 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. * Neither the name of the copyright holder nor the names of its contributors may 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 HOLDER 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-1.1.1/examples/tutorial/MANIFEST.in0000644000175000017500000000016613510701642020173 0ustar daviddavid00000000000000include LICENSE include flaskr/schema.sql graft flaskr/static graft flaskr/templates graft tests global-exclude *.pyc Flask-1.1.1/examples/tutorial/README.rst0000644000175000017500000000256513510701642020131 0ustar daviddavid00000000000000Flaskr ====== The basic blog app built in the Flask `tutorial`_. .. _tutorial: http://flask.pocoo.org/docs/tutorial/ Install ------- **Be sure to use the same version of the code as the version of the docs you're reading.** You probably want the latest tagged version, but the default Git version is the master branch. :: # clone the repository $ git clone https://github.com/pallets/flask $ cd flask # checkout the correct version $ git tag # shows the tagged versions $ git checkout latest-tag-found-above $ cd examples/tutorial Create a virtualenv and activate it:: $ python3 -m venv venv $ . venv/bin/activate Or on Windows cmd:: $ py -3 -m venv venv $ venv\Scripts\activate.bat Install Flaskr:: $ pip install -e . Or if you are using the master branch, install Flask from source before installing Flaskr:: $ pip install -e ../.. $ pip install -e . Run --- :: $ export FLASK_APP=flaskr $ export FLASK_ENV=development $ flask init-db $ flask run Or on Windows cmd:: > set FLASK_APP=flaskr > set FLASK_ENV=development > flask init-db > flask run Open http://127.0.0.1:5000 in a browser. Test ---- :: $ pip install '.[test]' $ pytest Run with coverage report:: $ coverage run -m pytest $ coverage report $ coverage html # open htmlcov/index.html in a browser Flask-1.1.1/examples/tutorial/flaskr/0000755000175000017500000000000013510702200017703 5ustar daviddavid00000000000000Flask-1.1.1/examples/tutorial/flaskr/__init__.py0000644000175000017500000000262613510701642022033 0ustar daviddavid00000000000000import os from flask import Flask def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # a default secret that should be overridden by instance config SECRET_KEY="dev", # store the database in the instance folder DATABASE=os.path.join(app.instance_path, "flaskr.sqlite"), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.route("/hello") def hello(): return "Hello, World!" # register the database commands from flaskr import db db.init_app(app) # apply the blueprints to the app from flaskr import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make url_for('index') == url_for('blog.index') # in another app, you might define a separate main index here with # app.route, while giving the blog blueprint a url_prefix, but for # the tutorial the blog will be the main index app.add_url_rule("/", endpoint="index") return app Flask-1.1.1/examples/tutorial/flaskr/auth.py0000644000175000017500000000631313510701642021232 0ustar daviddavid00000000000000import functools from flask import Blueprint from flask import flash from flask import g from flask import redirect from flask import render_template from flask import request from flask import session from flask import url_for from werkzeug.security import check_password_hash from werkzeug.security import generate_password_hash from flaskr.db import get_db bp = Blueprint("auth", __name__, url_prefix="/auth") def login_required(view): """View decorator that redirects anonymous users to the login page.""" @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for("auth.login")) return view(**kwargs) return wrapped_view @bp.before_app_request def load_logged_in_user(): """If a user id is stored in the session, load the user object from the database into ``g.user``.""" user_id = session.get("user_id") if user_id is None: g.user = None else: g.user = ( get_db().execute("SELECT * FROM user WHERE id = ?", (user_id,)).fetchone() ) @bp.route("/register", methods=("GET", "POST")) def register(): """Register a new user. Validates that the username is not already taken. Hashes the password for security. """ if request.method == "POST": username = request.form["username"] password = request.form["password"] db = get_db() error = None if not username: error = "Username is required." elif not password: error = "Password is required." elif ( db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone() is not None ): error = "User {0} is already registered.".format(username) if error is None: # the name is available, store it in the database and go to # the login page db.execute( "INSERT INTO user (username, password) VALUES (?, ?)", (username, generate_password_hash(password)), ) db.commit() return redirect(url_for("auth.login")) flash(error) return render_template("auth/register.html") @bp.route("/login", methods=("GET", "POST")) def login(): """Log in a registered user by adding the user id to the session.""" if request.method == "POST": username = request.form["username"] password = request.form["password"] db = get_db() error = None user = db.execute( "SELECT * FROM user WHERE username = ?", (username,) ).fetchone() if user is None: error = "Incorrect username." elif not check_password_hash(user["password"], password): error = "Incorrect password." if error is None: # store the user id in a new session and return to the index session.clear() session["user_id"] = user["id"] return redirect(url_for("index")) flash(error) return render_template("auth/login.html") @bp.route("/logout") def logout(): """Clear the current session, including the stored user id.""" session.clear() return redirect(url_for("index")) Flask-1.1.1/examples/tutorial/flaskr/blog.py0000644000175000017500000000637613510701642021225 0ustar daviddavid00000000000000from flask import Blueprint from flask import flash from flask import g from flask import redirect from flask import render_template from flask import request from flask import url_for from werkzeug.exceptions import abort from flaskr.auth import login_required from flaskr.db import get_db bp = Blueprint("blog", __name__) @bp.route("/") def index(): """Show all the posts, most recent first.""" db = get_db() posts = db.execute( "SELECT p.id, title, body, created, author_id, username" " FROM post p JOIN user u ON p.author_id = u.id" " ORDER BY created DESC" ).fetchall() return render_template("blog/index.html", posts=posts) def get_post(id, check_author=True): """Get a post and its author by id. Checks that the id exists and optionally that the current user is the author. :param id: id of post to get :param check_author: require the current user to be the author :return: the post with author information :raise 404: if a post with the given id doesn't exist :raise 403: if the current user isn't the author """ post = ( get_db() .execute( "SELECT p.id, title, body, created, author_id, username" " FROM post p JOIN user u ON p.author_id = u.id" " WHERE p.id = ?", (id,), ) .fetchone() ) if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post["author_id"] != g.user["id"]: abort(403) return post @bp.route("/create", methods=("GET", "POST")) @login_required def create(): """Create a new post for the current user.""" if request.method == "POST": title = request.form["title"] body = request.form["body"] error = None if not title: error = "Title is required." if error is not None: flash(error) else: db = get_db() db.execute( "INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)", (title, body, g.user["id"]), ) db.commit() return redirect(url_for("blog.index")) return render_template("blog/create.html") @bp.route("//update", methods=("GET", "POST")) @login_required def update(id): """Update a post if the current user is the author.""" post = get_post(id) if request.method == "POST": title = request.form["title"] body = request.form["body"] error = None if not title: error = "Title is required." if error is not None: flash(error) else: db = get_db() db.execute( "UPDATE post SET title = ?, body = ? WHERE id = ?", (title, body, id) ) db.commit() return redirect(url_for("blog.index")) return render_template("blog/update.html", post=post) @bp.route("//delete", methods=("POST",)) @login_required def delete(id): """Delete a post. Ensures that the post exists and that the logged in user is the author of the post. """ get_post(id) db = get_db() db.execute("DELETE FROM post WHERE id = ?", (id,)) db.commit() return redirect(url_for("blog.index")) Flask-1.1.1/examples/tutorial/flaskr/db.py0000644000175000017500000000234613510701642020660 0ustar daviddavid00000000000000import sqlite3 import click from flask import current_app from flask import g from flask.cli import with_appcontext def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again. """ if "db" not in g: g.db = sqlite3.connect( current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sqlite3.Row return g.db def close_db(e=None): """If this request connected to the database, close the connection. """ db = g.pop("db", None) if db is not None: db.close() def init_db(): """Clear existing data and create new tables.""" db = get_db() with current_app.open_resource("schema.sql") as f: db.executescript(f.read().decode("utf8")) @click.command("init-db") @with_appcontext def init_db_command(): """Clear existing data and create new tables.""" init_db() click.echo("Initialized the database.") def init_app(app): """Register database functions with the Flask app. This is called by the application factory. """ app.teardown_appcontext(close_db) app.cli.add_command(init_db_command) Flask-1.1.1/examples/tutorial/flaskr/schema.sql0000644000175000017500000000076213510701642021702 0ustar daviddavid00000000000000-- Initialize the database. -- Drop any existing data and create empty tables. DROP TABLE IF EXISTS user; DROP TABLE IF EXISTS post; CREATE TABLE user ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL ); CREATE TABLE post ( id INTEGER PRIMARY KEY AUTOINCREMENT, author_id INTEGER NOT NULL, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, title TEXT NOT NULL, body TEXT NOT NULL, FOREIGN KEY (author_id) REFERENCES user (id) ); Flask-1.1.1/examples/tutorial/flaskr/static/0000755000175000017500000000000013510702200021172 5ustar daviddavid00000000000000Flask-1.1.1/examples/tutorial/flaskr/static/style.css0000644000175000017500000000324013510701642023054 0ustar daviddavid00000000000000html { font-family: sans-serif; background: #eee; padding: 1rem; } body { max-width: 960px; margin: 0 auto; background: white; } h1, h2, h3, h4, h5, h6 { font-family: serif; color: #377ba8; margin: 1rem 0; } a { color: #377ba8; } hr { border: none; border-top: 1px solid lightgray; } nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; } nav h1 { flex: auto; margin: 0; } nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; } nav ul { display: flex; list-style: none; margin: 0; padding: 0; } nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; } .content { padding: 0 1rem 1rem; } .content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; } .content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; } .flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; } .post > header { display: flex; align-items: flex-end; font-size: 0.85em; } .post > header > div:first-of-type { flex: auto; } .post > header h1 { font-size: 1.5em; margin-bottom: 0; } .post .about { color: slategray; font-style: italic; } .post .body { white-space: pre-line; } .content:last-child { margin-bottom: 0; } .content form { margin: 1em 0; display: flex; flex-direction: column; } .content label { font-weight: bold; margin-bottom: 0.5em; } .content input, .content textarea { margin-bottom: 1em; } .content textarea { min-height: 12em; resize: vertical; } input.danger { color: #cc2f2e; } input[type=submit] { align-self: start; min-width: 10em; } Flask-1.1.1/examples/tutorial/flaskr/templates/0000755000175000017500000000000013510702200021701 5ustar daviddavid00000000000000Flask-1.1.1/examples/tutorial/flaskr/templates/auth/0000755000175000017500000000000013510702200022642 5ustar daviddavid00000000000000Flask-1.1.1/examples/tutorial/flaskr/templates/auth/login.html0000644000175000017500000000065013510701642024652 0ustar daviddavid00000000000000{% extends 'base.html' %} {% block header %}

{% block title %}Log In{% endblock %}

{% endblock %} {% block content %}
{% endblock %} Flask-1.1.1/examples/tutorial/flaskr/templates/auth/register.html0000644000175000017500000000065413510701642025372 0ustar daviddavid00000000000000{% extends 'base.html' %} {% block header %}

{% block title %}Register{% endblock %}

{% endblock %} {% block content %}
{% endblock %} Flask-1.1.1/examples/tutorial/flaskr/templates/base.html0000644000175000017500000000136013510701642023512 0ustar daviddavid00000000000000 {% block title %}{% endblock %} - Flaskr
{% block header %}{% endblock %}
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %} {% block content %}{% endblock %}
Flask-1.1.1/examples/tutorial/flaskr/templates/blog/0000755000175000017500000000000013510702200022624 5ustar daviddavid00000000000000Flask-1.1.1/examples/tutorial/flaskr/templates/blog/create.html0000644000175000017500000000067713510701642025000 0ustar daviddavid00000000000000{% extends 'base.html' %} {% block header %}

{% block title %}New Post{% endblock %}

{% endblock %} {% block content %}
{% endblock %} Flask-1.1.1/examples/tutorial/flaskr/templates/blog/index.html0000644000175000017500000000142613510701642024635 0ustar daviddavid00000000000000{% extends 'base.html' %} {% block header %}

{% block title %}Posts{% endblock %}

{% if g.user %} New {% endif %} {% endblock %} {% block content %} {% for post in posts %}

{{ post['title'] }}

by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}
{% if g.user['id'] == post['author_id'] %} Edit {% endif %}

{{ post['body'] }}

{% if not loop.last %}
{% endif %} {% endfor %} {% endblock %} Flask-1.1.1/examples/tutorial/flaskr/templates/blog/update.html0000644000175000017500000000126213510701642025006 0ustar daviddavid00000000000000{% extends 'base.html' %} {% block header %}

{% block title %}Edit "{{ post['title'] }}"{% endblock %}

{% endblock %} {% block content %}

{% endblock %} Flask-1.1.1/examples/tutorial/setup.cfg0000644000175000017500000000022513510701642020252 0ustar daviddavid00000000000000[metadata] license_file = LICENSE [bdist_wheel] universal = True [tool:pytest] testpaths = tests [coverage:run] branch = True source = flaskr Flask-1.1.1/examples/tutorial/setup.py0000644000175000017500000000115313510701642020144 0ustar daviddavid00000000000000import io from setuptools import find_packages from setuptools import setup with io.open("README.rst", "rt", encoding="utf8") as f: readme = f.read() setup( name="flaskr", version="1.0.0", url="http://flask.pocoo.org/docs/tutorial/", license="BSD", maintainer="Pallets team", maintainer_email="contact@palletsprojects.com", description="The basic blog app built in the Flask tutorial.", long_description=readme, packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=["flask"], extras_require={"test": ["pytest", "coverage"]}, ) Flask-1.1.1/examples/tutorial/tests/0000755000175000017500000000000013510702200017563 5ustar daviddavid00000000000000Flask-1.1.1/examples/tutorial/tests/conftest.py0000644000175000017500000000266613510701642022005 0ustar daviddavid00000000000000import os import tempfile import pytest from flaskr import create_app from flaskr.db import get_db from flaskr.db import init_db # read in SQL for populating test data with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f: _data_sql = f.read().decode("utf8") @pytest.fixture def app(): """Create and configure a new app instance for each test.""" # create a temporary file to isolate the database for each test db_fd, db_path = tempfile.mkstemp() # create the app with common test config app = create_app({"TESTING": True, "DATABASE": db_path}) # create the database and load test data with app.app_context(): init_db() get_db().executescript(_data_sql) yield app # close and remove the temporary database os.close(db_fd) os.unlink(db_path) @pytest.fixture def client(app): """A test client for the app.""" return app.test_client() @pytest.fixture def runner(app): """A test runner for the app's Click commands.""" return app.test_cli_runner() class AuthActions(object): def __init__(self, client): self._client = client def login(self, username="test", password="test"): return self._client.post( "/auth/login", data={"username": username, "password": password} ) def logout(self): return self._client.get("/auth/logout") @pytest.fixture def auth(client): return AuthActions(client) Flask-1.1.1/examples/tutorial/tests/data.sql0000644000175000017500000000061213510701642021225 0ustar daviddavid00000000000000INSERT INTO user (username, password) VALUES ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'), ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79'); INSERT INTO post (title, body, author_id, created) VALUES ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00'); Flask-1.1.1/examples/tutorial/tests/test_auth.py0000644000175000017500000000406613510701642022154 0ustar daviddavid00000000000000import pytest from flask import g from flask import session from flaskr.db import get_db def test_register(client, app): # test that viewing the page renders without template errors assert client.get("/auth/register").status_code == 200 # test that successful registration redirects to the login page response = client.post("/auth/register", data={"username": "a", "password": "a"}) assert "http://localhost/auth/login" == response.headers["Location"] # test that the user was inserted into the database with app.app_context(): assert ( get_db().execute("select * from user where username = 'a'").fetchone() is not None ) @pytest.mark.parametrize( ("username", "password", "message"), ( ("", "", b"Username is required."), ("a", "", b"Password is required."), ("test", "test", b"already registered"), ), ) def test_register_validate_input(client, username, password, message): response = client.post( "/auth/register", data={"username": username, "password": password} ) assert message in response.data def test_login(client, auth): # test that viewing the page renders without template errors assert client.get("/auth/login").status_code == 200 # test that successful login redirects to the index page response = auth.login() assert response.headers["Location"] == "http://localhost/" # login request set the user_id in the session # check that the user is loaded from the session with client: client.get("/") assert session["user_id"] == 1 assert g.user["username"] == "test" @pytest.mark.parametrize( ("username", "password", "message"), (("a", "test", b"Incorrect username."), ("test", "a", b"Incorrect password.")), ) def test_login_validate_input(auth, username, password, message): response = auth.login(username, password) assert message in response.data def test_logout(client, auth): auth.login() with client: auth.logout() assert "user_id" not in session Flask-1.1.1/examples/tutorial/tests/test_blog.py0000644000175000017500000000474713510701642022144 0ustar daviddavid00000000000000import pytest from flaskr.db import get_db def test_index(client, auth): response = client.get("/") assert b"Log In" in response.data assert b"Register" in response.data auth.login() response = client.get("/") assert b"test title" in response.data assert b"by test on 2018-01-01" in response.data assert b"test\nbody" in response.data assert b'href="/1/update"' in response.data @pytest.mark.parametrize("path", ("/create", "/1/update", "/1/delete")) def test_login_required(client, path): response = client.post(path) assert response.headers["Location"] == "http://localhost/auth/login" def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db = get_db() db.execute("UPDATE post SET author_id = 2 WHERE id = 1") db.commit() auth.login() # current user can't modify other user's post assert client.post("/1/update").status_code == 403 assert client.post("/1/delete").status_code == 403 # current user doesn't see edit link assert b'href="/1/update"' not in client.get("/").data @pytest.mark.parametrize("path", ("/2/update", "/2/delete")) def test_exists_required(client, auth, path): auth.login() assert client.post(path).status_code == 404 def test_create(client, auth, app): auth.login() assert client.get("/create").status_code == 200 client.post("/create", data={"title": "created", "body": ""}) with app.app_context(): db = get_db() count = db.execute("SELECT COUNT(id) FROM post").fetchone()[0] assert count == 2 def test_update(client, auth, app): auth.login() assert client.get("/1/update").status_code == 200 client.post("/1/update", data={"title": "updated", "body": ""}) with app.app_context(): db = get_db() post = db.execute("SELECT * FROM post WHERE id = 1").fetchone() assert post["title"] == "updated" @pytest.mark.parametrize("path", ("/create", "/1/update")) def test_create_update_validate(client, auth, path): auth.login() response = client.post(path, data={"title": "", "body": ""}) assert b"Title is required." in response.data def test_delete(client, auth, app): auth.login() response = client.post("/1/delete") assert response.headers["Location"] == "http://localhost/" with app.app_context(): db = get_db() post = db.execute("SELECT * FROM post WHERE id = 1").fetchone() assert post is None Flask-1.1.1/examples/tutorial/tests/test_db.py0000644000175000017500000000116013510701642021570 0ustar daviddavid00000000000000import sqlite3 import pytest from flaskr.db import get_db def test_get_close_db(app): with app.app_context(): db = get_db() assert db is get_db() with pytest.raises(sqlite3.ProgrammingError) as e: db.execute("SELECT 1") assert "closed" in str(e.value) def test_init_db_command(runner, monkeypatch): class Recorder(object): called = False def fake_init_db(): Recorder.called = True monkeypatch.setattr("flaskr.db.init_db", fake_init_db) result = runner.invoke(args=["init-db"]) assert "Initialized" in result.output assert Recorder.called Flask-1.1.1/examples/tutorial/tests/test_factory.py0000644000175000017500000000045213510701642022655 0ustar daviddavid00000000000000from flaskr import create_app def test_config(): """Test create_app without passing test config.""" assert not create_app().testing assert create_app({"TESTING": True}).testing def test_hello(client): response = client.get("/hello") assert response.data == b"Hello, World!" Flask-1.1.1/setup.cfg0000644000175000017500000000074013510702200014562 0ustar daviddavid00000000000000[metadata] license_file = LICENSE.rst [bdist_wheel] universal = true [tool:pytest] testpaths = tests [coverage:run] branch = True source = flask tests [coverage:paths] source = src/flask .tox/*/lib/python*/site-packages/flask .tox/*/site-packages/flask [flake8] select = B, E, F, W, B9 ignore = E203 E402 E501 E722 W503 max-line-length = 80 per-file-ignores = **/__init__.py: F401 src/flask/_compat.py: E731, B301, F401 [egg_info] tag_build = tag_date = 0 Flask-1.1.1/setup.py0000644000175000017500000000506313510702163014466 0ustar daviddavid00000000000000import io import re from setuptools import find_packages from setuptools import setup with io.open("README.rst", "rt", encoding="utf8") as f: readme = f.read() with io.open("src/flask/__init__.py", "rt", encoding="utf8") as f: version = re.search(r'__version__ = "(.*?)"', f.read()).group(1) setup( name="Flask", version=version, url="https://palletsprojects.com/p/flask/", project_urls={ "Documentation": "https://flask.palletsprojects.com/", "Code": "https://github.com/pallets/flask", "Issue tracker": "https://github.com/pallets/flask/issues", }, license="BSD-3-Clause", author="Armin Ronacher", author_email="armin.ronacher@active-4.com", maintainer="Pallets", maintainer_email="contact@palletsprojects.com", description="A simple framework for building complex web applications.", long_description=readme, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Flask", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", "Topic :: Software Development :: Libraries :: Application Frameworks", "Topic :: Software Development :: Libraries :: Python Modules", ], packages=find_packages("src"), package_dir={"": "src"}, include_package_data=True, python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*", install_requires=[ "Werkzeug>=0.15", "Jinja2>=2.10.1", "itsdangerous>=0.24", "click>=5.1", ], extras_require={ "dotenv": ["python-dotenv"], "dev": [ "pytest", "coverage", "tox", "sphinx", "pallets-sphinx-themes", "sphinxcontrib-log-cabinet", "sphinx-issues", ], "docs": [ "sphinx", "pallets-sphinx-themes", "sphinxcontrib-log-cabinet", "sphinx-issues", ], }, entry_points={"console_scripts": ["flask = flask.cli:main"]}, ) Flask-1.1.1/src/0000755000175000017500000000000013510702200013527 5ustar daviddavid00000000000000Flask-1.1.1/src/Flask.egg-info/0000755000175000017500000000000013510702200016261 5ustar daviddavid00000000000000Flask-1.1.1/src/Flask.egg-info/PKG-INFO0000644000175000017500000001040413510702200017355 0ustar daviddavid00000000000000Metadata-Version: 2.1 Name: Flask Version: 1.1.1 Summary: A simple framework for building complex web applications. Home-page: https://palletsprojects.com/p/flask/ Author: Armin Ronacher Author-email: armin.ronacher@active-4.com Maintainer: Pallets Maintainer-email: contact@palletsprojects.com License: BSD-3-Clause Project-URL: Documentation, https://flask.palletsprojects.com/ Project-URL: Code, https://github.com/pallets/flask Project-URL: Issue tracker, https://github.com/pallets/flask/issues Description: Flask ===== Flask is a lightweight `WSGI`_ web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around `Werkzeug`_ and `Jinja`_ and has become one of the most popular Python web application frameworks. Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. Installing ---------- Install and update using `pip`_: .. code-block:: text pip install -U Flask A Simple Example ---------------- .. code-block:: python from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" .. code-block:: text $ env FLASK_APP=hello.py flask run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Contributing ------------ For guidance on setting up a development environment and how to make a contribution to Flask, see the `contributing guidelines`_. .. _contributing guidelines: https://github.com/pallets/flask/blob/master/CONTRIBUTING.rst Donate ------ The Pallets organization develops and supports Flask and the libraries it uses. In order to grow the community of contributors and users, and allow the maintainers to devote more time to the projects, `please donate today`_. .. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=20 Links ----- * Website: https://palletsprojects.com/p/flask/ * Documentation: https://flask.palletsprojects.com/ * Releases: https://pypi.org/project/Flask/ * Code: https://github.com/pallets/flask * Issue tracker: https://github.com/pallets/flask/issues * Test status: https://dev.azure.com/pallets/flask/_build * Official chat: https://discord.gg/t6rrQZH .. _WSGI: https://wsgi.readthedocs.io .. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/ .. _Jinja: https://www.palletsprojects.com/p/jinja/ .. _pip: https://pip.pypa.io/en/stable/quickstart/ Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Framework :: Flask 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.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application Classifier: Topic :: Software Development :: Libraries :: Application Frameworks Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* Provides-Extra: dotenv Provides-Extra: dev Provides-Extra: docs Flask-1.1.1/src/Flask.egg-info/SOURCES.txt0000644000175000017500000001425013510702200020147 0ustar daviddavid00000000000000CHANGES.rst CONTRIBUTING.rst LICENSE.rst MANIFEST.in README.rst setup.cfg setup.py tox.ini artwork/LICENSE.rst artwork/logo-full.svg artwork/logo-lineart.svg 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/contributing.rst docs/design.rst docs/errorhandling.rst docs/extensiondev.rst docs/extensions.rst docs/foreword.rst docs/htmlfaq.rst docs/index.rst docs/installation.rst docs/license.rst docs/logging.rst docs/make.bat docs/quickstart.rst docs/reqcontext.rst docs/requirements.txt 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-icon.png docs/_static/flask-logo.png docs/_static/no.png docs/_static/pycharm-runconfig.png docs/_static/yes.png 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/mongoengine.rst docs/patterns/mongokit.rst docs/patterns/packages.rst docs/patterns/requestchecksum.rst docs/patterns/singlepageapplications.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/blog.rst docs/tutorial/database.rst docs/tutorial/deploy.rst docs/tutorial/factory.rst docs/tutorial/flaskr_edit.png docs/tutorial/flaskr_index.png docs/tutorial/flaskr_login.png docs/tutorial/index.rst docs/tutorial/install.rst docs/tutorial/layout.rst docs/tutorial/next.rst docs/tutorial/static.rst docs/tutorial/templates.rst docs/tutorial/tests.rst docs/tutorial/views.rst examples/javascript/.gitignore examples/javascript/LICENSE examples/javascript/MANIFEST.in examples/javascript/README.rst examples/javascript/setup.cfg examples/javascript/setup.py examples/javascript/js_example/__init__.py examples/javascript/js_example/views.py examples/javascript/js_example/templates/base.html examples/javascript/js_example/templates/fetch.html examples/javascript/js_example/templates/jquery.html examples/javascript/js_example/templates/plain.html examples/javascript/tests/conftest.py examples/javascript/tests/test_js_example.py examples/tutorial/.gitignore examples/tutorial/LICENSE examples/tutorial/MANIFEST.in examples/tutorial/README.rst examples/tutorial/setup.cfg examples/tutorial/setup.py examples/tutorial/flaskr/__init__.py examples/tutorial/flaskr/auth.py examples/tutorial/flaskr/blog.py examples/tutorial/flaskr/db.py examples/tutorial/flaskr/schema.sql examples/tutorial/flaskr/static/style.css examples/tutorial/flaskr/templates/base.html examples/tutorial/flaskr/templates/auth/login.html examples/tutorial/flaskr/templates/auth/register.html examples/tutorial/flaskr/templates/blog/create.html examples/tutorial/flaskr/templates/blog/index.html examples/tutorial/flaskr/templates/blog/update.html examples/tutorial/tests/conftest.py examples/tutorial/tests/data.sql examples/tutorial/tests/test_auth.py examples/tutorial/tests/test_blog.py examples/tutorial/tests/test_db.py examples/tutorial/tests/test_factory.py src/Flask.egg-info/PKG-INFO src/Flask.egg-info/SOURCES.txt src/Flask.egg-info/dependency_links.txt src/Flask.egg-info/entry_points.txt src/Flask.egg-info/requires.txt src/Flask.egg-info/top_level.txt src/flask/__init__.py src/flask/__main__.py src/flask/_compat.py src/flask/app.py src/flask/blueprints.py src/flask/cli.py src/flask/config.py src/flask/ctx.py src/flask/debughelpers.py src/flask/globals.py src/flask/helpers.py src/flask/logging.py src/flask/sessions.py src/flask/signals.py src/flask/templating.py src/flask/testing.py src/flask/views.py src/flask/wrappers.py src/flask/json/__init__.py src/flask/json/tag.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_converters.py tests/test_deprecations.py tests/test_helpers.py tests/test_instance_config.py tests/test_json_tag.py tests/test_logging.py tests/test_meta.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/.env tests/test_apps/.flaskenv 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/factory.py tests/test_apps/cliapp/importerrorapp.py tests/test_apps/cliapp/message.txt tests/test_apps/cliapp/multiapp.py tests/test_apps/cliapp/inner1/__init__.py tests/test_apps/cliapp/inner1/inner2/__init__.py tests/test_apps/cliapp/inner1/inner2/flask.py tests/test_apps/helloworld/hello.py tests/test_apps/helloworld/wsgi.py tests/test_apps/subdomaintestmodule/__init__.py tests/test_apps/subdomaintestmodule/static/hello.txtFlask-1.1.1/src/Flask.egg-info/dependency_links.txt0000644000175000017500000000000113510702200022327 0ustar daviddavid00000000000000 Flask-1.1.1/src/Flask.egg-info/entry_points.txt0000644000175000017500000000005213510702200021554 0ustar daviddavid00000000000000[console_scripts] flask = flask.cli:main Flask-1.1.1/src/Flask.egg-info/requires.txt0000644000175000017500000000040113510702200020654 0ustar daviddavid00000000000000Werkzeug>=0.15 Jinja2>=2.10.1 itsdangerous>=0.24 click>=5.1 [dev] pytest coverage tox sphinx pallets-sphinx-themes sphinxcontrib-log-cabinet sphinx-issues [docs] sphinx pallets-sphinx-themes sphinxcontrib-log-cabinet sphinx-issues [dotenv] python-dotenv Flask-1.1.1/src/Flask.egg-info/top_level.txt0000644000175000017500000000000613510702200021007 0ustar daviddavid00000000000000flask Flask-1.1.1/src/flask/0000755000175000017500000000000013510702200014627 5ustar daviddavid00000000000000Flask-1.1.1/src/flask/__init__.py0000644000175000017500000000354613510701642016761 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask ~~~~~ A microframework based on Werkzeug. It's extensively documented and follows best practice patterns. :copyright: 2010 Pallets :license: BSD-3-Clause """ # utilities we import from Werkzeug and Jinja2 that are unused # in the module but are exported as public interface. from jinja2 import escape from jinja2 import Markup from werkzeug.exceptions import abort from werkzeug.utils import redirect from . import json from ._compat import json_available from .app import Flask from .app import Request from .app import Response from .blueprints import Blueprint from .config import Config from .ctx import after_this_request from .ctx import copy_current_request_context from .ctx import has_app_context from .ctx import has_request_context from .globals import _app_ctx_stack from .globals import _request_ctx_stack from .globals import current_app from .globals import g from .globals import request from .globals import session from .helpers import flash from .helpers import get_flashed_messages from .helpers import get_template_attribute from .helpers import make_response from .helpers import safe_join from .helpers import send_file from .helpers import send_from_directory from .helpers import stream_with_context from .helpers import url_for from .json import jsonify from .signals import appcontext_popped from .signals import appcontext_pushed from .signals import appcontext_tearing_down from .signals import before_render_template from .signals import got_request_exception from .signals import message_flashed from .signals import request_finished from .signals import request_started from .signals import request_tearing_down from .signals import signals_available from .signals import template_rendered from .templating import render_template from .templating import render_template_string __version__ = "1.1.1" Flask-1.1.1/src/flask/__main__.py0000644000175000017500000000037613510701642016740 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.__main__ ~~~~~~~~~~~~~~ Alias for flask.run for the command line. :copyright: 2010 Pallets :license: BSD-3-Clause """ if __name__ == "__main__": from .cli import main main(as_module=True) Flask-1.1.1/src/flask/_compat.py0000644000175000017500000001000313510701642016626 0ustar daviddavid00000000000000# -*- 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: 2010 Pallets :license: BSD-3-Clause """ import sys PY2 = sys.version_info[0] == 2 _identity = lambda x: x try: # Python 2 text_type = unicode string_types = (str, unicode) integer_types = (int, long) except NameError: # Python 3 text_type = str string_types = (str,) integer_types = (int,) if not PY2: iterkeys = lambda d: iter(d.keys()) itervalues = lambda d: iter(d.values()) iteritems = lambda d: iter(d.items()) from inspect import getfullargspec as getargspec from io import StringIO import collections.abc as collections_abc def reraise(tp, value, tb=None): if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value implements_to_string = _identity else: iterkeys = lambda d: d.iterkeys() itervalues = lambda d: d.itervalues() iteritems = lambda d: d.iteritems() from inspect import getargspec from cStringIO import StringIO import collections as collections_abc 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__(metacls, 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: # noqa: B001 # We intentionally use a bare except here. See the comment above # regarding a pypy bug as to why. raise except TypeError: BROKEN_PYPY_CTXMGR_EXIT = True except AssertionError: pass try: from os import fspath except ImportError: # Backwards compatibility as proposed in PEP 0519: # https://www.python.org/dev/peps/pep-0519/#backwards-compatibility def fspath(path): return path.__fspath__() if hasattr(path, "__fspath__") else path class _DeprecatedBool(object): def __init__(self, name, version, value): self.message = "'{}' is deprecated and will be removed in version {}.".format( name, version ) self.value = value def _warn(self): import warnings warnings.warn(self.message, DeprecationWarning, stacklevel=2) def __eq__(self, other): self._warn() return other == self.value def __ne__(self, other): self._warn() return other != self.value def __bool__(self): self._warn() return self.value __nonzero__ = __bool__ json_available = _DeprecatedBool("flask.json_available", "2.0.0", True) Flask-1.1.1/src/flask/app.py0000644000175000017500000027742213510701642016010 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.app ~~~~~~~~~ This module implements the central WSGI application object. :copyright: 2010 Pallets :license: BSD-3-Clause """ import os import sys import warnings from datetime import timedelta from functools import update_wrapper from itertools import chain from threading import Lock from werkzeug.datastructures import Headers from werkzeug.datastructures import ImmutableDict from werkzeug.exceptions import BadRequest from werkzeug.exceptions import BadRequestKeyError from werkzeug.exceptions import default_exceptions from werkzeug.exceptions import HTTPException from werkzeug.exceptions import InternalServerError from werkzeug.exceptions import MethodNotAllowed from werkzeug.routing import BuildError from werkzeug.routing import Map from werkzeug.routing import RequestRedirect from werkzeug.routing import RoutingException from werkzeug.routing import Rule from werkzeug.wrappers import BaseResponse from . import cli from . import json from ._compat import integer_types from ._compat import reraise from ._compat import string_types from ._compat import text_type from .config import Config from .config import ConfigAttribute from .ctx import _AppCtxGlobals from .ctx import AppContext from .ctx import RequestContext from .globals import _request_ctx_stack from .globals import g from .globals import request from .globals import session from .helpers import _endpoint_from_view_func from .helpers import _PackageBoundObject from .helpers import find_package from .helpers import get_debug_flag from .helpers import get_env from .helpers import get_flashed_messages from .helpers import get_load_dotenv from .helpers import locked_cached_property from .helpers import url_for from .json import jsonify from .logging import create_logger from .sessions import SecureCookieSessionInterface from .signals import appcontext_tearing_down from .signals import got_request_exception from .signals import request_finished from .signals import request_started from .signals import request_tearing_down from .templating import _default_template_ctx_processor from .templating import DispatchingJinjaLoader from .templating import Environment from .wrappers import Request from .wrappers import Response # 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. .. versionadded:: 1.0 The ``host_matching`` and ``static_host`` parameters were added. .. versionadded:: 1.0 The ``subdomain_matching`` parameter was added. Subdomain matching needs to be enabled manually now. Setting :data:`SERVER_NAME` does not implicitly enable it. :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 static_host: the host to use when adding the static route. Defaults to None. Required when using ``host_matching=True`` with a ``static_folder`` configured. :param host_matching: set ``url_map.host_matching`` attribute. Defaults to False. :param subdomain_matching: consider the subdomain relative to :data:`SERVER_NAME` when matching routes. Defaults to False. :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 #: 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 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 test 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 #: :data:`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 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 to the Jinja environment in #: :meth:`create_jinja_environment`. Changing these options after #: the environment is created (accessing :attr:`jinja_env`) will #: have no effect. #: #: .. versionchanged:: 1.1.0 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow #: easier configuration. #: jinja_options = {"extensions": ["jinja2.ext.autoescape", "jinja2.ext.with_"]} #: Default configuration parameters. default_config = ImmutableDict( { "ENV": None, "DEBUG": None, "TESTING": False, "PROPAGATE_EXCEPTIONS": None, "PRESERVE_CONTEXT_ON_EXCEPTION": None, "SECRET_KEY": None, "PERMANENT_SESSION_LIFETIME": timedelta(days=31), "USE_X_SENDFILE": False, "SERVER_NAME": None, "APPLICATION_ROOT": "/", "SESSION_COOKIE_NAME": "session", "SESSION_COOKIE_DOMAIN": None, "SESSION_COOKIE_PATH": None, "SESSION_COOKIE_HTTPONLY": True, "SESSION_COOKIE_SECURE": False, "SESSION_COOKIE_SAMESITE": None, "SESSION_REFRESH_EACH_REQUEST": True, "MAX_CONTENT_LENGTH": None, "SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12), "TRAP_BAD_REQUEST_ERRORS": None, "TRAP_HTTP_EXCEPTIONS": False, "EXPLAIN_TEMPLATE_LOADING": False, "PREFERRED_URL_SCHEME": "http", "JSON_AS_ASCII": True, "JSON_SORT_KEYS": True, "JSONIFY_PRETTYPRINT_REGULAR": False, "JSONIFY_MIMETYPE": "application/json", "TEMPLATES_AUTO_RELOAD": None, "MAX_COOKIE_SIZE": 4093, } ) #: 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 map object to use for storing the URL rules and routing #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`. #: #: .. versionadded:: 1.1.0 url_map_class = Map #: the test client that is used with when `test_client` is used. #: #: .. versionadded:: 0.7 test_client_class = None #: The :class:`~click.testing.CliRunner` subclass, by default #: :class:`~flask.testing.FlaskCliRunner` that is used by #: :meth:`test_cli_runner`. Its ``__init__`` method should take a #: Flask app object as the first argument. #: #: .. versionadded:: 1.0 test_cli_runner_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() # TODO remove the next three attrs when Sphinx :inherited-members: works # https://github.com/sphinx-doc/sphinx/issues/741 #: The name of the package or module that this app belongs to. Do not #: change this once it is set by the constructor. import_name = None #: Location of the template files to be added to the template lookup. #: ``None`` if templates should not be added. template_folder = None #: Absolute path to the package on the filesystem. Used to look up #: resources contained in the package. root_path = None def __init__( self, import_name, static_url_path=None, static_folder="static", static_host=None, host_matching=False, subdomain_matching=False, 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 ) self.static_url_path = static_url_path 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) #: 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 = {} #: 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 an error handler, use the :meth:`errorhandler` #: decorator. self.error_handler_spec = {} #: 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 will be called at the #: beginning of each request. The key of the dictionary is the name of #: the blueprint this function is active for, or ``None`` for all #: requests. To register a function, use the :meth:`before_request` #: decorator. self.before_request_funcs = {} #: A list of functions that will be called at the beginning of the #: first request to this instance. To register a function, 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 are called before the #: :attr:`before_request_funcs` functions. The key of the dictionary is #: the name of the blueprint this function is active for, or ``None`` #: for all requests. To register a function, use #: :meth:`url_value_preprocessor`. #: #: .. 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 = self.url_map_class() self.url_map.host_matching = host_matching self.subdomain_matching = subdomain_matching # tracks internally if the application already handled at least one # request. self._got_first_request = False self._before_request_lock = Lock() # Add a static route using the provided static_url_path, static_host, # and static_folder if there is a configured static_folder. # Note we do this without checking if static_folder exists. # For one, it might be created while the server is running (e.g. during # development). Also, Google App Engine stores static files somewhere if self.has_static_folder: assert ( bool(static_host) == host_matching ), "Invalid static_host/host_matching combination" self.add_url_rule( self.static_url_path + "/", endpoint="static", host=static_host, view_func=self.send_static_file, ) # Set the name of the Click group in case someone wants to add # the app's commands to another CLI tool. self.cli.name = self.name @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 @locked_cached_property def logger(self): """A standard Python :class:`~logging.Logger` for the app, with the same name as :attr:`name`. In debug mode, the logger's :attr:`~logging.Logger.level` will be set to :data:`~logging.DEBUG`. If there are no handlers configured, a default handler will be added. See :doc:`/logging` for more information. .. versionchanged:: 1.1.0 The logger takes the same name as :attr:`name` rather than hard-coding ``"flask.app"``. .. versionchanged:: 1.0.0 Behavior was simplified. The logger is always named ``"flask.app"``. The level is only set during configuration, it doesn't check ``app.debug`` each time. Only one format is used, not different ones depending on ``app.debug``. No handlers are removed, and a handler is only added if no handlers are already configured. .. versionadded:: 0.3 """ return create_logger(self) @locked_cached_property def jinja_env(self): """The Jinja environment used to load templates. The environment is created the first time this property is accessed. Changing :attr:`jinja_options` after that will have no effect. """ 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 defaults = dict(self.default_config) defaults["ENV"] = get_env() defaults["DEBUG"] = get_debug_flag() return self.config_class(root_path, defaults) 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) @property def templates_auto_reload(self): """Reload templates when they are changed. Used by :meth:`create_jinja_environment`. This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If not set, it will be enabled in debug mode. .. versionadded:: 1.0 This property was added but the underlying config and behavior already existed. """ rv = self.config["TEMPLATES_AUTO_RELOAD"] return rv if rv is not None else self.debug @templates_auto_reload.setter def templates_auto_reload(self, value): self.config["TEMPLATES_AUTO_RELOAD"] = value def create_jinja_environment(self): """Create the Jinja environment based on :attr:`jinja_options` and the various Jinja-related methods of the app. Changing :attr:`jinja_options` after this will have no effect. Also adds Flask-related globals and filters to the environment. .. versionchanged:: 0.11 ``Environment.auto_reload`` set in accordance with ``TEMPLATES_AUTO_RELOAD`` configuration option. .. versionadded:: 0.5 """ options = dict(self.jinja_options) if "autoescape" not in options: options["autoescape"] = self.select_jinja_autoescape if "auto_reload" not in options: options["auto_reload"] = self.templates_auto_reload 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 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 #: What environment the app is running in. Flask and extensions may #: enable behaviors based on the environment, such as enabling debug #: mode. This maps to the :data:`ENV` config key. This is set by the #: :envvar:`FLASK_ENV` environment variable and may not behave as #: expected if set in code. #: #: **Do not enable development when deploying in production.** #: #: Default: ``'production'`` env = ConfigAttribute("ENV") @property def debug(self): """Whether debug mode is enabled. When using ``flask run`` to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. This maps to the :data:`DEBUG` config key. This is enabled when :attr:`env` is ``'development'`` and is overridden by the ``FLASK_DEBUG`` environment variable. It may not behave as expected if set in code. **Do not enable debug mode when deploying in production.** Default: ``True`` if :attr:`env` is ``'development'``, or ``False`` otherwise. """ return self.config["DEBUG"] @debug.setter def debug(self, value): self.config["DEBUG"] = value self.jinja_env.auto_reload = self.templates_auto_reload def run(self, host=None, port=None, debug=None, load_dotenv=True, **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. :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'`` or the host in the ``SERVER_NAME`` config variable if present. :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 load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv` files to set environment variables. Will also change the working directory to the directory containing the first file found. :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.serving.run_simple` for more information. .. versionchanged:: 1.0 If installed, python-dotenv will be used to load environment variables from :file:`.env` and :file:`.flaskenv` files. If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG` environment variables will override :attr:`env` and :attr:`debug`. Threaded mode is enabled by default. .. versionchanged:: 0.10 The default port is now picked from the ``SERVER_NAME`` variable. """ # Change this into a no-op if the server is invoked from the # command line. Have a look at cli.py for more information. if os.environ.get("FLASK_RUN_FROM_CLI") == "true": from .debughelpers import explain_ignored_app_run explain_ignored_app_run() return if get_load_dotenv(load_dotenv): cli.load_dotenv() # if set, let env vars override previous values if "FLASK_ENV" in os.environ: self.env = get_env() self.debug = get_debug_flag() elif "FLASK_DEBUG" in os.environ: self.debug = get_debug_flag() # debug passed to method overrides all other sources if debug is not None: self.debug = bool(debug) _host = "127.0.0.1" _port = 5000 server_name = self.config.get("SERVER_NAME") sn_host, sn_port = None, None if server_name: sn_host, _, sn_port = server_name.partition(":") host = host or sn_host or _host # pick the first value that's not None (0 is allowed) port = int(next((p for p in (port, sn_port) if p is not None), _port)) options.setdefault("use_reloader", self.debug) options.setdefault("use_debugger", self.debug) options.setdefault("threaded", True) cli.show_server_banner(self.env, self.debug, self.name, False) from werkzeug.serving import run_simple 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 .testing import FlaskClient as cls return cls(self, self.response_class, use_cookies=use_cookies, **kwargs) def test_cli_runner(self, **kwargs): """Create a CLI runner for testing CLI commands. See :ref:`testing-cli`. Returns an instance of :attr:`test_cli_runner_class`, by default :class:`~flask.testing.FlaskCliRunner`. The Flask app object is passed as the first argument. .. versionadded:: 1.0 """ cls = self.test_cli_runner_class if cls is None: from .testing import FlaskCliRunner as cls return cls(self, **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`. .. deprecated: 1.0 Will be removed in 1.1. Use ``session_interface.open_session`` instead. :param request: an instance of :attr:`request_class`. """ warnings.warn( DeprecationWarning( '"open_session" is deprecated and will be removed in 1.1. Use' ' "session_interface.open_session" instead.' ) ) 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`. .. deprecated: 1.0 Will be removed in 1.1. Use ``session_interface.save_session`` instead. :param session: the session to be saved (a :class:`~werkzeug.contrib.securecookie.SecureCookie` object) :param response: an instance of :attr:`response_class` """ warnings.warn( DeprecationWarning( '"save_session" is deprecated and will be removed in 1.1. Use' ' "session_interface.save_session" instead.' ) ) 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`. .. deprecated: 1.0 Will be removed in 1.1. Use ``session_interface.make_null_session`` instead. .. versionadded:: 0.7 """ warnings.warn( DeprecationWarning( '"make_null_session" is deprecated and will be removed in 1.1. Use' ' "session_interface.make_null_session" instead.' ) ) return self.session_interface.make_null_session(self) @setupmethod def register_blueprint(self, blueprint, **options): """Register a :class:`~flask.Blueprint` on the application. Keyword arguments passed to this method will override the defaults set on the blueprint. Calls the blueprint's :meth:`~flask.Blueprint.register` method after recording the blueprint in the application's :attr:`blueprints`. :param blueprint: The blueprint to register. :param url_prefix: Blueprint routes will be prefixed with this. :param subdomain: Blueprint routes will match on this subdomain. :param url_defaults: Blueprint routes will use these default values for view arguments. :param options: Additional keyword arguments are passed to :class:`~flask.blueprints.BlueprintSetupState`. They can be accessed in :meth:`~flask.Blueprint.record` callbacks. .. versionadded:: 0.7 """ first_registration = False if blueprint.name in self.blueprints: assert self.blueprints[blueprint.name] is blueprint, ( "A name collision occurred between blueprints %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, provide_automatic_options=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 provide_automatic_options: controls whether the ``OPTIONS`` method should be added automatically. This can also be controlled by setting the ``view_func.provide_automatic_options = False`` before adding the rule. :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. if provide_automatic_options is None: 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): """Get the exception class being handled. For HTTP status codes or ``HTTPException`` subclasses, return both the exception and status code. :param exc_class_or_code: Any exception class, or an HTTP status code as an integer. """ 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): """Register a function to handle errors by code or exception class. 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 .. 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 @setupmethod 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) ) try: exc_class, code = self._get_exc_class_and_code(code_or_exception) except KeyError: raise KeyError( "'{0}' is not a recognized HTTP error code. Use a subclass of" " HTTPException with that code instead.".format(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. For example, this can be used to open a database connection, or to load the logged in user from the session. The function will be called without any arguments. If it returns a non-None value, the value is 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 an 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 unhandled exception it will be passed an error object. If an :meth:`errorhandler` is registered, it will handle the exception and the teardown will not receive it. 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): """Register a URL value preprocessor function for all view functions in the application. These functions will be called before the :meth:`before_request` functions. The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in ``g`` rather than pass it to every view. The function is passed the endpoint name and values dict. The return value is ignored. """ 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): """Return a registered error handler for an exception in this order: blueprint handler for a specific code, app handler for a specific code, blueprint handler for an exception class, app handler for an exception class, or ``None`` if a suitable handler is not found. """ exc_class, code = self._get_exc_class_and_code(type(e)) for name, c in ( (request.blueprint, code), (None, code), (request.blueprint, None), (None, None), ): handler_map = self.error_handler_spec.setdefault(name, {}).get(c) if not handler_map: continue for cls in exc_class.__mro__: handler = handler_map.get(cls) if handler is not None: return handler 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. .. versionchanged:: 1.0.3 ``RoutingException``, used internally for actions such as slash redirects during routing, is not passed to error handlers. .. versionchanged:: 1.0 Exceptions are looked up by code *and* by MRO, so ``HTTPExcpetion`` subclasses can be handled with a catch-all handler for the base ``HTTPException``. .. 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 # RoutingExceptions are used internally to trigger routing # actions, such as slash redirects raising RequestRedirect. They # are not raised or handled in user code. if isinstance(e, RoutingException): 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. .. versionchanged:: 1.0 Bad request errors are not trapped by default in debug mode. .. versionadded:: 0.8 """ if self.config["TRAP_HTTP_EXCEPTIONS"]: return True trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"] # if unset, trap key errors in debug mode if ( trap_bad_request is None and self.debug and isinstance(e, BadRequestKeyError) ): return True if trap_bad_request: 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 is :class:`~werkzeug .exceptions.HTTPException` which is forwarded to the :meth:`handle_http_exception` method. This function will either return a response value or reraise the exception with the same traceback. .. versionchanged:: 1.0 Key errors raised from request data like ``form`` show the bad key in debug mode rather than a generic bad request message. .. 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, BadRequestKeyError): if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]: e.show_exception = True # Werkzeug < 0.15 doesn't add the KeyError to the 400 # message, add it in manually. # TODO: clean up once Werkzeug >= 0.15.5 is required if e.args[0] not in e.get_description(): e.description = "KeyError: '{}'".format(*e.args) elif not hasattr(BadRequestKeyError, "show_exception"): e.args = () 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): """Handle an exception that did not have an error handler associated with it, or that was raised from an error handler. This always causes a 500 ``InternalServerError``. Always sends the :data:`got_request_exception` signal. If :attr:`propagate_exceptions` is ``True``, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an :exc:`~werkzeug.exceptions.InternalServerError` is returned. If an error handler is registered for ``InternalServerError`` or ``500``, it will be used. For consistency, the handler will always receive the ``InternalServerError``. The original unhandled exception is available as ``e.original_exception``. .. note:: Prior to Werkzeug 1.0.0, ``InternalServerError`` will not always have an ``original_exception`` attribute. Use ``getattr(e, "original_exception", None)`` to simulate the behavior for compatibility. .. versionchanged:: 1.1.0 Always passes the ``InternalServerError`` instance to the handler, setting ``original_exception`` to the unhandled error. .. versionchanged:: 1.1.0 ``after_request`` functions and other finalization is done even for the default 500 response when there is no handler. .. versionadded:: 0.3 """ exc_type, exc_value, tb = sys.exc_info() got_request_exception.send(self, exception=e) 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)) server_error = InternalServerError() # TODO: pass as param when Werkzeug>=1.0.0 is required # TODO: also remove note about this from docstring and docs server_error.original_exception = e handler = self._find_error_handler(server_error) if handler is not None: server_error = handler(server_error) return self.finalize_request(server_error, 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: 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): """Convert the return value from a view function to an instance of :attr:`response_class`. :param rv: the return value from the view function. The view function must return a response. Returning ``None``, or the view ending without returning, is not allowed. The following types are allowed for ``view_rv``: ``str`` (``unicode`` in Python 2) A response object is created with the string encoded to UTF-8 as the body. ``bytes`` (``str`` in Python 2) A response object is created with the bytes as the body. ``dict`` A dictionary that will be jsonify'd before being returned. ``tuple`` Either ``(body, status, headers)``, ``(body, status)``, or ``(body, headers)``, where ``body`` is any of the other types allowed here, ``status`` is a string or an integer, and ``headers`` is a dictionary or a list of ``(key, value)`` tuples. If ``body`` is a :attr:`response_class` instance, ``status`` overwrites the exiting value and ``headers`` are extended. :attr:`response_class` The object is returned unchanged. other :class:`~werkzeug.wrappers.Response` class The object is coerced to :attr:`response_class`. :func:`callable` The function is called as a WSGI application. The result is used to create a response object. .. versionchanged:: 0.9 Previously a tuple was interpreted as the arguments for the response object. """ status = headers = None # unpack tuple returns if isinstance(rv, tuple): len_rv = len(rv) # a 3-tuple is unpacked directly if len_rv == 3: rv, status, headers = rv # decide if a 2-tuple has status or headers elif len_rv == 2: if isinstance(rv[1], (Headers, dict, tuple, list)): rv, headers = rv else: rv, status = rv # other sized tuples are not allowed else: raise TypeError( "The view function did not return a valid response tuple." " The tuple must have the form (body, status, headers)," " (body, status), or (body, headers)." ) # the body must not be None if rv is None: raise TypeError( "The view function did not return a valid response. The" " function either returned None or ended without a return" " statement." ) # make sure the body is an instance of the response class if not isinstance(rv, self.response_class): if isinstance(rv, (text_type, bytes, bytearray)): # let the response class set the status and headers instead of # waiting to do it manually, so that the class can handle any # special logic rv = self.response_class(rv, status=status, headers=headers) status = headers = None elif isinstance(rv, dict): rv = jsonify(rv) elif isinstance(rv, BaseResponse) or callable(rv): # evaluate a WSGI callable, or coerce a different response # class to the correct type try: rv = self.response_class.force_type(rv, request.environ) except TypeError as e: new_error = TypeError( "{e}\nThe view function did not return a valid" " response. The return type must be a string, dict, tuple," " Response instance, or WSGI callable, but it was a" " {rv.__class__.__name__}.".format(e=e, rv=rv) ) reraise(TypeError, new_error, sys.exc_info()[2]) else: raise TypeError( "The view function did not return a valid" " response. The return type must be a string, dict, tuple," " Response instance, or WSGI callable, but it was a" " {rv.__class__.__name__}.".format(rv=rv) ) # prefer the status if it was provided if status is not None: if isinstance(status, (text_type, bytes, bytearray)): rv.status = status else: rv.status_code = status # extend existing headers with provided 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. .. versionchanged:: 1.0 :data:`SERVER_NAME` no longer implicitly enables subdomain matching. Use :attr:`subdomain_matching` instead. """ if request is not None: # If subdomain matching is disabled (the default), use the # default subdomain in all cases. This should be the default # in Werkzeug but it currently does not have that feature. subdomain = ( (self.url_map.default_subdomain or None) if not self.subdomain_matching else None ) return self.url_map.bind_to_environ( request.environ, server_name=self.config["SERVER_NAME"], subdomain=subdomain, ) # 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"], 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 request is dispatched. Calls :attr:`url_value_preprocessors` registered with the app and the current blueprint (if any). Then calls :attr:`before_request_funcs` registered with the app and the blueprint. If any :meth:`before_request` handler returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. """ 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.session_interface.save_session(self, ctx.session, response) return response def do_teardown_request(self, exc=_sentinel): """Called after the request is dispatched and the response is returned, right before the request context is popped. This calls all functions decorated with :meth:`teardown_request`, and :meth:`Blueprint.teardown_request` if a blueprint handled the request. Finally, the :data:`request_tearing_down` signal is sent. This is called by :meth:`RequestContext.pop() `, which may be delayed during testing to maintain access to resources. :param exc: An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function. .. versionchanged:: 0.9 Added the ``exc`` argument. """ 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 right before the application context is popped. When handling a request, the application context is popped after the request context. See :meth:`do_teardown_request`. This calls all functions decorated with :meth:`teardown_appcontext`. Then the :data:`appcontext_tearing_down` signal is sent. This is called by :meth:`AppContext.pop() `. .. 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): """Create an :class:`~flask.ctx.AppContext`. Use as a ``with`` block to push the context, which will make :data:`current_app` point at this application. An application context is automatically pushed by :meth:`RequestContext.push() ` when handling a request, and when running a CLI command. Use this to manually create a context outside of these situations. :: with app.app_context(): init_db() See :doc:`/appcontext`. .. versionadded:: 0.9 """ return AppContext(self) def request_context(self, environ): """Create a :class:`~flask.ctx.RequestContext` representing a WSGI environment. Use a ``with`` block to push the context, which will make :data:`request` point at this request. See :doc:`/reqcontext`. Typically you should not call this from your own code. A request context is automatically pushed by the :meth:`wsgi_app` when handling a request. Use :meth:`test_request_context` to create an environment and context instead of this method. :param environ: a WSGI environment """ return RequestContext(self, environ) def test_request_context(self, *args, **kwargs): """Create a :class:`~flask.ctx.RequestContext` for a WSGI environment created from the given values. This is mostly useful during testing, where you may want to run a function that uses request data without dispatching a full request. See :doc:`/reqcontext`. Use a ``with`` block to push the context, which will make :data:`request` point at the request for the created environment. :: with test_request_context(...): generate_report() When using the shell, it may be easier to push and pop the context manually to avoid indentation. :: ctx = app.test_request_context(...) ctx.push() ... ctx.pop() Takes the same arguments as Werkzeug's :class:`~werkzeug.test.EnvironBuilder`, with some defaults from the application. See the linked Werkzeug docs for most of the available arguments. Flask-specific behavior is listed here. :param path: URL path being requested. :param base_url: Base URL where the app is being served, which ``path`` is relative to. If not given, built from :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`. :param subdomain: Subdomain name to append to :data:`SERVER_NAME`. :param url_scheme: Scheme to use instead of :data:`PREFERRED_URL_SCHEME`. :param data: The request body, either as a string or a dict of form keys and values. :param json: If given, this is serialized as JSON and passed as ``data``. Also defaults ``content_type`` to ``application/json``. :param args: other positional arguments passed to :class:`~werkzeug.test.EnvironBuilder`. :param kwargs: other keyword arguments passed to :class:`~werkzeug.test.EnvironBuilder`. """ from .testing import EnvironBuilder builder = EnvironBuilder(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 :meth:`__call__` so that middlewares can be applied without losing a reference to the app object. 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 Teardown events for the request and app contexts are called even if an unhandled error occurs. Other events may not be called depending on when an error occurs during dispatch. 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) error = None try: try: ctx.push() response = self.full_dispatch_request() except Exception as e: error = e response = self.handle_exception(e) except: # noqa: B001 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): """The WSGI server calls the Flask application object as the WSGI application. This calls :meth:`wsgi_app` which can be wrapped to applying middleware.""" return self.wsgi_app(environ, start_response) def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.name) Flask-1.1.1/src/flask/blueprints.py0000644000175000017500000005163013510701642017406 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.blueprints ~~~~~~~~~~~~~~~~ Blueprints are the recommended way to implement larger or more pluggable applications in Flask 0.7 and later. :copyright: 2010 Pallets :license: BSD-3-Clause """ from functools import update_wrapper from .helpers import _endpoint_from_view_func from .helpers import _PackageBoundObject # a singleton sentinel value for parameter defaults _sentinel = object() class BlueprintSetupState(object): """Temporary holder object for registering a blueprint with the application. An instance of this class is created by the :meth:`~flask.Blueprint.make_setup_state` method and later passed to all register callback functions. """ def __init__(self, blueprint, app, options, first_registration): #: a reference to the current application self.app = app #: a reference to the blueprint that created this setup state. self.blueprint = blueprint #: a dictionary with all options that were passed to the #: :meth:`~flask.Flask.register_blueprint` method. self.options = options #: as blueprints can be registered multiple times with the #: application and not everything wants to be registered #: multiple times on it, this attribute can be used to figure #: out if the blueprint was registered in the past already. self.first_registration = first_registration subdomain = self.options.get("subdomain") if subdomain is None: subdomain = self.blueprint.subdomain #: The subdomain that the blueprint should be active for, ``None`` #: otherwise. self.subdomain = subdomain url_prefix = self.options.get("url_prefix") if url_prefix is None: url_prefix = self.blueprint.url_prefix #: The prefix that should be used for all URLs defined on the #: blueprint. self.url_prefix = url_prefix #: A dictionary with URL defaults that is added to each and every #: URL that was defined with the blueprint. self.url_defaults = dict(self.blueprint.url_values_defaults) self.url_defaults.update(self.options.get("url_defaults", ())) def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint's name. """ if self.url_prefix is not None: if rule: rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/"))) else: rule = self.url_prefix options.setdefault("subdomain", self.subdomain) if endpoint is None: endpoint = _endpoint_from_view_func(view_func) defaults = self.url_defaults if "defaults" in options: defaults = dict(defaults, **options.pop("defaults")) self.app.add_url_rule( rule, "%s.%s" % (self.blueprint.name, endpoint), view_func, defaults=defaults, **options ) class Blueprint(_PackageBoundObject): """Represents a blueprint, a collection of routes and other app-related functions that can be registered on a real application later. A blueprint is an object that allows defining application functions without requiring an application object ahead of time. It uses the same decorators as :class:`~flask.Flask`, but defers the need for an application by recording them for later registration. Decorating a function with a blueprint creates a deferred function that is called with :class:`~flask.blueprints.BlueprintSetupState` when the blueprint is registered on an application. See :ref:`blueprints` for more information. .. versionchanged:: 1.1.0 Blueprints have a ``cli`` group to register nested CLI commands. The ``cli_group`` parameter controls the name of the group under the ``flask`` command. .. versionadded:: 0.7 :param name: The name of the blueprint. Will be prepended to each endpoint name. :param import_name: The name of the blueprint package, usually ``__name__``. This helps locate the ``root_path`` for the blueprint. :param static_folder: A folder with static files that should be served by the blueprint's static route. The path is relative to the blueprint's root path. Blueprint static files are disabled by default. :param static_url_path: The url to serve static files from. Defaults to ``static_folder``. If the blueprint does not have a ``url_prefix``, the app's static route will take precedence, and the blueprint's static files won't be accessible. :param template_folder: A folder with templates that should be added to the app's template search path. The path is relative to the blueprint's root path. Blueprint templates are disabled by default. Blueprint templates have a lower precedence than those in the app's templates folder. :param url_prefix: A path to prepend to all of the blueprint's URLs, to make them distinct from the rest of the app's routes. :param subdomain: A subdomain that blueprint routes will match on by default. :param url_defaults: A dict of default values that blueprint routes will receive by default. :param root_path: By default, the blueprint will automatically this based on ``import_name``. In certain situations this automatic detection can fail, so the path can be specified manually instead. """ warn_on_modifications = False _got_registered_once = False #: Blueprint local JSON decoder class to use. #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`. json_encoder = None #: Blueprint local JSON decoder class to use. #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`. json_decoder = None # TODO remove the next three attrs when Sphinx :inherited-members: works # https://github.com/sphinx-doc/sphinx/issues/741 #: The name of the package or module that this app belongs to. Do not #: change this once it is set by the constructor. import_name = None #: Location of the template files to be added to the template lookup. #: ``None`` if templates should not be added. template_folder = None #: Absolute path to the package on the filesystem. Used to look up #: resources contained in the package. root_path = None def __init__( self, name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, cli_group=_sentinel, ): _PackageBoundObject.__init__( self, import_name, template_folder, root_path=root_path ) self.name = name self.url_prefix = url_prefix self.subdomain = subdomain self.static_folder = static_folder self.static_url_path = static_url_path self.deferred_functions = [] if url_defaults is None: url_defaults = {} self.url_values_defaults = url_defaults self.cli_group = cli_group def record(self, func): """Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the :meth:`make_setup_state` method. """ if self._got_registered_once and self.warn_on_modifications: from warnings import warn warn( Warning( "The blueprint was already registered once " "but is getting modified now. These changes " "will not show up." ) ) self.deferred_functions.append(func) def record_once(self, func): """Works like :meth:`record` but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called. """ def wrapper(state): if state.first_registration: func(state) return self.record(update_wrapper(wrapper, func)) def make_setup_state(self, app, options, first_registration=False): """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState` object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state. """ return BlueprintSetupState(self, app, options, first_registration) def register(self, app, options, first_registration=False): """Called by :meth:`Flask.register_blueprint` to register all views and callbacks registered on the blueprint with the application. Creates a :class:`.BlueprintSetupState` and calls each :meth:`record` callback with it. :param app: The application this blueprint is being registered with. :param options: Keyword arguments forwarded from :meth:`~Flask.register_blueprint`. :param first_registration: Whether this is the first time this blueprint has been registered on the application. """ self._got_registered_once = True state = self.make_setup_state(app, options, first_registration) if self.has_static_folder: state.add_url_rule( self.static_url_path + "/", view_func=self.send_static_file, endpoint="static", ) for deferred in self.deferred_functions: deferred(state) cli_resolved_group = options.get("cli_group", self.cli_group) if not self.cli.commands: return if cli_resolved_group is None: app.cli.commands.update(self.cli.commands) elif cli_resolved_group is _sentinel: self.cli.name = self.name app.cli.add_command(self.cli) else: self.cli.name = cli_resolved_group app.cli.add_command(self.cli) def route(self, rule, **options): """Like :meth:`Flask.route` but for a blueprint. The endpoint for the :func:`url_for` function is prefixed with the name of the blueprint. """ def decorator(f): endpoint = options.pop("endpoint", f.__name__) self.add_url_rule(rule, endpoint, f, **options) return f return decorator def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for the :func:`url_for` function is prefixed with the name of the blueprint. """ if endpoint: assert "." not in endpoint, "Blueprint endpoints should not contain dots" if view_func and hasattr(view_func, "__name__"): assert ( "." not in view_func.__name__ ), "Blueprint view function name should not contain dots" self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options)) def endpoint(self, endpoint): """Like :meth:`Flask.endpoint` but for a blueprint. This does not prefix the endpoint with the blueprint name, this has to be done explicitly by the user of this method. If the endpoint is prefixed with a `.` it will be registered to the current blueprint, otherwise it's an application independent endpoint. """ def decorator(f): def register_endpoint(state): state.app.view_functions[endpoint] = f self.record_once(register_endpoint) return f return decorator def app_template_filter(self, name=None): """Register a custom template filter, available application wide. Like :meth:`Flask.template_filter` but for a blueprint. :param name: the optional name of the filter, otherwise the function name will be used. """ def decorator(f): self.add_app_template_filter(f, name=name) return f return decorator def add_app_template_filter(self, f, name=None): """Register a custom template filter, available application wide. Like :meth:`Flask.add_template_filter` but for a blueprint. Works exactly like the :meth:`app_template_filter` decorator. :param name: the optional name of the filter, otherwise the function name will be used. """ def register_template(state): state.app.jinja_env.filters[name or f.__name__] = f self.record_once(register_template) def app_template_test(self, name=None): """Register a custom template test, available application wide. Like :meth:`Flask.template_test` but for a blueprint. .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ def decorator(f): self.add_app_template_test(f, name=name) return f return decorator def add_app_template_test(self, f, name=None): """Register a custom template test, available application wide. Like :meth:`Flask.add_template_test` but for a blueprint. Works exactly like the :meth:`app_template_test` decorator. .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ def register_template(state): state.app.jinja_env.tests[name or f.__name__] = f self.record_once(register_template) def app_template_global(self, name=None): """Register a custom template global, available application wide. Like :meth:`Flask.template_global` but for a blueprint. .. versionadded:: 0.10 :param name: the optional name of the global, otherwise the function name will be used. """ def decorator(f): self.add_app_template_global(f, name=name) return f return decorator def add_app_template_global(self, f, name=None): """Register a custom template global, available application wide. Like :meth:`Flask.add_template_global` but for a blueprint. Works exactly like the :meth:`app_template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global, otherwise the function name will be used. """ def register_template(state): state.app.jinja_env.globals[name or f.__name__] = f self.record_once(register_template) def before_request(self, f): """Like :meth:`Flask.before_request` but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint. """ self.record_once( lambda s: s.app.before_request_funcs.setdefault(self.name, []).append(f) ) return f def before_app_request(self, f): """Like :meth:`Flask.before_request`. Such a function is executed before each request, even if outside of a blueprint. """ self.record_once( lambda s: s.app.before_request_funcs.setdefault(None, []).append(f) ) return f def before_app_first_request(self, f): """Like :meth:`Flask.before_first_request`. Such a function is executed before the first request to the application. """ self.record_once(lambda s: s.app.before_first_request_funcs.append(f)) return f def after_request(self, f): """Like :meth:`Flask.after_request` but for a blueprint. This function is only executed after each request that is handled by a function of that blueprint. """ self.record_once( lambda s: s.app.after_request_funcs.setdefault(self.name, []).append(f) ) return f def after_app_request(self, f): """Like :meth:`Flask.after_request` but for a blueprint. Such a function is executed after each request, even if outside of the blueprint. """ self.record_once( lambda s: s.app.after_request_funcs.setdefault(None, []).append(f) ) return f def teardown_request(self, f): """Like :meth:`Flask.teardown_request` but for a blueprint. This function is only executed when tearing down requests handled by a function of that blueprint. Teardown request functions are executed when the request context is popped, even when no actual request was performed. """ self.record_once( lambda s: s.app.teardown_request_funcs.setdefault(self.name, []).append(f) ) return f def teardown_app_request(self, f): """Like :meth:`Flask.teardown_request` but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint. """ self.record_once( lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f) ) return f def context_processor(self, f): """Like :meth:`Flask.context_processor` but for a blueprint. This function is only executed for requests handled by a blueprint. """ self.record_once( lambda s: s.app.template_context_processors.setdefault( self.name, [] ).append(f) ) return f def app_context_processor(self, f): """Like :meth:`Flask.context_processor` but for a blueprint. Such a function is executed each request, even if outside of the blueprint. """ self.record_once( lambda s: s.app.template_context_processors.setdefault(None, []).append(f) ) return f def app_errorhandler(self, code): """Like :meth:`Flask.errorhandler` but for a blueprint. This handler is used for all requests, even if outside of the blueprint. """ def decorator(f): self.record_once(lambda s: s.app.errorhandler(code)(f)) return f return decorator def url_value_preprocessor(self, f): """Registers a function as URL value preprocessor for this blueprint. It's called before the view functions are called and can modify the url values provided. """ self.record_once( lambda s: s.app.url_value_preprocessors.setdefault(self.name, []).append(f) ) return f def url_defaults(self, f): """Callback function for URL defaults for this blueprint. It's called with the endpoint and values and should update the values passed in place. """ self.record_once( lambda s: s.app.url_default_functions.setdefault(self.name, []).append(f) ) return f def app_url_value_preprocessor(self, f): """Same as :meth:`url_value_preprocessor` but application wide. """ self.record_once( lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f) ) return f def app_url_defaults(self, f): """Same as :meth:`url_defaults` but application wide. """ self.record_once( lambda s: s.app.url_default_functions.setdefault(None, []).append(f) ) return f def errorhandler(self, code_or_exception): """Registers an error handler that becomes active for this blueprint only. Please be aware that routing does not happen local to a blueprint so an error handler for 404 usually is not handled by a blueprint unless it is caused inside a view function. Another special case is the 500 internal server error which is always looked up from the application. Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator of the :class:`~flask.Flask` object. """ def decorator(f): self.record_once( lambda s: s.app._register_error_handler(self.name, code_or_exception, f) ) return f return decorator def register_error_handler(self, code_or_exception, f): """Non-decorator version of the :meth:`errorhandler` error attach function, akin to the :meth:`~flask.Flask.register_error_handler` application-wide function of the :class:`~flask.Flask` object but for error handlers limited to this blueprint. .. versionadded:: 0.11 """ self.record_once( lambda s: s.app._register_error_handler(self.name, code_or_exception, f) ) Flask-1.1.1/src/flask/cli.py0000644000175000017500000007432513510701642015774 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.cli ~~~~~~~~~ A simple command line application to run flask apps. :copyright: 2010 Pallets :license: BSD-3-Clause """ from __future__ import print_function import ast import inspect import os import platform import re import sys import traceback from functools import update_wrapper from operator import attrgetter from threading import Lock from threading import Thread import click from werkzeug.utils import import_string from ._compat import getargspec from ._compat import itervalues from ._compat import reraise from ._compat import text_type from .globals import current_app from .helpers import get_debug_flag from .helpers import get_env from .helpers import get_load_dotenv try: import dotenv except ImportError: dotenv = None try: import ssl except ImportError: ssl = None class NoAppException(click.UsageError): """Raised if an application cannot be found or loaded.""" def find_best_app(script_info, module): """Given a module instance this tries to find the best possible application in the module or raises an exception. """ from . import Flask # Search for the most common names first. for attr_name in ("app", "application"): app = getattr(module, attr_name, None) if isinstance(app, Flask): return app # Otherwise find the only object that is a Flask instance. matches = [v for v in itervalues(module.__dict__) if isinstance(v, Flask)] if len(matches) == 1: return matches[0] elif len(matches) > 1: raise NoAppException( 'Detected multiple Flask applications in module "{module}". Use ' '"FLASK_APP={module}:name" to specify the correct ' "one.".format(module=module.__name__) ) # Search for app factory functions. for attr_name in ("create_app", "make_app"): app_factory = getattr(module, attr_name, None) if inspect.isfunction(app_factory): try: app = call_factory(script_info, app_factory) if isinstance(app, Flask): return app except TypeError: if not _called_with_wrong_args(app_factory): raise raise NoAppException( 'Detected factory "{factory}" in module "{module}", but ' "could not call it without arguments. Use " "\"FLASK_APP='{module}:{factory}(args)'\" to specify " "arguments.".format(factory=attr_name, module=module.__name__) ) raise NoAppException( 'Failed to find Flask application or factory in module "{module}". ' 'Use "FLASK_APP={module}:name to specify one.'.format(module=module.__name__) ) def call_factory(script_info, app_factory, arguments=()): """Takes an app factory, a ``script_info` object and optionally a tuple of arguments. Checks for the existence of a script_info argument and calls the app_factory depending on that and the arguments provided. """ args_spec = getargspec(app_factory) arg_names = args_spec.args arg_defaults = args_spec.defaults if "script_info" in arg_names: return app_factory(*arguments, script_info=script_info) elif arguments: return app_factory(*arguments) elif not arguments and len(arg_names) == 1 and arg_defaults is None: return app_factory(script_info) return app_factory() def _called_with_wrong_args(factory): """Check whether calling a function raised a ``TypeError`` because the call failed or because something in the factory raised the error. :param factory: the factory function that was called :return: true if the call failed """ tb = sys.exc_info()[2] try: while tb is not None: if tb.tb_frame.f_code is factory.__code__: # in the factory, it was called successfully return False tb = tb.tb_next # didn't reach the factory return True finally: # explicitly delete tb as it is circular referenced # https://docs.python.org/2/library/sys.html#sys.exc_info del tb def find_app_by_string(script_info, module, app_name): """Checks if the given string is a variable name or a function. If it is a function, it checks for specified arguments and whether it takes a ``script_info`` argument and calls the function with the appropriate arguments. """ from . import Flask match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name) if not match: raise NoAppException( '"{name}" is not a valid variable name or function ' "expression.".format(name=app_name) ) name, args = match.groups() try: attr = getattr(module, name) except AttributeError as e: raise NoAppException(e.args[0]) if inspect.isfunction(attr): if args: try: args = ast.literal_eval("({args},)".format(args=args)) except (ValueError, SyntaxError) as e: raise NoAppException( "Could not parse the arguments in " '"{app_name}".'.format(e=e, app_name=app_name) ) else: args = () try: app = call_factory(script_info, attr, args) except TypeError as e: if not _called_with_wrong_args(attr): raise raise NoAppException( '{e}\nThe factory "{app_name}" in module "{module}" could not ' "be called with the specified arguments.".format( e=e, app_name=app_name, module=module.__name__ ) ) else: app = attr if isinstance(app, Flask): return app raise NoAppException( "A valid Flask application was not obtained from " '"{module}:{app_name}".'.format(module=module.__name__, app_name=app_name) ) def prepare_import(path): """Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. """ path = os.path.realpath(path) fname, ext = os.path.splitext(path) if ext == ".py": path = fname if os.path.basename(path) == "__init__": path = os.path.dirname(path) module_name = [] # move up until outside package structure (no __init__.py) while True: path, name = os.path.split(path) module_name.append(name) if not os.path.exists(os.path.join(path, "__init__.py")): break if sys.path[0] != path: sys.path.insert(0, path) return ".".join(module_name[::-1]) def locate_app(script_info, module_name, app_name, raise_if_not_found=True): __traceback_hide__ = True # noqa: F841 try: __import__(module_name) except ImportError: # Reraise the ImportError if it occurred within the imported module. # Determine this by checking whether the trace has a depth > 1. if sys.exc_info()[-1].tb_next: raise NoAppException( 'While importing "{name}", an ImportError was raised:' "\n\n{tb}".format(name=module_name, tb=traceback.format_exc()) ) elif raise_if_not_found: raise NoAppException('Could not import "{name}".'.format(name=module_name)) else: return module = sys.modules[module_name] if app_name is None: return find_best_app(script_info, module) else: return find_app_by_string(script_info, module, app_name) def get_version(ctx, param, value): if not value or ctx.resilient_parsing: return import werkzeug from . import __version__ message = "Python %(python)s\nFlask %(flask)s\nWerkzeug %(werkzeug)s" click.echo( message % { "python": platform.python_version(), "flask": __version__, "werkzeug": werkzeug.__version__, }, color=ctx.color, ) ctx.exit() version_option = click.Option( ["--version"], help="Show the flask version", expose_value=False, callback=get_version, is_flag=True, is_eager=True, ) class DispatchingApp(object): """Special application that dispatches to a Flask application which is imported by name in a background thread. If an error happens it is recorded and shown as part of the WSGI handling which in case of the Werkzeug debugger means that it shows up in the browser. """ def __init__(self, loader, use_eager_loading=False): self.loader = loader self._app = None self._lock = Lock() self._bg_loading_exc_info = None if use_eager_loading: self._load_unlocked() else: self._load_in_background() def _load_in_background(self): def _load_app(): __traceback_hide__ = True # noqa: F841 with self._lock: try: self._load_unlocked() except Exception: self._bg_loading_exc_info = sys.exc_info() t = Thread(target=_load_app, args=()) t.start() def _flush_bg_loading_exception(self): __traceback_hide__ = True # noqa: F841 exc_info = self._bg_loading_exc_info if exc_info is not None: self._bg_loading_exc_info = None reraise(*exc_info) def _load_unlocked(self): __traceback_hide__ = True # noqa: F841 self._app = rv = self.loader() self._bg_loading_exc_info = None return rv def __call__(self, environ, start_response): __traceback_hide__ = True # noqa: F841 if self._app is not None: return self._app(environ, start_response) self._flush_bg_loading_exception() with self._lock: if self._app is not None: rv = self._app else: rv = self._load_unlocked() return rv(environ, start_response) class ScriptInfo(object): """Helper object to deal with Flask applications. This is usually not necessary to interface with as it's used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it's created automatically by the :class:`FlaskGroup` but you can also manually create it and pass it onwards as click object. """ def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True): #: Optionally the import path for the Flask application. self.app_import_path = app_import_path or os.environ.get("FLASK_APP") #: Optionally a function that is passed the script info to create #: the instance of the application. self.create_app = create_app #: A dictionary with arbitrary data that can be associated with #: this script info. self.data = {} self.set_debug_flag = set_debug_flag self._loaded_app = None def load_app(self): """Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned. """ __traceback_hide__ = True # noqa: F841 if self._loaded_app is not None: return self._loaded_app app = None if self.create_app is not None: app = call_factory(self, self.create_app) else: if self.app_import_path: path, name = ( re.split(r":(?![\\/])", self.app_import_path, 1) + [None] )[:2] import_name = prepare_import(path) app = locate_app(self, import_name, name) else: for path in ("wsgi.py", "app.py"): import_name = prepare_import(path) app = locate_app(self, import_name, None, raise_if_not_found=False) if app: break if not app: raise NoAppException( "Could not locate a Flask application. You did not provide " 'the "FLASK_APP" environment variable, and a "wsgi.py" or ' '"app.py" module was not found in the current directory.' ) if self.set_debug_flag: # Update the app's debug flag through the descriptor so that # other values repopulate as well. app.debug = get_debug_flag() self._loaded_app = app return app pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True) def with_appcontext(f): """Wraps a callback so that it's guaranteed to be executed with the script's application context. If callbacks are registered directly to the ``app.cli`` object then they are wrapped with this function by default unless it's disabled. """ @click.pass_context def decorator(__ctx, *args, **kwargs): with __ctx.ensure_object(ScriptInfo).load_app().app_context(): return __ctx.invoke(f, *args, **kwargs) return update_wrapper(decorator, f) class AppGroup(click.Group): """This works similar to a regular click :class:`~click.Group` but it changes the behavior of the :meth:`command` decorator so that it automatically wraps the functions in :func:`with_appcontext`. Not to be confused with :class:`FlaskGroup`. """ def command(self, *args, **kwargs): """This works exactly like the method of the same name on a regular :class:`click.Group` but it wraps callbacks in :func:`with_appcontext` unless it's disabled by passing ``with_appcontext=False``. """ wrap_for_ctx = kwargs.pop("with_appcontext", True) def decorator(f): if wrap_for_ctx: f = with_appcontext(f) return click.Group.command(self, *args, **kwargs)(f) return decorator def group(self, *args, **kwargs): """This works exactly like the method of the same name on a regular :class:`click.Group` but it defaults the group class to :class:`AppGroup`. """ kwargs.setdefault("cls", AppGroup) return click.Group.group(self, *args, **kwargs) class FlaskGroup(AppGroup): """Special subclass of the :class:`AppGroup` group that supports loading more commands from the configured Flask app. Normally a developer does not have to interface with this class but there are some very advanced use cases for which it makes sense to create an instance of this. For information as of why this is useful see :ref:`custom-scripts`. :param add_default_commands: if this is True then the default run and shell commands will be added. :param add_version_option: adds the ``--version`` option. :param create_app: an optional callback that is passed the script info and returns the loaded app. :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv` files to set environment variables. Will also change the working directory to the directory containing the first file found. :param set_debug_flag: Set the app's debug flag based on the active environment .. versionchanged:: 1.0 If installed, python-dotenv will be used to load environment variables from :file:`.env` and :file:`.flaskenv` files. """ def __init__( self, add_default_commands=True, create_app=None, add_version_option=True, load_dotenv=True, set_debug_flag=True, **extra ): params = list(extra.pop("params", None) or ()) if add_version_option: params.append(version_option) AppGroup.__init__(self, params=params, **extra) self.create_app = create_app self.load_dotenv = load_dotenv self.set_debug_flag = set_debug_flag if add_default_commands: self.add_command(run_command) self.add_command(shell_command) self.add_command(routes_command) self._loaded_plugin_commands = False def _load_plugin_commands(self): if self._loaded_plugin_commands: return try: import pkg_resources except ImportError: self._loaded_plugin_commands = True return for ep in pkg_resources.iter_entry_points("flask.commands"): self.add_command(ep.load(), ep.name) self._loaded_plugin_commands = True def get_command(self, ctx, name): self._load_plugin_commands() # We load built-in commands first as these should always be the # same no matter what the app does. If the app does want to # override this it needs to make a custom instance of this group # and not attach the default commands. # # This also means that the script stays functional in case the # application completely fails. rv = AppGroup.get_command(self, ctx, name) if rv is not None: return rv info = ctx.ensure_object(ScriptInfo) try: rv = info.load_app().cli.get_command(ctx, name) if rv is not None: return rv except NoAppException: pass def list_commands(self, ctx): self._load_plugin_commands() # The commands available is the list of both the application (if # available) plus the builtin commands. rv = set(click.Group.list_commands(self, ctx)) info = ctx.ensure_object(ScriptInfo) try: rv.update(info.load_app().cli.list_commands(ctx)) except Exception: # Here we intentionally swallow all exceptions as we don't # want the help page to break if the app does not exist. # If someone attempts to use the command we try to create # the app again and this will give us the error. # However, we will not do so silently because that would confuse # users. traceback.print_exc() return sorted(rv) def main(self, *args, **kwargs): # Set a global flag that indicates that we were invoked from the # command line interface. This is detected by Flask.run to make the # call into a no-op. This is necessary to avoid ugly errors when the # script that is loaded here also attempts to start a server. os.environ["FLASK_RUN_FROM_CLI"] = "true" if get_load_dotenv(self.load_dotenv): load_dotenv() obj = kwargs.get("obj") if obj is None: obj = ScriptInfo( create_app=self.create_app, set_debug_flag=self.set_debug_flag ) kwargs["obj"] = obj kwargs.setdefault("auto_envvar_prefix", "FLASK") return super(FlaskGroup, self).main(*args, **kwargs) def _path_is_ancestor(path, other): """Take ``other`` and remove the length of ``path`` from it. Then join it to ``path``. If it is the original value, ``path`` is an ancestor of ``other``.""" return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other def load_dotenv(path=None): """Load "dotenv" files in order of precedence to set environment variables. If an env var is already set it is not overwritten, so earlier files in the list are preferred over later files. Changes the current working directory to the location of the first file found, with the assumption that it is in the top level project directory and will be where the Python path should import local packages from. This is a no-op if `python-dotenv`_ is not installed. .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme :param path: Load the file at this location instead of searching. :return: ``True`` if a file was loaded. .. versionchanged:: 1.1.0 Returns ``False`` when python-dotenv is not installed, or when the given path isn't a file. .. versionadded:: 1.0 """ if dotenv is None: if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"): click.secho( " * Tip: There are .env or .flaskenv files present." ' Do "pip install python-dotenv" to use them.', fg="yellow", err=True, ) return False # if the given path specifies the actual file then return True, # else False if path is not None: if os.path.isfile(path): return dotenv.load_dotenv(path) return False new_dir = None for name in (".env", ".flaskenv"): path = dotenv.find_dotenv(name, usecwd=True) if not path: continue if new_dir is None: new_dir = os.path.dirname(path) dotenv.load_dotenv(path) if new_dir and os.getcwd() != new_dir: os.chdir(new_dir) return new_dir is not None # at least one file was located and loaded def show_server_banner(env, debug, app_import_path, eager_loading): """Show extra startup messages the first time the server is run, ignoring the reloader. """ if os.environ.get("WERKZEUG_RUN_MAIN") == "true": return if app_import_path is not None: message = ' * Serving Flask app "{0}"'.format(app_import_path) if not eager_loading: message += " (lazy loading)" click.echo(message) click.echo(" * Environment: {0}".format(env)) if env == "production": click.secho( " WARNING: This is a development server. " "Do not use it in a production deployment.", fg="red", ) click.secho(" Use a production WSGI server instead.", dim=True) if debug is not None: click.echo(" * Debug mode: {0}".format("on" if debug else "off")) class CertParamType(click.ParamType): """Click option type for the ``--cert`` option. Allows either an existing file, the string ``'adhoc'``, or an import for a :class:`~ssl.SSLContext` object. """ name = "path" def __init__(self): self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True) def convert(self, value, param, ctx): if ssl is None: raise click.BadParameter( 'Using "--cert" requires Python to be compiled with SSL support.', ctx, param, ) try: return self.path_type(value, param, ctx) except click.BadParameter: value = click.STRING(value, param, ctx).lower() if value == "adhoc": try: import OpenSSL # noqa: F401 except ImportError: raise click.BadParameter( "Using ad-hoc certificates requires pyOpenSSL.", ctx, param ) return value obj = import_string(value, silent=True) if sys.version_info < (2, 7, 9): if obj: return obj else: if isinstance(obj, ssl.SSLContext): return obj raise def _validate_key(ctx, param, value): """The ``--key`` option must be specified when ``--cert`` is a file. Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed. """ cert = ctx.params.get("cert") is_adhoc = cert == "adhoc" if sys.version_info < (2, 7, 9): is_context = cert and not isinstance(cert, (text_type, bytes)) else: is_context = isinstance(cert, ssl.SSLContext) if value is not None: if is_adhoc: raise click.BadParameter( 'When "--cert" is "adhoc", "--key" is not used.', ctx, param ) if is_context: raise click.BadParameter( 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param ) if not cert: raise click.BadParameter('"--cert" must also be specified.', ctx, param) ctx.params["cert"] = cert, value else: if cert and not (is_adhoc or is_context): raise click.BadParameter('Required when using "--cert".', ctx, param) return value class SeparatedPathType(click.Path): """Click option type that accepts a list of values separated by the OS's path separator (``:``, ``;`` on Windows). Each value is validated as a :class:`click.Path` type. """ def convert(self, value, param, ctx): items = self.split_envvar_value(value) super_convert = super(SeparatedPathType, self).convert return [super_convert(item, param, ctx) for item in items] @click.command("run", short_help="Run a development server.") @click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.") @click.option("--port", "-p", default=5000, help="The port to bind to.") @click.option( "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS." ) @click.option( "--key", type=click.Path(exists=True, dir_okay=False, resolve_path=True), callback=_validate_key, expose_value=False, help="The key file to use when specifying a certificate.", ) @click.option( "--reload/--no-reload", default=None, help="Enable or disable the reloader. By default the reloader " "is active if debug is enabled.", ) @click.option( "--debugger/--no-debugger", default=None, help="Enable or disable the debugger. By default the debugger " "is active if debug is enabled.", ) @click.option( "--eager-loading/--lazy-loader", default=None, help="Enable or disable eager loading. By default eager " "loading is enabled if the reloader is disabled.", ) @click.option( "--with-threads/--without-threads", default=True, help="Enable or disable multithreading.", ) @click.option( "--extra-files", default=None, type=SeparatedPathType(), help=( "Extra files that trigger a reload on change. Multiple paths" " are separated by '{}'.".format(os.path.pathsep) ), ) @pass_script_info def run_command( info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files ): """Run a local development server. This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers. The reloader and debugger are enabled by default if FLASK_ENV=development or FLASK_DEBUG=1. """ debug = get_debug_flag() if reload is None: reload = debug if debugger is None: debugger = debug if eager_loading is None: eager_loading = not reload show_server_banner(get_env(), debug, info.app_import_path, eager_loading) app = DispatchingApp(info.load_app, use_eager_loading=eager_loading) from werkzeug.serving import run_simple run_simple( host, port, app, use_reloader=reload, use_debugger=debugger, threaded=with_threads, ssl_context=cert, extra_files=extra_files, ) @click.command("shell", short_help="Run a shell in the app context.") @with_appcontext def shell_command(): """Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to it's configuration. This is useful for executing small snippets of management code without having to manually configure the application. """ import code from .globals import _app_ctx_stack app = _app_ctx_stack.top.app banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % ( sys.version, sys.platform, app.import_name, app.env, app.instance_path, ) ctx = {} # Support the regular Python interpreter startup script if someone # is using it. startup = os.environ.get("PYTHONSTARTUP") if startup and os.path.isfile(startup): with open(startup, "r") as f: eval(compile(f.read(), startup, "exec"), ctx) ctx.update(app.make_shell_context()) code.interact(banner=banner, local=ctx) @click.command("routes", short_help="Show the routes for the app.") @click.option( "--sort", "-s", type=click.Choice(("endpoint", "methods", "rule", "match")), default="endpoint", help=( 'Method to sort routes by. "match" is the order that Flask will match ' "routes when dispatching a request." ), ) @click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.") @with_appcontext def routes_command(sort, all_methods): """Show all registered routes with endpoints and methods.""" rules = list(current_app.url_map.iter_rules()) if not rules: click.echo("No routes were registered.") return ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS")) if sort in ("endpoint", "rule"): rules = sorted(rules, key=attrgetter(sort)) elif sort == "methods": rules = sorted(rules, key=lambda rule: sorted(rule.methods)) rule_methods = [", ".join(sorted(rule.methods - ignored_methods)) for rule in rules] headers = ("Endpoint", "Methods", "Rule") widths = ( max(len(rule.endpoint) for rule in rules), max(len(methods) for methods in rule_methods), max(len(rule.rule) for rule in rules), ) widths = [max(len(h), w) for h, w in zip(headers, widths)] row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths) click.echo(row.format(*headers).strip()) click.echo(row.format(*("-" * width for width in widths))) for rule, methods in zip(rules, rule_methods): click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip()) cli = FlaskGroup( help="""\ A general utility script for Flask applications. Provides commands from Flask, extensions, and the application. Loads the application defined in the FLASK_APP environment variable, or from a wsgi.py file. Setting the FLASK_ENV environment variable to 'development' will enable debug mode. \b {prefix}{cmd} FLASK_APP=hello.py {prefix}{cmd} FLASK_ENV=development {prefix}flask run """.format( cmd="export" if os.name == "posix" else "set", prefix="$ " if os.name == "posix" else "> ", ) ) def main(as_module=False): cli.main(prog_name="python -m flask" if as_module else None) if __name__ == "__main__": main(as_module=True) Flask-1.1.1/src/flask/config.py0000644000175000017500000002350413510701642016463 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.config ~~~~~~~~~~~~ Implements the configuration related objects. :copyright: 2010 Pallets :license: BSD-3-Clause """ import errno import os import types from werkzeug.utils import import_string from . import json from ._compat import iteritems from ._compat import string_types 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, errno.ENOTDIR): 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) Nothing is done to the object before loading. If the object is a class and has ``@property`` attributes, it needs to be instantiated before being passed to this method. 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-1.1.1/src/flask/ctx.py0000644000175000017500000004052413510701642016015 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.ctx ~~~~~~~~~ Implements the objects required to keep the context. :copyright: 2010 Pallets :license: BSD-3-Clause """ import sys from functools import update_wrapper from werkzeug.exceptions import HTTPException from ._compat import BROKEN_PYPY_CTXMGR_EXIT from ._compat import reraise from .globals import _app_ctx_stack from .globals import _request_ctx_stack from .signals import appcontext_popped from .signals import appcontext_pushed # a singleton sentinel value for parameter defaults _sentinel = object() class _AppCtxGlobals(object): """A plain object. Used as a namespace for storing data during an application context. Creating an app context automatically creates this object, which is made available as the :data:`g` proxy. .. describe:: 'key' in g Check whether an attribute is present. .. versionadded:: 0.10 .. describe:: iter(g) Return an iterator over the attribute names. .. versionadded:: 0.10 """ def get(self, name, default=None): """Get an attribute by name, or a default value. Like :meth:`dict.get`. :param name: Name of attribute to get. :param default: Value to return if the attribute is not present. .. versionadded:: 0.10 """ return self.__dict__.get(name, default) def pop(self, name, default=_sentinel): """Get and remove an attribute by name. Like :meth:`dict.pop`. :param name: Name of attribute to pop. :param default: Value to return if the attribute is not present, instead of raise a ``KeyError``. .. versionadded:: 0.11 """ if default is _sentinel: return self.__dict__.pop(name) else: return self.__dict__.pop(name, default) def setdefault(self, name, default=None): """Get the value of an attribute if it is present, otherwise set and return a default value. Like :meth:`dict.setdefault`. :param name: Name of attribute to get. :param: default: Value to set and return if the attribute is not present. .. versionadded:: 0.11 """ 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. The current session is also included in the copied request context. 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 or # flask.session 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, session=None): self.app = app if request is None: request = app.request_class(environ) self.request = request self.url_adapter = None try: self.url_adapter = app.create_url_adapter(self.request) except HTTPException as e: self.request.routing_exception = e self.flashes = None self.session = session # 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 = [] @property def g(self): return _app_ctx_stack.top.g @g.setter def g(self, value): _app_ctx_stack.top.g = value 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 .. versionchanged:: 1.1 The current session object is used instead of reloading the original data. This prevents `flask.session` pointing to an out-of-date object. """ return self.__class__( self.app, environ=self.request.environ, request=self.request, session=self.session, ) def match_request(self): """Can be overridden by a subclass to hook into the matching of the request. """ try: result = self.url_adapter.match(return_rule=True) self.request.url_rule, self.request.view_args = result 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. # Only open a new session if this is the first time the request was # pushed, otherwise stream_with_context loses the session. if self.session is None: session_interface = self.app.session_interface self.session = session_interface.open_session(self.app, self.request) if self.session is None: self.session = session_interface.make_null_session(self.app) if self.url_adapter is not None: self.match_request() 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-1.1.1/src/flask/debughelpers.py0000644000175000017500000001451313510701642017667 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.debughelpers ~~~~~~~~~~~~~~~~~~ Various helpers to make the development experience better. :copyright: 2010 Pallets :license: BSD-3-Clause """ import os from warnings import warn from ._compat import implements_to_string from ._compat import 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)) def explain_ignored_app_run(): if os.environ.get("WERKZEUG_RUN_MAIN") != "true": warn( Warning( "Silently ignoring app.run() because the " "application is run from the flask command line " "executable. Consider putting app.run() behind an " 'if __name__ == "__main__" guard to silence this ' "warning." ), stacklevel=3, ) Flask-1.1.1/src/flask/globals.py0000644000175000017500000000314513510701642016640 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.globals ~~~~~~~~~~~~~ Defines all the global objects that are proxies to the current active context. :copyright: 2010 Pallets :license: BSD-3-Clause """ from functools import partial from werkzeug.local import LocalProxy from werkzeug.local import LocalStack _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 some 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-1.1.1/src/flask/helpers.py0000644000175000017500000012377413510701642016672 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.helpers ~~~~~~~~~~~~~ Implements various helpers. :copyright: 2010 Pallets :license: BSD-3-Clause """ import io import mimetypes import os import pkgutil import posixpath import socket import sys import unicodedata from functools import update_wrapper from threading import RLock from time import time from zlib import adler32 from jinja2 import FileSystemLoader from werkzeug.datastructures import Headers from werkzeug.exceptions import BadRequest from werkzeug.exceptions import NotFound from werkzeug.exceptions import RequestedRangeNotSatisfiable from werkzeug.routing import BuildError from werkzeug.urls import url_quote from werkzeug.wsgi import wrap_file from ._compat import fspath from ._compat import PY2 from ._compat import string_types from ._compat import text_type from .globals import _app_ctx_stack from .globals import _request_ctx_stack from .globals import current_app from .globals import request from .globals import session from .signals import message_flashed # sentinel _missing = object() # what separators does this operating system provide that are not a slash? # this is used by the send_from_directory function to ensure that nobody is # able to access files from outside the filesystem. _os_alt_seps = list( sep for sep in [os.path.sep, os.path.altsep] if sep not in (None, "/") ) def get_env(): """Get the environment the app is running in, indicated by the :envvar:`FLASK_ENV` environment variable. The default is ``'production'``. """ return os.environ.get("FLASK_ENV") or "production" def get_debug_flag(): """Get whether debug mode should be enabled for the app, indicated by the :envvar:`FLASK_DEBUG` environment variable. The default is ``True`` if :func:`.get_env` returns ``'development'``, or ``False`` otherwise. """ val = os.environ.get("FLASK_DEBUG") if not val: return get_env() == "development" return val.lower() not in ("0", "false", "no") def get_load_dotenv(default=True): """Get whether the user has disabled loading dotenv files by setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the files. :param default: What to return if the env var isn't set. """ val = os.environ.get("FLASK_SKIP_DOTENV") if not val: return default return val.lower() in ("0", "false", "no") def _endpoint_from_view_func(view_func): """Internal helper that returns the default endpoint for a given function. This always is the function name. """ assert view_func is not None, "expected view func if endpoint is not provided." return view_func.__name__ def stream_with_context(generator_or_function): """Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more. This function however can help you keep the context around for longer:: from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): @stream_with_context def generate(): yield 'Hello ' yield request.args['name'] yield '!' return Response(generate()) Alternatively it can also be used around a specific generator:: from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): def generate(): yield 'Hello ' yield request.args['name'] yield '!' return Response(stream_with_context(generate())) .. versionadded:: 0.9 """ try: gen = iter(generator_or_function) except TypeError: def decorator(*args, **kwargs): gen = generator_or_function(*args, **kwargs) return stream_with_context(gen) return update_wrapper(decorator, generator_or_function) def generator(): ctx = _request_ctx_stack.top if ctx is None: raise RuntimeError( "Attempted to stream with context but " "there was no context in the first place to keep around." ) with ctx: # Dummy sentinel. Has to be inside the context block or we're # not actually keeping the context around. yield None # The try/finally is here so that if someone passes a WSGI level # iterator in we're still running the cleanup logic. Generators # don't need that because they are closed on their destruction # automatically. try: for item in gen: yield item finally: if hasattr(gen, "close"): gen.close() # The trick is to start the generator. Then the code execution runs until # the first dummy None is yielded at which point the context was already # pushed. This item is discarded. Then when the iteration continues the # real generator is executed. wrapped_g = generator() next(wrapped_g) return wrapped_g def make_response(*args): """Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers. If view looked like this and you want to add a new header:: def index(): return render_template('index.html', foo=42) You can now do something like this:: def index(): response = make_response(render_template('index.html', foo=42)) response.headers['X-Parachutes'] = 'parachutes are cool' return response This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:: response = make_response(render_template('not_found.html'), 404) The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:: response = make_response(view_function()) response.headers['X-Parachutes'] = 'parachutes are cool' Internally this function does the following things: - if no arguments are passed, it creates a new response argument - if one argument is passed, :meth:`flask.Flask.make_response` is invoked with it. - if more than one argument is passed, the arguments are passed to the :meth:`flask.Flask.make_response` function as tuple. .. versionadded:: 0.6 """ if not args: return current_app.response_class() if len(args) == 1: args = args[0] return current_app.make_response(args) def url_for(endpoint, **values): """Generates a URL to the given endpoint with the method provided. Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is ``None``, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (``.``). This will reference the index function local to the current blueprint:: url_for('.index') For more information, head over to the :ref:`Quickstart `. Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when generating URLs outside of a request context. To integrate applications, :class:`Flask` has a hook to intercept URL build errors through :attr:`Flask.url_build_error_handlers`. The `url_for` function results in a :exc:`~werkzeug.routing.BuildError` when the current app does not have a URL for the given endpoint and values. When it does, the :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if it is not ``None``, which can return a string to use as the result of `url_for` (instead of `url_for`'s default to raise the :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception. An example:: def external_url_handler(error, endpoint, values): "Looks up an external URL when `url_for` cannot build a URL." # This is an example of hooking the build_error_handler. # Here, lookup_url is some utility function you've built # which looks up the endpoint in some external URL registry. url = lookup_url(endpoint, **values) if url is None: # External lookup did not have a URL. # Re-raise the BuildError, in context of original traceback. exc_type, exc_value, tb = sys.exc_info() if exc_value is error: raise exc_type, exc_value, tb else: raise error # url_for will use this result, instead of raising BuildError. return url app.url_build_error_handlers.append(external_url_handler) Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and `endpoint` and `values` are the arguments passed into `url_for`. Note that this is for building URLs outside the current application, and not for handling 404 NotFound errors. .. versionadded:: 0.10 The `_scheme` parameter was added. .. versionadded:: 0.9 The `_anchor` and `_method` parameters were added. .. versionadded:: 0.9 Calls :meth:`Flask.handle_build_error` on :exc:`~werkzeug.routing.BuildError`. :param endpoint: the endpoint of the URL (name of the function) :param values: the variable arguments of the URL rule :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which falls back to the `Host` header, then to the IP and port of the request. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration ` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. :param _anchor: if provided this is added as anchor to the URL. :param _method: if provided this explicitly specifies an HTTP method. """ appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError( "Attempted to generate a URL without the application context being" " pushed. This has to be executed when application context is" " available." ) # If request specific information is available we have some extra # features that support "relative" URLs. if reqctx is not None: url_adapter = reqctx.url_adapter blueprint_name = request.blueprint if endpoint[:1] == ".": if blueprint_name is not None: endpoint = blueprint_name + endpoint else: endpoint = endpoint[1:] external = values.pop("_external", False) # Otherwise go with the url adapter from the appctx and make # the URLs external by default. else: url_adapter = appctx.url_adapter if url_adapter is None: raise RuntimeError( "Application was not able to create a URL adapter for request" " independent URL generation. You might be able to fix this by" " setting the SERVER_NAME config variable." ) external = values.pop("_external", True) anchor = values.pop("_anchor", None) method = values.pop("_method", None) scheme = values.pop("_scheme", None) appctx.app.inject_url_defaults(endpoint, values) # This is not the best way to deal with this but currently the # underlying Werkzeug router does not support overriding the scheme on # a per build call basis. old_scheme = None if scheme is not None: if not external: raise ValueError("When specifying _scheme, _external must be True") old_scheme = url_adapter.url_scheme url_adapter.url_scheme = scheme try: try: rv = url_adapter.build( endpoint, values, method=method, force_external=external ) finally: if old_scheme is not None: url_adapter.url_scheme = old_scheme except BuildError as error: # We need to inject the values again so that the app callback can # deal with that sort of stuff. values["_external"] = external values["_anchor"] = anchor values["_method"] = method values["_scheme"] = scheme return appctx.app.handle_url_build_error(error, endpoint, values) if anchor is not None: rv += "#" + url_quote(anchor) return rv def get_template_attribute(template_name, attribute): """Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named :file:`_cider.html` with the following contents: .. sourcecode:: html+jinja {% macro hello(name) %}Hello {{ name }}!{% endmacro %} You can access this from Python code like this:: hello = get_template_attribute('_cider.html', 'hello') return hello('World') .. versionadded:: 0.2 :param template_name: the name of the template :param attribute: the name of the variable of macro to access """ return getattr(current_app.jinja_env.get_template(template_name).module, attribute) def flash(message, category="message"): """Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call :func:`get_flashed_messages`. .. versionchanged:: 0.3 `category` parameter added. :param message: the message to be flashed. :param category: the category for the message. The following values are recommended: ``'message'`` for any kind of message, ``'error'`` for errors, ``'info'`` for information messages and ``'warning'`` for warnings. However any kind of string can be used as category. """ # Original implementation: # # session.setdefault('_flashes', []).append((category, message)) # # This assumed that changes made to mutable structures in the session are # always in sync with the session object, which is not true for session # implementations that use external storage for keeping their keys/values. flashes = session.get("_flashes", []) flashes.append((category, message)) session["_flashes"] = flashes message_flashed.send( current_app._get_current_object(), message=message, category=category ) def get_flashed_messages(with_categories=False, category_filter=()): """Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when `with_categories` is set to ``True``, the return value will be a list of tuples in the form ``(category, message)`` instead. Filter the flashed messages to one or more categories by providing those categories in `category_filter`. This allows rendering categories in separate html blocks. The `with_categories` and `category_filter` arguments are distinct: * `with_categories` controls whether categories are returned with message text (``True`` gives a tuple, where ``False`` gives just the message text). * `category_filter` filters the messages down to only those matching the provided categories. See :ref:`message-flashing-pattern` for examples. .. versionchanged:: 0.3 `with_categories` parameter added. .. versionchanged:: 0.9 `category_filter` parameter added. :param with_categories: set to ``True`` to also receive categories. :param category_filter: whitelist of categories to limit return values """ flashes = _request_ctx_stack.top.flashes if flashes is None: _request_ctx_stack.top.flashes = flashes = ( session.pop("_flashes") if "_flashes" in session else [] ) if category_filter: flashes = list(filter(lambda f: f[0] in category_filter, flashes)) if not with_categories: return [x[1] for x in flashes] return flashes def send_file( filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=None, conditional=False, last_modified=None, ): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an ``X-Sendfile`` header. This however requires support of the underlying webserver for ``X-Sendfile``. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to send certain files as attachment (HTML for instance). The mimetype guessing requires a `filename` or an `attachment_filename` to be provided. ETags will also be attached automatically if a `filename` is provided. You can turn this off by setting `add_etags=False`. If `conditional=True` and `filename` is provided, this method will try to upgrade the response stream to support range requests. This will allow the request to be answered with partial content response. Please never pass filenames to this function from user sources; you should use :func:`send_from_directory` instead. .. versionadded:: 0.2 .. versionadded:: 0.5 The `add_etags`, `cache_timeout` and `conditional` parameters were added. The default behavior is now to attach etags. .. versionchanged:: 0.7 mimetype guessing and etag support for file objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. This functionality will be removed in Flask 1.0 .. versionchanged:: 0.9 cache_timeout pulls its default from application config, when None. .. versionchanged:: 0.12 The filename is no longer automatically inferred from file objects. If you want to use automatic mimetype and etag support, pass a filepath via `filename_or_fp` or `attachment_filename`. .. versionchanged:: 0.12 The `attachment_filename` is preferred over `filename` for MIME-type detection. .. versionchanged:: 1.0 UTF-8 filenames, as specified in `RFC 2231`_, are supported. .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4 .. versionchanged:: 1.0.3 Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers. .. versionchanged:: 1.1 Filename may be a :class:`~os.PathLike` object. .. versionadded:: 1.1 Partial content supports :class:`~io.BytesIO`. :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case ``X-Sendfile`` might not work and fall back to the traditional method. Make sure that the file pointer is positioned at the start of data to send before calling :func:`send_file`. :param mimetype: the mimetype of the file if provided. If a file path is given, auto detection happens as fallback, otherwise an error will be raised. :param as_attachment: set to ``True`` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. :param add_etags: set to ``False`` to disable attaching of etags. :param conditional: set to ``True`` to enable conditional responses. :param cache_timeout: the timeout in seconds for the headers. When ``None`` (default), this value is set by :meth:`~Flask.get_send_file_max_age` of :data:`~flask.current_app`. :param last_modified: set the ``Last-Modified`` header to this value, a :class:`~datetime.datetime` or timestamp. If a file was passed, this overrides its mtime. """ mtime = None fsize = None if hasattr(filename_or_fp, "__fspath__"): filename_or_fp = fspath(filename_or_fp) if isinstance(filename_or_fp, string_types): filename = filename_or_fp if not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) file = None if attachment_filename is None: attachment_filename = os.path.basename(filename) else: file = filename_or_fp filename = None if mimetype is None: if attachment_filename is not None: mimetype = ( mimetypes.guess_type(attachment_filename)[0] or "application/octet-stream" ) if mimetype is None: raise ValueError( "Unable to infer MIME-type because no filename is available. " "Please set either `attachment_filename`, pass a filepath to " "`filename_or_fp` or set your own MIME-type via `mimetype`." ) headers = Headers() if as_attachment: if attachment_filename is None: raise TypeError("filename unavailable, required for sending as attachment") if not isinstance(attachment_filename, text_type): attachment_filename = attachment_filename.decode("utf-8") try: attachment_filename = attachment_filename.encode("ascii") except UnicodeEncodeError: filenames = { "filename": unicodedata.normalize("NFKD", attachment_filename).encode( "ascii", "ignore" ), "filename*": "UTF-8''%s" % url_quote(attachment_filename, safe=b""), } else: filenames = {"filename": attachment_filename} headers.add("Content-Disposition", "attachment", **filenames) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers["X-Sendfile"] = filename fsize = os.path.getsize(filename) headers["Content-Length"] = fsize data = None else: if file is None: file = open(filename, "rb") mtime = os.path.getmtime(filename) fsize = os.path.getsize(filename) headers["Content-Length"] = fsize elif isinstance(file, io.BytesIO): try: fsize = file.getbuffer().nbytes except AttributeError: # Python 2 doesn't have getbuffer fsize = len(file.getvalue()) headers["Content-Length"] = fsize data = wrap_file(request.environ, file) rv = current_app.response_class( data, mimetype=mimetype, headers=headers, direct_passthrough=True ) if last_modified is not None: rv.last_modified = last_modified elif mtime is not None: rv.last_modified = mtime rv.cache_control.public = True if cache_timeout is None: cache_timeout = current_app.get_send_file_max_age(filename) if cache_timeout is not None: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if add_etags and filename is not None: from warnings import warn try: rv.set_etag( "%s-%s-%s" % ( os.path.getmtime(filename), os.path.getsize(filename), adler32( filename.encode("utf-8") if isinstance(filename, text_type) else filename ) & 0xFFFFFFFF, ) ) except OSError: warn( "Access %s failed, maybe it does not exist, so ignore etags in " "headers" % filename, stacklevel=2, ) if conditional: try: rv = rv.make_conditional(request, accept_ranges=True, complete_length=fsize) except RequestedRangeNotSatisfiable: if file is not None: file.close() raise # make sure we don't send x-sendfile for servers that # ignore the 304 status code for x-sendfile. if rv.status_code == 304: rv.headers.pop("x-sendfile", None) return rv def safe_join(directory, *pathnames): """Safely join `directory` and zero or more untrusted `pathnames` components. Example usage:: @app.route('/wiki/') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content = fd.read() # Read and process the file content... :param directory: the trusted base directory. :param pathnames: the untrusted pathnames relative to that directory. :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed paths fall out of its boundaries. """ parts = [directory] for filename in pathnames: if filename != "": filename = posixpath.normpath(filename) if ( any(sep in filename for sep in _os_alt_seps) or os.path.isabs(filename) or filename == ".." or filename.startswith("../") ): raise NotFound() parts.append(filename) return posixpath.join(*parts) def send_from_directory(directory, filename, **options): """Send a file from a given directory with :func:`send_file`. This is a secure way to quickly expose static files from an upload folder or something similar. Example usage:: @app.route('/uploads/') def download_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True) .. admonition:: Sending files and Performance It is strongly recommended to activate either ``X-Sendfile`` support in your webserver or (if no authentication happens) to tell the webserver to serve files for the given path on its own without calling into the web application for improved performance. .. versionadded:: 0.5 :param directory: the directory where all the files are stored. :param filename: the filename relative to that directory to download. :param options: optional keyword arguments that are directly forwarded to :func:`send_file`. """ filename = fspath(filename) directory = fspath(directory) filename = safe_join(directory, filename) if not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) try: if not os.path.isfile(filename): raise NotFound() except (TypeError, ValueError): raise BadRequest() options.setdefault("conditional", True) return send_file(filename, **options) def get_root_path(import_name): """Returns the path to a package or cwd if that cannot be found. This returns the path of a package or the folder that contains a module. Not to be confused with the package path returned by :func:`find_package`. """ # Module already imported and has a file attribute. Use that first. mod = sys.modules.get(import_name) if mod is not None and hasattr(mod, "__file__"): return os.path.dirname(os.path.abspath(mod.__file__)) # Next attempt: check the loader. loader = pkgutil.get_loader(import_name) # Loader does not exist or we're referring to an unloaded main module # or a main module without path (interactive sessions), go with the # current working directory. if loader is None or import_name == "__main__": return os.getcwd() # For .egg, zipimporter does not have get_filename until Python 2.7. # Some other loaders might exhibit the same behavior. if hasattr(loader, "get_filename"): filepath = loader.get_filename(import_name) else: # Fall back to imports. __import__(import_name) mod = sys.modules[import_name] filepath = getattr(mod, "__file__", None) # If we don't have a filepath it might be because we are a # namespace package. In this case we pick the root path from the # first module that is contained in our package. if filepath is None: raise RuntimeError( "No root path can be found for the provided " 'module "%s". This can happen because the ' "module came from an import hook that does " "not provide file name information or because " "it's a namespace package. In this case " "the root path needs to be explicitly " "provided." % import_name ) # filepath is import_name.py for a module, or __init__.py for a package. return os.path.dirname(os.path.abspath(filepath)) def _matching_loader_thinks_module_is_package(loader, mod_name): """Given the loader that loaded a module and the module this function attempts to figure out if the given module is actually a package. """ # If the loader can tell us if something is a package, we can # directly ask the loader. if hasattr(loader, "is_package"): return loader.is_package(mod_name) # importlib's namespace loaders do not have this functionality but # all the modules it loads are packages, so we can take advantage of # this information. elif ( loader.__class__.__module__ == "_frozen_importlib" and loader.__class__.__name__ == "NamespaceLoader" ): return True # Otherwise we need to fail with an error that explains what went # wrong. raise AttributeError( ( "%s.is_package() method is missing but is required by Flask of " "PEP 302 import hooks. If you do not use import hooks and " "you encounter this error please file a bug against Flask." ) % loader.__class__.__name__ ) def _find_package_path(root_mod_name): """Find the path where the module's root exists in""" if sys.version_info >= (3, 4): import importlib.util try: spec = importlib.util.find_spec(root_mod_name) if spec is None: raise ValueError("not found") # ImportError: the machinery told us it does not exist # ValueError: # - the module name was invalid # - the module name is __main__ # - *we* raised `ValueError` due to `spec` being `None` except (ImportError, ValueError): pass # handled below else: # namespace package if spec.origin in {"namespace", None}: return os.path.dirname(next(iter(spec.submodule_search_locations))) # a package (with __init__.py) elif spec.submodule_search_locations: return os.path.dirname(os.path.dirname(spec.origin)) # just a normal module else: return os.path.dirname(spec.origin) # we were unable to find the `package_path` using PEP 451 loaders loader = pkgutil.get_loader(root_mod_name) if loader is None or root_mod_name == "__main__": # import name is not found, or interactive/main module return os.getcwd() else: # For .egg, zipimporter does not have get_filename until Python 2.7. if hasattr(loader, "get_filename"): filename = loader.get_filename(root_mod_name) elif hasattr(loader, "archive"): # zipimporter's loader.archive points to the .egg or .zip # archive filename is dropped in call to dirname below. filename = loader.archive else: # At least one loader is missing both get_filename and archive: # Google App Engine's HardenedModulesHook # # Fall back to imports. __import__(root_mod_name) filename = sys.modules[root_mod_name].__file__ package_path = os.path.abspath(os.path.dirname(filename)) # In case the root module is a package we need to chop of the # rightmost part. This needs to go through a helper function # because of python 3.3 namespace packages. if _matching_loader_thinks_module_is_package(loader, root_mod_name): package_path = os.path.dirname(package_path) return package_path def find_package(import_name): """Finds a package and returns the prefix (or None if the package is not installed) as well as the folder that contains the package or module as a tuple. The package path returned is the module that would have to be added to the pythonpath in order to make it possible to import the module. The prefix is the path below which a UNIX like folder structure exists (lib, share etc.). """ root_mod_name, _, _ = import_name.partition(".") package_path = _find_package_path(root_mod_name) site_parent, site_folder = os.path.split(package_path) py_prefix = os.path.abspath(sys.prefix) if package_path.startswith(py_prefix): return py_prefix, package_path elif site_folder.lower() == "site-packages": parent, folder = os.path.split(site_parent) # Windows like installations if folder.lower() == "lib": base_dir = parent # UNIX like installations elif os.path.basename(parent).lower() == "lib": base_dir = os.path.dirname(parent) else: base_dir = site_parent return base_dir, package_path return None, package_path class locked_cached_property(object): """A decorator that converts a function into a lazy property. The function wrapped is called the first time to retrieve the result and then that calculated result is used the next time you access the value. Works like the one in Werkzeug but has a lock for thread safety. """ def __init__(self, func, name=None, doc=None): self.__name__ = name or func.__name__ self.__module__ = func.__module__ self.__doc__ = doc or func.__doc__ self.func = func self.lock = RLock() def __get__(self, obj, type=None): if obj is None: return self with self.lock: value = obj.__dict__.get(self.__name__, _missing) if value is _missing: value = self.func(obj) obj.__dict__[self.__name__] = value return value class _PackageBoundObject(object): #: The name of the package or module that this app belongs to. Do not #: change this once it is set by the constructor. import_name = None #: Location of the template files to be added to the template lookup. #: ``None`` if templates should not be added. template_folder = None #: Absolute path to the package on the filesystem. Used to look up #: resources contained in the package. root_path = None def __init__(self, import_name, template_folder=None, root_path=None): self.import_name = import_name self.template_folder = template_folder if root_path is None: root_path = get_root_path(self.import_name) self.root_path = root_path self._static_folder = None self._static_url_path = None # circular import from .cli import AppGroup #: The Click command group for registration of CLI commands #: on the application and associated blueprints. These commands #: are accessible via the :command:`flask` command once the #: application has been discovered and blueprints registered. self.cli = AppGroup() @property def static_folder(self): """The absolute path to the configured static folder.""" if self._static_folder is not None: return os.path.join(self.root_path, self._static_folder) @static_folder.setter def static_folder(self, value): self._static_folder = value @property def static_url_path(self): """The URL prefix that the static route will be accessible from. If it was not configured during init, it is derived from :attr:`static_folder`. """ if self._static_url_path is not None: return self._static_url_path if self.static_folder is not None: basename = os.path.basename(self.static_folder) return ("/" + basename).rstrip("/") @static_url_path.setter def static_url_path(self, value): if value is not None: value = value.rstrip("/") self._static_url_path = value @property def has_static_folder(self): """This is ``True`` if the package bound object's container has a folder for static files. .. versionadded:: 0.5 """ return self.static_folder is not None @locked_cached_property def jinja_loader(self): """The Jinja loader for this package bound object. .. versionadded:: 0.5 """ if self.template_folder is not None: return FileSystemLoader(os.path.join(self.root_path, self.template_folder)) def get_send_file_max_age(self, filename): """Provides default cache_timeout for the :func:`send_file` functions. By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from the configuration of :data:`~flask.current_app`. Static file functions such as :func:`send_from_directory` use this function, and :func:`send_file` calls this function on :data:`~flask.current_app` when the given cache_timeout is ``None``. If a cache_timeout is given in :func:`send_file`, that timeout is used; otherwise, this method is called. This allows subclasses to change the behavior when sending files based on the filename. For example, to set the cache timeout for .js files to 60 seconds:: class MyFlask(flask.Flask): def get_send_file_max_age(self, name): if name.lower().endswith('.js'): return 60 return flask.Flask.get_send_file_max_age(self, name) .. versionadded:: 0.9 """ return total_seconds(current_app.send_file_max_age_default) def send_static_file(self, filename): """Function used internally to send static files from the static folder to the browser. .. versionadded:: 0.5 """ if not self.has_static_folder: raise RuntimeError("No static folder for this object") # Ensure get_send_file_max_age is called in all cases. # Here, we ensure get_send_file_max_age is called for Blueprints. cache_timeout = self.get_send_file_max_age(filename) return send_from_directory( self.static_folder, filename, cache_timeout=cache_timeout ) def open_resource(self, resource, mode="rb"): """Opens a resource from the application's resource folder. To see how this works, consider the following folder structure:: /myapplication.py /schema.sql /static /style.css /templates /layout.html /index.html If you want to open the :file:`schema.sql` file you would do the following:: with app.open_resource('schema.sql') as f: contents = f.read() do_something_with(contents) :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. :param mode: Open file in this mode. Only reading is supported, valid values are "r" (or "rt") and "rb". """ if mode not in {"r", "rt", "rb"}: raise ValueError("Resources can only be opened for reading") return open(os.path.join(self.root_path, resource), mode) def total_seconds(td): """Returns the total seconds from a timedelta object. :param timedelta td: the timedelta to be converted in seconds :returns: number of seconds :rtype: int """ return td.days * 60 * 60 * 24 + td.seconds def is_ip(value): """Determine if the given string is an IP address. Python 2 on Windows doesn't provide ``inet_pton``, so this only checks IPv4 addresses in that environment. :param value: value to check :type value: str :return: True if string is an IP address :rtype: bool """ if PY2 and os.name == "nt": try: socket.inet_aton(value) return True except socket.error: return False for family in (socket.AF_INET, socket.AF_INET6): try: socket.inet_pton(family, value) except socket.error: pass else: return True return False Flask-1.1.1/src/flask/json/0000755000175000017500000000000013510702200015600 5ustar daviddavid00000000000000Flask-1.1.1/src/flask/json/__init__.py0000644000175000017500000002732413510701642017732 0ustar daviddavid00000000000000# -*- coding: utf-8 -*- """ flask.json ~~~~~~~~~~ :copyright: 2010 Pallets :license: BSD-3-Clause """ import codecs import io import uuid from datetime import date from datetime import datetime from itsdangerous import json as _json from jinja2 import Markup from werkzeug.http import http_date from .._compat import PY2 from .._compat import text_type from ..globals import current_app from ..globals import request try: import dataclasses except ImportError: dataclasses = None # 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 encoder by also supporting ``datetime``, ``UUID``, ``dataclasses``, and ``Markup`` objects. ``datetime`` objects are serialized as RFC 822 datetime strings. This is the 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, datetime): return http_date(o.utctimetuple()) if isinstance(o, date): return http_date(o.timetuple()) if isinstance(o, uuid.UUID): return str(o) if dataclasses and dataclasses.is_dataclass(o): return dataclasses.asdict(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, app=None): """Inject default arguments for dump functions.""" if app is None: app = current_app if app: bp = app.blueprints.get(request.blueprint) if request else None kwargs.setdefault( "cls", bp.json_encoder if bp and bp.json_encoder else app.json_encoder ) if not app.config["JSON_AS_ASCII"]: kwargs.setdefault("ensure_ascii", False) kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"]) else: kwargs.setdefault("sort_keys", True) kwargs.setdefault("cls", JSONEncoder) def _load_arg_defaults(kwargs, app=None): """Inject default arguments for load functions.""" if app is None: app = current_app if app: bp = app.blueprints.get(request.blueprint) if request else None kwargs.setdefault( "cls", bp.json_decoder if bp and bp.json_decoder else app.json_decoder ) else: kwargs.setdefault("cls", JSONDecoder) def detect_encoding(data): """Detect which UTF codec was used to encode the given bytes. The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big or little endian. Some editors or libraries may prepend a BOM. :param data: Bytes in unknown UTF encoding. :return: UTF encoding name """ head = data[:4] if head[:3] == codecs.BOM_UTF8: return "utf-8-sig" if b"\x00" not in head: return "utf-8" if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE): return "utf-32" if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE): return "utf-16" if len(head) == 4: if head[:3] == b"\x00\x00\x00": return "utf-32-be" if head[::2] == b"\x00\x00": return "utf-16-be" if head[1:] == b"\x00\x00\x00": return "utf-32-le" if head[1::2] == b"\x00\x00": return "utf-16-le" if len(head) == 2: return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le" return "utf-8" def dumps(obj, app=None, **kwargs): """Serialize ``obj`` to a JSON-formatted string. If there is an app context pushed, use the current app's configured encoder (:attr:`~flask.Flask.json_encoder`), or fall back to the default :class:`JSONEncoder`. Takes the same arguments as the built-in :func:`json.dumps`, and does some extra configuration based on the application. If the simplejson package is installed, it is preferred. :param obj: Object to serialize to JSON. :param app: App instance to use to configure the JSON encoder. Uses ``current_app`` if not given, and falls back to the default encoder when not in an app context. :param kwargs: Extra arguments passed to :func:`json.dumps`. .. versionchanged:: 1.0.3 ``app`` can be passed directly, rather than requiring an app context for configuration. """ _dump_arg_defaults(kwargs, app=app) 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, app=None, **kwargs): """Like :func:`dumps` but writes into a file object.""" _dump_arg_defaults(kwargs, app=app) 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, app=None, **kwargs): """Deserialize an object from a JSON-formatted string ``s``. If there is an app context pushed, use the current app's configured decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the default :class:`JSONDecoder`. Takes the same arguments as the built-in :func:`json.loads`, and does some extra configuration based on the application. If the simplejson package is installed, it is preferred. :param s: JSON string to deserialize. :param app: App instance to use to configure the JSON decoder. Uses ``current_app`` if not given, and falls back to the default encoder when not in an app context. :param kwargs: Extra arguments passed to :func:`json.dumps`. .. versionchanged:: 1.0.3 ``app`` can be passed directly, rather than requiring an app context for configuration. """ _load_arg_defaults(kwargs, app=app) if isinstance(s, bytes): encoding = kwargs.pop("encoding", None) if encoding is None: encoding = detect_encoding(s) s = s.decode(encoding) return _json.loads(s, **kwargs) def load(fp, app=None, **kwargs): """Like :func:`loads` but reads from a file object.""" _load_arg_defaults(kwargs, app=app) 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 ``") 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('{{ "

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. Check out the :gh:`example source ` for a full application demonstrating the code on this page, as well as the same thing using ``XMLHttpRequest`` and ``fetch``. Flask-1.1.1/docs/patterns/lazyloading.rst0000644000175000017500000000740113510701642020612 0ustar daviddavid00000000000000Lazily 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-1.1.1/docs/patterns/methodoverrides.rst0000644000175000017500000000266013510701642021502 0ustar daviddavid00000000000000Adding 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. Then the method is replaced with the header value before being passed to Flask. This can 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: 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, wrap the app object with the middleware:: from flask import Flask app = Flask(__name__) app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) Flask-1.1.1/docs/patterns/mongoengine.rst0000644000175000017500000000545213510701642020606 0ustar daviddavid00000000000000MongoDB with MongoEngine ======================== Using a document database like MongoDB is a common alternative to relational SQL databases. This pattern shows how to use `MongoEngine`_, a document mapper library, to integrate with MongoDB. A running MongoDB server and `Flask-MongoEngine`_ are required. :: pip install flask-mongoengine .. _MongoEngine: http://mongoengine.org .. _Flask-MongoEngine: https://flask-mongoengine.readthedocs.io Configuration ------------- Basic setup can be done by defining ``MONGODB_SETTINGS`` on ``app.config`` and creating a ``MongoEngine`` instance. :: from flask import Flask from flask_mongoengine import MongoEngine app = Flask(__name__) app.config['MONGODB_SETTINGS'] = { "db": "myapp", } db = MongoEngine(app) Mapping Documents ----------------- To declare a model that represents a Mongo document, create a class that inherits from ``Document`` and declare each of the fields. :: import mongoengine as me class Movie(me.Document): title = me.StringField(required=True) year = me.IntField() rated = me.StringField() director = me.StringField() actors = me.ListField() If the document has nested fields, use ``EmbeddedDocument`` to defined the fields of the embedded document and ``EmbeddedDocumentField`` to declare it on the parent document. :: class Imdb(me.EmbeddedDocument): imdb_id = me.StringField() rating = me.DecimalField() votes = me.IntField() class Movie(me.Document): ... imdb = me.EmbeddedDocumentField(Imdb) Creating Data ------------- Instantiate your document class with keyword arguments for the fields. You can also assign values to the field attributes after instantiation. Then call ``doc.save()``. :: bttf = Movie(title="Back To The Future", year=1985) bttf.actors = [ "Michael J. Fox", "Christopher Lloyd" ] bttf.imdb = Imdb(imdb_id="tt0088763", rating=8.5) bttf.save() Queries ------- Use the class ``objects`` attribute to make queries. A keyword argument looks for an equal value on the field. :: bttf = Movies.objects(title="Back To The Future").get_or_404() Query operators may be used by concatenating them with the field name using a double-underscore. ``objects``, and queries returned by calling it, are iterable. :: some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first() for recents in Movie.objects(year__gte=2017): print(recents.title) Documentation ------------- There are many more ways to define and query documents with MongoEngine. For more information, check out the `official documentation `_. Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check out their `documentation `_ as well. Flask-1.1.1/docs/patterns/mongokit.rst0000644000175000017500000000020313510701642020115 0ustar daviddavid00000000000000:orphan: MongoDB with MongoKit ===================== MongoKit is no longer maintained. See :doc:`/patterns/mongoengine` instead. Flask-1.1.1/docs/patterns/packages.rst0000644000175000017500000001072013510701642020051 0ustar daviddavid00000000000000.. _larger-applications: Larger Applications =================== Imagine a simple flask application structure that looks like this:: /yourapplication yourapplication.py /static style.css /templates layout.html index.html login.html ... While this is fine for small applications, for larger applications it's a good idea to use a package instead of a module. The :ref:`tutorial ` is structured to use the package pattern, see the :gh:`example code `. 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. Similarly you can turn on the development features like this:: $ export FLASK_ENV=development 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-1.1.1/docs/patterns/requestchecksum.rst0000644000175000017500000000350713510701642021513 0ustar daviddavid00000000000000Request 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-1.1.1/docs/patterns/singlepageapplications.rst0000644000175000017500000000130313510701642023015 0ustar daviddavid00000000000000Single-Page Applications ======================== Flask can be used to serve Single-Page Applications (SPA) by placing static files produced by your frontend framework in a subfolder inside of your project. You will also need to create a catch-all endpoint that routes all requests to your SPA. The following example demonstrates how to serve an SPA along with an API:: from flask import Flask, jsonify app = Flask(__name__, static_folder='app') @app.route("/heartbeat") def heartbeat(): return jsonify({"status": "healthy"}) @app.route('/', defaults={'path': ''}) @app.route('/') def catch_all(path): return app.send_static_file("index.html") Flask-1.1.1/docs/patterns/sqlalchemy.rst0000644000175000017500000001643413510701642020445 0ustar daviddavid00000000000000.. _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: https://flask-sqlalchemy.palletsprojects.com/ 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: https://www.sqlalchemy.org/ .. _declarative: https://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-1.1.1/docs/patterns/sqlite3.rst0000644000175000017500000001206113510701642017657 0ustar daviddavid00000000000000.. _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 `get_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-1.1.1/docs/patterns/streaming.rst0000644000175000017500000000613413510701642020270 0ustar daviddavid00000000000000Streaming Contents ================== Sometimes you want to send an enormous amount of data to the client, much more than you want to keep in memory. When you are generating the data on the fly though, how do you send that back to the client without the roundtrip to the filesystem? The answer is by using generators and direct responses. Basic Usage ----------- This is a basic view function that generates a lot of CSV data on the fly. The trick is to have an inner function that uses a generator to generate data and to then invoke that function and pass it to a response object:: from flask import Response @app.route('/large.csv') def generate_large_csv(): def generate(): for row in iter_all_rows(): yield ','.join(row) + '\n' return Response(generate(), mimetype='text/csv') Each ``yield`` expression is directly sent to the browser. Note though that some WSGI middlewares might break streaming, so be careful there in debug environments with profilers and other things you might have enabled. Streaming from Templates ------------------------ The Jinja2 template engine also supports rendering templates piece by piece. This functionality is not directly exposed by Flask because it is quite uncommon, but you can easily do it yourself:: from flask import Response def stream_template(template_name, **context): app.update_template_context(context) t = app.jinja_env.get_template(template_name) rv = t.stream(context) rv.enable_buffering(5) return rv @app.route('/my-large-page.html') def render_large_template(): rows = iter_all_rows() return Response(stream_template('the_template.html', rows=rows)) The trick here is to get the template object from the Jinja2 environment on the application and to call :meth:`~jinja2.Template.stream` instead of :meth:`~jinja2.Template.render` which returns a stream object instead of a string. Since we're bypassing the Flask template render functions and using the template object itself we have to make sure to update the render context ourselves by calling :meth:`~flask.Flask.update_template_context`. The template is then evaluated as the stream is iterated over. Since each time you do a yield the server will flush the content to the client you might want to buffer up a few items in the template which you can do with ``rv.enable_buffering(size)``. ``5`` is a sane default. Streaming with Context ---------------------- .. versionadded:: 0.9 Note that when you stream data, the request context is already gone the moment the function executes. Flask 0.9 provides you with a helper that can keep the request context around during the execution of the generator:: from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): def generate(): yield 'Hello ' yield request.args['name'] yield '!' return Response(stream_with_context(generate())) Without the :func:`~flask.stream_with_context` function you would get a :class:`RuntimeError` at that point. Flask-1.1.1/docs/patterns/subclassing.rst0000644000175000017500000000124413510701642020611 0ustar daviddavid00000000000000Subclassing 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-1.1.1/docs/patterns/templateinheritance.rst0000644000175000017500000000426013510701642022322 0ustar daviddavid00000000000000.. _template-inheritance: Template Inheritance ==================== The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines **blocks** that child templates can override. Sounds complicated but is very basic. It's easiest to understand it by starting with an example. Base Template ------------- This template, which we'll call :file:`layout.html`, defines a simple HTML skeleton document that you might use for a simple two-column page. It's the job of "child" templates to fill the empty blocks with content: .. sourcecode:: html+jinja {% block head %} {% block title %}{% endblock %} - My Webpage {% endblock %}