diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..45198266c6 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,17 @@ +{ + "name": "pallets/flask", + "image": "mcr.microsoft.com/devcontainers/python:3", + "customizations": { + "vscode": { + "settings": { + "python.defaultInterpreterPath": "${workspaceFolder}/.venv", + "python.terminal.activateEnvInCurrentTerminal": true, + "python.terminal.launchArgs": [ + "-X", + "dev" + ] + } + } + }, + "onCreateCommand": ".devcontainer/on-create-command.sh" +} diff --git a/.devcontainer/on-create-command.sh b/.devcontainer/on-create-command.sh new file mode 100755 index 0000000000..eaebea6185 --- /dev/null +++ b/.devcontainer/on-create-command.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -e +python3 -m venv --upgrade-deps .venv +. .venv/bin/activate +pip install -r requirements/dev.txt +pip install -e . +pre-commit install --install-hooks diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..2ff985a67a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true +end_of_line = lf +charset = utf-8 +max_line_length = 88 + +[*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}] +indent_size = 2 diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 8383fff94e..0000000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -CHANGES merge=union diff --git a/.github/ISSUE_TEMPLATE.rst b/.github/ISSUE_TEMPLATE.rst deleted file mode 100644 index 8854961ae1..0000000000 --- a/.github/ISSUE_TEMPLATE.rst +++ /dev/null @@ -1,2 +0,0 @@ -The issue tracker is a tool to address bugs. -Please use the #pocoo IRC channel on freenode or Stack Overflow for questions. diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 0000000000..0917c79791 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,27 @@ +--- +name: Bug report +about: Report a bug in Flask (not other projects which depend on Flask) +--- + + + + + + + +Environment: + +- Python version: +- Flask version: diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000..a8f9f0b75a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: Security issue + url: https://github.com/pallets/flask/security/advisories/new + about: Do not report security issues publicly. Create a private advisory. + - name: Questions on GitHub Discussions + url: https://github.com/pallets/flask/discussions/ + about: Ask questions about your own code on the Discussions tab. + - name: Questions on Discord + url: https://discord.gg/pallets + about: Ask questions about your own code on our Discord chat. diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md new file mode 100644 index 0000000000..52c2aed416 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.md @@ -0,0 +1,15 @@ +--- +name: Feature request +about: Suggest a new feature for Flask +--- + + + + diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..eb124d251a --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,25 @@ + + + + + diff --git a/.github/workflows/lock.yaml b/.github/workflows/lock.yaml new file mode 100644 index 0000000000..f3055c5459 --- /dev/null +++ b/.github/workflows/lock.yaml @@ -0,0 +1,24 @@ +name: Lock inactive closed issues +# Lock closed issues that have not received any further activity for two weeks. +# This does not close open issues, only humans may do that. It is easier to +# respond to new issues with fresh examples rather than continuing discussions +# on old issues. + +on: + schedule: + - cron: '0 0 * * *' +permissions: + issues: write + pull-requests: write + discussions: write +concurrency: + group: lock +jobs: + lock: + runs-on: ubuntu-latest + steps: + - uses: dessant/lock-threads@1bf7ec25051fe7c00bdd17e6a7cf3d7bfb7dc771 # v5.0.1 + with: + issue-inactive-days: 14 + pr-inactive-days: 14 + discussion-inactive-days: 14 diff --git a/.github/workflows/pre-commit.yaml b/.github/workflows/pre-commit.yaml new file mode 100644 index 0000000000..4c27fb447e --- /dev/null +++ b/.github/workflows/pre-commit.yaml @@ -0,0 +1,25 @@ +name: pre-commit +on: + pull_request: + push: + branches: [main, stable] +jobs: + main: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1 + with: + enable-cache: true + prune-cache: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + id: setup-python + with: + python-version-file: pyproject.toml + - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 + with: + path: ~/.cache/pre-commit + key: pre-commit|${{ hashFiles('pyproject.toml', '.pre-commit-config.yaml') }} + - run: uv run --locked --group pre-commit pre-commit run --show-diff-on-failure --color=always --all-files + - uses: pre-commit-ci/lite-action@5d6cc0eb514c891a40562a58a8e71576c5c7fb43 # v1.1.0 + if: ${{ !cancelled() }} diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml new file mode 100644 index 0000000000..0846199fee --- /dev/null +++ b/.github/workflows/publish.yaml @@ -0,0 +1,63 @@ +name: Publish +on: + push: + tags: ['*'] +jobs: + build: + runs-on: ubuntu-latest + outputs: + hash: ${{ steps.hash.outputs.hash }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1 + with: + enable-cache: true + prune-cache: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version-file: pyproject.toml + - run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV + - run: uv build + - name: generate hash + id: hash + run: cd dist && echo "hash=$(sha256sum * | base64 -w0)" >> $GITHUB_OUTPUT + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + path: ./dist + provenance: + needs: [build] + permissions: + actions: read + id-token: write + contents: write + # Can't pin with hash due to how this workflow works. + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.1.0 + with: + base64-subjects: ${{ needs.build.outputs.hash }} + create-release: + needs: [provenance] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + - name: create release + run: > + gh release create --draft --repo ${{ github.repository }} + ${{ github.ref_name }} + *.intoto.jsonl/* artifact/* + env: + GH_TOKEN: ${{ github.token }} + publish-pypi: + needs: [provenance] + environment: + name: publish + url: https://pypi.org/project/Flask/${{ github.ref_name }} + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + - uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4 + with: + packages-dir: artifact/ diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 0000000000..c438af2666 --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,51 @@ +name: Tests +on: + pull_request: + paths-ignore: ['docs/**', 'README.md'] + push: + branches: [main, stable] + paths-ignore: ['docs/**', 'README.md'] +jobs: + tests: + name: ${{ matrix.name || matrix.python }} + runs-on: ${{ matrix.os || 'ubuntu-latest' }} + strategy: + fail-fast: false + matrix: + include: + - {python: '3.13'} + - {name: Windows, python: '3.13', os: windows-latest} + - {name: Mac, python: '3.13', os: macos-latest} + - {python: '3.12'} + - {python: '3.11'} + - {python: '3.10'} + - {name: PyPy, python: 'pypy-3.11', tox: pypy3.11} + - {name: Minimum Versions, python: '3.13', tox: tests-min} + - {name: Development Versions, python: '3.10', tox: tests-dev} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1 + with: + enable-cache: true + prune-cache: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: ${{ matrix.python }} + - run: uv run --locked tox run -e ${{ matrix.tox || format('py{0}', matrix.python) }} + typing: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1 + with: + enable-cache: true + prune-cache: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version-file: pyproject.toml + - name: cache mypy + uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 + with: + path: ./.mypy_cache + key: mypy|${{ hashFiles('pyproject.toml') }} + - run: uv run --locked tox run -e typing diff --git a/.gitignore b/.gitignore index 9bf4f063aa..8441e5a64f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,8 @@ -.DS_Store -*.pyc -*.pyo -env -env* -dist -build -*.egg -*.egg-info -_mailinglist -.tox -.cache/ .idea/ +.vscode/ +__pycache__/ +dist/ +.coverage* +htmlcov/ +.tox/ +docs/_build/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 3d7df1490a..0000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "docs/_themes"] - path = docs/_themes - url = https://github.com/mitsuhiko/flask-sphinx-themes.git diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000..3708663006 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,18 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: 24e02b24b8ab2b7c76225602d13fa60e12d114e6 # frozen: v0.11.9 + hooks: + - id: ruff + - id: ruff-format + - repo: https://github.com/astral-sh/uv-pre-commit + rev: 14ac15b122e538e407d036ff45e3895b7cf4a2bf # frozen: 0.7.3 + hooks: + - id: uv-lock + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: cef0300fd0fc4d2a87a85fa2093c6b283ea36f4b # frozen: v5.0.0 + hooks: + - id: check-merge-conflict + - id: debug-statements + - id: fix-byte-order-marker + - id: trailing-whitespace + - id: end-of-file-fixer diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000000..acbd83f90b --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,10 @@ +version: 2 +build: + os: ubuntu-24.04 + tools: + python: '3.13' + commands: + - asdf plugin add uv + - asdf install uv latest + - asdf global uv latest + - uv run --group docs sphinx-build -W -b dirhtml docs $READTHEDOCS_OUTPUT/html diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0f99a7e8c9..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,55 +0,0 @@ -sudo: false -language: python - -python: - - "2.6" - - "2.7" - - "pypy" - - "3.3" - - "3.4" - - "3.5" - -env: - - REQUIREMENTS=lowest - - REQUIREMENTS=lowest-simplejson - - REQUIREMENTS=release - - REQUIREMENTS=release-simplejson - - REQUIREMENTS=devel - - REQUIREMENTS=devel-simplejson - -matrix: - exclude: - # Python 3 support currently does not work with lowest requirements - - python: "3.3" - env: REQUIREMENTS=lowest - - python: "3.3" - env: REQUIREMENTS=lowest-simplejson - - python: "3.4" - env: REQUIREMENTS=lowest - - python: "3.4" - env: REQUIREMENTS=lowest-simplejson - - python: "3.5" - env: REQUIREMENTS=lowest - - python: "3.5" - env: REQUIREMENTS=lowest-simplejson - - -install: - - pip install tox - -script: - - tox -e py-$REQUIREMENTS - -branches: - except: - - website - -notifications: - email: false - irc: - channels: - - "chat.freenode.net#pocoo" - on_success: change - on_failure: always - use_notice: true - skip_join: true diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index cc157dc41b..0000000000 --- a/AUTHORS +++ /dev/null @@ -1,37 +0,0 @@ -Flask is written and maintained by Armin Ronacher and -various contributors: - -Development Lead -```````````````` - -- Armin Ronacher - -Patches and Suggestions -``````````````````````` - -- Adam Zapletal -- Ali Afshar -- Chris Edgemon -- Chris Grindstaff -- Christopher Grebs -- Daniel Neuhäuser -- Dan Sully -- David Lord @davidism -- Edmond Burnett -- Florent Xicluna -- Georg Brandl -- Jeff Widman @jeffwidman -- Justin Quick -- Kenneth Reitz -- Keyan Pishdadian -- Marian Sigler -- Martijn Pieters -- Matt Campell -- Matthew Frazier -- Michael van Tellingen -- Ron DuPlain -- Sebastien Estienne -- Simon Sapin -- Stephane Wirtel -- Thomas Schranz -- Zhao Xiaohong diff --git a/CHANGES b/CHANGES deleted file mode 100644 index 13ce156c22..0000000000 --- a/CHANGES +++ /dev/null @@ -1,599 +0,0 @@ -Flask Changelog -=============== - -Here you can see the full list of changes between each Flask release. - -Version 0.12 ------------- - -- the cli command now responds to `--version`. -- Mimetype guessing and ETag generation for file-like objects in ``send_file`` - has been removed, as per issue ``#104``. See pull request ``#1849``. -- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to - ``application/octet-stream``. See pull request ``#1988``. -- Make ``flask.safe_join`` able to join multiple paths like ``os.path.join`` - (pull request ``#1730``). -- Revert a behavior change that made the dev server crash instead of returning - a Internal Server Error (pull request ``#2006``). -- Correctly invoke response handlers for both regular request dispatching as - well as error handlers. -- Disable logger propagation by default for the app logger. -- Add support for range requests in ``send_file``. -- ``app.test_client`` includes preset default environment, which can now be - directly set, instead of per ``client.get``. - -Version 0.11.2 --------------- - -Bugfix release, unreleased - -- Fix crash when running under PyPy3, see pull request ``#1814``. - -Version 0.11.1 --------------- - -Bugfix release, released on June 7th 2016. - -- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. See - pull request ``#1872``. - -Version 0.11 ------------- - -Released on May 29th 2016, codename Absinthe. - -- Added support to serializing top-level arrays to :func:`flask.jsonify`. This - introduces a security risk in ancient browsers. See - :ref:`json-security` for details. -- Added before_render_template signal. -- Added `**kwargs` to :meth:`flask.Test.test_client` to support passing - additional keyword arguments to the constructor of - :attr:`flask.Flask.test_client_class`. -- Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the - set-cookie behavior. If set to ``True`` a permanent session will be - refreshed each request and get their lifetime extended, if set to - ``False`` it will only be modified if the session actually modifies. - Non permanent sessions are not affected by this and will always - expire if the browser window closes. -- Made Flask support custom JSON mimetypes for incoming data. -- Added support for returning tuples in the form ``(response, headers)`` - from a view function. -- Added :meth:`flask.Config.from_json`. -- Added :attr:`flask.Flask.config_class`. -- Added :meth:`flask.Config.get_namespace`. -- Templates are no longer automatically reloaded outside of debug mode. This - can be configured with the new ``TEMPLATES_AUTO_RELOAD`` config key. -- Added a workaround for a limitation in Python 3.3's namespace loader. -- Added support for explicit root paths when using Python 3.3's namespace - packages. -- Added :command:`flask` and the ``flask.cli`` module to start the local - debug server through the click CLI system. This is recommended over the old - ``flask.run()`` method as it works faster and more reliable due to a - different design and also replaces ``Flask-Script``. -- Error handlers that match specific classes are now checked first, - thereby allowing catching exceptions that are subclasses of HTTP - exceptions (in ``werkzeug.exceptions``). This makes it possible - for an extension author to create exceptions that will by default - result in the HTTP error of their choosing, but may be caught with - a custom error handler if desired. -- Added :meth:`flask.Config.from_mapping`. -- Flask will now log by default even if debug is disabled. The log format is - now hardcoded but the default log handling can be disabled through the - ``LOGGER_HANDLER_POLICY`` configuration key. -- Removed deprecated module functionality. -- Added the ``EXPLAIN_TEMPLATE_LOADING`` config flag which when enabled will - instruct Flask to explain how it locates templates. This should help - users debug when the wrong templates are loaded. -- Enforce blueprint handling in the order they were registered for template - loading. -- Ported test suite to py.test. -- Deprecated ``request.json`` in favour of ``request.get_json()``. -- Add "pretty" and "compressed" separators definitions in jsonify() method. - Reduces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing - unnecessary white space included by default after separators. -- JSON responses are now terminated with a newline character, because it is a - convention that UNIX text files end with a newline and some clients don't - deal well when this newline is missing. See - https://github.com/pallets/flask/pull/1262 -- this came up originally as a - part of https://github.com/kennethreitz/httpbin/issues/168 -- The automatically provided ``OPTIONS`` method is now correctly disabled if - the user registered an overriding rule with the lowercase-version - ``options`` (issue ``#1288``). -- ``flask.json.jsonify`` now supports the ``datetime.date`` type (pull request - ``#1326``). -- Don't leak exception info of already catched exceptions to context teardown - handlers (pull request ``#1393``). -- Allow custom Jinja environment subclasses (pull request ``#1422``). -- ``flask.g`` now has ``pop()`` and ``setdefault`` methods. -- Turn on autoescape for ``flask.templating.render_template_string`` by default - (pull request ``#1515``). -- ``flask.ext`` is now deprecated (pull request ``#1484``). -- ``send_from_directory`` now raises BadRequest if the filename is invalid on - the server OS (pull request ``#1763``). -- Added the ``JSONIFY_MIMETYPE`` configuration variable (pull request ``#1728``). -- Exceptions during teardown handling will no longer leave bad application - contexts lingering around. - -Version 0.10.2 --------------- - -(bugfix release, release date to be announced) - -- Fixed broken `test_appcontext_signals()` test case. -- Raise an :exc:`AttributeError` in :func:`flask.helpers.find_package` with a - useful message explaining why it is raised when a PEP 302 import hook is used - without an `is_package()` method. -- Fixed an issue causing exceptions raised before entering a request or app - context to be passed to teardown handlers. -- Fixed an issue with query parameters getting removed from requests in - the test client when absolute URLs were requested. -- Made `@before_first_request` into a decorator as intended. -- Fixed an etags bug when sending a file streams with a name. -- Fixed `send_from_directory` not expanding to the application root path - correctly. -- Changed logic of before first request handlers to flip the flag after - invoking. This will allow some uses that are potentially dangerous but - should probably be permitted. -- Fixed Python 3 bug when a handler from `app.url_build_error_handlers` - reraises the `BuildError`. - -Version 0.10.1 --------------- - -(bugfix release, released on June 14th 2013) - -- Fixed an issue where ``|tojson`` was not quoting single quotes which - made the filter not work properly in HTML attributes. Now it's - possible to use that filter in single quoted attributes. This should - make using that filter with angular.js easier. -- Added support for byte strings back to the session system. This broke - compatibility with the common case of people putting binary data for - token verification into the session. -- Fixed an issue where registering the same method twice for the same endpoint - would trigger an exception incorrectly. - -Version 0.10 ------------- - -Released on June 13th 2013, codename Limoncello. - -- Changed default cookie serialization format from pickle to JSON to - limit the impact an attacker can do if the secret key leaks. See - :ref:`upgrading-to-010` for more information. -- Added ``template_test`` methods in addition to the already existing - ``template_filter`` method family. -- Added ``template_global`` methods in addition to the already existing - ``template_filter`` method family. -- Set the content-length header for x-sendfile. -- ``tojson`` filter now does not escape script blocks in HTML5 parsers. -- ``tojson`` used in templates is now safe by default due. This was - allowed due to the different escaping behavior. -- Flask will now raise an error if you attempt to register a new function - on an already used endpoint. -- Added wrapper module around simplejson and added default serialization - of datetime objects. This allows much easier customization of how - JSON is handled by Flask or any Flask extension. -- Removed deprecated internal ``flask.session`` module alias. Use - ``flask.sessions`` instead to get the session module. This is not to - be confused with ``flask.session`` the session proxy. -- Templates can now be rendered without request context. The behavior is - slightly different as the ``request``, ``session`` and ``g`` objects - will not be available and blueprint's context processors are not - called. -- The config object is now available to the template as a real global and - not through a context processor which makes it available even in imported - templates by default. -- Added an option to generate non-ascii encoded JSON which should result - in less bytes being transmitted over the network. It's disabled by - default to not cause confusion with existing libraries that might expect - ``flask.json.dumps`` to return bytestrings by default. -- ``flask.g`` is now stored on the app context instead of the request - context. -- ``flask.g`` now gained a ``get()`` method for not erroring out on non - existing items. -- ``flask.g`` now can be used with the ``in`` operator to see what's defined - and it now is iterable and will yield all attributes stored. -- ``flask.Flask.request_globals_class`` got renamed to - ``flask.Flask.app_ctx_globals_class`` which is a better name to what it - does since 0.10. -- `request`, `session` and `g` are now also added as proxies to the template - context which makes them available in imported templates. One has to be - very careful with those though because usage outside of macros might - cause caching. -- Flask will no longer invoke the wrong error handlers if a proxy - exception is passed through. -- Added a workaround for chrome's cookies in localhost not working - as intended with domain names. -- Changed logic for picking defaults for cookie values from sessions - to work better with Google Chrome. -- Added `message_flashed` signal that simplifies flashing testing. -- Added support for copying of request contexts for better working with - greenlets. -- Removed custom JSON HTTP exception subclasses. If you were relying on them - you can reintroduce them again yourself trivially. Using them however is - strongly discouraged as the interface was flawed. -- Python requirements changed: requiring Python 2.6 or 2.7 now to prepare - for Python 3.3 port. -- Changed how the teardown system is informed about exceptions. This is now - more reliable in case something handles an exception halfway through - the error handling process. -- Request context preservation in debug mode now keeps the exception - information around which means that teardown handlers are able to - distinguish error from success cases. -- Added the ``JSONIFY_PRETTYPRINT_REGULAR`` configuration variable. -- Flask now orders JSON keys by default to not trash HTTP caches due to - different hash seeds between different workers. -- Added `appcontext_pushed` and `appcontext_popped` signals. -- The builtin run method now takes the ``SERVER_NAME`` into account when - picking the default port to run on. -- Added `flask.request.get_json()` as a replacement for the old - `flask.request.json` property. - -Version 0.9 ------------ - -Released on July 1st 2012, codename Campari. - -- The :func:`flask.Request.on_json_loading_failed` now returns a JSON formatted - response by default. -- The :func:`flask.url_for` function now can generate anchors to the - generated links. -- The :func:`flask.url_for` function now can also explicitly generate - URL rules specific to a given HTTP method. -- Logger now only returns the debug log setting if it was not set - explicitly. -- Unregister a circular dependency between the WSGI environment and - the request object when shutting down the request. This means that - environ ``werkzeug.request`` will be ``None`` after the response was - returned to the WSGI server but has the advantage that the garbage - collector is not needed on CPython to tear down the request unless - the user created circular dependencies themselves. -- Session is now stored after callbacks so that if the session payload - is stored in the session you can still modify it in an after - request callback. -- The :class:`flask.Flask` class will avoid importing the provided import name - if it can (the required first parameter), to benefit tools which build Flask - instances programmatically. The Flask class will fall back to using import - on systems with custom module hooks, e.g. Google App Engine, or when the - import name is inside a zip archive (usually a .egg) prior to Python 2.7. -- Blueprints now have a decorator to add custom template filters application - wide, :meth:`flask.Blueprint.app_template_filter`. -- The Flask and Blueprint classes now have a non-decorator method for adding - custom template filters application wide, - :meth:`flask.Flask.add_template_filter` and - :meth:`flask.Blueprint.add_app_template_filter`. -- The :func:`flask.get_flashed_messages` function now allows rendering flashed - message categories in separate blocks, through a ``category_filter`` - argument. -- The :meth:`flask.Flask.run` method now accepts ``None`` for `host` and `port` - arguments, using default values when ``None``. This allows for calling run - using configuration values, e.g. ``app.run(app.config.get('MYHOST'), - app.config.get('MYPORT'))``, with proper behavior whether or not a config - file is provided. -- The :meth:`flask.render_template` method now accepts a either an iterable of - template names or a single template name. Previously, it only accepted a - single template name. On an iterable, the first template found is rendered. -- Added :meth:`flask.Flask.app_context` which works very similar to the - request context but only provides access to the current application. This - also adds support for URL generation without an active request context. -- View functions can now return a tuple with the first instance being an - instance of :class:`flask.Response`. This allows for returning - ``jsonify(error="error msg"), 400`` from a view function. -- :class:`~flask.Flask` and :class:`~flask.Blueprint` now provide a - :meth:`~flask.Flask.get_send_file_max_age` hook for subclasses to override - behavior of serving static files from Flask when using - :meth:`flask.Flask.send_static_file` (used for the default static file - handler) and :func:`~flask.helpers.send_file`. This hook is provided a - filename, which for example allows changing cache controls by file extension. - The default max-age for `send_file` and static files can be configured - through a new ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, which is - used in the default `get_send_file_max_age` implementation. -- Fixed an assumption in sessions implementation which could break message - flashing on sessions implementations which use external storage. -- Changed the behavior of tuple return values from functions. They are no - longer arguments to the response object, they now have a defined meaning. -- Added :attr:`flask.Flask.request_globals_class` to allow a specific class to - be used on creation of the :data:`~flask.g` instance of each request. -- Added `required_methods` attribute to view functions to force-add methods - on registration. -- Added :func:`flask.after_this_request`. -- Added :func:`flask.stream_with_context` and the ability to push contexts - multiple times without producing unexpected behavior. - -Version 0.8.1 -------------- - -Bugfix release, released on July 1st 2012 - -- Fixed an issue with the undocumented `flask.session` module to not - work properly on Python 2.5. It should not be used but did cause - some problems for package managers. - -Version 0.8 ------------ - -Released on September 29th 2011, codename Rakija - -- Refactored session support into a session interface so that - the implementation of the sessions can be changed without - having to override the Flask class. -- Empty session cookies are now deleted properly automatically. -- View functions can now opt out of getting the automatic - OPTIONS implementation. -- HTTP exceptions and Bad Request errors can now be trapped so that they - show up normally in the traceback. -- Flask in debug mode is now detecting some common problems and tries to - warn you about them. -- Flask in debug mode will now complain with an assertion error if a view - was attached after the first request was handled. This gives earlier - feedback when users forget to import view code ahead of time. -- Added the ability to register callbacks that are only triggered once at - the beginning of the first request. (:meth:`Flask.before_first_request`) -- Malformed JSON data will now trigger a bad request HTTP exception instead - of a value error which usually would result in a 500 internal server - error if not handled. This is a backwards incompatible change. -- Applications now not only have a root path where the resources and modules - are located but also an instance path which is the designated place to - drop files that are modified at runtime (uploads etc.). Also this is - conceptually only instance depending and outside version control so it's - the perfect place to put configuration files etc. For more information - see :ref:`instance-folders`. -- Added the ``APPLICATION_ROOT`` configuration variable. -- Implemented :meth:`~flask.testing.TestClient.session_transaction` to - easily modify sessions from the test environment. -- Refactored test client internally. The ``APPLICATION_ROOT`` configuration - variable as well as ``SERVER_NAME`` are now properly used by the test client - as defaults. -- Added :attr:`flask.views.View.decorators` to support simpler decorating of - pluggable (class-based) views. -- Fixed an issue where the test client if used with the "with" statement did not - trigger the execution of the teardown handlers. -- Added finer control over the session cookie parameters. -- HEAD requests to a method view now automatically dispatch to the `get` - method if no handler was implemented. -- Implemented the virtual :mod:`flask.ext` package to import extensions from. -- The context preservation on exceptions is now an integral component of - Flask itself and no longer of the test client. This cleaned up some - internal logic and lowers the odds of runaway request contexts in unittests. - -Version 0.7.3 -------------- - -Bugfix release, release date to be decided - -- Fixed the Jinja2 environment's list_templates method not returning the - correct names when blueprints or modules were involved. - -Version 0.7.2 -------------- - -Bugfix release, released on July 6th 2011 - -- Fixed an issue with URL processors not properly working on - blueprints. - -Version 0.7.1 -------------- - -Bugfix release, released on June 29th 2011 - -- Added missing future import that broke 2.5 compatibility. -- Fixed an infinite redirect issue with blueprints. - -Version 0.7 ------------ - -Released on June 28th 2011, codename Grappa - -- Added :meth:`~flask.Flask.make_default_options_response` - which can be used by subclasses to alter the default - behavior for ``OPTIONS`` responses. -- Unbound locals now raise a proper :exc:`RuntimeError` instead - of an :exc:`AttributeError`. -- Mimetype guessing and etag support based on file objects is now - deprecated for :func:`flask.send_file` because it was unreliable. - Pass filenames instead or attach your own etags and provide a - proper mimetype by hand. -- Static file handling for modules now requires the name of the - static folder to be supplied explicitly. The previous autodetection - was not reliable and caused issues on Google's App Engine. Until - 1.0 the old behavior will continue to work but issue dependency - warnings. -- fixed a problem for Flask to run on jython. -- added a ``PROPAGATE_EXCEPTIONS`` configuration variable that can be - used to flip the setting of exception propagation which previously - was linked to ``DEBUG`` alone and is now linked to either ``DEBUG`` or - ``TESTING``. -- Flask no longer internally depends on rules being added through the - `add_url_rule` function and can now also accept regular werkzeug - rules added to the url map. -- Added an `endpoint` method to the flask application object which - allows one to register a callback to an arbitrary endpoint with - a decorator. -- Use Last-Modified for static file sending instead of Date which - was incorrectly introduced in 0.6. -- Added `create_jinja_loader` to override the loader creation process. -- Implemented a silent flag for `config.from_pyfile`. -- Added `teardown_request` decorator, for functions that should run at the end - of a request regardless of whether an exception occurred. Also the behavior - for `after_request` was changed. It's now no longer executed when an exception - is raised. See :ref:`upgrading-to-new-teardown-handling` -- Implemented :func:`flask.has_request_context` -- Deprecated `init_jinja_globals`. Override the - :meth:`~flask.Flask.create_jinja_environment` method instead to - achieve the same functionality. -- Added :func:`flask.safe_join` -- The automatic JSON request data unpacking now looks at the charset - mimetype parameter. -- Don't modify the session on :func:`flask.get_flashed_messages` if there - are no messages in the session. -- `before_request` handlers are now able to abort requests with errors. -- it is not possible to define user exception handlers. That way you can - provide custom error messages from a central hub for certain errors that - might occur during request processing (for instance database connection - errors, timeouts from remote resources etc.). -- Blueprints can provide blueprint specific error handlers. -- Implemented generic :ref:`views` (class-based views). - -Version 0.6.1 -------------- - -Bugfix release, released on December 31st 2010 - -- Fixed an issue where the default ``OPTIONS`` response was - not exposing all valid methods in the ``Allow`` header. -- Jinja2 template loading syntax now allows "./" in front of - a template load path. Previously this caused issues with - module setups. -- Fixed an issue where the subdomain setting for modules was - ignored for the static folder. -- Fixed a security problem that allowed clients to download arbitrary files - if the host server was a windows based operating system and the client - uses backslashes to escape the directory the files where exposed from. - -Version 0.6 ------------ - -Released on July 27th 2010, codename Whisky - -- after request functions are now called in reverse order of - registration. -- OPTIONS is now automatically implemented by Flask unless the - application explicitly adds 'OPTIONS' as method to the URL rule. - In this case no automatic OPTIONS handling kicks in. -- static rules are now even in place if there is no static folder - for the module. This was implemented to aid GAE which will - remove the static folder if it's part of a mapping in the .yml - file. -- the :attr:`~flask.Flask.config` is now available in the templates - as `config`. -- context processors will no longer override values passed directly - to the render function. -- added the ability to limit the incoming request data with the - new ``MAX_CONTENT_LENGTH`` configuration value. -- the endpoint for the :meth:`flask.Module.add_url_rule` method - is now optional to be consistent with the function of the - same name on the application object. -- added a :func:`flask.make_response` function that simplifies - creating response object instances in views. -- added signalling support based on blinker. This feature is currently - optional and supposed to be used by extensions and applications. If - you want to use it, make sure to have `blinker`_ installed. -- refactored the way URL adapters are created. This process is now - fully customizable with the :meth:`~flask.Flask.create_url_adapter` - method. -- modules can now register for a subdomain instead of just an URL - prefix. This makes it possible to bind a whole module to a - configurable subdomain. - -.. _blinker: https://pypi.python.org/pypi/blinker - -Version 0.5.2 -------------- - -Bugfix Release, released on July 15th 2010 - -- fixed another issue with loading templates from directories when - modules were used. - -Version 0.5.1 -------------- - -Bugfix Release, released on July 6th 2010 - -- fixes an issue with template loading from directories when modules - where used. - -Version 0.5 ------------ - -Released on July 6th 2010, codename Calvados - -- fixed a bug with subdomains that was caused by the inability to - specify the server name. The server name can now be set with - the ``SERVER_NAME`` config key. This key is now also used to set - the session cookie cross-subdomain wide. -- autoescaping is no longer active for all templates. Instead it - is only active for ``.html``, ``.htm``, ``.xml`` and ``.xhtml``. - Inside templates this behavior can be changed with the - ``autoescape`` tag. -- refactored Flask internally. It now consists of more than a - single file. -- :func:`flask.send_file` now emits etags and has the ability to - do conditional responses builtin. -- (temporarily) dropped support for zipped applications. This was a - rarely used feature and led to some confusing behavior. -- added support for per-package template and static-file directories. -- removed support for `create_jinja_loader` which is no longer used - in 0.5 due to the improved module support. -- added a helper function to expose files from any directory. - -Version 0.4 ------------ - -Released on June 18th 2010, codename Rakia - -- added the ability to register application wide error handlers - from modules. -- :meth:`~flask.Flask.after_request` handlers are now also invoked - if the request dies with an exception and an error handling page - kicks in. -- test client has not the ability to preserve the request context - for a little longer. This can also be used to trigger custom - requests that do not pop the request stack for testing. -- because the Python standard library caches loggers, the name of - the logger is configurable now to better support unittests. -- added ``TESTING`` switch that can activate unittesting helpers. -- the logger switches to ``DEBUG`` mode now if debug is enabled. - -Version 0.3.1 -------------- - -Bugfix release, released on May 28th 2010 - -- fixed a error reporting bug with :meth:`flask.Config.from_envvar` -- removed some unused code from flask -- release does no longer include development leftover files (.git - folder for themes, built documentation in zip and pdf file and - some .pyc files) - -Version 0.3 ------------ - -Released on May 28th 2010, codename Schnaps - -- added support for categories for flashed messages. -- the application now configures a :class:`logging.Handler` and will - log request handling exceptions to that logger when not in debug - mode. This makes it possible to receive mails on server errors - for example. -- added support for context binding that does not require the use of - the with statement for playing in the console. -- the request context is now available within the with statement making - it possible to further push the request context or pop it. -- added support for configurations. - -Version 0.2 ------------ - -Released on May 12th 2010, codename Jägermeister - -- various bugfixes -- integrated JSON support -- added :func:`~flask.get_template_attribute` helper function. -- :meth:`~flask.Flask.add_url_rule` can now also register a - view function. -- refactored internal request dispatching. -- server listens on 127.0.0.1 by default now to fix issues with chrome. -- added external URL support. -- added support for :func:`~flask.send_file` -- module support and internal request handling refactoring - to better support pluggable applications. -- sessions can be set to be permanent now on a per-session basis. -- better error reporting on missing secret keys. -- added support for Google Appengine. - -Version 0.1 ------------ - -First public preview release. diff --git a/CHANGES.rst b/CHANGES.rst new file mode 100644 index 0000000000..37e777dca8 --- /dev/null +++ b/CHANGES.rst @@ -0,0 +1,1622 @@ +Version 3.2.0 +------------- + +Unreleased + +- Drop support for Python 3.9. :pr:`5730` +- Remove previously deprecated code: ``__version__``. :pr:`5648` + + +Version 3.1.1 +------------- + +Released 2025-05-13 + +- Fix signing key selection order when key rotation is enabled via + ``SECRET_KEY_FALLBACKS``. :ghsa:`4grg-w6v8-c28g` +- Fix type hint for ``cli_runner.invoke``. :issue:`5645` +- ``flask --help`` loads the app and plugins first to make sure all commands + are shown. :issue:`5673` +- Mark sans-io base class as being able to handle views that return + ``AsyncIterable``. This is not accurate for Flask, but makes typing easier + for Quart. :pr:`5659` + + +Version 3.1.0 +------------- + +Released 2024-11-13 + +- Drop support for Python 3.8. :pr:`5623` +- Update minimum dependency versions to latest feature releases. + Werkzeug >= 3.1, ItsDangerous >= 2.2, Blinker >= 1.9. :pr:`5624,5633` +- Provide a configuration option to control automatic option + responses. :pr:`5496` +- ``Flask.open_resource``/``open_instance_resource`` and + ``Blueprint.open_resource`` take an ``encoding`` parameter to use when + opening in text mode. It defaults to ``utf-8``. :issue:`5504` +- ``Request.max_content_length`` can be customized per-request instead of only + through the ``MAX_CONTENT_LENGTH`` config. Added + ``MAX_FORM_MEMORY_SIZE`` and ``MAX_FORM_PARTS`` config. Added documentation + about resource limits to the security page. :issue:`5625` +- Add support for the ``Partitioned`` cookie attribute (CHIPS), with the + ``SESSION_COOKIE_PARTITIONED`` config. :issue:`5472` +- ``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files. + ``load_dotenv`` loads default files in addition to a path unless + ``load_defaults=False`` is passed. :issue:`5628` +- Support key rotation with the ``SECRET_KEY_FALLBACKS`` config, a list of old + secret keys that can still be used for unsigning. Extensions will need to + add support. :issue:`5621` +- Fix how setting ``host_matching=True`` or ``subdomain_matching=False`` + interacts with ``SERVER_NAME``. Setting ``SERVER_NAME`` no longer restricts + requests to only that domain. :issue:`5553` +- ``Request.trusted_hosts`` is checked during routing, and can be set through + the ``TRUSTED_HOSTS`` config. :issue:`5636` + + +Version 3.0.3 +------------- + +Released 2024-04-07 + +- The default ``hashlib.sha1`` may not be available in FIPS builds. Don't + access it at import time so the developer has time to change the default. + :issue:`5448` +- Don't initialize the ``cli`` attribute in the sansio scaffold, but rather in + the ``Flask`` concrete class. :pr:`5270` + + +Version 3.0.2 +------------- + +Released 2024-02-03 + +- Correct type for ``jinja_loader`` property. :issue:`5388` +- Fix error with ``--extra-files`` and ``--exclude-patterns`` CLI options. + :issue:`5391` + + +Version 3.0.1 +------------- + +Released 2024-01-18 + +- Correct type for ``path`` argument to ``send_file``. :issue:`5336` +- Fix a typo in an error message for the ``flask run --key`` option. :pr:`5344` +- Session data is untagged without relying on the built-in ``json.loads`` + ``object_hook``. This allows other JSON providers that don't implement that. + :issue:`5381` +- Address more type findings when using mypy strict mode. :pr:`5383` + + +Version 3.0.0 +------------- + +Released 2023-09-30 + +- Remove previously deprecated code. :pr:`5223` +- Deprecate the ``__version__`` attribute. Use feature detection, or + ``importlib.metadata.version("flask")``, instead. :issue:`5230` +- Restructure the code such that the Flask (app) and Blueprint + classes have Sans-IO bases. :pr:`5127` +- Allow self as an argument to url_for. :pr:`5264` +- Require Werkzeug >= 3.0.0. + + +Version 2.3.3 +------------- + +Released 2023-08-21 + +- Python 3.12 compatibility. +- Require Werkzeug >= 2.3.7. +- Use ``flit_core`` instead of ``setuptools`` as build backend. +- Refactor how an app's root and instance paths are determined. :issue:`5160` + + +Version 2.3.2 +------------- + +Released 2023-05-01 + +- Set ``Vary: Cookie`` header when the session is accessed, modified, or refreshed. +- Update Werkzeug requirement to >=2.3.3 to apply recent bug fixes. + :ghsa:`m2qf-hxjv-5gpq` + + +Version 2.3.1 +------------- + +Released 2023-04-25 + +- Restore deprecated ``from flask import Markup``. :issue:`5084` + + +Version 2.3.0 +------------- + +Released 2023-04-25 + +- Drop support for Python 3.7. :pr:`5072` +- Update minimum requirements to the latest versions: Werkzeug>=2.3.0, Jinja2>3.1.2, + itsdangerous>=2.1.2, click>=8.1.3. +- Remove previously deprecated code. :pr:`4995` + + - The ``push`` and ``pop`` methods of the deprecated ``_app_ctx_stack`` and + ``_request_ctx_stack`` objects are removed. ``top`` still exists to give + extensions more time to update, but it will be removed. + - The ``FLASK_ENV`` environment variable, ``ENV`` config key, and ``app.env`` + property are removed. + - The ``session_cookie_name``, ``send_file_max_age_default``, ``use_x_sendfile``, + ``propagate_exceptions``, and ``templates_auto_reload`` properties on ``app`` + are removed. + - The ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_MIMETYPE``, and + ``JSONIFY_PRETTYPRINT_REGULAR`` config keys are removed. + - The ``app.before_first_request`` and ``bp.before_app_first_request`` decorators + are removed. + - ``json_encoder`` and ``json_decoder`` attributes on app and blueprint, and the + corresponding ``json.JSONEncoder`` and ``JSONDecoder`` classes, are removed. + - The ``json.htmlsafe_dumps`` and ``htmlsafe_dump`` functions are removed. + - Calling setup methods on blueprints after registration is an error instead of a + warning. :pr:`4997` + +- Importing ``escape`` and ``Markup`` from ``flask`` is deprecated. Import them + directly from ``markupsafe`` instead. :pr:`4996` +- The ``app.got_first_request`` property is deprecated. :pr:`4997` +- The ``locked_cached_property`` decorator is deprecated. Use a lock inside the + decorated function if locking is needed. :issue:`4993` +- Signals are always available. ``blinker>=1.6.2`` is a required dependency. The + ``signals_available`` attribute is deprecated. :issue:`5056` +- Signals support ``async`` subscriber functions. :pr:`5049` +- Remove uses of locks that could cause requests to block each other very briefly. + :issue:`4993` +- Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``. + :pr:`4947` +- Ensure subdomains are applied with nested blueprints. :issue:`4834` +- ``config.from_file`` can use ``text=False`` to indicate that the parser wants a + binary file instead. :issue:`4989` +- If a blueprint is created with an empty name it raises a ``ValueError``. + :issue:`5010` +- ``SESSION_COOKIE_DOMAIN`` does not fall back to ``SERVER_NAME``. The default is not + to set the domain, which modern browsers interpret as an exact match rather than + a subdomain match. Warnings about ``localhost`` and IP addresses are also removed. + :issue:`5051` +- The ``routes`` command shows each rule's ``subdomain`` or ``host`` when domain + matching is in use. :issue:`5004` +- Use postponed evaluation of annotations. :pr:`5071` + + +Version 2.2.5 +------------- + +Released 2023-05-02 + +- Update for compatibility with Werkzeug 2.3.3. +- Set ``Vary: Cookie`` header when the session is accessed, modified, or refreshed. + + +Version 2.2.4 +------------- + +Released 2023-04-25 + +- Update for compatibility with Werkzeug 2.3. + + +Version 2.2.3 +------------- + +Released 2023-02-15 + +- Autoescape is enabled by default for ``.svg`` template files. :issue:`4831` +- Fix the type of ``template_folder`` to accept ``pathlib.Path``. :issue:`4892` +- Add ``--debug`` option to the ``flask run`` command. :issue:`4777` + + +Version 2.2.2 +------------- + +Released 2022-08-08 + +- Update Werkzeug dependency to >= 2.2.2. This includes fixes related + to the new faster router, header parsing, and the development + server. :pr:`4754` +- Fix the default value for ``app.env`` to be ``"production"``. This + attribute remains deprecated. :issue:`4740` + + +Version 2.2.1 +------------- + +Released 2022-08-03 + +- Setting or accessing ``json_encoder`` or ``json_decoder`` raises a + deprecation warning. :issue:`4732` + + +Version 2.2.0 +------------- + +Released 2022-08-01 + +- Remove previously deprecated code. :pr:`4667` + + - Old names for some ``send_file`` parameters have been removed. + ``download_name`` replaces ``attachment_filename``, ``max_age`` + replaces ``cache_timeout``, and ``etag`` replaces ``add_etags``. + Additionally, ``path`` replaces ``filename`` in + ``send_from_directory``. + - The ``RequestContext.g`` property returning ``AppContext.g`` is + removed. + +- Update Werkzeug dependency to >= 2.2. +- The app and request contexts are managed using Python context vars + directly rather than Werkzeug's ``LocalStack``. This should result + in better performance and memory use. :pr:`4682` + + - Extension maintainers, be aware that ``_app_ctx_stack.top`` + and ``_request_ctx_stack.top`` are deprecated. Store data on + ``g`` instead using a unique prefix, like + ``g._extension_name_attr``. + +- The ``FLASK_ENV`` environment variable and ``app.env`` attribute are + deprecated, removing the distinction between development and debug + mode. Debug mode should be controlled directly using the ``--debug`` + option or ``app.run(debug=True)``. :issue:`4714` +- Some attributes that proxied config keys on ``app`` are deprecated: + ``session_cookie_name``, ``send_file_max_age_default``, + ``use_x_sendfile``, ``propagate_exceptions``, and + ``templates_auto_reload``. Use the relevant config keys instead. + :issue:`4716` +- Add new customization points to the ``Flask`` app object for many + previously global behaviors. + + - ``flask.url_for`` will call ``app.url_for``. :issue:`4568` + - ``flask.abort`` will call ``app.aborter``. + ``Flask.aborter_class`` and ``Flask.make_aborter`` can be used + to customize this aborter. :issue:`4567` + - ``flask.redirect`` will call ``app.redirect``. :issue:`4569` + - ``flask.json`` is an instance of ``JSONProvider``. A different + provider can be set to use a different JSON library. + ``flask.jsonify`` will call ``app.json.response``, other + functions in ``flask.json`` will call corresponding functions in + ``app.json``. :pr:`4692` + +- JSON configuration is moved to attributes on the default + ``app.json`` provider. ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, + ``JSONIFY_MIMETYPE``, and ``JSONIFY_PRETTYPRINT_REGULAR`` are + deprecated. :pr:`4692` +- Setting custom ``json_encoder`` and ``json_decoder`` classes on the + app or a blueprint, and the corresponding ``json.JSONEncoder`` and + ``JSONDecoder`` classes, are deprecated. JSON behavior can now be + overridden using the ``app.json`` provider interface. :pr:`4692` +- ``json.htmlsafe_dumps`` and ``json.htmlsafe_dump`` are deprecated, + the function is built-in to Jinja now. :pr:`4692` +- Refactor ``register_error_handler`` to consolidate error checking. + Rewrite some error messages to be more consistent. :issue:`4559` +- Use Blueprint decorators and functions intended for setup after + registering the blueprint will show a warning. In the next version, + this will become an error just like the application setup methods. + :issue:`4571` +- ``before_first_request`` is deprecated. Run setup code when creating + the application instead. :issue:`4605` +- Added the ``View.init_every_request`` class attribute. If a view + subclass sets this to ``False``, the view will not create a new + instance on every request. :issue:`2520`. +- A ``flask.cli.FlaskGroup`` Click group can be nested as a + sub-command in a custom CLI. :issue:`3263` +- Add ``--app`` and ``--debug`` options to the ``flask`` CLI, instead + of requiring that they are set through environment variables. + :issue:`2836` +- Add ``--env-file`` option to the ``flask`` CLI. This allows + specifying a dotenv file to load in addition to ``.env`` and + ``.flaskenv``. :issue:`3108` +- It is no longer required to decorate custom CLI commands on + ``app.cli`` or ``blueprint.cli`` with ``@with_appcontext``, an app + context will already be active at that point. :issue:`2410` +- ``SessionInterface.get_expiration_time`` uses a timezone-aware + value. :pr:`4645` +- View functions can return generators directly instead of wrapping + them in a ``Response``. :pr:`4629` +- Add ``stream_template`` and ``stream_template_string`` functions to + render a template as a stream of pieces. :pr:`4629` +- A new implementation of context preservation during debugging and + testing. :pr:`4666` + + - ``request``, ``g``, and other context-locals point to the + correct data when running code in the interactive debugger + console. :issue:`2836` + - Teardown functions are always run at the end of the request, + even if the context is preserved. They are also run after the + preserved context is popped. + - ``stream_with_context`` preserves context separately from a + ``with client`` block. It will be cleaned up when + ``response.get_data()`` or ``response.close()`` is called. + +- Allow returning a list from a view function, to convert it to a + JSON response like a dict is. :issue:`4672` +- When type checking, allow ``TypedDict`` to be returned from view + functions. :pr:`4695` +- Remove the ``--eager-loading/--lazy-loading`` options from the + ``flask run`` command. The app is always eager loaded the first + time, then lazily loaded in the reloader. The reloader always prints + errors immediately but continues serving. Remove the internal + ``DispatchingApp`` middleware used by the previous implementation. + :issue:`4715` + + +Version 2.1.3 +------------- + +Released 2022-07-13 + +- Inline some optional imports that are only used for certain CLI + commands. :pr:`4606` +- Relax type annotation for ``after_request`` functions. :issue:`4600` +- ``instance_path`` for namespace packages uses the path closest to + the imported submodule. :issue:`4610` +- Clearer error message when ``render_template`` and + ``render_template_string`` are used outside an application context. + :pr:`4693` + + +Version 2.1.2 +------------- + +Released 2022-04-28 + +- Fix type annotation for ``json.loads``, it accepts str or bytes. + :issue:`4519` +- The ``--cert`` and ``--key`` options on ``flask run`` can be given + in either order. :issue:`4459` + + +Version 2.1.1 +------------- + +Released on 2022-03-30 + +- Set the minimum required version of importlib_metadata to 3.6.0, + which is required on Python < 3.10. :issue:`4502` + + +Version 2.1.0 +------------- + +Released 2022-03-28 + +- Drop support for Python 3.6. :pr:`4335` +- Update Click dependency to >= 8.0. :pr:`4008` +- Remove previously deprecated code. :pr:`4337` + + - The CLI does not pass ``script_info`` to app factory functions. + - ``config.from_json`` is replaced by + ``config.from_file(name, load=json.load)``. + - ``json`` functions no longer take an ``encoding`` parameter. + - ``safe_join`` is removed, use ``werkzeug.utils.safe_join`` + instead. + - ``total_seconds`` is removed, use ``timedelta.total_seconds`` + instead. + - The same blueprint cannot be registered with the same name. Use + ``name=`` when registering to specify a unique name. + - The test client's ``as_tuple`` parameter is removed. Use + ``response.request.environ`` instead. :pr:`4417` + +- Some parameters in ``send_file`` and ``send_from_directory`` were + renamed in 2.0. The deprecation period for the old names is extended + to 2.2. Be sure to test with deprecation warnings visible. + + - ``attachment_filename`` is renamed to ``download_name``. + - ``cache_timeout`` is renamed to ``max_age``. + - ``add_etags`` is renamed to ``etag``. + - ``filename`` is renamed to ``path``. + +- The ``RequestContext.g`` property is deprecated. Use ``g`` directly + or ``AppContext.g`` instead. :issue:`3898` +- ``copy_current_request_context`` can decorate async functions. + :pr:`4303` +- The CLI uses ``importlib.metadata`` instead of ``pkg_resources`` to + load command entry points. :issue:`4419` +- Overriding ``FlaskClient.open`` will not cause an error on redirect. + :issue:`3396` +- Add an ``--exclude-patterns`` option to the ``flask run`` CLI + command to specify patterns that will be ignored by the reloader. + :issue:`4188` +- When using lazy loading (the default with the debugger), the Click + context from the ``flask run`` command remains available in the + loader thread. :issue:`4460` +- Deleting the session cookie uses the ``httponly`` flag. + :issue:`4485` +- Relax typing for ``errorhandler`` to allow the user to use more + precise types and decorate the same function multiple times. + :issue:`4095, 4295, 4297` +- Fix typing for ``__exit__`` methods for better compatibility with + ``ExitStack``. :issue:`4474` +- From Werkzeug, for redirect responses the ``Location`` header URL + will remain relative, and exclude the scheme and domain, by default. + :pr:`4496` +- Add ``Config.from_prefixed_env()`` to load config values from + environment variables that start with ``FLASK_`` or another prefix. + This parses values as JSON by default, and allows setting keys in + nested dicts. :pr:`4479` + + +Version 2.0.3 +------------- + +Released 2022-02-14 + +- The test client's ``as_tuple`` parameter is deprecated and will be + removed in Werkzeug 2.1. It is now also deprecated in Flask, to be + removed in Flask 2.1, while remaining compatible with both in + 2.0.x. Use ``response.request.environ`` instead. :pr:`4341` +- Fix type annotation for ``errorhandler`` decorator. :issue:`4295` +- Revert a change to the CLI that caused it to hide ``ImportError`` + tracebacks when importing the application. :issue:`4307` +- ``app.json_encoder`` and ``json_decoder`` are only passed to + ``dumps`` and ``loads`` if they have custom behavior. This improves + performance, mainly on PyPy. :issue:`4349` +- Clearer error message when ``after_this_request`` is used outside a + request context. :issue:`4333` + + +Version 2.0.2 +------------- + +Released 2021-10-04 + +- Fix type annotation for ``teardown_*`` methods. :issue:`4093` +- Fix type annotation for ``before_request`` and ``before_app_request`` + decorators. :issue:`4104` +- Fixed the issue where typing requires template global + decorators to accept functions with no arguments. :issue:`4098` +- Support View and MethodView instances with async handlers. :issue:`4112` +- Enhance typing of ``app.errorhandler`` decorator. :issue:`4095` +- Fix registering a blueprint twice with differing names. :issue:`4124` +- Fix the type of ``static_folder`` to accept ``pathlib.Path``. + :issue:`4150` +- ``jsonify`` handles ``decimal.Decimal`` by encoding to ``str``. + :issue:`4157` +- Correctly handle raising deferred errors in CLI lazy loading. + :issue:`4096` +- The CLI loader handles ``**kwargs`` in a ``create_app`` function. + :issue:`4170` +- Fix the order of ``before_request`` and other callbacks that trigger + before the view returns. They are called from the app down to the + closest nested blueprint. :issue:`4229` + + +Version 2.0.1 +------------- + +Released 2021-05-21 + +- Re-add the ``filename`` parameter in ``send_from_directory``. The + ``filename`` parameter has been renamed to ``path``, the old name + is deprecated. :pr:`4019` +- Mark top-level names as exported so type checking understands + imports in user projects. :issue:`4024` +- Fix type annotation for ``g`` and inform mypy that it is a namespace + object that has arbitrary attributes. :issue:`4020` +- Fix some types that weren't available in Python 3.6.0. :issue:`4040` +- Improve typing for ``send_file``, ``send_from_directory``, and + ``get_send_file_max_age``. :issue:`4044`, :pr:`4026` +- Show an error when a blueprint name contains a dot. The ``.`` has + special meaning, it is used to separate (nested) blueprint names and + the endpoint name. :issue:`4041` +- Combine URL prefixes when nesting blueprints that were created with + a ``url_prefix`` value. :issue:`4037` +- Revert a change to the order that URL matching was done. The + URL is again matched after the session is loaded, so the session is + available in custom URL converters. :issue:`4053` +- Re-add deprecated ``Config.from_json``, which was accidentally + removed early. :issue:`4078` +- Improve typing for some functions using ``Callable`` in their type + signatures, focusing on decorator factories. :issue:`4060` +- Nested blueprints are registered with their dotted name. This allows + different blueprints with the same name to be nested at different + locations. :issue:`4069` +- ``register_blueprint`` takes a ``name`` option to change the + (pre-dotted) name the blueprint is registered with. This allows the + same blueprint to be registered multiple times with unique names for + ``url_for``. Registering the same blueprint with the same name + multiple times is deprecated. :issue:`1091` +- Improve typing for ``stream_with_context``. :issue:`4052` + + +Version 2.0.0 +------------- + +Released 2021-05-11 + +- Drop support for Python 2 and 3.5. +- Bump minimum versions of other Pallets projects: Werkzeug >= 2, + Jinja2 >= 3, MarkupSafe >= 2, ItsDangerous >= 2, Click >= 8. Be sure + to check the change logs for each project. For better compatibility + with other applications (e.g. Celery) that still require Click 7, + there is no hard dependency on Click 8 yet, but using Click 7 will + trigger a DeprecationWarning and Flask 2.1 will depend on Click 8. +- JSON support no longer uses simplejson. To use another JSON module, + override ``app.json_encoder`` and ``json_decoder``. :issue:`3555` +- The ``encoding`` option to JSON functions is deprecated. :pr:`3562` +- Passing ``script_info`` to app factory functions is deprecated. This + was not portable outside the ``flask`` command. Use + ``click.get_current_context().obj`` if it's needed. :issue:`3552` +- The CLI shows better error messages when the app failed to load + when looking up commands. :issue:`2741` +- Add ``SessionInterface.get_cookie_name`` to allow setting the + session cookie name dynamically. :pr:`3369` +- Add ``Config.from_file`` to load config using arbitrary file + loaders, such as ``toml.load`` or ``json.load``. + ``Config.from_json`` is deprecated in favor of this. :pr:`3398` +- The ``flask run`` command will only defer errors on reload. Errors + present during the initial call will cause the server to exit with + the traceback immediately. :issue:`3431` +- ``send_file`` raises a ``ValueError`` when passed an ``io`` object + in text mode. Previously, it would respond with 200 OK and an empty + file. :issue:`3358` +- When using ad-hoc certificates, check for the cryptography library + instead of PyOpenSSL. :pr:`3492` +- When specifying a factory function with ``FLASK_APP``, keyword + argument can be passed. :issue:`3553` +- When loading a ``.env`` or ``.flaskenv`` file, the current working + directory is no longer changed to the location of the file. + :pr:`3560` +- When returning a ``(response, headers)`` tuple from a view, the + headers replace rather than extend existing headers on the response. + For example, this allows setting the ``Content-Type`` for + ``jsonify()``. Use ``response.headers.extend()`` if extending is + desired. :issue:`3628` +- The ``Scaffold`` class provides a common API for the ``Flask`` and + ``Blueprint`` classes. ``Blueprint`` information is stored in + attributes just like ``Flask``, rather than opaque lambda functions. + This is intended to improve consistency and maintainability. + :issue:`3215` +- Include ``samesite`` and ``secure`` options when removing the + session cookie. :pr:`3726` +- Support passing a ``pathlib.Path`` to ``static_folder``. :pr:`3579` +- ``send_file`` and ``send_from_directory`` are wrappers around the + implementations in ``werkzeug.utils``. :pr:`3828` +- Some ``send_file`` parameters have been renamed, the old names are + deprecated. ``attachment_filename`` is renamed to ``download_name``. + ``cache_timeout`` is renamed to ``max_age``. ``add_etags`` is + renamed to ``etag``. :pr:`3828, 3883` +- ``send_file`` passes ``download_name`` even if + ``as_attachment=False`` by using ``Content-Disposition: inline``. + :pr:`3828` +- ``send_file`` sets ``conditional=True`` and ``max_age=None`` by + default. ``Cache-Control`` is set to ``no-cache`` if ``max_age`` is + not set, otherwise ``public``. This tells browsers to validate + conditional requests instead of using a timed cache. :pr:`3828` +- ``helpers.safe_join`` is deprecated. Use + ``werkzeug.utils.safe_join`` instead. :pr:`3828` +- The request context does route matching before opening the session. + This could allow a session interface to change behavior based on + ``request.endpoint``. :issue:`3776` +- Use Jinja's implementation of the ``|tojson`` filter. :issue:`3881` +- Add route decorators for common HTTP methods. For example, + ``@app.post("/login")`` is a shortcut for + ``@app.route("/login", methods=["POST"])``. :pr:`3907` +- Support async views, error handlers, before and after request, and + teardown functions. :pr:`3412` +- Support nesting blueprints. :issue:`593, 1548`, :pr:`3923` +- Set the default encoding to "UTF-8" when loading ``.env`` and + ``.flaskenv`` files to allow to use non-ASCII characters. :issue:`3931` +- ``flask shell`` sets up tab and history completion like the default + ``python`` shell if ``readline`` is installed. :issue:`3941` +- ``helpers.total_seconds()`` is deprecated. Use + ``timedelta.total_seconds()`` instead. :pr:`3962` +- Add type hinting. :pr:`3973`. + + +Version 1.1.4 +------------- + +Released 2021-05-13 + +- Update ``static_folder`` to use ``_compat.fspath`` instead of + ``os.fspath`` to continue supporting Python < 3.6 :issue:`4050` + + +Version 1.1.3 +------------- + +Released 2021-05-13 + +- Set maximum versions of Werkzeug, Jinja, Click, and ItsDangerous. + :issue:`4043` +- Re-add support for passing a ``pathlib.Path`` for ``static_folder``. + :pr:`3579` + + +Version 1.1.2 +------------- + +Released 2020-04-03 + +- Work around an issue when running the ``flask`` command with an + external debugger on Windows. :issue:`3297` +- The static route will not catch all URLs if the ``Flask`` + ``static_folder`` argument ends with a slash. :issue:`3452` + + +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` + + - ``Flask.finalize_request`` is called for all unhandled + exceptions even if there is no ``500`` error handler. + +- ``Flask.logger`` takes the same name as ``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` +- ``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` +- ``send_file`` supports ``PathLike`` objects as described in + :pep:`519`, to support ``pathlib`` in Python 3. :pr:`3059` +- ``send_file`` supports ``BytesIO`` partial content. + :issue:`2957` +- ``open_resource`` accepts the "rt" file mode. This still does the + same thing as "r". :issue:`3163` +- The ``MethodView.methods`` attribute set in a base class is used by + subclasses. :issue:`3138` +- ``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` +- ``jsonify`` supports ``dataclass`` objects. :pr:`3195` +- Allow customizing the ``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 ``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 :pep:`451` 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 + +- ``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` +- ``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 ``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 ``JSONIFY_PRETTYPRINT_REGULAR`` to + ``False``. ``~json.jsonify`` returns a compact format by default, + and an indented format in debug mode. :pr:`2193` +- ``Flask.__init__`` accepts the ``host_matching`` argument and sets + it on ``Flask.url_map``. :issue:`1559` +- ``Flask.__init__`` accepts the ``static_host`` argument and passes + it as the ``host`` argument when defining the static route. + :issue:`1559` +- ``send_file`` supports Unicode in ``attachment_filename``. + :pr:`2223` +- Pass ``_scheme`` argument from ``url_for`` to + ``Flask.handle_url_build_error``. :pr:`2017` +- ``Flask.add_url_rule`` accepts the ``provide_automatic_options`` + argument to disable adding the ``OPTIONS`` method. :pr:`1489` +- ``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 ``Blueprint.json_encoder`` and + ``Blueprint.json_decoder`` attributes to override the app's + encoder and decoder. :pr:`1898` +- ``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 ``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 ``View`` class attribute + ``View.provide_automatic_options`` is set in ``View.as_view``, to be + detected by ``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` +- ``Flask.test_request_context`` accepts ``subdomain`` and + ``url_scheme`` arguments for use when building the base URL. + :pr:`1621` +- Set ``APPLICATION_ROOT`` to ``'/'`` by default. This was already the + implicit default when it was set to ``None``. +- ``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 ``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 ``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 ``Request`` and + ``Response`` classes. This adds the ``Response.is_json`` and + ``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 if + ``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 + ``Flask.create_jinja_environment`` instead. + - ``Flask.error_handlers`` - tracked by + ``Flask.error_handler_spec``, use ``Flask.errorhandler`` + to register handlers. + - ``Flask.request_globals_class`` - use + ``Flask.app_ctx_globals_class`` instead. + - ``Flask.static_path`` - use ``Flask.static_url_path`` instead. + - ``Request.module`` - use ``Request.blueprint`` instead. + +- The ``Request.json`` property is no longer deprecated. :issue:`1421` +- Support passing a ``EnvironBuilder`` or ``dict`` to + ``test_client.open``. :pr:`2412` +- The ``flask`` command and ``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 ``PREFERRED_URL_SCHEME``. :pr:`2430` +- ``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 ``Flask.debug`` each time. Only one format is used, + not different ones depending on ``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 ``ENOTDIR`` + errors. :pr:`2581` +- Pass ``--cert`` and ``--key`` options to ``flask run`` to run the + development server over HTTPS. :pr:`2606` +- Added ``SESSION_COOKIE_SAMESITE`` to control the ``SameSite`` + attribute on the session cookie. :pr:`2607` +- Added ``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 + ``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` +- ``Request.get_json`` doesn't cache the result if parsing fails when + ``silent`` is true. :issue:`2651` +- ``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 ``MAX_COOKIE_SIZE`` and ``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.5 +-------------- + +Released 2020-02-10 + +- Pin Werkzeug to < 1.0.0. :issue:`3497` + + +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 + +- ``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 ``jsonify``. This + introduces a security risk in ancient browsers. +- Added before_render_template signal. +- Added ``**kwargs`` to ``Flask.test_client`` to support passing + additional keyword arguments to the constructor of + ``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 ``Config.from_json``. +- Added ``Flask.config_class``. +- Added ``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 ``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 ``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. :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 ``AttributeError`` in ``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. +- 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. 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 bytes 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 ``Request.on_json_loading_failed`` now returns a JSON formatted + response by default. +- The ``url_for`` function now can generate anchors to the generated + links. +- The ``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 ``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 an + egg) prior to Python 2.7. +- Blueprints now have a decorator to add custom template filters + application wide, ``Blueprint.app_template_filter``. +- The Flask and Blueprint classes now have a non-decorator method for + adding custom template filters application wide, + ``Flask.add_template_filter`` and + ``Blueprint.add_app_template_filter``. +- The ``get_flashed_messages`` function now allows rendering flashed + message categories in separate blocks, through a ``category_filter`` + argument. +- The ``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 ``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 ``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 ``Response``. This allows for returning + ``jsonify(error="error msg"), 400`` from a view function. +- ``Flask`` and ``Blueprint`` now provide a ``get_send_file_max_age`` + hook for subclasses to override behavior of serving static files + from Flask when using ``Flask.send_static_file`` (used for the + default static file handler) and ``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 ``Flask.request_globals_class`` to allow a specific class to + be used on creation of the ``g`` instance of each request. +- Added ``required_methods`` attribute to view functions to force-add + methods on registration. +- Added ``flask.after_this_request``. +- Added ``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 with + ``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. +- Added the ``APPLICATION_ROOT`` configuration variable. +- Implemented ``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 ``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 ``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 ``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 ``RuntimeError`` instead of an + ``AttributeError``. +- Mimetype guessing and etag support based on file objects is now + deprecated for ``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. +- Implemented ``has_request_context``. +- Deprecated ``init_jinja_globals``. Override the + ``Flask.create_jinja_environment`` method instead to achieve the + same functionality. +- Added ``safe_join``. +- The automatic JSON request data unpacking now looks at the charset + mimetype parameter. +- Don't modify the session on ``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 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. +- ``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 ``Module.add_url_rule`` method is now optional + to be consistent with the function of the same name on the + application object. +- Added a ``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 ``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. + + +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. +- ``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. +- ``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 ``Config.from_envvar``. +- Removed some unused code. +- 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 ``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 ``get_template_attribute`` helper function. +- ``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 ``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. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst deleted file mode 100644 index ca7b4af2c8..0000000000 --- a/CONTRIBUTING.rst +++ /dev/null @@ -1,89 +0,0 @@ -========================== -How to contribute to Flask -========================== - -Thanks for considering contributing to Flask. - -Support questions -================= - -Please, don't use the issue tracker for this. Check whether the ``#pocoo`` IRC -channel on Freenode can help with your issue. If your problem is not strictly -Werkzeug or Flask specific, ``#python`` is generally more active. -`Stack Overflow `_ is also worth considering. - -Reporting issues -================ - -- Under which versions of Python does this happen? This is even more important - if your issue is encoding related. - -- Under which versions of Werkzeug does this happen? Check if this issue is - fixed in the repository. - -Submitting patches -================== - -- 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. - -- Try to follow `PEP8 `_, but you - may ignore the line-length-limit if following it would make the code uglier. - - -Running the testsuite ---------------------- - -You probably want to set up a `virtualenv -`_. - -The minimal requirement for running the testsuite is ``py.test``. You can -install it with:: - - pip install pytest - -Clone this repository:: - - git clone https://github.com/pallets/flask.git - -Install Flask as an editable package using the current source:: - - cd flask - pip install --editable . - -Then you can run the testsuite with:: - - py.test - -With only py.test installed, a large part of the testsuite will get skipped -though. Whether this is relevant depends on which part of Flask you're working -on. Travis is set up to run the full testsuite when you submit your pull -request anyways. - -If you really want to test everything, you will have to install ``tox`` instead -of ``pytest``. You can install it with:: - - pip install tox - -The ``tox`` command will then run all tests against multiple combinations -Python versions and dependency versions. - -Running test coverage ---------------------- -Generating a report of lines that do not have unit test coverage can indicate where -to start contributing. ``pytest`` integrates with ``coverage.py``, using the ``pytest-cov`` -plugin. This assumes you have already run the testsuite (see previous section):: - - pip install pytest-cov - -After this has been installed, you can output a report to the command line using this command:: - - py.test --cov=flask tests/ - -Generate a HTML report can be done using this command:: - - py.test --cov-report html --cov=flask tests/ - -Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io - diff --git a/LICENSE b/LICENSE deleted file mode 100644 index a7da10e176..0000000000 --- a/LICENSE +++ /dev/null @@ -1,33 +0,0 @@ -Copyright (c) 2015 by Armin Ronacher and contributors. See AUTHORS -for more details. - -Some rights reserved. - -Redistribution and use in source and binary forms of the software as well -as documentation, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - -* The names of the contributors may not be used to endorse or - promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND -CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT -NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000000..9d227a0cc4 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 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. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index f8d9c2ae6b..0000000000 --- a/MANIFEST.in +++ /dev/null @@ -1,11 +0,0 @@ -include Makefile CHANGES LICENSE AUTHORS - -graft artwork -graft tests -graft examples -graft docs - -global-exclude *.py[co] - -prune docs/_build -prune docs/_themes diff --git a/Makefile b/Makefile deleted file mode 100644 index 9bcdebc230..0000000000 --- a/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -.PHONY: clean-pyc ext-test test tox-test test-with-mem upload-docs docs audit - -all: clean-pyc test - -test: - pip install -r test-requirements.txt -q - FLASK_DEBUG= py.test tests examples - -tox-test: - tox - -audit: - python setup.py audit - -release: - python scripts/make-release.py - -ext-test: - python tests/flaskext_test.py --browse - -clean-pyc: - find . -name '*.pyc' -exec rm -f {} + - find . -name '*.pyo' -exec rm -f {} + - find . -name '*~' -exec rm -f {} + - -upload-docs: - $(MAKE) -C docs html dirhtml latex epub - $(MAKE) -C docs/_build/latex all-pdf - cd docs/_build/; mv html flask-docs; zip -r flask-docs.zip flask-docs; mv flask-docs html - rsync -a docs/_build/dirhtml/ flow.srv.pocoo.org:/srv/websites/flask.pocoo.org/docs/ - rsync -a docs/_build/latex/Flask.pdf flow.srv.pocoo.org:/srv/websites/flask.pocoo.org/docs/flask-docs.pdf - rsync -a docs/_build/flask-docs.zip flow.srv.pocoo.org:/srv/websites/flask.pocoo.org/docs/flask-docs.zip - rsync -a docs/_build/epub/Flask.epub flow.srv.pocoo.org:/srv/websites/flask.pocoo.org/docs/flask-docs.epub - -# ebook-convert docs: http://manual.calibre-ebook.com/cli/ebook-convert.html -ebook: - @echo 'Using .epub from `make upload-docs` to create .mobi.' - @echo 'Command `ebook-covert` is provided by calibre package.' - @echo 'Requires X-forwarding for Qt features used in conversion (ssh -X).' - @echo 'Do not mind "Invalid value for ..." CSS errors if .mobi renders.' - ssh -X pocoo.org ebook-convert /var/www/flask.pocoo.org/docs/flask-docs.epub /var/www/flask.pocoo.org/docs/flask-docs.mobi --cover http://flask.pocoo.org/docs/_images/logo-full.png --authors 'Armin Ronacher' - -docs: - $(MAKE) -C docs html diff --git a/README b/README deleted file mode 100644 index baea6b2427..0000000000 --- a/README +++ /dev/null @@ -1,49 +0,0 @@ - - - // Flask // - - web development, one drop at a time - - - ~ What is Flask? - - Flask is a microframework for Python based on Werkzeug - and Jinja2. It's intended for getting started very quickly - and was developed with best intentions in mind. - - ~ Is it ready? - - It's still not 1.0 but it's shaping up nicely and is - already widely used. Consider the API to slightly - improve over time but we don't plan on breaking it. - - ~ What do I need? - - All dependencies are installed by using `pip install Flask`. - We encourage you to use a virtualenv. Check the docs for - complete installation and usage instructions. - - ~ Where are the docs? - - Go to http://flask.pocoo.org/docs/ for a prebuilt version - of the current documentation. Otherwise build them yourself - from the sphinx sources in the docs folder. - - ~ Where are the tests? - - Good that you're asking. The tests are in the - tests/ folder. To run the tests use the - `py.test` testing tool: - - $ py.test - - Details on contributing can be found in CONTRIBUTING.rst - - ~ Where can I get help? - - Either use the #pocoo IRC channel on irc.freenode.net or - ask on the mailinglist: http://flask.pocoo.org/mailinglist/ - - See http://flask.pocoo.org/community/ for more resources. - - diff --git a/README.md b/README.md new file mode 100644 index 0000000000..29312c6569 --- /dev/null +++ b/README.md @@ -0,0 +1,51 @@ +# 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. + +[WSGI]: https://wsgi.readthedocs.io/ +[Werkzeug]: https://werkzeug.palletsprojects.com/ +[Jinja]: https://jinja.palletsprojects.com/ + +## A Simple Example + +```python +# save this as app.py +from flask import Flask + +app = Flask(__name__) + +@app.route("/") +def hello(): + return "Hello, World!" +``` + +``` +$ flask run + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) +``` + +## 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://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ diff --git a/artwork/LICENSE b/artwork/LICENSE deleted file mode 100644 index c6df416cde..0000000000 --- a/artwork/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2010 by Armin Ronacher. - -Some rights reserved. - -This logo or a modified version may be used by anyone to refer to the -Flask project, but does not indicate endorsement by the project. - -Redistribution and use in source (the SVG file) and binary forms (rendered -PNG files etc.) of the image, with or without modification, are permitted -provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright - notice and this list of conditions. - -* The names of the contributors to the Flask software (see AUTHORS) may - not be used to endorse or promote products derived from this software - without specific prior written permission. - -Note: we would appreciate that you make the image a link to -http://flask.pocoo.org/ if you use it on a web page. diff --git a/artwork/logo-full.svg b/artwork/logo-full.svg deleted file mode 100644 index 8c0748a286..0000000000 --- a/artwork/logo-full.svg +++ /dev/null @@ -1,290 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/artwork/logo-lineart.svg b/artwork/logo-lineart.svg deleted file mode 100644 index 615260dce6..0000000000 --- a/artwork/logo-lineart.svg +++ /dev/null @@ -1,165 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - diff --git a/docs/.gitignore b/docs/.gitignore deleted file mode 100644 index e35d8850c9..0000000000 --- a/docs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_build diff --git a/docs/Makefile b/docs/Makefile index 52d78d9efe..d4bb2cbb9e 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -1,118 +1,20 @@ -# Makefile for Sphinx documentation +# Minimal makefile for Sphinx documentation # -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . BUILDDIR = _build -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp epub latex changes linkcheck doctest - +# Put it first so that "make" without argument is like "make help". help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - -rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) _build/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask" - @echo "# ln -s _build/devhelp $$HOME/.local/share/devhelp/Flask" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ - "run these through (pdf)latex." - -latexpdf: latex - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex - @echo "Running LaTeX files through pdflatex..." - make -C _build/latex all-pdf - @echo "pdflatex finished; the PDF files are in _build/latex." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." +.PHONY: help Makefile -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." +# 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) diff --git a/docs/_static/debugger.png b/docs/_static/debugger.png index 4f47229d6a..7d4181f6a4 100644 Binary files a/docs/_static/debugger.png and b/docs/_static/debugger.png differ diff --git a/docs/_static/flask-favicon.ico b/docs/_static/flask-favicon.ico deleted file mode 100644 index bf0a961573..0000000000 Binary files a/docs/_static/flask-favicon.ico and /dev/null differ diff --git a/docs/_static/flask-horizontal.png b/docs/_static/flask-horizontal.png new file mode 100644 index 0000000000..a0df2c6109 Binary files /dev/null and b/docs/_static/flask-horizontal.png differ diff --git a/docs/_static/flask-vertical.png b/docs/_static/flask-vertical.png new file mode 100644 index 0000000000..d1fd149907 Binary files /dev/null and b/docs/_static/flask-vertical.png differ diff --git a/docs/_static/flask.png b/docs/_static/flask.png deleted file mode 100644 index 5c603cc22c..0000000000 Binary files a/docs/_static/flask.png and /dev/null differ diff --git a/docs/_static/flaskr.png b/docs/_static/flaskr.png deleted file mode 100644 index 07d027dd97..0000000000 Binary files a/docs/_static/flaskr.png and /dev/null differ diff --git a/docs/_static/logo-full.png b/docs/_static/logo-full.png deleted file mode 100644 index 5deaf1b84e..0000000000 Binary files a/docs/_static/logo-full.png and /dev/null differ diff --git a/docs/_static/no.png b/docs/_static/no.png deleted file mode 100644 index 4ac1083d91..0000000000 Binary files a/docs/_static/no.png and /dev/null differ diff --git a/docs/_static/pycharm-run-config.png b/docs/_static/pycharm-run-config.png new file mode 100644 index 0000000000..ad025545a7 Binary files /dev/null and b/docs/_static/pycharm-run-config.png differ diff --git a/docs/_static/shortcut-icon.png b/docs/_static/shortcut-icon.png new file mode 100644 index 0000000000..4d3e6c3774 Binary files /dev/null and b/docs/_static/shortcut-icon.png differ diff --git a/docs/_static/touch-icon.png b/docs/_static/touch-icon.png deleted file mode 100644 index cd1e91e155..0000000000 Binary files a/docs/_static/touch-icon.png and /dev/null differ diff --git a/docs/_static/yes.png b/docs/_static/yes.png deleted file mode 100644 index ac27c4e187..0000000000 Binary files a/docs/_static/yes.png and /dev/null differ diff --git a/docs/_templates/sidebarintro.html b/docs/_templates/sidebarintro.html deleted file mode 100644 index ec1608fd72..0000000000 --- a/docs/_templates/sidebarintro.html +++ /dev/null @@ -1,22 +0,0 @@ -

About Flask

-

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

-

Other Formats

-

- You can download the documentation in other formats as well: -

- -

Useful Links

- diff --git a/docs/_templates/sidebarlogo.html b/docs/_templates/sidebarlogo.html deleted file mode 100644 index 3bc7f7624b..0000000000 --- a/docs/_templates/sidebarlogo.html +++ /dev/null @@ -1,3 +0,0 @@ - diff --git a/docs/_themes b/docs/_themes deleted file mode 160000 index 3d964b6604..0000000000 --- a/docs/_themes +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 3d964b660442e23faedf801caed6e3c7bd42d5c9 diff --git a/docs/advanced_foreword.rst b/docs/advanced_foreword.rst deleted file mode 100644 index 82b3dc58be..0000000000 --- a/docs/advanced_foreword.rst +++ /dev/null @@ -1,55 +0,0 @@ -.. _advanced_foreword: - -Foreword for Experienced Programmers -==================================== - -Thread-Locals in Flask ----------------------- - -One of the design decisions in Flask was that simple tasks should be simple; -they should not take a lot of code and yet they should not limit you. Because -of that, Flask has a few design choices that some people might find surprising or -unorthodox. For example, Flask uses thread-local objects internally so that you -don’t have to pass objects around from function to function within a request in -order to stay threadsafe. This approach is convenient, but requires a valid -request context for dependency injection or when attempting to reuse code which -uses a value pegged to the request. The Flask project is honest about -thread-locals, does not hide them, and calls out in the code and documentation -where they are used. - -Develop for the Web with Caution --------------------------------- - -Always keep security in mind when building web applications. - -If you write a web application, you are probably allowing users to register -and leave their data on your server. The users are entrusting you with data. -And even if you are the only user that might leave data in your application, -you still want that data to be stored securely. - -Unfortunately, there are many ways the security of a web application can be -compromised. Flask protects you against one of the most common security -problems of modern web applications: cross-site scripting (XSS). Unless you -deliberately mark insecure HTML as secure, Flask and the underlying Jinja2 -template engine have you covered. But there are many more ways to cause -security problems. - -The documentation will warn you about aspects of web development that require -attention to security. Some of these security concerns are far more complex -than one might think, and we all sometimes underestimate the likelihood that a -vulnerability will be exploited - until a clever attacker figures out a way to -exploit our applications. And don't think that your application is not -important enough to attract an attacker. Depending on the kind of attack, -chances are that automated bots are probing for ways to fill your database with -spam, links to malicious software, and the like. - -Flask is no different from any other framework in that you the developer must -build with caution, watching for exploits when building to your requirements. - -Python 3 Support in Flask -------------------------- - -Flask, its dependencies, and most Flask extensions all support Python 3. -If you want to use Flask with Python 3 have a look at the :ref:`python3-support` page. - -Continue to :ref:`installation` or the :ref:`quickstart`. diff --git a/docs/api.rst b/docs/api.rst index d77da3de20..1aa8048f55 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,11 +1,9 @@ -.. _api: - API === .. module:: flask -This part of the documentation covers all the interfaces of Flask. For +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. @@ -29,151 +27,49 @@ Incoming Request Data --------------------- .. autoclass:: Request - :members: - - .. attribute:: form - - A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST`` - or ``PUT`` requests. Please keep in mind that file uploads will not - end up here, but instead in the :attr:`files` attribute. - - .. attribute:: args - - A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query - string. (The part in the URL after the question mark). - - .. attribute:: values - - A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both - :attr:`form` and :attr:`args`. - - .. attribute:: cookies - - A :class:`dict` with the contents of all cookies transmitted with - the request. - - .. attribute:: stream - - If the incoming form data was not encoded with a known mimetype - the data is stored unmodified in this stream for consumption. Most - of the time it is a better idea to use :attr:`data` which will give - you that data as a string. The stream only returns the data once. - - .. attribute:: headers - - The incoming request headers as a dictionary like object. - - .. attribute:: data - - Contains the incoming request data as string in case it came with - a mimetype Flask does not handle. - - .. attribute:: files - - A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a - ``POST`` or ``PUT`` request. Each file is stored as - :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a - standard file object you know from Python, with the difference that - it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can - store the file on the filesystem. - - .. attribute:: environ - - The underlying WSGI environment. - - .. attribute:: method - - The current request method (``POST``, ``GET`` etc.) - - .. attribute:: path - .. attribute:: full_path - .. attribute:: script_root - .. attribute:: url - .. attribute:: base_url - .. attribute:: url_root - - Provides different ways to look at the current `IRI - `_. Imagine your application is - listening on the following application root:: - - http://www.example.com/myapplication + :members: + :inherited-members: + :exclude-members: json_module - 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/%CF%80/page.html'`` - `url` ``u'http://www.example.com/myapplication/%CF%80/page.html?x=y'`` - `url_root` ``u'http://www.example.com/myapplication/'`` - ============= ====================================================== - - .. attribute:: is_xhr - - ``True`` if the request was triggered via a JavaScript - `XMLHttpRequest`. This only works with libraries that support the - ``X-Requested-With`` header and set it to `XMLHttpRequest`. - Libraries that do that are prototype, jQuery and Mochikit and - probably some more. - -.. class:: request +.. 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 + 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. + 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. + The request object is an instance of a :class:`~flask.Request`. Response Objects ---------------- .. autoclass:: flask.Response - :members: set_cookie, data, mimetype - - .. attribute:: headers - - A :class:`~werkzeug.datastructures.Headers` object representing the response headers. - - .. attribute:: status - - A string with a response status. - - .. attribute:: status_code - - The response status as integer. - + :members: + :inherited-members: + :exclude-members: json_module Sessions -------- -If you have the :attr:`Flask.secret_key` set you can use sessions in Flask -applications. A session basically makes it possible to remember -information from one request to another. The way Flask does this is by -using a signed cookie. So the user can look at the session contents, but -not modify it unless they know the secret key, so make sure to set that -to something complex and unguessable. +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 on modifications. + difference that it keeps track of modifications. - This is a proxy. See :ref:`notes-on-proxies` for more information. + This is a proxy. See :ref:`notes-on-proxies` for more information. The following attributes are interesting: @@ -183,10 +79,10 @@ To access the current session you can use the :class:`session` object: .. attribute:: modified - ``True`` if the session object detected a modification. Be advised + ``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:: + attribute to ``True`` yourself. Here an example:: # this change is not picked up because a mutable object (here # a list) is changed. @@ -197,8 +93,8 @@ To access the current session you can use the :class:`session` object: .. 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 + :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. @@ -227,24 +123,11 @@ implementation that Flask is using. .. autoclass:: SessionMixin :members: -.. autodata:: session_json_serializer - - This object provides dumping and loading methods similar to simplejson - but it also tags certain builtin Python objects that commonly appear in - sessions. Currently the following extended values are supported in - the JSON it dumps: - - - :class:`~markupsafe.Markup` objects - - :class:`~uuid.UUID` objects - - :class:`~datetime.datetime` objects - - :class:`tuple`\s - .. admonition:: Notice - The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer - starting with Flask 0.8. Either catch this down yourself or use - the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the - app which converts the result to an integer automatically. + The :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``. + The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a + ``timedelta``. Test Client @@ -256,6 +139,15 @@ Test Client :members: +Test CLI Runner +--------------- + +.. currentmodule:: flask.testing + +.. autoclass:: FlaskCliRunner + :members: + + Application Globals ------------------- @@ -263,36 +155,29 @@ Application Globals 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 +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 +different values for each request. In a nutshell: it does the right thing, like it does for :class:`request` and :class:`session`. .. data:: g - Just store on this whatever you want. For example a database - connection or the user that is currently logged in. - - Starting with Flask 0.10 this is stored on the application context and - no longer on the request context which means it becomes available if - only the application context is bound and not yet a request. This - is especially useful when combined with the :ref:`faking-resources` - pattern for testing. + 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`. - Additionally as of 0.10 you can use the :meth:`get` method to - get an attribute or ``None`` (or the second argument) if it's not set. - These two usages are now equivalent:: + This is a good place to store resources during a request. For + example, a ``before_request`` function could load a user object from + a session id, then set ``g.user`` to be used in the view function. - user = getattr(flask.g, 'user', None) - user = flask.g.get('user', None) + This is a proxy. See :ref:`notes-on-proxies` for more information. - It's now also possible to use the ``in`` operator on it to see if an - attribute is defined and it yields all keys on iteration. + .. versionchanged:: 0.10 + Bound to the application context instead of the request context. - As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same - way you would use them on a dictionary. - - This is a proxy. See :ref:`notes-on-proxies` for more information. +.. autoclass:: flask.ctx._AppCtxGlobals + :members: Useful Functions and Classes @@ -300,13 +185,17 @@ Useful Functions and Classes .. data:: current_app - Points to the application handling the request. This is useful for - extensions that want to support multiple applications running side - by side. This is powered by the application context and not by the - request context, so you can change the value of this proxy by - using the :meth:`~flask.Flask.app_context` method. + 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. + This is a proxy. See :ref:`notes-on-proxies` for more information. .. autofunction:: has_request_context @@ -328,12 +217,6 @@ Useful Functions and Classes .. autofunction:: send_from_directory -.. autofunction:: safe_join - -.. autofunction:: escape - -.. autoclass:: Markup - :members: escape, unescape, striptags Message Flashing ---------------- @@ -342,58 +225,29 @@ Message Flashing .. 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: +Flask uses Python's built-in :mod:`json` module for handling JSON by +default. The JSON implementation can be changed by assigning a different +provider to :attr:`flask.Flask.json_provider_class` or +:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will +use methods on ``app.json`` if an app context is active. -1. ``datetime`` objects are serialized as :rfc:`822` strings. -2. Any object with an ``__html__`` method (like :class:`~flask.Markup`) - will have that method called and then the return value is serialized - as string. - -The :func:`~htmlsafe_dumps` function of this json module is also available -as filter called ``|tojson`` in Jinja2. Note that inside ``script`` -tags no escaping must take place, so make sure to disable escaping -with ``|safe`` if you intend to use it inside ``script`` tags unless -you are using Flask 0.10 which implies that: +Jinja's ``|tojson`` filter is configured to use the app's JSON provider. +The filter marks the output with ``|safe``. Use it to render data inside +HTML `` -.. 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 @@ -404,11 +258,16 @@ you are using Flask 0.10 which implies that: .. autofunction:: load -.. autoclass:: JSONEncoder - :members: +.. autoclass:: flask.json.provider.JSONProvider + :members: + :member-order: bysource + +.. autoclass:: flask.json.provider.DefaultJSONProvider + :members: + :member-order: bysource + +.. automodule:: flask.json.tag -.. autoclass:: JSONDecoder - :members: Template Rendering ------------------ @@ -419,6 +278,10 @@ Template Rendering .. autofunction:: render_template_string +.. autofunction:: stream_template + +.. autofunction:: stream_template_string + .. autofunction:: get_template_attribute Configuration @@ -427,22 +290,6 @@ Configuration .. autoclass:: Config :members: -Extensions ----------- - -.. data:: flask.ext - - This module acts as redirect import module to Flask extensions. It was - added in 0.8 as the canonical way to import Flask extensions and makes - it possible for us to have more flexibility in how we distribute - extensions. - - If you want to use an extension named “Flask-Foo” you would import it - from :data:`~flask.ext` as follows:: - - from flask.ext import foo - - .. versionadded:: 0.8 Stream Helpers -------------- @@ -455,52 +302,28 @@ Useful Internals .. autoclass:: flask.ctx.RequestContext :members: -.. data:: _request_ctx_stack - - The internal :class:`~werkzeug.local.LocalStack` that is used to implement - all the context local objects used in Flask. This is a documented - instance and can be used by extensions and application code but the - use is discouraged in general. - - The following attributes are always present on each layer of the - stack: - - `app` - the active Flask application. +.. data:: flask.globals.request_ctx - `url_adapter` - the URL adapter that was used to match the request. + The current :class:`~flask.ctx.RequestContext`. If a request context + is not active, accessing attributes on this proxy will raise a + ``RuntimeError``. - `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 + This is an internal object that is essential to how Flask handles + requests. Accessing this should not be needed in most cases. Most + likely you want :data:`request` and :data:`session` instead. .. autoclass:: flask.ctx.AppContext :members: -.. data:: _app_ctx_stack +.. data:: flask.globals.app_ctx - Works similar to the request context but only binds the application. - This is mainly there for extensions to store data. + The current :class:`~flask.ctx.AppContext`. If an app context is not + active, accessing attributes on this proxy will raise a + ``RuntimeError``. - .. versionadded:: 0.9 + This is an internal object that is essential to how Flask handles + requests. Accessing this should not be needed in most cases. Most + likely you want :data:`current_app` and :data:`g` instead. .. autoclass:: flask.blueprints.BlueprintSetupState :members: @@ -510,18 +333,13 @@ Useful Internals Signals ------- -.. versionadded:: 0.6 - -.. data:: signals.signals_available - - ``True`` if the signaling system is available. This is the case - when `blinker`_ is installed. +Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction. -The following signals exist in Flask: +.. _blinker: https://blinker.readthedocs.io/ .. data:: template_rendered - This signal is sent when a template was successfully rendered. The + 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`). @@ -555,7 +373,7 @@ The following signals exist in Flask: .. 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 + 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`. @@ -575,7 +393,7 @@ The following signals exist in Flask: Example subscriber:: def log_response(sender, response, **extra): - sender.logger.debug('Request context is about to close down. ' + sender.logger.debug('Request context is about to close down. ' 'Response: %s', response) from flask import request_finished @@ -583,23 +401,37 @@ The following signals exist in Flask: .. 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`. + This signal is sent when an unhandled exception happens during + request processing, including when debugging. The exception is + passed to the subscriber as ``exception``. - Example subscriber:: + This signal is not sent for + :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that + have error handlers registered, unless the exception was raised from + an error handler. + + This example shows how to do some extra logging if a theoretical + ``SecurityException`` was raised: - def log_exception(sender, exception, **extra): - sender.logger.debug('Got exception during processing: %s', exception) + .. code-block:: python from flask import got_request_exception - got_request_exception.connect(log_exception, app) + + def log_security_exception(sender, exception, **extra): + if not isinstance(exception, SecurityException): + return + + security_logger.exception( + f"SecurityException at {request.url!r}", + exc_info=exception, + ) + + got_request_exception.connect(log_security_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 + 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. @@ -617,8 +449,8 @@ The following signals exist in Flask: .. 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 + 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. @@ -635,9 +467,9 @@ The following signals exist in Flask: .. 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 + 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:: @@ -664,16 +496,15 @@ The following signals exist in Flask: .. 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 + 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 + This signal is sent when the application is flashing a message. The messages is sent as `message` keyword argument and the category as `category`. @@ -688,23 +519,6 @@ The following signals exist in Flask: .. versionadded:: 0.10 -.. class:: signals.Namespace - - An alias for :class:`blinker.base.Namespace` if blinker is available, - otherwise a dummy class that creates fake signals. This class is - available for Flask extensions that want to provide the same fallback - system as Flask itself. - - .. method:: signal(name, doc=None) - - Creates a new signal for this namespace if blinker is available, - otherwise returns a fake signal that has a send method that will - do nothing but will fail with a :exc:`RuntimeError` for all other - operations, including connecting. - - -.. _blinker: https://pypi.python.org/pypi/blinker - Class-Based Views ----------------- @@ -732,7 +546,7 @@ Generally there are three ways to define rules for the 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 +(``/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 ````. @@ -766,7 +580,7 @@ Here are some examples:: 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 +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 @@ -775,11 +589,11 @@ apply: 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 +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 +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}) @@ -788,39 +602,49 @@ definition for a URL that accepts an optional page:: pass This specifies that ``/users/`` will be the URL for page one and -``/users/page/N`` will be the URL for page `N`. +``/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 +: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 +`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 + 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 +`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 + 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 + :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 + 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. + handling. They have to be specified as keyword arguments. =============== ========================================================== -.. _view-func-options: View Function Options --------------------- @@ -830,19 +654,19 @@ 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 +- `__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 + 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 + HTTP ``OPTIONS`` response. This can be useful when working with decorators that want to customize the ``OPTIONS`` response on a per-view basis. @@ -879,6 +703,8 @@ Command Line Interface .. autoclass:: ScriptInfo :members: +.. autofunction:: load_dotenv + .. autofunction:: with_appcontext .. autofunction:: pass_script_info diff --git a/docs/appcontext.rst b/docs/appcontext.rst index 166c5aa376..5509a9a781 100644 --- a/docs/appcontext.rst +++ b/docs/appcontext.rst @@ -1,138 +1,147 @@ -.. _app-context: +.. currentmodule:: flask The Application Context ======================= -.. versionadded:: 0.9 +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. -One of the design ideas behind Flask is that there are two different -“states” in which code is executed. The application setup state in which -the application implicitly is on the module level. It starts when the -:class:`Flask` object is instantiated, and it implicitly ends when the -first request comes in. While the application is in this state a few -assumptions are true: +This is similar to :doc:`/reqcontext`, which keeps track of +request-level data during a request. A corresponding application context +is pushed when a request context is pushed. -- the programmer can modify the application object safely. -- no request handling happened so far -- you have to have a reference to the application object in order to - modify it, there is no magic proxy that can give you a reference to - the application object you're currently creating or modifying. +Purpose of the Context +---------------------- -In contrast, during request handling, a couple of other rules exist: +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. -- while a request is active, the context local objects - (:data:`flask.request` and others) point to the current request. -- any code can get hold of these objects at any time. +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. -There is a third state which is sitting in between a little bit. -Sometimes you are dealing with an application in a way that is similar to -how you interact with applications during request handling; just that there -is no request active. Consider, for instance, that you're sitting in an -interactive Python shell and interacting with the application, or a -command line application. +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`. -The application context is what powers the :data:`~flask.current_app` -context local. +Flask will also automatically push an app context when running CLI +commands registered with :attr:`Flask.cli` using ``@app.cli.command()``. -Purpose of the Application Context ----------------------------------- -The main reason for the application's context existence is that in the -past a bunch of functionality was attached to the request context for lack -of a better solution. Since one of the pillars of Flask's design is that -you can have more than one application in the same Python process. +Lifetime of the Context +----------------------- -So how does the code find the “right” application? In the past we -recommended passing applications around explicitly, but that caused issues -with libraries that were not designed with that in mind. +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. -A common workaround for that problem was to use the -:data:`~flask.current_app` proxy later on, which was bound to the current -request's application reference. Since creating such a request context is -an unnecessarily expensive operation in case there is no request around, -the application context was introduced. +See :doc:`/reqcontext` for more information about how the contexts work +and the full life cycle of a request. -Creating an Application Context -------------------------------- -There are two ways to make an application context. The first one is -implicit: whenever a request context is pushed, an application context -will be created alongside if this is necessary. As a result, you can -ignore the existence of the application context unless you need it. +Manually Push a Context +----------------------- -The second way is the explicit way using the -:meth:`~flask.Flask.app_context` method:: +If you try to access :data:`current_app`, or anything that uses it, +outside an application context, you'll get this error message: - from flask import Flask, current_app +.. code-block:: pytb - app = Flask(__name__) - with app.app_context(): - # within this block, current_app points to app. - print current_app.name + RuntimeError: Working outside of application context. -The application context is also used by the :func:`~flask.url_for` -function in case a ``SERVER_NAME`` was configured. This allows you to -generate URLs even in the absence of a request. + 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 no request context has been pushed and an application context has -not been explicitly set, a ``RuntimeError`` will be raised. :: +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`. :: - RuntimeError: Working outside of application context. + def create_app(): + app = Flask(__name__) -Locality of the Context ------------------------ + with app.app_context(): + init_db() + + return app -The application context is created and destroyed as necessary. It never -moves between threads and it will not be shared between requests. As such -it is the perfect place to store database connection information and other -things. The internal stack object is called :data:`flask._app_ctx_stack`. -Extensions are free to store additional information on the topmost level, -assuming they pick a sufficiently unique name and should put their -information there, instead of on the :data:`flask.g` object which is reserved -for user code. +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. -For more information about that, see :ref:`extension-dev`. -Context Usage -------------- +Storing Data +------------ -The context is typically used to cache resources that need to be created -on a per-request or usage case. For instance, database connections are -destined to go there. When storing things on the application context -unique names should be chosen as this is a place that is shared between -Flask applications and extensions. +The 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. -The most common usage is to split resource management into two parts: +.. 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. -1. an implicit resource caching on the context. -2. a context teardown based resource deallocation. +A common use for :data:`g` is to manage resources during a request. -Generally there would be a ``get_X()`` function that creates resource -``X`` if it does not exist yet and otherwise returns the same resource, -and a ``teardown_X()`` function that is registered as teardown handler. +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. -This is an example that connects to a database:: +For example, you can manage a database connection using this pattern:: - import sqlite3 from flask import g def get_db(): - db = getattr(g, '_database', None) - if db is None: - db = g._database = connect_to_database() - return db + if 'db' not in g: + g.db = connect_to_database() + + return g.db @app.teardown_appcontext def teardown_db(exception): - db = getattr(g, '_database', None) + db = g.pop('db', None) + if db is not None: db.close() -The first time ``get_db()`` is called the connection will be established. -To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used:: +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) -That way a user can directly access ``db`` which internally calls -``get_db()``. +Accessing ``db`` will call ``get_db`` internally, in the same way that +:data:`current_app` works. + + +Events and Signals +------------------ + +The application will call functions registered with :meth:`~Flask.teardown_appcontext` +when the application context is popped. + +The following signals are sent: :data:`appcontext_pushed`, +:data:`appcontext_tearing_down`, and :data:`appcontext_popped`. diff --git a/docs/async-await.rst b/docs/async-await.rst new file mode 100644 index 0000000000..16b61945e2 --- /dev/null +++ b/docs/async-await.rst @@ -0,0 +1,125 @@ +.. _async_await: + +Using ``async`` and ``await`` +============================= + +.. versionadded:: 2.0 + +Routes, error handlers, before request, after request, and teardown +functions can all be coroutine functions if Flask is installed with the +``async`` extra (``pip install flask[async]``). This allows views to be +defined with ``async def`` and use ``await``. + +.. code-block:: python + + @app.route("/get-data") + async def get_data(): + data = await async_db_query(...) + return jsonify(data) + +Pluggable class-based views also support handlers that are implemented as +coroutines. This applies to the :meth:`~flask.views.View.dispatch_request` +method in views that inherit from the :class:`flask.views.View` class, as +well as all the HTTP method handlers in views that inherit from the +:class:`flask.views.MethodView` class. + +.. admonition:: Using ``async`` with greenlet + + When using gevent or eventlet to serve an application or patch the + runtime, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is + required. + + +Performance +----------- + +Async functions require an event loop to run. Flask, as a WSGI +application, uses one worker to handle one request/response cycle. +When a request comes in to an async view, Flask will start an event loop +in a thread, run the view function there, then return the result. + +Each request still ties up one worker, even for async views. The upside +is that you can run async code within a view, for example to make +multiple concurrent database queries, HTTP requests to an external API, +etc. However, the number of requests your application can handle at one +time will remain the same. + +**Async is not inherently faster than sync code.** Async is beneficial +when performing concurrent IO-bound tasks, but will probably not improve +CPU-bound tasks. Traditional Flask views will still be appropriate for +most use cases, but Flask's async support enables writing and using +code that wasn't possible natively before. + + +Background tasks +---------------- + +Async functions will run in an event loop until they complete, at +which stage the event loop will stop. This means any additional +spawned tasks that haven't completed when the async function completes +will be cancelled. Therefore you cannot spawn background tasks, for +example via ``asyncio.create_task``. + +If you wish to use background tasks it is best to use a task queue to +trigger background work, rather than spawn tasks in a view +function. With that in mind you can spawn asyncio tasks by serving +Flask with an ASGI server and utilising the asgiref WsgiToAsgi adapter +as described in :doc:`deploying/asgi`. This works as the adapter creates +an event loop that runs continually. + + +When to use Quart instead +------------------------- + +Flask's async support is less performant than async-first frameworks due +to the way it is implemented. If you have a mainly async codebase it +would make sense to consider `Quart`_. Quart is a reimplementation of +Flask based on the `ASGI`_ standard instead of WSGI. This allows it to +handle many concurrent requests, long running requests, and websockets +without requiring multiple worker processes or threads. + +It has also already been possible to run Flask with Gevent or Eventlet +to get many of the benefits of async request handling. These libraries +patch low-level Python functions to accomplish this, whereas ``async``/ +``await`` and ASGI use standard, modern Python capabilities. Deciding +whether you should use Flask, Quart, or something else is ultimately up +to understanding the specific needs of your project. + +.. _Quart: https://github.com/pallets/quart +.. _ASGI: https://asgi.readthedocs.io/en/latest/ + + +Extensions +---------- + +Flask extensions predating Flask's async support do not expect async views. +If they provide decorators to add functionality to views, those will probably +not work with async views because they will not await the function or be +awaitable. Other functions they provide will not be awaitable either and +will probably be blocking if called within an async view. + +Extension authors can support async functions by utilising the +:meth:`flask.Flask.ensure_sync` method. For example, if the extension +provides a view function decorator add ``ensure_sync`` before calling +the decorated function, + +.. code-block:: python + + def extension(func): + @wraps(func) + def wrapper(*args, **kwargs): + ... # Extension logic + return current_app.ensure_sync(func)(*args, **kwargs) + + return wrapper + +Check the changelog of the extension you want to use to see if they've +implemented async support, or make a feature request or PR to them. + + +Other event loops +----------------- + +At the moment Flask only supports :mod:`asyncio`. It's possible to +override :meth:`flask.Flask.ensure_sync` to change how async functions +are wrapped to use a different library. diff --git a/docs/becomingbig.rst b/docs/becomingbig.rst deleted file mode 100644 index df470a765b..0000000000 --- a/docs/becomingbig.rst +++ /dev/null @@ -1,101 +0,0 @@ -.. _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; it's documentation is published so you can use its internal -APIs. Flask sticks to documented APIs in upstream libraries, and documents its -internal utilities so that you can find the hook points needed for your -project. - -Hook. Extend. -------------- - -The :ref:`api` docs are full of available overrides, hook points, and -:ref:`signals`. You can provide custom classes for things like the request and -response objects. Dig deeper on the APIs you use, and look for the -customizations which are available out of the box in a Flask release. Look for -ways in which your project can be refactored into a collection of utilities and -Flask extensions. Explore the many `extensions -`_ in the community, and look for patterns to -build your own extensions if you do not find the tools you need. - -Subclass. ---------- - -The :class:`~flask.Flask` class has many methods designed for subclassing. You -can quickly add or customize behavior by subclassing :class:`~flask.Flask` (see -the linked method docs) and using that subclass wherever you instantiate an -application class. This works well with :ref:`app-factories`. See :doc:`/patterns/subclassing` for an example. - -Wrap with middleware. ---------------------- - -The :ref:`app-dispatch` chapter shows in detail how to apply middleware. You -can introduce WSGI middleware to wrap your Flask instances and introduce fixes -and changes at the layer between your Flask application and your HTTP -server. Werkzeug includes several `middlewares -`_. - -Fork. ------ - -If none of the above options work, fork Flask. The majority of code of Flask -is within Werkzeug and Jinja2. These libraries do the majority of the work. -Flask is just the paste that glues those together. For every project there is -the point where the underlying framework gets in the way (due to assumptions -the original developers had). This is natural because if this would not be the -case, the framework would be a very complex system to begin with which causes a -steep learning curve and a lot of user frustration. - -This is not unique to Flask. Many people use patched and modified -versions of their framework to counter shortcomings. This idea is also -reflected in the license of Flask. You don't have to contribute any -changes back if you decide to modify the framework. - -The downside of forking is of course that Flask extensions will most -likely break because the new framework has a different import name. -Furthermore integrating upstream changes can be a complex process, -depending on the number of changes. Because of that, forking should be -the very last resort. - -Scale like a pro. ------------------ - -For many web applications the complexity of the code is less an issue than -the scaling for the number of users or data entries expected. Flask by -itself is only limited in terms of scaling by your application code, the -data store you want to use and the Python implementation and webserver you -are running on. - -Scaling well means for example that if you double the amount of servers -you get about twice the performance. Scaling bad means that if you add a -new server the application won't perform any better or would not even -support a second server. - -There is only one limiting factor regarding scaling in Flask which are -the context local proxies. They depend on context which in Flask is -defined as being either a thread, process or greenlet. If your server -uses some kind of concurrency that is not based on threads or greenlets, -Flask will no longer be able to support these global proxies. However the -majority of servers are using either threads, greenlets or separate -processes to achieve concurrency which are all methods well supported by -the underlying Werkzeug library. - -Discuss with the community. ---------------------------- - -The Flask developers keep the framework accessible to users with codebases big -and small. If you find an obstacle in your way, caused by Flask, don't hesitate -to contact the developers on the mailinglist or IRC channel. The best way for -the Flask and Flask extension developers to improve the tools for larger -applications is getting feedback from users. diff --git a/docs/blueprints.rst b/docs/blueprints.rst index 89d3701e67..d5cf3d8237 100644 --- a/docs/blueprints.rst +++ b/docs/blueprints.rst @@ -1,5 +1,3 @@ -.. _blueprints: - Modular Applications with Blueprints ==================================== @@ -37,8 +35,9 @@ Blueprints in Flask are intended for these cases: 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. +objects? You can do that (see :doc:`/patterns/appdispatch`), 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 @@ -70,16 +69,17 @@ implement a blueprint that does simple rendering of static templates:: @simple_page.route('/') def show(page): try: - return render_template('pages/%s.html' % page) + return render_template(f'pages/{page}.html') 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. +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``). +constructor (in this case also ``simple_page``). The blueprint's name +does not modify the URL, only the endpoint. Registering Blueprints ---------------------- @@ -95,9 +95,10 @@ So how do you register that blueprint? Like this:: If you check the rules registered on the application, you will find these:: - [' (HEAD, OPTIONS, GET) -> static>, + >>> app.url_map + Map([' (HEAD, OPTIONS, GET) -> static>, ' (HEAD, OPTIONS, GET) -> simple_page.show>, - 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`` @@ -110,14 +111,53 @@ Blueprints however can also be mounted at different locations:: And sure enough, these are the generated rules:: - [' (HEAD, OPTIONS, GET) -> static>, + >>> app.url_map + Map([' (HEAD, OPTIONS, GET) -> static>, ' (HEAD, OPTIONS, GET) -> simple_page.show>, - 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. +Nesting Blueprints +------------------ + +It is possible to register a blueprint on another blueprint. + +.. code-block:: python + + parent = Blueprint('parent', __name__, url_prefix='/parent') + child = Blueprint('child', __name__, url_prefix='/child') + parent.register_blueprint(child) + app.register_blueprint(parent) + +The child blueprint will gain the parent's name as a prefix to its +name, and child URLs will be prefixed with the parent's URL prefix. + +.. code-block:: python + + url_for('parent.child.create') + /parent/child/create + +In addition a child blueprint's will gain their parent's subdomain, +with their subdomain as prefix if present i.e. + +.. code-block:: python + + parent = Blueprint('parent', __name__, subdomain='parent') + child = Blueprint('child', __name__, subdomain='child') + parent.register_blueprint(child) + app.register_blueprint(parent) + + url_for('parent.child.create', _external=True) + "child.parent.domain.tld" + +Blueprint-specific before request functions, etc. registered with the +parent will trigger for the child. If a child does not have an error +handler that can handle a given exception, the parent's will be tried. + + Blueprint Resources ------------------- @@ -151,23 +191,31 @@ To quickly open sources from this folder you can use the Static Files ```````````` -A blueprint can expose a folder with static files by providing a path to a -folder on the filesystem via the `static_folder` keyword argument. It can -either be an absolute path or one relative to the folder of the -blueprint:: +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. Because the folder is called :file:`static` here it will be available at -the location of the blueprint + ``/static``. Say the blueprint is -registered for ``/admin`` the static folder will be at ``/admin/static``. +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` so you can generate URLs to -it like you would do to the static folder of the application:: +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 ````````` @@ -177,11 +225,11 @@ 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. +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. +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 @@ -194,7 +242,7 @@ want to render the template ``'admin/index.html'`` and you have provided 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. +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 @@ -232,10 +280,11 @@ you can use relative redirects by prefixing the endpoint with a dot only:: 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` +Blueprint 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. @@ -245,4 +294,22 @@ Here is an example for a "404 Page Not Found" exception:: def page_not_found(e): return render_template('pages/404.html') -More information on error handling see :ref:`errorpages`. +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=str(ex)), ex.code + else: + return ex + +See :doc:`/errorhandling`. diff --git a/docs/changelog.rst b/docs/changelog.rst deleted file mode 100644 index d6c5f48c79..0000000000 --- a/docs/changelog.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../CHANGES diff --git a/docs/changes.rst b/docs/changes.rst new file mode 100644 index 0000000000..955deaf27b --- /dev/null +++ b/docs/changes.rst @@ -0,0 +1,4 @@ +Changes +======= + +.. include:: ../CHANGES.rst diff --git a/docs/cli.rst b/docs/cli.rst index 7ddf50f357..a72e6d51cb 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -1,248 +1,556 @@ -.. _cli: +.. currentmodule:: flask Command Line Interface ====================== -.. versionadded:: 0.11 +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. -.. currentmodule:: flask +.. _Click: https://click.palletsprojects.com/ -One of the nice new features in Flask 0.11 is the built-in integration of -the `click `_ command line interface. This -enables a wide range of new features for the Flask ecosystem and your own -applications. -Basic Usage ------------ +Application Discovery +--------------------- -After installation of Flask you will now find a :command:`flask` script -installed into your virtualenv. If you don't want to install Flask or you -have a special use-case you can also use ``python -m flask`` to accomplish -exactly the same. +The ``flask`` command is installed by Flask, not your application; it must be +told where to find your application in order to use it. The ``--app`` +option is used to specify how to load the application. -The way this script works is by providing access to all the commands on -your Flask application's :attr:`Flask.cli` instance as well as some -built-in commands that are always there. Flask extensions can also -register more commands there if they desire so. +While ``--app`` supports a variety of options for specifying your +application, most use cases should be simple. Here are the typical values: -For the :command:`flask` script to work, an application needs to be -discovered. This is achieved by exporting the ``FLASK_APP`` environment -variable. It can be either set to an import path or to a filename of a -Python module that contains a Flask application. +(nothing) + The name "app" or "wsgi" is imported (as a ".py" file, or package), + automatically detecting an app (``app`` or ``application``) or + factory (``create_app`` or ``make_app``). -In that imported file the name of the app needs to be called ``app`` or -optionally be specified after a colon. For instance -``mymodule:application`` would tell it to use the `application` object in -the :file:`mymodule.py` file. +``--app hello`` + The given name is imported, automatically detecting an app (``app`` + or ``application``) or factory (``create_app`` or ``make_app``). -Given a :file:`hello.py` file with the application in it named ``app`` -this is how it can be run. +---- -Environment variables (On Windows use ``set`` instead of ``export``):: +``--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: - export FLASK_APP=hello - flask run +``--app src/hello`` + Sets the current working directory to ``src`` then imports ``hello``. -Or with a filename:: +``--app hello.web`` + Imports the path ``hello.web``. - export FLASK_APP=/path/to/hello.py - flask run +``--app hello:app2`` + Uses the ``app2`` Flask instance in ``hello``. -Virtualenv Integration ----------------------- +``--app 'hello:create_app("dev")'`` + The ``create_app`` factory in ``hello`` is called with the string ``'dev'`` + as the argument. -If you are constantly working with a virtualenv you can also put the -``export FLASK_APP`` into your ``activate`` script by adding it to the -bottom of the file. That way every time you activate your virtualenv you -automatically also activate the correct application name. +If ``--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. -Debug Flag ----------- +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. -The :command:`flask` script can also be instructed to enable the debug -mode of the application automatically by exporting ``FLASK_DEBUG``. If -set to ``1`` debug is enabled or ``0`` disables it:: +If parentheses follow the factory name, their contents are parsed as +Python literals and passed as arguments and keyword arguments to the +function. This means that strings must still be in quotes. - export FLASK_DEBUG=1 -Running a Shell ---------------- +Run the Development Server +-------------------------- + +The :func:`run ` command will start the development server. It +replaces the :meth:`Flask.run` method in most cases. :: + + $ flask --app hello 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 :doc:`/deploying/index` for how to run in production. + +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. + + +Debug Mode +~~~~~~~~~~ + +In debug mode, the ``flask run`` command will enable the interactive debugger and the +reloader by default, and make errors easier to see and debug. To enable debug mode, use +the ``--debug`` option. + +.. code-block:: console + + $ flask --app hello run --debug + * Serving Flask app "hello" + * 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 + +The ``--debug`` option can also be passed to the top level ``flask`` command to enable +debug mode for any command. The following two ``run`` calls are equivalent. + +.. code-block:: console + + $ flask --app hello --debug run + $ flask --app hello run --debug + + +Watch and Ignore Files with the Reloader +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When using debug mode, the reloader will trigger whenever your Python code or imported +modules change. The reloader can watch additional files with the ``--extra-files`` +option. Multiple paths are separated with ``:``, or ``;`` on Windows. + +.. code-block:: text + + $ flask run --extra-files file1:dirA/file2:dirB/ + * Running on http://127.0.0.1:8000/ + * Detected change in '/path/to/file1', reloading + +The reloader can also ignore files using :mod:`fnmatch` patterns with the +``--exclude-patterns`` option. Multiple patterns are separated with ``:``, or ``;`` on +Windows. + + +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.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux + App: example [production] + Instance: /home/david/Projects/pallets/flask/instance + >>> + +Use :meth:`~Flask.shell_context_processor` to add other automatic imports. + + +.. _dotenv: + +Environment Variables From dotenv +--------------------------------- + +The ``flask`` command supports setting any option for any command with +environment variables. The variables are named like ``FLASK_OPTION`` or +``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or +``FLASK_RUN_PORT``. + +Rather than passing options every time you run a command, or environment +variables every 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 ``.env`` and ``.flaskenv``. +You can also specify an extra file to load with the ``--env-file`` +option. Dotenv files can be used to avoid having to set ``--app`` or +``FLASK_APP`` manually, 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 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``: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_RUN_PORT=8000 + $ flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x FLASK_RUN_PORT 8000 + $ flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_RUN_PORT=8000 + > flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env: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. + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_SKIP_DOTENV=1 + $ flask run + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x FLASK_SKIP_DOTENV 1 + $ flask run + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_SKIP_DOTENV=1 + > flask run + + .. group-tab:: Powershell + + .. code-block:: text + + > $env: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. + +.. tabs:: + + .. group-tab:: Bash + + Unix Bash, :file:`.venv/bin/activate`:: + + $ export FLASK_APP=hello + + .. group-tab:: Fish + + Fish, :file:`.venv/bin/activate.fish`:: -To run an interactive Python shell you can use the ``shell`` command:: + $ set -x FLASK_APP hello - flask shell + .. group-tab:: CMD + + Windows CMD, :file:`.venv\\Scripts\\activate.bat`:: + + > set FLASK_APP=hello + + .. group-tab:: Powershell + + Windows Powershell, :file:`.venv\\Scripts\\activate.ps1`:: + + > $env: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. -This will start up an interactive Python shell, setup the correct -application context and setup the local variables in the shell. This is -done by invoking the :meth:`Flask.make_shell_context` method of the -application. By default you have access to your ``app`` and :data:`g`. Custom Commands --------------- -If you want to add more commands to the shell script you can do this -easily. Flask uses `click`_ for the command interface which makes -creating custom commands very easy. For instance if you want a shell -command to initialize the database you can do this:: +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: - @app.cli.command() - def initdb(): - """Initialize the database.""" - click.echo('Init the db') +.. code-block:: python -The command will then show up on the command line:: + bp = Blueprint('students', __name__, cli_group=None) + # or + app.register_blueprint(bp, cli_group=None) + +.. code-block:: text + + $ flask create alice - $ flask initdb - Init the db Application Context -------------------- +~~~~~~~~~~~~~~~~~~~ + +Commands added using the Flask app's :attr:`~Flask.cli` or +:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator +will be executed with an application context pushed, so your custom +commands and parameters have access to the app and its configuration. The +:func:`~cli.with_appcontext` decorator can be used to get the same +behavior, but is not needed in most cases. + +.. code-block:: python + + import click + from flask.cli import with_appcontext + + @click.command() + @with_appcontext + def do_work(): + ... -Most commands operate on the application so it makes a lot of sense if -they have the application context setup. Because of this, if you register -a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the -callback will automatically be wrapped through :func:`cli.with_appcontext` -which informs the cli system to ensure that an application context is set -up. This behavior is not available if a command is added later with -:func:`~click.Group.add_command` or through other means. + app.cli.add_command(do_work) -It can also be disabled by passing ``with_appcontext=False`` to the -decorator:: - @app.cli.command(with_appcontext=False) - def example(): - pass +Plugins +------- -Factory Functions ------------------ +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:`pyproject.toml`: -In case you are using factory functions to create your application (see -:ref:`app-factories`) you will discover that the :command:`flask` command -cannot work with them directly. Flask won't be able to figure out how to -instantiate your application properly by itself. Because of this reason -the recommendation is to create a separate file that instantiates -applications. This is not the only way to make this work. Another is the -:ref:`custom-scripts` support. +.. code-block:: toml -For instance if you have a factory function that creates an application -from a filename you could make a separate file that creates such an -application from an environment variable. + [project.entry-points."flask.commands"] + my-command = "my_extension.commands:cli" -This could be a file named :file:`autoapp.py` with these contents:: +.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points - import os - from yourapplication import create_app - app = create_app(os.environ['YOURAPPLICATION_CONFIG']) +Inside :file:`my_extension/commands.py` you can then export a Click +object:: -Once this has happened you can make the flask command automatically pick -it up:: + import click + + @click.command() + def cli(): + ... - export YOURAPPLICATION_CONFIG=/path/to/config.cfg - export FLASK_APP=/path/to/autoapp.py +Once that package is installed in the same virtualenv as your Flask project, +you can run ``flask my-command`` to invoke the command. -From this point onwards :command:`flask` will find your application. .. _custom-scripts: Custom Scripts -------------- -While the most common way is to use the :command:`flask` command, you can -also make your own "driver scripts". Since Flask uses click for the -scripts there is no reason you cannot hook these scripts into any click -application. There is one big caveat and that is, that commands -registered to :attr:`Flask.cli` will expect to be (indirectly at least) -launched from a :class:`flask.cli.FlaskGroup` click group. This is -necessary so that the commands know which Flask application they have to -work with. - -To understand why you might want custom scripts you need to understand how -click finds and executes the Flask application. If you use the -:command:`flask` script you specify the application to work with on the -command line or environment variable as an import name. This is simple -but it has some limitations. Primarily it does not work with application -factory functions (see :ref:`app-factories`). - -With a custom script you don't have this problem as you can fully -customize how the application will be created. This is very useful if you -write reusable applications that you want to ship to users and they should -be presented with a custom management script. - -To explain all of this, here is an example :file:`manage.py` script that -manages a hypothetical wiki application. We will go through the details -afterwards:: - - import os +When you are using the app factory pattern, it may be more convenient to define +your own Click script. Instead of using ``--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_wiki_app(info): - from yourwiki import create_app - return create_app( - config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py')) + def create_app(): + app = Flask('wiki') + # other setup + return app - @click.group(cls=FlaskGroup, create_app=create_wiki_app) + @click.group(cls=FlaskGroup, create_app=create_app) def cli(): - """This is a management script for the wiki application.""" - - if __name__ == '__main__': - cli() - -That's a lot of code for not much, so let's go through all parts step by -step. - -1. First we import the ``click`` library as well as the click extensions - from the ``flask.cli`` package. Primarily we are here interested - in the :class:`~flask.cli.FlaskGroup` click group. -2. The next thing we do is defining a function that is invoked with the - script info object (:class:`~flask.cli.ScriptInfo`) from Flask and its - purpose is to fully import and create the application. This can - either directly import an application object or create it (see - :ref:`app-factories`). In this case we load the config from an - environment variable. -3. Next step is to create a :class:`FlaskGroup`. In this case we just - make an empty function with a help doc string that just does nothing - and then pass the ``create_wiki_app`` function as a factory function. - - Whenever click now needs to operate on a Flask application it will - call that function with the script info and ask for it to be created. -4. All is rounded up by invoking the script. - -CLI Plugins ------------ - -Flask extensions can always patch the :attr:`Flask.cli` instance with more -commands if they want. However there is a second way to add CLI plugins -to Flask which is through ``setuptools``. If you make a Python package that -should export a Flask command line plugin you can ship a :file:`setup.py` file -that declares an entrypoint that points to a click command: - -Example :file:`setup.py`:: - - from setuptools import setup - - setup( - name='flask-my-extension', - ... - entry_points=''' - [flask.commands] - my-command=mypackage.commands:cli - ''', - ) + """Management script for the Wiki application.""" -Inside :file:`mypackage/commands.py` you can then export a Click object:: +Define the entry point in :file:`pyproject.toml`: - import click +.. code-block:: toml - @click.command() - def cli(): - """This is an example command.""" + [project.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 ``--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 +------------------- + +PyCharm Professional provides a special Flask run configuration to run the development +server. For the Community Edition, and for other commands besides ``run``, you need to +create a custom run configuration. These instructions should be similar for any other +IDE you use. + +In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit +Configurations*. You'll see a screen similar to this: + +.. image:: _static/pycharm-run-config.png + :align: center + :class: screenshot + :alt: Screenshot of PyCharm run configuration. + +Once you create a configuration for the ``flask run``, you can copy and change it to +call any other command. + +Click the *+ (Add New Configuration)* button and select *Python*. Give the configuration +a name such as "flask run". + +Click the *Script path* dropdown and change it to *Module name*, then input ``flask``. + +The *Parameters* field is set to the CLI command to execute along with any arguments. +This example uses ``--app hello run --debug``, which will run the development server in +debug mode. ``--app hello`` should be the import or file with your Flask app. + +If you installed your project as a package in your virtualenv, you may uncheck the +*PYTHONPATH* options. This will more accurately match how you deploy later. + +Click *OK* to save and close the configuration. Select the configuration in the main +PyCharm window and click the play button next to it to run the server. -Once that package is installed in the same virtualenv as Flask itself you -can run ``flask my-command`` to invoke your command. This is useful to -provide extra functionality that Flask itself cannot ship. +Now that you have a configuration for ``flask run``, you can copy that configuration and +change the *Parameters* argument to run a different CLI command. diff --git a/docs/conf.py b/docs/conf.py index b37427a812..eca4f81042 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,299 +1,101 @@ -# -*- coding: utf-8 -*- -# -# Flask documentation build configuration file, created by -# sphinx-quickstart on Tue Apr 6 15:24:58 2010. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. -from __future__ import print_function -from datetime import datetime -import os -import sys -import pkg_resources +import packaging.version +from pallets_sphinx_themes import get_version +from pallets_sphinx_themes import ProjectLink -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.append(os.path.join(os.path.dirname(__file__), '_themes')) -sys.path.append(os.path.dirname(__file__)) +# Project -------------------------------------------------------------- -# -- General configuration ----------------------------------------------------- +project = "Flask" +copyright = "2010 Pallets" +author = "Pallets" +release, version = get_version("Flask") -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# General -------------------------------------------------------------- -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +default_role = "code" extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'flaskdocext' + "sphinx.ext.autodoc", + "sphinx.ext.extlinks", + "sphinx.ext.intersphinx", + "sphinxcontrib.log_cabinet", + "sphinx_tabs.tabs", + "pallets_sphinx_themes", ] +autodoc_member_order = "bysource" +autodoc_typehints = "description" +autodoc_preserve_defaults = True +extlinks = { + "issue": ("https://github.com/pallets/flask/issues/%s", "#%s"), + "pr": ("https://github.com/pallets/flask/pull/%s", "#%s"), + "ghsa": ("https://github.com/pallets/flask/security/advisories/GHSA-%s", "GHSA-%s"), +} +intersphinx_mapping = { + "python": ("https://docs.python.org/3/", None), + "werkzeug": ("https://werkzeug.palletsprojects.com/", None), + "click": ("https://click.palletsprojects.com/", None), + "jinja": ("https://jinja.palletsprojects.com/", None), + "itsdangerous": ("https://itsdangerous.palletsprojects.com/", None), + "sqlalchemy": ("https://docs.sqlalchemy.org/", None), + "wtforms": ("https://wtforms.readthedocs.io/", None), + "blinker": ("https://blinker.readthedocs.io/", None), +} -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'Flask' -copyright = u'2010 - {0}, Armin Ronacher'.format(datetime.utcnow().year) - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -try: - release = pkg_resources.get_distribution('Flask').version -except pkg_resources.DistributionNotFound: - print('Flask must be installed to build the documentation.') - print('Install from source using `pip install -e .` in a virtualenv.') - sys.exit(1) - -if 'dev' in release: - release = ''.join(release.partition('dev')[:2]) - -version = '.'.join(release.split('.')[:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. Major themes that come with -# Sphinx are currently 'default' and 'sphinxdoc'. -# html_theme = 'default' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -html_theme_path = ['_themes'] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. Do not set, template magic! -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -html_favicon = '_static/flask-favicon.ico' - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -html_sidebars = { - 'index': [ - 'sidebarintro.html', - 'sourcelink.html', - 'searchbox.html' - ], - '**': [ - 'sidebarlogo.html', - 'localtoc.html', - 'relations.html', - 'sourcelink.html', - 'searchbox.html' +# HTML ----------------------------------------------------------------- + +html_theme = "flask" +html_theme_options = {"index_sidebar_logo": False} +html_context = { + "project_links": [ + ProjectLink("Donate", "https://palletsprojects.com/donate"), + 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/"), + ProjectLink("Chat", "https://discord.gg/pallets"), ] } - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -html_use_modindex = False - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -html_show_sphinx = False - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = '' - -# Output file base name for HTML help builder. -htmlhelp_basename = 'Flaskdoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('latexindex', 'Flask.tex', u'Flask Documentation', u'Armin Ronacher', 'manual'), -] - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -latex_use_modindex = False - -latex_elements = { - 'fontpkg': r'\usepackage{mathpazo}', - 'papersize': 'a4paper', - 'pointsize': '12pt', - 'preamble': r'\usepackage{flaskstyle}' +html_sidebars = { + "index": ["project.html", "localtoc.html", "searchbox.html", "ethicalads.html"], + "**": ["localtoc.html", "relations.html", "searchbox.html", "ethicalads.html"], } -latex_use_parts = True - -latex_additional_files = ['flaskstyle.sty', 'logo.pdf'] - - -# -- Options for Epub output --------------------------------------------------- +singlehtml_sidebars = {"index": ["project.html", "localtoc.html", "ethicalads.html"]} +html_static_path = ["_static"] +html_favicon = "_static/shortcut-icon.png" +html_logo = "_static/flask-vertical.png" +html_title = f"Flask Documentation ({version})" +html_show_sourcelink = False -# Bibliographic Dublin Core info. -#epub_title = '' -#epub_author = '' -#epub_publisher = '' -#epub_copyright = '' +gettext_uuid = True +gettext_compact = False -# The language of the text. It defaults to the language option -# or en if the language is not set. -#epub_language = '' +# Local Extensions ----------------------------------------------------- -# The scheme of the identifier. Typical schemes are ISBN or URL. -#epub_scheme = '' -# The unique identifier of the text. This can be a ISBN number -# or the project homepage. -#epub_identifier = '' +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/" -# A unique identification for the text. -#epub_uid = '' - -# HTML files that should be inserted before the pages created by sphinx. -# The format is a list of tuples containing the path and title. -#epub_pre_files = [] - -# HTML files shat should be inserted after the pages created by sphinx. -# The format is a list of tuples containing the path and title. -#epub_post_files = [] - -# A list of files that should not be packed into the epub file. -#epub_exclude_files = [] - -# The depth of the table of contents in toc.ncx. -#epub_tocdepth = 3 - -intersphinx_mapping = { - 'python': ('https://docs.python.org/3/', None), - 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None), - 'click': ('http://click.pocoo.org/', None), - 'jinja': ('http://jinja.pocoo.org/docs/', None), - 'sqlalchemy': ('http://docs.sqlalchemy.org/en/latest/', None), - 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None), - 'blinker': ('https://pythonhosted.org/blinker/', None) -} + if text.endswith(">"): + words, text = text[:-1].rsplit("<", 1) + words = words.strip() + else: + words = None -try: - __import__('flask_theme_support') - pygments_style = 'flask_theme_support.FlaskyStyle' - html_theme = 'flask' - html_theme_options = { - 'touch_icon': 'touch-icon.png' - } -except ImportError: - print('-' * 74) - print('Warning: Flask themes unavailable. Building with default theme') - print('If you want the Flask themes, run this command and build again:') - print() - print(' git submodule update --init') - print('-' * 74) + if packaging.version.parse(release).is_devrelease: + url = f"{base_url}main/{text}" + else: + url = f"{base_url}{release}/{text}" + if words is None: + words = url -# unwrap decorators -def unwrap_decorators(): - import sphinx.util.inspect as inspect - import functools + from docutils.nodes import reference + from docutils.parsers.rst.roles import set_classes - old_getargspec = inspect.getargspec - def getargspec(x): - return old_getargspec(getattr(x, '_original_function', x)) - inspect.getargspec = getargspec + options = options or {} + set_classes(options) + node = reference(rawtext, words, refuri=url, **options) + return [node], [] - old_update_wrapper = functools.update_wrapper - def update_wrapper(wrapper, wrapped, *a, **kw): - rv = old_update_wrapper(wrapper, wrapped, *a, **kw) - rv._original_function = wrapped - return rv - functools.update_wrapper = update_wrapper -unwrap_decorators() -del unwrap_decorators +def setup(app): + app.add_role("gh", github_link) diff --git a/docs/config.rst b/docs/config.rst index 89fa092497..e7d4410a6a 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -1,17 +1,13 @@ -.. _config: - Configuration Handling ====================== -.. versionadded:: 0.3 - 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 hardcode the +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. @@ -22,6 +18,7 @@ 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 -------------------- @@ -29,193 +26,373 @@ 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['DEBUG'] = True + 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.debug = True + app.testing = True To update multiple keys at once you can use the :meth:`dict.update` method:: app.config.update( - DEBUG=True, - SECRET_KEY='...' + TESTING=True, + SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' ) + +Debug Mode +---------- + +The :data:`DEBUG` config value is special because it may behave inconsistently if +changed after the app has begun setting up. In order to set debug mode reliably, use the +``--debug`` option on the ``flask`` or ``flask run`` command. ``flask run`` will use the +interactive debugger and reloader by default in debug mode. + +.. code-block:: text + + $ flask --app hello run --debug + +Using the option is recommended. While it is possible to set :data:`DEBUG` in your +config or code, this is strongly discouraged. It can't be read early by the +``flask run`` 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: -.. tabularcolumns:: |p{6.5cm}|p{8.5cm}| - -================================= ========================================= -``DEBUG`` enable/disable debug mode -``TESTING`` enable/disable testing mode -``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the - propagation of exceptions. If not set or - explicitly set to ``None`` this is - implicitly true if either ``TESTING`` or - ``DEBUG`` is true. -``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in - debug mode the request context is not - popped on exceptions to enable debuggers - to introspect the data. This can be - disabled by this key. You can also use - this setting to force-enable it for non - debug execution which might be useful to - debug production applications (but also - very risky). -``SECRET_KEY`` the secret key -``SESSION_COOKIE_NAME`` the name of the session cookie -``SESSION_COOKIE_DOMAIN`` the domain for the session cookie. If - this is not set, the cookie will be - valid for all subdomains of - ``SERVER_NAME``. -``SESSION_COOKIE_PATH`` the path for the session cookie. If - this is not set the cookie will be valid - for all of ``APPLICATION_ROOT`` or if - that is not set for ``'/'``. -``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set - with the httponly flag. Defaults to - ``True``. -``SESSION_COOKIE_SECURE`` controls if the cookie should be set - with the secure flag. Defaults to - ``False``. -``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as - :class:`datetime.timedelta` object. - Starting with Flask 0.8 this can also be - an integer representing seconds. -``SESSION_REFRESH_EACH_REQUEST`` this flag controls how permanent - sessions are refreshed. If set to ``True`` - (which is the default) then the cookie - is refreshed each request which - automatically bumps the lifetime. If - set to ``False`` a `set-cookie` header is - only sent if the session is modified. - Non permanent sessions are not affected - by this. -``USE_X_SENDFILE`` enable/disable x-sendfile -``LOGGER_NAME`` the name of the logger -``LOGGER_HANDLER_POLICY`` the policy of the default logging - handler. The default is ``'always'`` - which means that the default logging - handler is always active. ``'debug'`` - will only activate logging in debug - mode, ``'production'`` will only log in - production and ``'never'`` disables it - entirely. -``SERVER_NAME`` the name and port number of the server. - Required for subdomain support (e.g.: - ``'myapp.dev:5000'``) Note that - localhost does not support subdomains so - setting this to “localhost” does not - help. Setting a ``SERVER_NAME`` also - by default enables URL generation - without a request context but with an - application context. -``APPLICATION_ROOT`` If the application does not occupy - a whole domain or subdomain this can - be set to the path where the application - is configured to live. This is for - session cookie as path value. If - domains are used, this should be - ``None``. -``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will - reject incoming requests with a - content length greater than this by - returning a 413 status code. -``SEND_FILE_MAX_AGE_DEFAULT`` Default cache control max age to use with - :meth:`~flask.Flask.send_static_file` (the - default static file handler) and - :func:`~flask.send_file`, as - :class:`datetime.timedelta` or as seconds. - Override this value on a per-file - basis using the - :meth:`~flask.Flask.get_send_file_max_age` - hook on :class:`~flask.Flask` or - :class:`~flask.Blueprint`, - respectively. Defaults to 43200 (12 hours). -``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will - not execute the error handlers of HTTP - exceptions but instead treat the - exception like any other and bubble it - through the exception stack. This is - helpful for hairy debugging situations - where you have to find out where an HTTP - exception is coming from. -``TRAP_BAD_REQUEST_ERRORS`` Werkzeug's internal data structures that - deal with request specific data will - raise special key errors that are also - bad request exceptions. Likewise many - operations can implicitly fail with a - BadRequest exception for consistency. - Since it's nice for debugging to know - why exactly it failed this flag can be - used to debug those situations. If this - config is set to ``True`` you will get - a regular traceback instead. -``PREFERRED_URL_SCHEME`` The URL scheme that should be used for - URL generation if no URL scheme is - available. This defaults to ``http``. -``JSON_AS_ASCII`` By default Flask serialize object to - ascii-encoded JSON. If this is set to - ``False`` Flask will not encode to ASCII - and output strings as-is and return - unicode strings. ``jsonify`` will - automatically encode it in ``utf-8`` - then for transport for instance. -``JSON_SORT_KEYS`` By default Flask will serialize JSON - objects in a way that the keys are - ordered. This is done in order to - ensure that independent of the hash seed - of the dictionary the return value will - be consistent to not trash external HTTP - caches. You can override the default - behavior by changing this variable. - This is not recommended but might give - you a performance improvement on the - cost of cacheability. -``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` (the default) - jsonify responses will be pretty printed - if they are not requested by an - XMLHttpRequest object (controlled by - the ``X-Requested-With`` header) -``JSONIFY_MIMETYPE`` MIME type used for jsonify responses. -``TEMPLATES_AUTO_RELOAD`` Whether to check for modifications of - the template source and reload it - automatically. By default the value is - ``None`` which means that Flask checks - original file only in debug mode. -``EXPLAIN_TEMPLATE_LOADING`` If this is enabled then every attempt to - load a template will write an info - message to the logger explaining the - attempts to locate the template. This - can be useful to figure out why - templates cannot be found or wrong - templates appear to be loaded. -================================= ========================================= - -.. admonition:: More on ``SERVER_NAME`` - - The ``SERVER_NAME`` key is used for the subdomain support. Because - Flask cannot guess the subdomain part without the knowledge of the - actual server name, this is required if you want to work with - subdomains. This is also used for the session cookie. - - Please keep in mind that not only Flask has the problem of not knowing - what subdomains are, your web browser does as well. Most modern web - browsers will not allow cross-subdomain cookies to be set on a - server name without dots in it. So if your server name is - ``'localhost'`` you will not be able to set a cookie for - ``'localhost'`` and every subdomain of it. Please choose a different - server name in that case, like ``'myapplication.local'`` and add - this name + the subdomains you want to use into your host config - or setup a local `bind`_. - -.. _bind: https://www.isc.org/downloads/bind/ +.. 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 set with 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: ``False`` + +.. 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:: 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 ``bytes`` or ``str``. For + example, copy the output of this to your config:: + + $ python -c 'import secrets; print(secrets.token_hex())' + '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + + **Do not reveal the secret key when posting questions or committing code.** + + Default: ``None`` + +.. py:data:: SECRET_KEY_FALLBACKS + + A list of old secret keys that can still be used for unsigning. This allows + a project to implement key rotation without invalidating active sessions or + other recently-signed secrets. + + Keys should be removed after an appropriate period of time, as checking each + additional key adds some overhead. + + Order should not matter, but the default implementation will test the last + key in the list first, so it might make sense to order oldest to newest. + + Flask's built-in secure cookie session supports this. Extensions that use + :data:`SECRET_KEY` may not support this yet. + + Default: ``None`` + + .. versionadded:: 3.1 + +.. 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 value of the ``Domain`` parameter on the session cookie. If not set, browsers + will only send the cookie to the exact domain it was set from. Otherwise, they + will send it to any subdomain of the given value as well. + + Not setting this value is more restricted and secure than setting it. + + Default: ``None`` + + .. warning:: + If this is changed after the browser created a cookie is created with + one setting, it may result in another being created. Browsers may send + send both in an undefined order. In that case, you may want to change + :data:`SESSION_COOKIE_NAME` as well or otherwise invalidate old sessions. + + .. versionchanged:: 2.3 + Not set by default, does not fall back to ``SERVER_NAME``. + +.. 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_PARTITIONED + + Browsers will send cookies based on the top-level document's domain, rather + than only the domain of the document setting the cookie. This prevents third + party cookies set in iframes from "leaking" between separate sites. + + Browsers are beginning to disallow non-partitioned third party cookies, so + you need to mark your cookies partitioned if you expect them to work in such + embedded situations. + + Enabling this implicitly enables :data:`SESSION_COOKIE_SECURE` as well, as + it is only valid when served over HTTPS. + + Default: ``False`` + + .. versionadded:: 3.1 + +.. 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 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. + + If ``None``, ``send_file`` tells the browser to use conditional + requests will be used instead of a timed cache, which is usually + preferable. + + Default: ``None`` + +.. py:data:: TRUSTED_HOSTS + + Validate :attr:`.Request.host` and other attributes that use it against + these trusted values. Raise a :exc:`~werkzeug.exceptions.SecurityError` if + the host is invalid, which results in a 400 error. If it is ``None``, all + hosts are valid. Each value is either an exact match, or can start with + a dot ``.`` to match any subdomain. + + Validation is done during routing against this value. ``before_request`` and + ``after_request`` callbacks will still be called. + + Default: ``None`` + + .. versionadded:: 3.1 + +.. py:data:: SERVER_NAME + + Inform the application what host and port it is bound to. + + Must be set if ``subdomain_matching`` is enabled, to be able to extract the + subdomain from the request. + + Must be set for ``url_for`` to generate external URLs outside of a + request context. + + Default: ``None`` + + .. versionchanged:: 3.1 + Does not restrict requests to only this domain, for both + ``subdomain_matching`` and ``host_matching``. + + .. versionchanged:: 1.0 + Does not implicitly enable ``subdomain_matching``. + + .. versionchanged:: 2.3 + Does not affect ``SESSION_COOKIE_DOMAIN``. + +.. 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 :doc:`/patterns/appdispatch` + 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 + + The maximum number of bytes that will be read during this request. If + this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge` + error is raised. If it is set to ``None``, no limit is enforced at the + Flask application level. However, if it is ``None`` and the request has no + ``Content-Length`` header and the WSGI server does not indicate that it + terminates the stream, then no data is read to avoid an infinite stream. + + Each request defaults to this config. It can be set on a specific + :attr:`.Request.max_content_length` to apply the limit to that specific + view. This should be set appropriately based on an application's or view's + specific needs. + + Default: ``None`` + + .. versionadded:: 0.6 + +.. py:data:: MAX_FORM_MEMORY_SIZE + + The maximum size in bytes any non-file form field may be in a + ``multipart/form-data`` body. If this limit is exceeded, a 413 + :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it is + set to ``None``, no limit is enforced at the Flask application level. + + Each request defaults to this config. It can be set on a specific + :attr:`.Request.max_form_memory_parts` to apply the limit to that specific + view. This should be set appropriately based on an application's or view's + specific needs. + + Default: ``500_000`` + + .. versionadded:: 3.1 + +.. py:data:: MAX_FORM_PARTS + + The maximum number of fields that may be present in a + ``multipart/form-data`` body. If this limit is exceeded, a 413 + :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it + is set to ``None``, no limit is enforced at the Flask application level. + + Each request defaults to this config. It can be set on a specific + :attr:`.Request.max_form_parts` to apply the limit to that specific view. + This should be set appropriately based on an application's or view's + specific needs. + + Default: ``1_000`` + + .. versionadded:: 3.1 + +.. 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. + +.. py:data:: PROVIDE_AUTOMATIC_OPTIONS + + Set to ``False`` to disable the automatic addition of OPTIONS + responses. This can be overridden per route by altering the + ``provide_automatic_options`` attribute. .. versionadded:: 0.4 ``LOGGER_NAME`` @@ -245,16 +422,42 @@ The following configuration values are used internally by Flask: ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``, ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING`` -Configuring from Files ----------------------- +.. versionchanged:: 1.0 + ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See + :doc:`/logging` for information about configuration. -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. + Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment + variable. -So a common pattern is this:: + Added :data:`SESSION_COOKIE_SAMESITE` to control the session + cookie's ``SameSite`` option. + + Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug. + +.. versionchanged:: 2.2 + Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``. + +.. versionchanged:: 2.3 + ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_MIMETYPE``, and + ``JSONIFY_PRETTYPRINT_REGULAR`` were removed. The default ``app.json`` provider has + equivalent attributes instead. + +.. versionchanged:: 2.3 + ``ENV`` was removed. + +.. versionadded:: 3.10 + Added :data:`PROVIDE_AUTOMATIC_OPTIONS` to control the default + addition of autogenerated OPTIONS responses. + + +Configuring from Python Files +----------------------------- + +Configuration becomes more useful if you can store it in a separate file, ideally +located outside the actual application package. You can deploy your application, then +separately configure it for the specific deployment. + +A common pattern is this:: app = Flask(__name__) app.config.from_object('yourapplication.default_settings') @@ -262,19 +465,43 @@ So a common pattern is this:: 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:: +with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS` +environment variable points to. This environment variable can be set +in the shell before starting the server: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg + $ flask run + * Running on http://127.0.0.1:5000/ - $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg - $ python run-app.py - * Running on http://127.0.0.1:5000/ - * Restarting with reloader... + .. group-tab:: Fish -On Windows systems use the `set` builtin instead:: + .. code-block:: text - >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg + $ set -x YOURAPPLICATION_SETTINGS /path/to/settings.cfg + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: CMD + + .. code-block:: text + + > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg + > flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:YOURAPPLICATION_SETTINGS = "\path\to\settings.cfg" + > flask run + * Running on http://127.0.0.1:5000/ The configuration files themselves are actual Python files. Only values in uppercase are actually stored in the config object later on. So make @@ -283,8 +510,7 @@ sure to use uppercase letters for your config keys. Here is an example of a configuration file:: # Example configuration - DEBUG = False - SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83' + SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' 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 @@ -293,6 +519,118 @@ complete reference, read the :class:`~flask.Config` object's documentation. +Configuring from Data Files +--------------------------- + +It is also possible to load configuration from a file in a format of +your choice using :meth:`~flask.Config.from_file`. For example to load +from a TOML file: + +.. code-block:: python + + import tomllib + app.config.from_file("config.toml", load=tomllib.load, text=False) + +Or from a JSON file: + +.. code-block:: python + + import json + app.config.from_file("config.json", load=json.load) + + +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. Flask can be +instructed to load all environment variables starting with a specific +prefix into the config using :meth:`~flask.Config.from_prefixed_env`. + +Environment variables can be set in the shell before starting the +server: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f" + $ export FLASK_MAIL_ENABLED=false + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f" + $ set -x FLASK_MAIL_ENABLED false + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f" + > set FLASK_MAIL_ENABLED=false + > flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f" + > $env:FLASK_MAIL_ENABLED = "false" + > flask run + * Running on http://127.0.0.1:5000/ + +The variables can then be loaded and accessed via the config with a key +equal to the environment variable name without the prefix i.e. + +.. code-block:: python + + app.config.from_prefixed_env() + app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f" + +The prefix is ``FLASK_`` by default. This is configurable via the +``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`. + +Values will be parsed to attempt to convert them to a more specific type +than strings. By default :func:`json.loads` is used, so any valid JSON +value is possible, including lists and dicts. This is configurable via +the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`. + +When adding a boolean value with the default JSON parsing, only "true" +and "false", lowercase, are valid values. Keep in mind that any +non-empty string is considered ``True`` by Python. + +It is possible to set keys in nested dictionaries by separating the +keys with double underscore (``__``). Any intermediate keys that don't +exist on the parent dict will be initialized to an empty dict. + +.. code-block:: text + + $ export FLASK_MYAPI__credentials__username=user123 + +.. code-block:: python + + app.config["MYAPI"]["credentials"]["username"] # Is "user123" + +On Windows, environment variable keys are always uppercase, therefore +the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``. + +For even more config loading features, including merging and +case-insensitive Windows support, try a dedicated library such as +Dynaconf_, which includes integration with Flask. + +.. _Dynaconf: https://www.dynaconf.com/ + + Configuration Best Practices ---------------------------- @@ -303,13 +641,17 @@ 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 unittesting a lot + 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. +3. Make sure to load the configuration very early on, so that + extensions can access the configuration when calling ``init_app``. + + .. _config-dev-prod: Development / Production @@ -336,23 +678,22 @@ 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 hardcoded files based on that. +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 + DATABASE_URI = "sqlite:////tmp/foo.db" class TestingConfig(Config): + DATABASE_URI = 'sqlite:///:memory:' TESTING = True To enable such a config you just have to call into @@ -360,6 +701,41 @@ To enable such a config you just have to call into 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.""" + TESTING = False + DB_SERVER = '192.168.1.56' + + @property + def DATABASE_URI(self): # Note: all caps + return f"mysql://user@{self.DB_SERVER}/foo" + + class ProductionConfig(Config): + """Uses production database server.""" + DB_SERVER = '192.168.19.32' + + class DevelopmentConfig(Config): + DB_SERVER = 'localhost' + + class TestingConfig(Config): + DB_SERVER = 'localhost' + 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: @@ -373,12 +749,10 @@ your configuration files. However here a list of good recommendations: 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. +- Use a tool like `fabric`_ to push code and configuration separately + to the production server(s). -.. _fabric: http://www.fabfile.org/ +.. _fabric: https://www.fabfile.org/ .. _instance-folders: @@ -426,7 +800,7 @@ locations are used: - Installed module or package:: - $PREFIX/lib/python2.X/site-packages/myapp + $PREFIX/lib/pythonX.Y/site-packages/myapp $PREFIX/var/myapp-instance ``$PREFIX`` is the prefix of your Python installation. This can be @@ -443,7 +817,7 @@ root” (the default) to “relative to instance folder” via the 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 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) diff --git a/docs/contents.rst.inc b/docs/contents.rst.inc deleted file mode 100644 index 8b25e61db3..0000000000 --- a/docs/contents.rst.inc +++ /dev/null @@ -1,61 +0,0 @@ -User's Guide ------------- - -This part of the documentation, which is mostly prose, begins with some -background information about Flask, then focuses on step-by-step -instructions for web development with Flask. - -.. toctree:: - :maxdepth: 2 - - foreword - advanced_foreword - installation - quickstart - tutorial/index - templating - testing - errorhandling - config - signals - views - appcontext - reqcontext - blueprints - extensions - cli - server - shell - patterns/index - deploying/index - becomingbig - -API Reference -------------- - -If you are looking for information on a specific function, class or -method, this part of the documentation is for you. - -.. toctree:: - :maxdepth: 2 - - api - -Additional Notes ----------------- - -Design notes, legal information and changelog are here for the interested. - -.. toctree:: - :maxdepth: 2 - - design - htmlfaq - security - unicode - extensiondev - styleguide - python3 - upgrading - changelog - license diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000000..d44f865f57 --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1,8 @@ +Contributing +============ + +See the Pallets `detailed contributing documentation <_contrib>`_ for many ways +to contribute, including reporting issues, requesting features, asking or +answering questions, and making PRs. + +.. _contrib: https://palletsprojects.com/contributing/ diff --git a/docs/debugging.rst b/docs/debugging.rst new file mode 100644 index 0000000000..f6b56cab2f --- /dev/null +++ b/docs/debugging.rst @@ -0,0 +1,99 @@ +Debugging Application Errors +============================ + + +In Production +------------- + +**Do not run the development server, or enable the built-in debugger, in +a production environment.** The debugger allows executing arbitrary +Python code from the browser. It's protected by a pin, but that should +not be relied on for security. + +Use an error logging tool, such as Sentry, as described in +:ref:`error-logging-tools`, or enable logging and notifications as +described in :doc:`/logging`. + +If you have access to the server, you could add some code to start an +external debugger if ``request.remote_addr`` matches your IP. Some IDE +debuggers also have a remote mode so breakpoints on the server can be +interacted with locally. Only enable a debugger temporarily. + + +The Built-In Debugger +--------------------- + +The built-in Werkzeug development server provides a debugger which shows +an interactive traceback in the browser when an unhandled error occurs +during a request. This debugger should only be used during development. + +.. image:: _static/debugger.png + :align: center + :class: screenshot + :alt: screenshot of debugger in action + +.. warning:: + + The debugger allows executing arbitrary Python code from the + browser. It is protected by a pin, but still represents a major + security risk. Do not run the development server or debugger in a + production environment. + +The debugger is enabled by default when the development server is run in debug mode. + +.. code-block:: text + + $ flask --app hello run --debug + +When running from Python code, passing ``debug=True`` enables debug mode, which is +mostly equivalent. + +.. code-block:: python + + app.run(debug=True) + +:doc:`/server` and :doc:`/cli` have more information about running the debugger and +debug mode. More information about the debugger can be found in the `Werkzeug +documentation `__. + + +External Debuggers +------------------ + +External debuggers, such as those provided by IDEs, can offer a more +powerful debugging experience than the built-in debugger. They can also +be used to step through code during a request before an error is raised, +or if no error is raised. Some even have a remote mode so you can debug +code running on another machine. + +When using an external debugger, the app should still be in debug mode, otherwise Flask +turns unhandled errors into generic 500 error pages. However, the built-in debugger and +reloader should be disabled so they don't interfere with the external debugger. + +.. code-block:: text + + $ flask --app hello run --debug --no-debugger --no-reload + +When running from Python: + +.. code-block:: python + + app.run(debug=True, use_debugger=False, use_reloader=False) + +Disabling these isn't required, an external debugger will continue to work with the +following caveats. + +- If the built-in debugger is not disabled, it will catch unhandled exceptions before + the external debugger can. +- If the reloader is not disabled, it could cause an unexpected reload if code changes + during a breakpoint. +- The development server will still catch unhandled exceptions if the built-in + debugger is disabled, otherwise it would crash on any error. If you want that (and + usually you don't) pass ``passthrough_errors=True`` to ``app.run``. + + .. code-block:: python + + app.run( + debug=True, passthrough_errors=True, + use_debugger=False, use_reloader=False + ) diff --git a/docs/deploying/apache-httpd.rst b/docs/deploying/apache-httpd.rst new file mode 100644 index 0000000000..bdeaf62657 --- /dev/null +++ b/docs/deploying/apache-httpd.rst @@ -0,0 +1,66 @@ +Apache httpd +============ + +`Apache httpd`_ is a fast, production level HTTP server. When serving +your application with one of the WSGI servers listed in :doc:`index`, it +is often good or necessary to put a dedicated HTTP server in front of +it. This "reverse proxy" can handle incoming requests, TLS, and other +security and performance concerns better than the WSGI server. + +httpd can be installed using your system package manager, or a pre-built +executable for Windows. Installing and running httpd itself is outside +the scope of this doc. This page outlines the basics of configuring +httpd to proxy your application. Be sure to read its documentation to +understand what features are available. + +.. _Apache httpd: https://httpd.apache.org/ + + +Domain Name +----------- + +Acquiring and configuring a domain name is outside the scope of this +doc. In general, you will buy a domain name from a registrar, pay for +server space with a hosting provider, and then point your registrar +at the hosting provider's name servers. + +To simulate this, you can also edit your ``hosts`` file, located at +``/etc/hosts`` on Linux. Add a line that associates a name with the +local IP. + +Modern Linux systems may be configured to treat any domain name that +ends with ``.localhost`` like this without adding it to the ``hosts`` +file. + +.. code-block:: python + :caption: ``/etc/hosts`` + + 127.0.0.1 hello.localhost + + +Configuration +------------- + +The httpd configuration is located at ``/etc/httpd/conf/httpd.conf`` on +Linux. It may be different depending on your operating system. Check the +docs and look for ``httpd.conf``. + +Remove or comment out any existing ``DocumentRoot`` directive. Add the +config lines below. We'll assume the WSGI server is listening locally at +``http://127.0.0.1:8000``. + +.. code-block:: apache + :caption: ``/etc/httpd/conf/httpd.conf`` + + LoadModule proxy_module modules/mod_proxy.so + LoadModule proxy_http_module modules/mod_proxy_http.so + ProxyPass / http://127.0.0.1:8000/ + RequestHeader set X-Forwarded-Proto http + RequestHeader set X-Forwarded-Prefix / + +The ``LoadModule`` lines might already exist. If so, make sure they are +uncommented instead of adding them manually. + +Then :doc:`proxy_fix` so that your application uses the ``X-Forwarded`` +headers. ``X-Forwarded-For`` and ``X-Forwarded-Host`` are automatically +set by ``ProxyPass``. diff --git a/docs/deploying/asgi.rst b/docs/deploying/asgi.rst new file mode 100644 index 0000000000..1dc0aa2493 --- /dev/null +++ b/docs/deploying/asgi.rst @@ -0,0 +1,27 @@ +ASGI +==== + +If you'd like to use an ASGI server you will need to utilise WSGI to +ASGI middleware. The asgiref +`WsgiToAsgi `_ +adapter is recommended as it integrates with the event loop used for +Flask's :ref:`async_await` support. You can use the adapter by +wrapping the Flask app, + +.. code-block:: python + + from asgiref.wsgi import WsgiToAsgi + from flask import Flask + + app = Flask(__name__) + + ... + + asgi_app = WsgiToAsgi(app) + +and then serving the ``asgi_app`` with the ASGI server, e.g. using +`Hypercorn `_, + +.. sourcecode:: text + + $ hypercorn module:asgi_app diff --git a/docs/deploying/cgi.rst b/docs/deploying/cgi.rst deleted file mode 100644 index 503d942617..0000000000 --- a/docs/deploying/cgi.rst +++ /dev/null @@ -1,61 +0,0 @@ -CGI -=== - -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://developers.google.com/appengine/ diff --git a/docs/deploying/eventlet.rst b/docs/deploying/eventlet.rst new file mode 100644 index 0000000000..8a718b22f7 --- /dev/null +++ b/docs/deploying/eventlet.rst @@ -0,0 +1,80 @@ +eventlet +======== + +Prefer using :doc:`gunicorn` with eventlet workers rather than using +`eventlet`_ directly. Gunicorn provides a much more configurable and +production-tested server. + +`eventlet`_ allows writing asynchronous, coroutine-based code that looks +like standard synchronous Python. It uses `greenlet`_ to enable task +switching without writing ``async/await`` or using ``asyncio``. + +:doc:`gevent` is another library that does the same thing. Certain +dependencies you have, or other considerations, may affect which of the +two you choose to use. + +eventlet provides a WSGI server that can handle many connections at once +instead of one per worker process. You must actually use eventlet in +your own code to see any benefit to using the server. + +.. _eventlet: https://eventlet.net/ +.. _greenlet: https://greenlet.readthedocs.io/en/latest/ + + +Installing +---------- + +When using eventlet, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +Create a virtualenv, install your application, then install +``eventlet``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install eventlet + + +Running +------- + +To use eventlet to serve your application, write a script that imports +its ``wsgi.server``, as well as your app or app factory. + +.. code-block:: python + :caption: ``wsgi.py`` + + import eventlet + from eventlet import wsgi + from hello import create_app + + app = create_app() + wsgi.server(eventlet.listen(("127.0.0.1", 8000)), app) + +.. code-block:: text + + $ python wsgi.py + (x) wsgi starting up on http://127.0.0.1:8000 + + +Binding Externally +------------------ + +eventlet should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of eventlet. + +You can bind to all external IPs on a non-privileged port by using +``0.0.0.0`` in the server arguments shown in the previous section. +Don't do this when using a reverse proxy setup, otherwise it will be +possible to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/docs/deploying/fastcgi.rst b/docs/deploying/fastcgi.rst deleted file mode 100644 index c0beae0ced..0000000000 --- a/docs/deploying/fastcgi.rst +++ /dev/null @@ -1,240 +0,0 @@ -.. _deploying-fastcgi: - -FastCGI -======= - -FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and -`cherokee`_; see :ref:`deploying-uwsgi` and :ref:`deploying-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/python2.6/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: http://nginx.org/ -.. _lighttpd: http://www.lighttpd.net/ -.. _cherokee: http://cherokee-project.com/ -.. _flup: https://pypi.python.org/pypi/flup diff --git a/docs/deploying/gevent.rst b/docs/deploying/gevent.rst new file mode 100644 index 0000000000..448b93e78c --- /dev/null +++ b/docs/deploying/gevent.rst @@ -0,0 +1,80 @@ +gevent +====== + +Prefer using :doc:`gunicorn` or :doc:`uwsgi` with gevent workers rather +than using `gevent`_ directly. Gunicorn and uWSGI provide much more +configurable and production-tested servers. + +`gevent`_ allows writing asynchronous, coroutine-based code that looks +like standard synchronous Python. It uses `greenlet`_ to enable task +switching without writing ``async/await`` or using ``asyncio``. + +:doc:`eventlet` is another library that does the same thing. Certain +dependencies you have, or other considerations, may affect which of the +two you choose to use. + +gevent provides a WSGI server that can handle many connections at once +instead of one per worker process. You must actually use gevent in your +own code to see any benefit to using the server. + +.. _gevent: https://www.gevent.org/ +.. _greenlet: https://greenlet.readthedocs.io/en/latest/ + + +Installing +---------- + +When using gevent, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +Create a virtualenv, install your application, then install ``gevent``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install gevent + + +Running +------- + +To use gevent to serve your application, write a script that imports its +``WSGIServer``, as well as your app or app factory. + +.. code-block:: python + :caption: ``wsgi.py`` + + from gevent.pywsgi import WSGIServer + from hello import create_app + + app = create_app() + http_server = WSGIServer(("127.0.0.1", 8000), app) + http_server.serve_forever() + +.. code-block:: text + + $ python wsgi.py + +No output is shown when the server starts. + + +Binding Externally +------------------ + +gevent should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of gevent. + +You can bind to all external IPs on a non-privileged port by using +``0.0.0.0`` in the server arguments shown in the previous section. Don't +do this when using a reverse proxy setup, otherwise it will be possible +to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/docs/deploying/gunicorn.rst b/docs/deploying/gunicorn.rst new file mode 100644 index 0000000000..c50edc2326 --- /dev/null +++ b/docs/deploying/gunicorn.rst @@ -0,0 +1,130 @@ +Gunicorn +======== + +`Gunicorn`_ is a pure Python WSGI server with simple configuration and +multiple worker implementations for performance tuning. + +* It tends to integrate easily with hosting platforms. +* It does not support Windows (but does run on WSL). +* It is easy to install as it does not require additional dependencies + or compilation. +* It has built-in async worker support using gevent or eventlet. + +This page outlines the basics of running Gunicorn. Be sure to read its +`documentation`_ and use ``gunicorn --help`` to understand what features +are available. + +.. _Gunicorn: https://gunicorn.org/ +.. _documentation: https://docs.gunicorn.org/ + + +Installing +---------- + +Gunicorn is easy to install, as it does not require external +dependencies or compilation. It runs on Windows only under WSL. + +Create a virtualenv, install your application, then install +``gunicorn``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install gunicorn + + +Running +------- + +The only required argument to Gunicorn tells it how to load your Flask +application. The syntax is ``{module_import}:{app_variable}``. +``module_import`` is the dotted import name to the module with your +application. ``app_variable`` is the variable with the application. It +can also be a function call (with any arguments) if you're using the +app factory pattern. + +.. code-block:: text + + # equivalent to 'from hello import app' + $ gunicorn -w 4 'hello:app' + + # equivalent to 'from hello import create_app; create_app()' + $ gunicorn -w 4 'hello:create_app()' + + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: sync + Booting worker with pid: x + Booting worker with pid: x + Booting worker with pid: x + Booting worker with pid: x + +The ``-w`` option specifies the number of processes to run; a starting +value could be ``CPU * 2``. The default is only 1 worker, which is +probably not what you want for the default worker type. + +Logs for each request aren't shown by default, only worker info and +errors are shown. To show access logs on stdout, use the +``--access-logfile=-`` option. + + +Binding Externally +------------------ + +Gunicorn should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of Gunicorn. + +You can bind to all external IPs on a non-privileged port using the +``-b 0.0.0.0`` option. Don't do this when using a reverse proxy setup, +otherwise it will be possible to bypass the proxy. + +.. code-block:: text + + $ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()' + Listening at: http://0.0.0.0:8000 (x) + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. + + +Async with gevent or eventlet +----------------------------- + +The default sync worker is appropriate for many use cases. If you need +asynchronous support, Gunicorn provides workers using either `gevent`_ +or `eventlet`_. This is not the same as Python's ``async/await``, or the +ASGI server spec. You must actually use gevent/eventlet in your own code +to see any benefit to using the workers. + +When using either gevent or eventlet, greenlet>=1.0 is required, +otherwise context locals such as ``request`` will not work as expected. +When using PyPy, PyPy>=7.3.7 is required. + +To use gevent: + +.. code-block:: text + + $ gunicorn -k gevent 'hello:create_app()' + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: gevent + Booting worker with pid: x + +To use eventlet: + +.. code-block:: text + + $ gunicorn -k eventlet 'hello:create_app()' + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: eventlet + Booting worker with pid: x + +.. _gevent: https://www.gevent.org/ +.. _eventlet: https://eventlet.net/ diff --git a/docs/deploying/index.rst b/docs/deploying/index.rst index 5d88cf72e0..4135596a4f 100644 --- a/docs/deploying/index.rst +++ b/docs/deploying/index.rst @@ -1,37 +1,79 @@ -.. _deployment: +Deploying to Production +======================= -Deployment Options -================== +After developing your application, you'll want to make it available +publicly to other users. When you're developing locally, you're probably +using the built-in development server, debugger, and reloader. These +should not be used in production. Instead, you should use a dedicated +WSGI server or hosting platform, some of which will be described here. -While lightweight and easy to use, **Flask's built-in server is not suitable -for production** as it doesn't scale well and by default serves only one -request at a time. Some of the options available for properly running Flask in -production are documented here. +"Production" means "not development", which applies whether you're +serving your application publicly to millions of users or privately / +locally to a single user. **Do not use the development server when +deploying to production. It is intended for use only during local +development. It is not designed to be particularly secure, stable, or +efficient.** -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. +Self-Hosted Options +------------------- +Flask is a WSGI *application*. A WSGI *server* is used to run the +application, converting incoming HTTP requests to the standard WSGI +environ, and converting outgoing WSGI responses to HTTP responses. -Hosted options --------------- +The primary goal of these docs is to familiarize you with the concepts +involved in running a WSGI application using a production WSGI server +and HTTP server. There are many WSGI servers and HTTP servers, with many +configuration possibilities. The pages below discuss the most common +servers, and show the basics of running each one. The next section +discusses platforms that can manage this for you. -- `Deploying Flask on Heroku `_ -- `Deploying Flask on OpenShift `_ -- `Deploying Flask on Webfaction `_ -- `Deploying Flask on Google App Engine `_ -- `Sharing your Localhost Server with Localtunnel `_ -- `Deploying on Azure (IIS) `_ +.. toctree:: + :maxdepth: 1 -Self-hosted options -------------------- + gunicorn + waitress + mod_wsgi + uwsgi + gevent + eventlet + asgi + +WSGI servers have HTTP servers built-in. However, a dedicated HTTP +server may be safer, more efficient, or more capable. Putting an HTTP +server in front of the WSGI server is called a "reverse proxy." .. toctree:: - :maxdepth: 2 + :maxdepth: 1 + + proxy_fix + nginx + apache-httpd + +This list is not exhaustive, and you should evaluate these and other +servers based on your application's needs. Different servers will have +different capabilities, configuration, and support. + + +Hosting Platforms +----------------- + +There are many services available for hosting web applications without +needing to maintain your own server, networking, domain, etc. Some +services may have a free tier up to a certain time or bandwidth. Many of +these services use one of the WSGI servers described above, or a similar +interface. The links below are for some of the most common platforms, +which have instructions for Flask, WSGI, or Python. + +- `PythonAnywhere `_ +- `Google App Engine `_ +- `Google Cloud Run `_ +- `AWS Elastic Beanstalk `_ +- `Microsoft Azure `_ + +This list is not exhaustive, and you should evaluate these and other +services based on your application's needs. Different services will have +different capabilities, configuration, pricing, and support. - mod_wsgi - wsgi-standalone - uwsgi - fastcgi - cgi +You'll probably need to :doc:`proxy_fix` when using most hosting +platforms. diff --git a/docs/deploying/mod_wsgi.rst b/docs/deploying/mod_wsgi.rst index 0f4af6c34e..23e8227989 100644 --- a/docs/deploying/mod_wsgi.rst +++ b/docs/deploying/mod_wsgi.rst @@ -1,217 +1,94 @@ -.. _mod_wsgi-deployment: +mod_wsgi +======== -mod_wsgi (Apache) -================= +`mod_wsgi`_ is a WSGI server integrated with the `Apache httpd`_ server. +The modern `mod_wsgi-express`_ command makes it easy to configure and +start the server without needing to write Apache httpd configuration. -If you are using the `Apache`_ webserver, consider using `mod_wsgi`_. +* Tightly integrated with Apache httpd. +* Supports Windows directly. +* Requires a compiler and the Apache development headers to install. +* Does not require a reverse proxy setup. -.. admonition:: Watch Out +This page outlines the basics of running mod_wsgi-express, not the more +complex installation and configuration with httpd. Be sure to read the +`mod_wsgi-express`_, `mod_wsgi`_, and `Apache httpd`_ documentation to +understand what features are available. - 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. +.. _mod_wsgi-express: https://pypi.org/project/mod-wsgi/ +.. _mod_wsgi: https://modwsgi.readthedocs.io/ +.. _Apache httpd: https://httpd.apache.org/ -.. _Apache: http://httpd.apache.org/ -Installing `mod_wsgi` ---------------------- +Installing +---------- -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. +Installing mod_wsgi requires a compiler and the Apache server and +development headers installed. You will get an error if they are not. +How to install them depends on the OS and package manager that you use. -If you are using Ubuntu/Debian you can apt-get it and activate it as -follows: +Create a virtualenv, install your application, then install +``mod_wsgi``. -.. sourcecode:: text +.. code-block:: text - # apt-get install libapache2-mod-wsgi + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install mod_wsgi -If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you -can install it as follows: -.. sourcecode:: text +Running +------- - # yum install mod_wsgi +The only argument to ``mod_wsgi-express`` specifies a script containing +your Flask application, which must be called ``application``. You can +write a small script to import your app with this name, or to create it +if using the app factory pattern. -On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by -using pkg_add: +.. code-block:: python + :caption: ``wsgi.py`` -.. sourcecode:: text + from hello import app - # pkg install ap22-mod_wsgi2 + application = app -If you are using pkgsrc you can install `mod_wsgi` by compiling the -`www/ap2-wsgi` package. +.. code-block:: python + :caption: ``wsgi.py`` -If you encounter segfaulting child processes after the first apache -reload you can safely ignore them. Just restart the server. + from hello import create_app -Creating a `.wsgi` file ------------------------ + application = create_app() -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. +Now run the ``mod_wsgi-express start-server`` command. -For most applications the following file should be sufficient:: +.. code-block:: text - from yourapplication import app as application + $ mod_wsgi-express start-server wsgi.py --processes 4 -If you don't have a factory function for application creation but a singleton -instance you can directly import that one as `application`. +The ``--processes`` option specifies the number of worker processes to +run; a starting value could be ``CPU * 2``. -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:: +Logs for each request aren't show in the terminal. If an error occurs, +its information is written to the error log file shown when starting the +server. - import sys - sys.path.insert(0, '/path/to/the/application') -Configuring Apache +Binding Externally ------------------ -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: +Unlike the other WSGI servers in these docs, mod_wsgi can be run as +root to bind to privileged ports like 80 and 443. However, it must be +configured to drop permissions to a different user and group for the +worker processes. -.. sourcecode:: apache +For example, if you created a ``hello`` user and group, you should +install your virtualenv and application as that user, then tell +mod_wsgi to drop to that user after starting. - - ServerName example.com +.. code-block:: text - 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: http://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: http://modwsgi.readthedocs.io/en/develop/installation.html -.. _virtual python: https://pypi.python.org/pypi/virtualenv -.. _mod_wsgi documentation: http://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. + $ sudo /home/hello/.venv/bin/mod_wsgi-express start-server \ + /home/hello/wsgi.py \ + --user hello --group hello --port 80 --processes 4 diff --git a/docs/deploying/nginx.rst b/docs/deploying/nginx.rst new file mode 100644 index 0000000000..6b25c073e8 --- /dev/null +++ b/docs/deploying/nginx.rst @@ -0,0 +1,69 @@ +nginx +===== + +`nginx`_ is a fast, production level HTTP server. When serving your +application with one of the WSGI servers listed in :doc:`index`, it is +often good or necessary to put a dedicated HTTP server in front of it. +This "reverse proxy" can handle incoming requests, TLS, and other +security and performance concerns better than the WSGI server. + +Nginx can be installed using your system package manager, or a pre-built +executable for Windows. Installing and running Nginx itself is outside +the scope of this doc. This page outlines the basics of configuring +Nginx to proxy your application. Be sure to read its documentation to +understand what features are available. + +.. _nginx: https://nginx.org/ + + +Domain Name +----------- + +Acquiring and configuring a domain name is outside the scope of this +doc. In general, you will buy a domain name from a registrar, pay for +server space with a hosting provider, and then point your registrar +at the hosting provider's name servers. + +To simulate this, you can also edit your ``hosts`` file, located at +``/etc/hosts`` on Linux. Add a line that associates a name with the +local IP. + +Modern Linux systems may be configured to treat any domain name that +ends with ``.localhost`` like this without adding it to the ``hosts`` +file. + +.. code-block:: python + :caption: ``/etc/hosts`` + + 127.0.0.1 hello.localhost + + +Configuration +------------- + +The nginx configuration is located at ``/etc/nginx/nginx.conf`` on +Linux. It may be different depending on your operating system. Check the +docs and look for ``nginx.conf``. + +Remove or comment out any existing ``server`` section. Add a ``server`` +section and use the ``proxy_pass`` directive to point to the address the +WSGI server is listening on. We'll assume the WSGI server is listening +locally at ``http://127.0.0.1:8000``. + +.. code-block:: nginx + :caption: ``/etc/nginx.conf`` + + server { + listen 80; + server_name _; + + location / { + proxy_pass http://127.0.0.1:8000/; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_set_header X-Forwarded-Prefix /; + } + } + +Then :doc:`proxy_fix` so that your application uses these headers. diff --git a/docs/deploying/proxy_fix.rst b/docs/deploying/proxy_fix.rst new file mode 100644 index 0000000000..e2c42e8257 --- /dev/null +++ b/docs/deploying/proxy_fix.rst @@ -0,0 +1,33 @@ +Tell Flask it is Behind a Proxy +=============================== + +When using a reverse proxy, or many Python hosting platforms, the proxy +will intercept and forward all external requests to the local WSGI +server. + +From the WSGI server and Flask application's perspectives, requests are +now coming from the HTTP server to the local address, rather than from +the remote address to the external server address. + +HTTP servers should set ``X-Forwarded-`` headers to pass on the real +values to the application. The application can then be told to trust and +use those values by wrapping it with the +:doc:`werkzeug:middleware/proxy_fix` middleware provided by Werkzeug. + +This middleware should only be used if the application is actually +behind a proxy, and should be configured with the number of proxies that +are chained in front of it. Not all proxies set all the headers. Since +incoming headers can be faked, you must set how many proxies are setting +each header so the middleware knows what to trust. + +.. code-block:: python + + from werkzeug.middleware.proxy_fix import ProxyFix + + app.wsgi_app = ProxyFix( + app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 + ) + +Remember, only apply this middleware if you are behind a proxy, and set +the correct number of proxies that set each header. It can be a security +issue if you get this configuration wrong. diff --git a/docs/deploying/uwsgi.rst b/docs/deploying/uwsgi.rst index fc991e72be..1f9d5eca00 100644 --- a/docs/deploying/uwsgi.rst +++ b/docs/deploying/uwsgi.rst @@ -1,72 +1,145 @@ -.. _deploying-uwsgi: - uWSGI ===== -uWSGI is a deployment option on servers like `nginx`_, `lighttpd`_, and -`cherokee`_; see :ref:`deploying-fastcgi` and :ref:`deploying-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. +`uWSGI`_ is a fast, compiled server suite with extensive configuration +and capabilities beyond a basic server. + +* It can be very performant due to being a compiled program. +* It is complex to configure beyond the basic application, and has so + many options that it can be difficult for beginners to understand. +* It does not support Windows (but does run on WSL). +* It requires a compiler to install in some cases. + +This page outlines the basics of running uWSGI. Be sure to read its +documentation to understand what features are available. + +.. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/ + + +Installing +---------- + +uWSGI has multiple ways to install it. The most straightforward is to +install the ``pyuwsgi`` package, which provides precompiled wheels for +common platforms. However, it does not provide SSL support, which can be +provided with a reverse proxy instead. + +Create a virtualenv, install your application, then install ``pyuwsgi``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install pyuwsgi + +If you have a compiler available, you can install the ``uwsgi`` package +instead. Or install the ``pyuwsgi`` package from sdist instead of wheel. +Either method will include SSL support. + +.. code-block:: text + + $ pip install uwsgi + + # or + $ pip install --no-binary pyuwsgi pyuwsgi + -The most popular uWSGI server is `uwsgi`_, which we will use for this -guide. Make sure to have it installed to follow along. +Running +------- -.. admonition:: Watch Out +The most basic way to run uWSGI is to tell it to start an HTTP server +and import your application. - 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. +.. code-block:: text -Starting your app with uwsgi ----------------------------- + $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app -`uwsgi` is designed to operate on WSGI callables found in python modules. + *** Starting uWSGI 2.0.20 (64bit) on [x] *** + *** Operational MODE: preforking *** + mounting hello:app on / + spawned uWSGI master process (pid: x) + spawned uWSGI worker 1 (pid: x, cores: 1) + spawned uWSGI worker 2 (pid: x, cores: 1) + spawned uWSGI worker 3 (pid: x, cores: 1) + spawned uWSGI worker 4 (pid: x, cores: 1) + spawned uWSGI http 1 (pid: x) -Given a flask application in myapp.py, use the following command: +If you're using the app factory pattern, you'll need to create a small +Python file to create the app, then point uWSGI at that. -.. sourcecode:: text +.. code-block:: python + :caption: ``wsgi.py`` - $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app + from hello import create_app -The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` to uwsgi, -since its 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__)``. + app = create_app() -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. +.. code-block:: text -Configuring nginx + $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app + +The ``--http`` option starts an HTTP server at 127.0.0.1 port 8000. The +``--master`` option specifies the standard worker manager. The ``-p`` +option starts 4 worker processes; a starting value could be ``CPU * 2``. +The ``-w`` option tells uWSGI how to import your application + + +Binding Externally +------------------ + +uWSGI should not be run as root with the configuration shown in this doc +because it would cause your application code to run as root, which is +not secure. However, this means it will not be possible to bind to port +80 or 443. Instead, a reverse proxy such as :doc:`nginx` or +:doc:`apache-httpd` should be used in front of uWSGI. It is possible to +run uWSGI as root securely, but that is beyond the scope of this doc. + +uWSGI has optimized integration with `Nginx uWSGI`_ and +`Apache mod_proxy_uwsgi`_, and possibly other servers, instead of using +a standard HTTP proxy. That configuration is beyond the scope of this +doc, see the links for more information. + +.. _Nginx uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/Nginx.html +.. _Apache mod_proxy_uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/Apache.html#mod-proxy-uwsgi + +You can bind to all external IPs on a non-privileged port using the +``--http 0.0.0.0:8000`` option. Don't do this when using a reverse proxy +setup, otherwise it will be possible to bypass the proxy. + +.. code-block:: text + + $ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. + + +Async with gevent ----------------- -A basic flask nginx configuration looks like this:: +The default sync worker is appropriate for many use cases. If you need +asynchronous support, uWSGI provides a `gevent`_ worker. This is not the +same as Python's ``async/await``, or the ASGI server spec. You must +actually use gevent in your own code to see any benefit to using the +worker. + +When using gevent, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +.. code-block:: text - location = /yourapplication { rewrite ^ /yourapplication/; } - location /yourapplication { try_files $uri @yourapplication; } - location @yourapplication { - include uwsgi_params; - uwsgi_pass unix:/tmp/yourapplication.sock; - } + $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app -This configuration binds the application to ``/yourapplication``. If you want -to have it in the URL root its a bit simpler:: + *** Starting uWSGI 2.0.20 (64bit) on [x] *** + *** Operational MODE: async *** + mounting hello:app on / + spawned uWSGI master process (pid: x) + spawned uWSGI worker 1 (pid: x, cores: 100) + spawned uWSGI http 1 (pid: x) + *** running gevent loop engine [addr:x] *** - location / { try_files $uri @yourapplication; } - location @yourapplication { - include uwsgi_params; - uwsgi_pass unix:/tmp/yourapplication.sock; - } -.. _nginx: http://nginx.org/ -.. _lighttpd: http://www.lighttpd.net/ -.. _cherokee: http://cherokee-project.com/ -.. _uwsgi: http://projects.unbit.it/uwsgi/ +.. _gevent: https://www.gevent.org/ diff --git a/docs/deploying/waitress.rst b/docs/deploying/waitress.rst new file mode 100644 index 0000000000..7bdd695b1b --- /dev/null +++ b/docs/deploying/waitress.rst @@ -0,0 +1,75 @@ +Waitress +======== + +`Waitress`_ is a pure Python WSGI server. + +* It is easy to configure. +* It supports Windows directly. +* It is easy to install as it does not require additional dependencies + or compilation. +* It does not support streaming requests, full request data is always + buffered. +* It uses a single process with multiple thread workers. + +This page outlines the basics of running Waitress. Be sure to read its +documentation and ``waitress-serve --help`` to understand what features +are available. + +.. _Waitress: https://docs.pylonsproject.org/projects/waitress/ + + +Installing +---------- + +Create a virtualenv, install your application, then install +``waitress``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install waitress + + +Running +------- + +The only required argument to ``waitress-serve`` tells it how to load +your Flask application. The syntax is ``{module}:{app}``. ``module`` is +the dotted import name to the module with your application. ``app`` is +the variable with the application. If you're using the app factory +pattern, use ``--call {module}:{factory}`` instead. + +.. code-block:: text + + # equivalent to 'from hello import app' + $ waitress-serve --host 127.0.0.1 hello:app + + # equivalent to 'from hello import create_app; create_app()' + $ waitress-serve --host 127.0.0.1 --call hello:create_app + + Serving on http://127.0.0.1:8080 + +The ``--host`` option binds the server to local ``127.0.0.1`` only. + +Logs for each request aren't shown, only errors are shown. Logging can +be configured through the Python interface instead of the command line. + + +Binding Externally +------------------ + +Waitress should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of Waitress. + +You can bind to all external IPs on a non-privileged port by not +specifying the ``--host`` option. Don't do this when using a reverse +proxy setup, otherwise it will be possible to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/docs/deploying/wsgi-standalone.rst b/docs/deploying/wsgi-standalone.rst deleted file mode 100644 index ad43c1441f..0000000000 --- a/docs/deploying/wsgi-standalone.rst +++ /dev/null @@ -1,134 +0,0 @@ -.. _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 - -.. _Gunicorn: http://gunicorn.org/ -.. _eventlet: http://eventlet.net/ -.. _greenlet: https://greenlet.readthedocs.io/en/latest/ - -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.wsgi 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 8080 --wsgi myproject.app - -.. _Twisted: https://twistedmatrix.com/ -.. _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.contrib.fixers import ProxyFix - app.wsgi_app = ProxyFix(app.wsgi_app) - -.. 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) diff --git a/docs/design.rst b/docs/design.rst index f0f7126d09..066cf107c1 100644 --- a/docs/design.rst +++ b/docs/design.rst @@ -1,5 +1,3 @@ -.. _design: - Design Decisions in Flask ========================= @@ -41,7 +39,7 @@ 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 unittesting. When you want to test +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. @@ -76,8 +74,8 @@ 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 unittesting and similar -things (:ref:`app-factories`). +create the application which is very helpful for unit testing and similar +things (:doc:`/patterns/appfactories`). The Routing System ------------------ @@ -109,14 +107,14 @@ 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. +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, 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, @@ -132,9 +130,25 @@ being present. You can easily use your own templating language, but an extension could still depend on Jinja itself. -Micro with Dependencies +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. + 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 @@ -169,8 +183,24 @@ 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. + +Async/await and ASGI support +---------------------------- + +Flask supports ``async`` coroutines for view functions by executing the +coroutine on a separate thread instead of using an event loop on the +main thread as an async-first (ASGI) framework would. This is necessary +for Flask to remain backwards compatible with extensions and code built +before ``async`` was introduced into Python. This compromise introduces +a performance cost compared with the ASGI frameworks, due to the +overhead of the threads. + +Due to how tied to WSGI Flask's code is, it's not clear if it's possible +to make the ``Flask`` class support ASGI and WSGI at the same time. Work +is currently being done in Werkzeug to work with ASGI, which may +eventually enable support in Flask as well. + +See :doc:`/async-await` for more discussion. What Flask is, What Flask is Not @@ -187,5 +217,12 @@ 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. +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. + The idea of Flask is to build a good foundation for all applications. Everything else is up to you or extensions. diff --git a/docs/errorhandling.rst b/docs/errorhandling.rst index 3bda5f1522..faca58c240 100644 --- a/docs/errorhandling.rst +++ b/docs/errorhandling.rst @@ -1,14 +1,10 @@ -.. _application-errors: +Handling 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 +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 @@ -20,13 +16,16 @@ errors: - 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`. +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, and an exception is raised 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. +with errors including custom exceptions and 3rd party tools. + + +.. _error-logging-tools: Error Logging Tools ------------------- @@ -34,360 +33,491 @@ 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 +`_ for dealing with application errors. It's +available as a source-available project `on GitHub +`_ and is also available as a `hosted version +`_ which you can try for free. Sentry aggregates duplicate errors, captures the full stack trace and local variables for debugging, and sends you mails based on new errors or frequency thresholds. -To use Sentry you need to install the `raven` client:: +To use Sentry you need to install the ``sentry-sdk`` client with extra +``flask`` dependencies. - $ pip install raven +.. code-block:: text -And then add this to your Flask app:: + $ pip install sentry-sdk[flask] - from raven.contrib.flask import Sentry - sentry = Sentry(app, dsn='YOUR_DSN_HERE') +And then add this to your Flask app: -Or if you are using factories you can also init it later:: +.. code-block:: python - from raven.contrib.flask import Sentry - sentry = Sentry(dsn='YOUR_DSN_HERE') + import sentry_sdk + from sentry_sdk.integrations.flask import FlaskIntegration - def create_app(): - app = Flask(__name__) - sentry.init_app(app) - ... - return app + 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. -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. -Afterwards failures are automatically reported to Sentry and from there -you can receive error notifications. +See also: -.. _error-handlers: +- Sentry also supports catching errors from a worker queue + (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs + `__ for more information. +- `Flask-specific documentation `__ -Error handlers + +Error Handlers -------------- +When an error occurs in Flask, an appropriate `HTTP status code +`__ will be +returned. 400-499 indicate errors with the client's request data, or +about the data requested. 500-599 indicate errors with the server or +application itself. + You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers. -Error handlers are normal :ref:`views` but instead of being registered for -routes, they are registered for exceptions that are raised while trying to -do something else. +An error handler is a function that returns a response when a type of error is +raised, similar to how a view is a function that returns a response when a +request URL is matched. It is passed the instance of the error being handled, +which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. + +The status code of the response will not be set to the handler's code. Make +sure to provide the appropriate HTTP status code when returning a response from +a handler. + Registering ``````````` -Register error handlers using :meth:`~flask.Flask.errorhandler` or -:meth:`~flask.Flask.register_error_handler`:: +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. + +.. code-block:: python @app.errorhandler(werkzeug.exceptions.BadRequest) def handle_bad_request(e): - return 'bad request!' - - app.register_error_handler(400, lambda e: 'bad request!') + return 'bad request!', 400 + + # or, without the decorator + app.register_error_handler(400, handle_bad_request) -Those two ways are equivalent, but the first one is more clear and leaves -you with a function to call on your whim (and in tests). Note that :exc:`werkzeug.exceptions.HTTPException` subclasses like -:exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes -are interchangeable when handed to the registration methods or decorator -(``BadRequest.code == 400``). +: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. + +.. code-block:: python -You are however not limited to :exc:`~werkzeug.exceptions.HTTPException` -or HTTP status codes but can register a handler for every exception class you -like. + class InsufficientStorage(werkzeug.exceptions.HTTPException): + code = 507 + description = 'Not enough storage space.' -.. versionchanged:: 0.11 + 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. - Errorhandlers are now prioritized by specificity of the exception classes - they are registered for instead of the order they are registered in. Handling ```````` -Once an exception instance is raised, its class hierarchy is traversed, -and searched for in the exception classes for which handlers are registered. -The most specific handler is selected. - -E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler -is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`, -the more specific :exc:`ConnectionRefusedError` handler is called on the -exception instance, and its response is shown to the user. - -Error Mails ------------ - -If the application runs in production mode (which it will do on your -server) you might not see any log messages. The reason for that is that -Flask by default will just report to the WSGI error stream or stderr -(depending on what's available). Where this ends up is sometimes hard to -find. Often it's in your webserver's log files. - -I can pretty much promise you however that if you only use a logfile for -the application errors you will never look at it except for debugging an -issue when a user reported it for you. What you probably want instead is -a mail the second the exception happened. Then you get an alert and you -can do something about it. - -Flask uses the Python builtin logging system, and it can actually send -you mails for errors which is probably what you want. Here is how you can -configure the Flask logger to send you mails for exceptions:: - - ADMINS = ['yourname@example.com'] - if not app.debug: - import logging - from logging.handlers import SMTPHandler - mail_handler = SMTPHandler('127.0.0.1', - 'server-error@example.com', - ADMINS, 'YourApplication Failed') - mail_handler.setLevel(logging.ERROR) - app.logger.addHandler(mail_handler) - -So what just happened? We created a new -:class:`~logging.handlers.SMTPHandler` that will send mails with the mail -server listening on ``127.0.0.1`` to all the `ADMINS` from the address -*server-error@example.com* with the subject "YourApplication Failed". If -your mail server requires credentials, these can also be provided. For -that check out the documentation for the -:class:`~logging.handlers.SMTPHandler`. - -We also tell the handler to only send errors and more critical messages. -Because we certainly don't want to get a mail for warnings or other -useless logs that might happen during request handling. - -Before you run that in production, please also look at :ref:`logformat` to -put more information into that error mail. That will save you from a lot -of frustration. - - -Logging to a File ------------------ - -Even if you get mails, you probably also want to log warnings. It's a -good idea to keep as much information around that might be required to -debug a problem. By default as of Flask 0.11, errors are logged to your -webserver's log automatically. Warnings however are not. Please note -that Flask itself will not issue any warnings in the core system, so it's -your responsibility to warn in the code if something seems odd. - -There are a couple of handlers provided by the logging system out of the -box but not all of them are useful for basic error logging. The most -interesting are probably the following: - -- :class:`~logging.FileHandler` - logs messages to a file on the - filesystem. -- :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file - on the filesystem and will rotate after a certain number of messages. -- :class:`~logging.handlers.NTEventLogHandler` - will log to the system - event log of a Windows system. If you are deploying on a Windows box, - this is what you want to use. -- :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX - syslog. - -Once you picked your log handler, do like you did with the SMTP handler -above, just make sure to use a lower setting (I would recommend -`WARNING`):: - - if not app.debug: - import logging - from themodule import TheHandlerYouWant - file_handler = TheHandlerYouWant(...) - file_handler.setLevel(logging.WARNING) - app.logger.addHandler(file_handler) - -.. _logformat: - -Controlling the Log Format --------------------------- - -By default a handler will only write the message string into a file or -send you that message as mail. A log record stores more information, -and it makes a lot of sense to configure your logger to also contain that -information so that you have a better idea of why that error happened, and -more importantly, where it did. - -A formatter can be instantiated with a format string. Note that -tracebacks are appended to the log entry automatically. You don't have to -do that in the log formatter format string. - -Here some example setups: - -Email -````` - -:: - - from logging import Formatter - mail_handler.setFormatter(Formatter(''' - Message type: %(levelname)s - Location: %(pathname)s:%(lineno)d - Module: %(module)s - Function: %(funcName)s - Time: %(asctime)s - - Message: - - %(message)s - ''')) - -File logging -```````````` - -:: - - from logging import Formatter - file_handler.setFormatter(Formatter( - '%(asctime)s %(levelname)s: %(message)s ' - '[in %(pathname)s:%(lineno)d]' - )) - - -Complex Log Formatting -`````````````````````` - -Here is a list of useful formatting variables for the format string. Note -that this list is not complete, consult the official documentation of the -:mod:`logging` package for a full list. - -.. tabularcolumns:: |p{3cm}|p{12cm}| - -+------------------+----------------------------------------------------+ -| Format | Description | -+==================+====================================================+ -| ``%(levelname)s``| Text logging level for the message | -| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, | -| | ``'ERROR'``, ``'CRITICAL'``). | -+------------------+----------------------------------------------------+ -| ``%(pathname)s`` | Full pathname of the source file where the | -| | logging call was issued (if available). | -+------------------+----------------------------------------------------+ -| ``%(filename)s`` | Filename portion of pathname. | -+------------------+----------------------------------------------------+ -| ``%(module)s`` | Module (name portion of filename). | -+------------------+----------------------------------------------------+ -| ``%(funcName)s`` | Name of function containing the logging call. | -+------------------+----------------------------------------------------+ -| ``%(lineno)d`` | Source line number where the logging call was | -| | issued (if available). | -+------------------+----------------------------------------------------+ -| ``%(asctime)s`` | Human-readable time when the LogRecord` was | -| | created. By default this is of the form | -| | ``"2003-07-08 16:49:45,896"`` (the numbers after | -| | the comma are millisecond portion of the time). | -| | This can be changed by subclassing the formatter | -| | and overriding the | -| | :meth:`~logging.Formatter.formatTime` method. | -+------------------+----------------------------------------------------+ -| ``%(message)s`` | The logged message, computed as ``msg % args`` | -+------------------+----------------------------------------------------+ - -If you want to further customize the formatting, you can subclass the -formatter. The formatter has three interesting methods: - -:meth:`~logging.Formatter.format`: - handles the actual formatting. It is passed a - :class:`~logging.LogRecord` object and has to return the formatted - string. -:meth:`~logging.Formatter.formatTime`: - called for `asctime` formatting. If you want a different time format - you can override this method. -:meth:`~logging.Formatter.formatException` - called for exception formatting. It is passed an :attr:`~sys.exc_info` - tuple and has to return a string. The default is usually fine, you - don't have to override it. - -For more information, head over to the official documentation. - - -Other Libraries ---------------- - -So far we only configured the logger your application created itself. -Other libraries might log themselves as well. For example, SQLAlchemy uses -logging heavily in its core. While there is a method to configure all -loggers at once in the :mod:`logging` package, I would not recommend using -it. There might be a situation in which you want to have multiple -separate applications running side by side in the same Python interpreter -and then it becomes impossible to have different logging setups for those. - -Instead, I would recommend figuring out which loggers you are interested -in, getting the loggers with the :func:`~logging.getLogger` function and -iterating over them to attach handlers:: - - from logging import getLogger - loggers = [app.logger, getLogger('sqlalchemy'), - getLogger('otherlibrary')] - for logger in loggers: - logger.addHandler(mail_handler) - logger.addHandler(file_handler) - - -Debugging Application Errors -============================ - -For production applications, configure your application with logging and -notifications as described in :ref:`application-errors`. This section provides -pointers when debugging deployment configuration and digging deeper with a -full-featured Python debugger. - - -When in Doubt, Run Manually ---------------------------- - -Having problems getting your application configured for production? If you -have shell access to your host, verify that you can run your application -manually from the shell in the deployment environment. Be sure to run under -the same user account as the configured deployment to troubleshoot permission -issues. You can use Flask's builtin development server with `debug=True` on -your production host, which is helpful in catching configuration issues, but -**be sure to do this temporarily in a controlled environment.** Do not run in -production with `debug=True`. - - -.. _working-with-debuggers: - -Working with Debuggers ----------------------- - -To dig deeper, possibly to trace code execution, Flask provides a debugger out -of the box (see :ref:`debug-mode`). If you would like to use another Python -debugger, note that debuggers interfere with each other. You have to set some -options in order to use your favorite debugger: - -* ``debug`` - whether to enable debug mode and catch exceptions -* ``use_debugger`` - whether to use the internal Flask debugger -* ``use_reloader`` - whether to reload and fork the process on exception - -``debug`` must be True (i.e., exceptions must be caught) in order for the other -two options to have any value. - -If you're using Aptana/Eclipse for debugging you'll need to set both -``use_debugger`` and ``use_reloader`` to False. - -A possible useful pattern for configuration is to set the following in your -config.yaml (change the block as appropriate for your application, of course):: - - FLASK: - DEBUG: True - DEBUG_WITH_APTANA: True - -Then in your application's entry-point (main.py), you could have something like:: - - if __name__ == "__main__": - # To allow aptana to receive errors, set use_debugger=False - app = create_app(config="config.yaml") - - if app.debug: use_debugger = True - try: - # Disable Flask's debugger if external debugger is requested - use_debugger = not(app.config.get('DEBUG_WITH_APTANA')) - except: - pass - app.run(use_debugger=use_debugger, debug=app.debug, - use_reloader=use_debugger, host='0.0.0.0') +When building a Flask application you *will* run into exceptions. If some part +of your code breaks while handling a request (and you have no error handlers +registered), a "500 Internal Server Error" +(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default. +Similarly, "404 Not Found" +(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route. +If a route receives an unallowed request method, a "405 Method Not Allowed" +(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all +subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by +default in Flask. + +Flask gives you the ability to raise any HTTP exception registered by +Werkzeug. However, the default HTTP exceptions return simple exception +pages. You might want to show custom error pages to the user when an error occurs. +This can be done by registering error handlers. + +When Flask catches an exception while handling a request, it is first looked up by code. +If no handler is registered for the code, Flask looks up the error 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. + +For example, an error handler for ``HTTPException`` might be useful for turning +the default HTML errors pages into JSON. 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 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_exception``. + +An error handler for "500 Internal Server Error" will be passed uncaught +exceptions in addition to explicit 500 errors. In debug mode, a handler +for "500 Internal Server Error" will not be used. Instead, the +interactive debugger will be shown. + + +Custom Error Pages +------------------ + +Sometimes when building a Flask application, you might want to raise a +:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that +something is wrong with the request. Fortunately, Flask comes with a handy +:func:`~flask.abort` function that aborts a request with a HTTP error from +werkzeug as desired. It will also provide a plain black and white error page +for you with a basic description, but nothing fancy. + +Depending on the error code it is less or more likely for the user to +actually see such an error. + +Consider the code below, we might have a user profile route, and if the user +fails to pass a username we can raise a "400 Bad Request". If the user passes a +username and we can't find it, we raise a "404 Not Found". + +.. code-block:: python + + from flask import abort, render_template, request + + # a username needs to be supplied in the query args + # a successful request would be like /profile?username=jack + @app.route("/profile") + def user_profile(): + username = request.arg.get("username") + # if a username isn't supplied in the request, return a 400 bad request + if username is None: + abort(400) + + user = get_user(username=username) + # if a user can't be found by their username, return 404 not found + if user is None: + abort(404) + + return render_template("profile.html", user=user) + +Here is another example implementation for a "404 Page Not Found" exception: + +.. code-block:: python + + from flask import render_template + + @app.errorhandler(404) + def page_not_found(e): + # note that we set the 404 status explicitly + return render_template('404.html'), 404 + +When using :doc:`/patterns/appfactories`: + +.. code-block:: python + + from flask import Flask, render_template + + def page_not_found(e): + return render_template('404.html'), 404 + + def create_app(config_filename): + app = Flask(__name__) + app.register_error_handler(404, page_not_found) + return app + +An example template might be this: + +.. code-block:: html+jinja + + {% extends "layout.html" %} + {% block title %}Page Not Found{% endblock %} + {% block body %} +

Page Not Found

+

What you were looking for is just not there. +

go somewhere nice + {% endblock %} + + +Further Examples +```````````````` + +The above examples wouldn't actually be an improvement on the default +exception pages. We can create a custom 500.html template like this: + +.. code-block:: html+jinja + + {% extends "layout.html" %} + {% block title %}Internal Server Error{% endblock %} + {% block body %} +

Internal Server Error

+

Oops... we seem to have made a mistake, sorry!

+

Go somewhere nice instead + {% endblock %} + +It can be implemented by rendering the template on "500 Internal Server Error": + +.. code-block:: python + + from flask import render_template + + @app.errorhandler(500) + def internal_server_error(e): + # note that we set the 500 status explicitly + return render_template('500.html'), 500 + +When using :doc:`/patterns/appfactories`: + +.. code-block:: python + + from flask import Flask, render_template + + def internal_server_error(e): + return render_template('500.html'), 500 + + def create_app(): + app = Flask(__name__) + app.register_error_handler(500, internal_server_error) + return app + +When using :doc:`/blueprints`: + +.. code-block:: python + + from flask import Blueprint + + blog = Blueprint('blog', __name__) + + # as a decorator + @blog.errorhandler(500) + def internal_server_error(e): + return render_template('500.html'), 500 + + # or with register_error_handler + blog.register_error_handler(500, internal_server_error) + + +Blueprint Error Handlers +------------------------ + +In :doc:`/blueprints`, most error handlers will work as expected. +However, there is a caveat concerning handlers for 404 and 405 +exceptions. These error handlers 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. + +.. code-block:: python + + from flask import jsonify, render_template + + # at the application level + # not the blueprint level + @app.errorhandler(404) + def page_not_found(e): + # if a request is in our blog URL space + if request.path.startswith('/blog/'): + # we return a custom blog 404 page + return render_template("blog/404.html"), 404 + else: + # otherwise we return our generic site-wide 404 page + return render_template("404.html"), 404 + + @app.errorhandler(405) + def method_not_allowed(e): + # if a request has the wrong method to our API + if request.path.startswith('/api/'): + # we return a json saying so + return jsonify(message="Method Not Allowed"), 405 + else: + # otherwise we return a generic site-wide 405 page + return render_template("405.html"), 405 + + +Returning API Errors as JSON +---------------------------- + +When building APIs in Flask, some developers realise that the built-in +exceptions are not expressive enough for APIs and that the content type of +:mimetype:`text/html` they are emitting is not very useful for API consumers. + +Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON +responses to API errors. :func:`~flask.abort` is called +with a ``description`` parameter. The error handler will +use that as the JSON error message, and set the status code to 404. + +.. code-block:: python + + from flask import abort, jsonify + + @app.errorhandler(404) + def resource_not_found(e): + return jsonify(error=str(e)), 404 + + @app.route("/cheese") + def get_one_cheese(): + resource = get_resource() + + if resource is None: + abort(404, description="Resource not found") + + return jsonify(resource) + +We can also create custom exception classes. For instance, we can +introduce a new custom exception for an API that can take a proper human readable message, +a status code for the error and some optional payload to give more context +for the error. + +This is a simple example: + +.. code-block:: python + + from flask import jsonify, request + + class InvalidAPIUsage(Exception): + status_code = 400 + + def __init__(self, message, status_code=None, payload=None): + super().__init__() + self.message = message + if status_code is not None: + self.status_code = status_code + self.payload = payload + + def to_dict(self): + rv = dict(self.payload or ()) + rv['message'] = self.message + return rv + + @app.errorhandler(InvalidAPIUsage) + def invalid_api_usage(e): + return jsonify(e.to_dict()), e.status_code + + # an API app route for getting user information + # a correct request might be /api/user?user_id=420 + @app.route("/api/user") + def user_api(user_id): + user_id = request.arg.get("user_id") + if not user_id: + raise InvalidAPIUsage("No user id provided!") + + user = get_user(user_id=user_id) + if not user: + raise InvalidAPIUsage("No such user!", status_code=404) + + return jsonify(user.to_dict()) + +A view can now raise that exception with an error message. Additionally +some extra payload can be provided as a dictionary through the `payload` +parameter. + + +Logging +------- + +See :doc:`/logging` for information about how to log exceptions, such as +by emailing them to admins. + + +Debugging +--------- + +See :doc:`/debugging` for information about how to debug errors in +development and production. diff --git a/docs/extensiondev.rst b/docs/extensiondev.rst index d73d60191c..c397d06b8c 100644 --- a/docs/extensiondev.rst +++ b/docs/extensiondev.rst @@ -1,418 +1,306 @@ -.. _extension-dev: - Flask Extension Development =========================== -Flask, being a microframework, often requires some repetitive steps to get -a third party library working. Because very often these steps could be -abstracted to support multiple projects the `Flask Extension Registry`_ -was created. - -If you want to create your own Flask extension for something that does not -exist yet, this guide to extension development will help you get your -extension running in no time and to feel like users would expect your -extension to behave. - -.. _Flask Extension Registry: http://flask.pocoo.org/extensions/ - -Anatomy of an Extension ------------------------ - -Extensions are all located in a package called ``flask_something`` -where "something" is the name of the library you want to bridge. So for -example if you plan to add support for a library named `simplexml` to -Flask, you would name your extension's package ``flask_simplexml``. - -The name of the actual extension (the human readable name) however would -be something like "Flask-SimpleXML". Make sure to include the name -"Flask" somewhere in that name and that you check the capitalization. -This is how users can then register dependencies to your extension in -their :file:`setup.py` files. - -Flask sets up a redirect package called :data:`flask.ext` where users -should import the extensions from. If you for instance have a package -called ``flask_something`` users would import it as -``flask.ext.something``. This is done to transition from the old -namespace packages. See :ref:`ext-import-transition` for more details. - -But what do extensions look like themselves? An extension has to ensure -that it works with multiple Flask application instances at once. This is -a requirement because many people will use patterns like the -:ref:`app-factories` pattern to create their application as needed to aid -unittests and to support multiple configurations. Because of that it is -crucial that your application supports that kind of behavior. - -Most importantly the extension must be shipped with a :file:`setup.py` file and -registered on PyPI. Also the development checkout link should work so -that people can easily install the development version into their -virtualenv without having to download the library by hand. - -Flask extensions must be licensed under a BSD, MIT or more liberal license -to be able to be enlisted in the Flask Extension Registry. Keep in mind -that the Flask Extension Registry is a moderated place and libraries will -be reviewed upfront if they behave as required. - -"Hello Flaskext!" ------------------ - -So let's get started with creating such a Flask extension. The extension -we want to create here will provide very basic support for SQLite3. - -First we create the following folder structure:: - - flask-sqlite3/ - flask_sqlite3.py - LICENSE - README - -Here's the contents of the most important files: - -setup.py -```````` - -The next file that is absolutely required is the :file:`setup.py` file which is -used to install your Flask extension. The following contents are -something you can work with:: - - """ - Flask-SQLite3 - ------------- - - This is the description for that library - """ - from setuptools import setup - - - setup( - name='Flask-SQLite3', - version='1.0', - url='http://example.com/flask-sqlite3/', - license='BSD', - author='Your Name', - author_email='your-email@example.com', - description='Very short description', - long_description=__doc__, - py_modules=['flask_sqlite3'], - # if you would be using a package instead use packages instead - # of py_modules: - # packages=['flask_sqlite3'], - zip_safe=False, - include_package_data=True, - platforms='any', - install_requires=[ - 'Flask' - ], - classifiers=[ - 'Environment :: Web Environment', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: BSD License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', - 'Topic :: Software Development :: Libraries :: Python Modules' - ] - ) - -That's a lot of code but you can really just copy/paste that from existing -extensions and adapt. - -flask_sqlite3.py -```````````````` - -Now this is where your extension code goes. But how exactly should such -an extension look like? What are the best practices? Continue reading -for some insight. - -Initializing Extensions ------------------------ - -Many extensions will need some kind of initialization step. For example, -consider an application that's currently connecting to SQLite like the -documentation suggests (:ref:`sqlite3`). So how does the extension -know the name of the application object? - -Quite simple: you pass it to it. - -There are two recommended ways for an extension to initialize: - -initialization functions: - - If your extension is called `helloworld` you might have a function - called ``init_helloworld(app[, extra_args])`` that initializes the - extension for that application. It could attach before / after - handlers etc. - -classes: - - Classes work mostly like initialization functions but can later be - used to further change the behavior. For an example look at how the - `OAuth extension`_ works: there is an `OAuth` object that provides - some helper functions like `OAuth.remote_app` to create a reference to - a remote application that uses OAuth. - -What to use depends on what you have in mind. For the SQLite 3 extension -we will use the class-based approach because it will provide users with an -object that handles opening and closing database connections. - -What's important about classes is that they encourage to be shared around -on module level. In that case, the object itself must not under any -circumstances store any application specific state and must be shareable -between different application. - -The Extension Code ------------------- - -Here's the contents of the `flask_sqlite3.py` for copy/paste:: - - import sqlite3 - from flask import current_app - - # Find the stack on which we want to store the database connection. - # Starting with Flask 0.9, the _app_ctx_stack is the correct one, - # before that we need to use the _request_ctx_stack. - try: - from flask import _app_ctx_stack as stack - except ImportError: - from flask import _request_ctx_stack as stack - - - class SQLite3(object): +.. currentmodule:: flask + +Extensions are extra packages that add functionality to a Flask +application. While `PyPI`_ contains many Flask extensions, you may not +find one that fits your need. If this is the case, you can create your +own, and publish it for others to use as well. + +This guide will show how to create a Flask extension, and some of the +common patterns and requirements involved. Since extensions can do +anything, this guide won't be able to cover every possibility. + +The best ways to learn about extensions are to look at how other +extensions you use are written, and discuss with others. Discuss your +design ideas with others on our `Discord Chat`_ or +`GitHub Discussions`_. + +The best extensions share common patterns, so that anyone familiar with +using one extension won't feel completely lost with another. This can +only work if collaboration happens early. + + +Naming +------ + +A Flask extension typically has ``flask`` in its name as a prefix or +suffix. If it wraps another library, it should include the library name +as well. This makes it easy to search for extensions, and makes their +purpose clearer. + +A general Python packaging recommendation is that the install name from +the package index and the name used in ``import`` statements should be +related. The import name is lowercase, with words separated by +underscores (``_``). The install name is either lower case or title +case, with words separated by dashes (``-``). If it wraps another +library, prefer using the same case as that library's name. + +Here are some example install and import names: +- ``Flask-Name`` imported as ``flask_name`` +- ``flask-name-lower`` imported as ``flask_name_lower`` +- ``Flask-ComboName`` imported as ``flask_comboname`` +- ``Name-Flask`` imported as ``name_flask`` + + +The Extension Class and Initialization +-------------------------------------- + +All extensions will need some entry point that initializes the +extension with the application. The most common pattern is to create a +class that represents the extension's configuration and behavior, with +an ``init_app`` method to apply the extension instance to the given +application instance. + +.. code-block:: python + + class HelloExtension: def __init__(self, app=None): - self.app = app if app is not None: self.init_app(app) def init_app(self, app): - app.config.setdefault('SQLITE3_DATABASE', ':memory:') - # Use the newstyle teardown_appcontext if it's available, - # otherwise fall back to the request context - if hasattr(app, 'teardown_appcontext'): - app.teardown_appcontext(self.teardown) - else: - app.teardown_request(self.teardown) - - def connect(self): - return sqlite3.connect(current_app.config['SQLITE3_DATABASE']) - - def teardown(self, exception): - ctx = stack.top - if hasattr(ctx, 'sqlite3_db'): - ctx.sqlite3_db.close() - - @property - def connection(self): - ctx = stack.top - if ctx is not None: - if not hasattr(ctx, 'sqlite3_db'): - ctx.sqlite3_db = self.connect() - return ctx.sqlite3_db - - -So here's what these lines of code do: - -1. The ``__init__`` method takes an optional app object and, if supplied, will - call ``init_app``. -2. The ``init_app`` method exists so that the ``SQLite3`` object can be - instantiated without requiring an app object. This method supports the - factory pattern for creating applications. The ``init_app`` will set the - configuration for the database, defaulting to an in memory database if - no configuration is supplied. In addition, the ``init_app`` method attaches - the ``teardown`` handler. It will try to use the newstyle app context - handler and if it does not exist, falls back to the request context - one. -3. Next, we define a ``connect`` method that opens a database connection. -4. Finally, we add a ``connection`` property that on first access opens - the database connection and stores it on the context. This is also - the recommended way to handling resources: fetch resources lazily the - first time they are used. - - Note here that we're attaching our database connection to the top - application context via ``_app_ctx_stack.top``. Extensions should use - the top context for storing their own information with a sufficiently - complex name. Note that we're falling back to the - ``_request_ctx_stack.top`` if the application is using an older - version of Flask that does not support it. - -So why did we decide on a class-based approach here? Because using our -extension looks something like this:: - - from flask import Flask - from flask_sqlite3 import SQLite3 - - app = Flask(__name__) - app.config.from_pyfile('the-config.cfg') - db = SQLite3(app) - -You can then use the database from views like this:: - - @app.route('/') - def show_all(): - cur = db.connection.cursor() - cur.execute(...) - -Likewise if you are outside of a request but you are using Flask 0.9 or -later with the app context support, you can use the database in the same -way:: - - with app.app_context(): - cur = db.connection.cursor() - cur.execute(...) - -At the end of the ``with`` block the teardown handles will be executed -automatically. - -Additionally, the ``init_app`` method is used to support the factory pattern -for creating apps:: - - db = Sqlite3() - # Then later on. - app = create_app('the-config.cfg') - db.init_app(app) + app.before_request(...) + +It is important that the app is not stored on the extension, don't do +``self.app = app``. The only time the extension should have direct +access to an app is during ``init_app``, otherwise it should use +:data:`current_app`. + +This allows the extension to support the application factory pattern, +avoids circular import issues when importing the extension instance +elsewhere in a user's code, and makes testing with different +configurations easier. + +.. code-block:: python + + hello = HelloExtension() + + def create_app(): + app = Flask(__name__) + hello.init_app(app) + return app + +Above, the ``hello`` extension instance exists independently of the +application. This means that other modules in a user's project can do +``from project import hello`` and use the extension in blueprints before +the app exists. + +The :attr:`Flask.extensions` dict can be used to store a reference to +the extension on the application, or some other state specific to the +application. Be aware that this is a single namespace, so use a name +unique to your extension, such as the extension's name without the +"flask" prefix. + + +Adding Behavior +--------------- + +There are many ways that an extension can add behavior. Any setup +methods that are available on the :class:`Flask` object can be used +during an extension's ``init_app`` method. + +A common pattern is to use :meth:`~Flask.before_request` to initialize +some data or a connection at the beginning of each request, then +:meth:`~Flask.teardown_request` to clean it up at the end. This can be +stored on :data:`g`, discussed more below. + +A more lazy approach is to provide a method that initializes and caches +the data or connection. For example, a ``ext.get_db`` method could +create a database connection the first time it's called, so that a view +that doesn't use the database doesn't create a connection. + +Besides doing something before and after every view, your extension +might want to add some specific views as well. In this case, you could +define a :class:`Blueprint`, then call :meth:`~Flask.register_blueprint` +during ``init_app`` to add the blueprint to the app. + + +Configuration Techniques +------------------------ + +There can be multiple levels and sources of configuration for an +extension. You should consider what parts of your extension fall into +each one. + +- Configuration per application instance, through ``app.config`` + values. This is configuration that could reasonably change for each + deployment of an application. A common example is a URL to an + external resource, such as a database. Configuration keys should + start with the extension's name so that they don't interfere with + other extensions. +- Configuration per extension instance, through ``__init__`` + arguments. This configuration usually affects how the extension + is used, such that it wouldn't make sense to change it per + deployment. +- Configuration per extension instance, through instance attributes + and decorator methods. It might be more ergonomic to assign to + ``ext.value``, or use a ``@ext.register`` decorator to register a + function, after the extension instance has been created. +- Global configuration through class attributes. Changing a class + attribute like ``Ext.connection_class`` can customize default + behavior without making a subclass. This could be combined + per-extension configuration to override defaults. +- Subclassing and overriding methods and attributes. Making the API of + the extension itself something that can be overridden provides a + very powerful tool for advanced customization. + +The :class:`~flask.Flask` object itself uses all of these techniques. + +It's up to you to decide what configuration is appropriate for your +extension, based on what you need and what you want to support. + +Configuration should not be changed after the application setup phase is +complete and the server begins handling requests. Configuration is +global, any changes to it are not guaranteed to be visible to other +workers. + + +Data During a Request +--------------------- + +When writing a Flask application, the :data:`~flask.g` object is used to +store information during a request. For example the +:doc:`tutorial ` stores a connection to a SQLite +database as ``g.db``. Extensions can also use this, with some care. +Since ``g`` is a single global namespace, extensions must use unique +names that won't collide with user data. For example, use the extension +name as a prefix, or as a namespace. + +.. code-block:: python + + # an internal prefix with the extension name + g._hello_user_id = 2 + + # or an internal prefix as a namespace + from types import SimpleNamespace + g._hello = SimpleNamespace() + g._hello.user_id = 2 + +The data in ``g`` lasts for an application context. An application +context is active when a request context is, or when a CLI command is +run. If you're storing something that should be closed, use +:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed +when the application context ends. If it should only be valid during a +request, or would not be used in the CLI outside a request, use +:meth:`~flask.Flask.teardown_request`. + + +Views and Models +---------------- + +Your extension views might want to interact with specific models in your +database, or some other extension or data connected to your application. +For example, let's consider a ``Flask-SimpleBlog`` extension that works +with Flask-SQLAlchemy to provide a ``Post`` model and views to write +and read posts. + +The ``Post`` model needs to subclass the Flask-SQLAlchemy ``db.Model`` +object, but that's only available once you've created an instance of +that extension, not when your extension is defining its views. So how +can the view code, defined before the model exists, access the model? + +One method could be to use :doc:`views`. During ``__init__``, create +the model, then create the views by passing the model to the view +class's :meth:`~views.View.as_view` method. + +.. code-block:: python + + class PostAPI(MethodView): + def __init__(self, model): + self.model = model + + def get(self, id): + post = self.model.query.get(id) + return jsonify(post.to_json()) + + class BlogExtension: + def __init__(self, db): + class Post(db.Model): + id = db.Column(primary_key=True) + title = db.Column(db.String, nullable=False) + + self.post_model = Post + + def init_app(self, app): + api_view = PostAPI.as_view(model=self.post_model) -Keep in mind that supporting this factory pattern for creating apps is required -for approved flask extensions (described below). - -.. admonition:: Note on ``init_app`` - - As you noticed, ``init_app`` does not assign ``app`` to ``self``. This - is intentional! Class based Flask extensions must only store the - application on the object when the application was passed to the - constructor. This tells the extension: I am not interested in using - multiple applications. - - When the extension needs to find the current application and it does - not have a reference to it, it must either use the - :data:`~flask.current_app` context local or change the API in a way - that you can pass the application explicitly. - - -Using _app_ctx_stack --------------------- - -In the example above, before every request, a ``sqlite3_db`` variable is -assigned to ``_app_ctx_stack.top``. In a view function, this variable is -accessible using the ``connection`` property of ``SQLite3``. During the -teardown of a request, the ``sqlite3_db`` connection is closed. By using -this pattern, the *same* connection to the sqlite3 database is accessible -to anything that needs it for the duration of the request. - -If the :data:`~flask._app_ctx_stack` does not exist because the user uses -an old version of Flask, it is recommended to fall back to -:data:`~flask._request_ctx_stack` which is bound to a request. - -Teardown Behavior ------------------ - -*This is only relevant if you want to support Flask 0.6 and older* - -Due to the change in Flask 0.7 regarding functions that are run at the end -of the request your extension will have to be extra careful there if it -wants to continue to support older versions of Flask. The following -pattern is a good way to support both:: - - def close_connection(response): - ctx = _request_ctx_stack.top - ctx.sqlite3_db.close() - return response - - if hasattr(app, 'teardown_request'): - app.teardown_request(close_connection) - else: - app.after_request(close_connection) - -Strictly speaking the above code is wrong, because teardown functions are -passed the exception and typically don't return anything. However because -the return value is discarded this will just work assuming that the code -in between does not touch the passed parameter. - -Learn from Others ------------------ - -This documentation only touches the bare minimum for extension -development. If you want to learn more, it's a very good idea to check -out existing extensions on the `Flask Extension Registry`_. If you feel -lost there is still the `mailinglist`_ and the `IRC channel`_ to get some -ideas for nice looking APIs. Especially if you do something nobody before -you did, it might be a very good idea to get some more input. This not -only to get an idea about what people might want to have from an -extension, but also to avoid having multiple developers working on pretty -much the same side by side. - -Remember: good API design is hard, so introduce your project on the -mailinglist, and let other developers give you a helping hand with -designing the API. - -The best Flask extensions are extensions that share common idioms for the -API. And this can only work if collaboration happens early. - -Approved Extensions -------------------- - -Flask also has the concept of approved extensions. Approved extensions -are tested as part of Flask itself to ensure extensions do not break on -new releases. These approved extensions are listed on the `Flask -Extension Registry`_ and marked appropriately. If you want your own -extension to be approved you have to follow these guidelines: - -0. An approved Flask extension requires a maintainer. In the event an - extension author would like to move beyond the project, the project should - find a new maintainer including full source hosting transition and PyPI - access. If no maintainer is available, give access to the Flask core team. -1. An approved Flask extension must provide exactly one package or module - named ``flask_extensionname``. -2. It must ship a testing suite that can either be invoked with ``make test`` - or ``python setup.py test``. For test suites invoked with ``make - test`` the extension has to ensure that all dependencies for the test - are installed automatically. If tests are invoked with ``python setup.py - test``, test dependencies can be specified in the :file:`setup.py` file. The - test suite also has to be part of the distribution. -3. APIs of approved extensions will be checked for the following - characteristics: - - - an approved extension has to support multiple applications - running in the same Python process. - - it must be possible to use the factory pattern for creating - applications. - -4. The license must be BSD/MIT/WTFPL licensed. -5. The naming scheme for official extensions is *Flask-ExtensionName* or - *ExtensionName-Flask*. -6. Approved extensions must define all their dependencies in the - :file:`setup.py` file unless a dependency cannot be met because it is not - available on PyPI. -7. The extension must have documentation that uses one of the two Flask - themes for Sphinx documentation. -8. The setup.py description (and thus the PyPI description) has to - link to the documentation, website (if there is one) and there - must be a link to automatically install the development version - (``PackageName==dev``). -9. The ``zip_safe`` flag in the setup script must be set to ``False``, - even if the extension would be safe for zipping. -10. An extension currently has to support Python 2.6 as well as - Python 2.7 - - -.. _ext-import-transition: - -Extension Import Transition ---------------------------- - -In early versions of Flask we recommended using namespace packages for Flask -extensions, of the form ``flaskext.foo``. This turned out to be problematic in -practice because it meant that multiple ``flaskext`` packages coexist. -Consequently we have recommended to name extensions ``flask_foo`` over -``flaskext.foo`` for a long time. - -Flask 0.8 introduced a redirect import system as a compatibility aid for app -developers: Importing ``flask.ext.foo`` would try ``flask_foo`` and -``flaskext.foo`` in that order. - -As of Flask 0.11, most Flask extensions have transitioned to the new naming -schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is -now deprecated -- you should use ``flask_foo``. - - -.. _OAuth extension: http://pythonhosted.org/Flask-OAuth/ -.. _mailinglist: http://flask.pocoo.org/mailinglist/ -.. _IRC channel: http://flask.pocoo.org/community/irc/ + db = SQLAlchemy() + blog = BlogExtension(db) + db.init_app(app) + blog.init_app(app) + +Another technique could be to use an attribute on the extension, such as +``self.post_model`` from above. Add the extension to ``app.extensions`` +in ``init_app``, then access +``current_app.extensions["simple_blog"].post_model`` from views. + +You may also want to provide base classes so that users can provide +their own ``Post`` model that conforms to the API your extension +expects. So they could implement ``class Post(blog.BasePost)``, then +set it as ``blog.post_model``. + +As you can see, this can get a bit complex. Unfortunately, there's no +perfect solution here, only different strategies and tradeoffs depending +on your needs and how much customization you want to offer. Luckily, +this sort of resource dependency is not a common need for most +extensions. Remember, if you need help with design, ask on our +`Discord Chat`_ or `GitHub Discussions`_. + + +Recommended Extension Guidelines +-------------------------------- + +Flask previously had the concept of "approved extensions", where the +Flask maintainers evaluated the quality, support, and compatibility of +the extensions before listing them. While the list became too difficult +to maintain over time, the guidelines are still relevant to all +extensions maintained and developed today, as they help the Flask +ecosystem remain consistent and compatible. + +1. An extension requires a maintainer. In the event an extension author + would like to move beyond the project, the project should find a new + maintainer and transfer access to the repository, documentation, + PyPI, and any other services. The `Pallets-Eco`_ organization on + GitHub allows for community maintenance with oversight from the + Pallets maintainers. +2. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*. + It must provide exactly one package or module named + ``flask_extension_name``. +3. The extension must use an open source license. The Python web + ecosystem tends to prefer BSD or MIT. It must be open source and + publicly available. +4. The extension's API must have the following characteristics: + + - It must support multiple applications running in the same Python + process. Use ``current_app`` instead of ``self.app``, store + configuration and state per application instance. + - It must be possible to use the factory pattern for creating + applications. Use the ``ext.init_app()`` pattern. + +5. From a clone of the repository, an extension with its dependencies + must be installable in editable mode with ``pip install -e .``. +6. It must ship tests that can be invoked with a common tool like + ``tox -e py``, ``nox -s test`` or ``pytest``. If not using ``tox``, + the test dependencies should be specified in a requirements file. + The tests must be part of the sdist distribution. +7. A link to the documentation or project website must be in the PyPI + metadata or the readme. The documentation should use the Flask theme + from the `Official Pallets Themes`_. +8. The extension's dependencies should not use upper bounds or assume + any particular version scheme, but should use lower bounds to + indicate minimum compatibility support. For example, + ``sqlalchemy>=1.4``. +9. Indicate the versions of Python supported using ``python_requires=">=version"``. + Flask and Pallets policy is to support all Python versions that are not + within six months of end of life (EOL). See Python's `EOL calendar`_ for + timing. + +.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask +.. _Discord Chat: https://discord.gg/pallets +.. _GitHub Discussions: https://github.com/pallets/flask/discussions +.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/ +.. _Pallets-Eco: https://github.com/pallets-eco +.. _EOL calendar: https://devguide.python.org/versions/ diff --git a/docs/extensions.rst b/docs/extensions.rst index 6deb965213..4713ec8e2d 100644 --- a/docs/extensions.rst +++ b/docs/extensions.rst @@ -1,58 +1,48 @@ -.. _extensions: +Extensions +========== -Flask 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. -Flask extensions extend the functionality of Flask in various different -ways. For instance they add support for databases and other common tasks. Finding Extensions ------------------ -Flask extensions are listed on the `Flask Extension Registry`_ and can be -downloaded with :command:`easy_install` or :command:`pip`. If you add a Flask extension -as dependency to your :file:`requirements.txt` or :file:`setup.py` file they are -usually installed with a simple command or when your application installs. +Flask extensions are usually named "Flask-Foo" or "Foo-Flask". You can +search PyPI for packages tagged with `Framework :: Flask `_. + Using Extensions ---------------- -Extensions typically have documentation that goes along that shows how to -use it. There are no general rules in how extensions are supposed to -behave but they are imported from common locations. If you have an -extension called ``Flask-Foo`` or ``Foo-Flask`` it should be always -importable from ``flask_foo``:: - - import flask_foo - -Building Extensions -------------------- +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:: -While `Flask Extension Registry`_ contains many Flask extensions, you may not find -an extension that fits your need. If this is the case, you can always create your own. -Consider reading :ref:`extension-dev` to develop your own Flask extension. + from flask_foo import Foo -Flask Before 0.8 ----------------- + foo = Foo() -If you are using Flask 0.7 or earlier the :data:`flask.ext` package will not -exist, instead you have to import from ``flaskext.foo`` or ``flask_foo`` -depending on how the extension is distributed. If you want to develop an -application that supports Flask 0.7 or earlier you should still import -from the :data:`flask.ext` package. We provide you with a compatibility -module that provides this package for older versions of Flask. You can -download it from GitHub: `flaskext_compat.py`_ + app = Flask(__name__) + app.config.update( + FOO_BAR='baz', + FOO_SPAM='eggs', + ) -And here is how you can use it:: + foo.init_app(app) - import flaskext_compat - flaskext_compat.activate() - from flask.ext import foo +Building Extensions +------------------- -Once the ``flaskext_compat`` module is activated the :data:`flask.ext` will -exist and you can start importing from there. +While `PyPI `_ contains many Flask extensions, you may not find +an extension that fits your need. If this is the case, you can create +your own, and publish it for others to use as well. Read +:doc:`extensiondev` to develop your own Flask extension. -.. _Flask Extension Registry: http://flask.pocoo.org/extensions/ -.. _flaskext_compat.py: https://raw.githubusercontent.com/pallets/flask/master/scripts/flaskext_compat.py +.. _pypi: https://pypi.org/search/?c=Framework+%3A%3A+Flask diff --git a/docs/flaskdocext.py b/docs/flaskdocext.py deleted file mode 100644 index db4cfd2092..0000000000 --- a/docs/flaskdocext.py +++ /dev/null @@ -1,16 +0,0 @@ -import re -import inspect - - -_internal_mark_re = re.compile(r'^\s*:internal:\s*$(?m)') - - -def skip_member(app, what, name, obj, skip, options): - docstring = inspect.getdoc(obj) - if skip: - return True - return _internal_mark_re.search(docstring or '') is not None - - -def setup(app): - app.connect('autodoc-skip-member', skip_member) diff --git a/docs/flaskext.py b/docs/flaskext.py deleted file mode 100644 index 33f47449c1..0000000000 --- a/docs/flaskext.py +++ /dev/null @@ -1,86 +0,0 @@ -# flasky extensions. flasky pygments style based on tango style -from pygments.style import Style -from pygments.token import Keyword, Name, Comment, String, Error, \ - Number, Operator, Generic, Whitespace, Punctuation, Other, Literal - - -class FlaskyStyle(Style): - background_color = "#f8f8f8" - default_style = "" - - styles = { - # No corresponding class for the following: - #Text: "", # class: '' - Whitespace: "underline #f8f8f8", # class: 'w' - Error: "#a40000 border:#ef2929", # class: 'err' - Other: "#000000", # class 'x' - - Comment: "italic #8f5902", # class: 'c' - Comment.Preproc: "noitalic", # class: 'cp' - - Keyword: "bold #004461", # class: 'k' - Keyword.Constant: "bold #004461", # class: 'kc' - Keyword.Declaration: "bold #004461", # class: 'kd' - Keyword.Namespace: "bold #004461", # class: 'kn' - Keyword.Pseudo: "bold #004461", # class: 'kp' - Keyword.Reserved: "bold #004461", # class: 'kr' - Keyword.Type: "bold #004461", # class: 'kt' - - Operator: "#582800", # class: 'o' - Operator.Word: "bold #004461", # class: 'ow' - like keywords - - Punctuation: "bold #000000", # class: 'p' - - # because special names such as Name.Class, Name.Function, etc. - # are not recognized as such later in the parsing, we choose them - # to look the same as ordinary variables. - Name: "#000000", # class: 'n' - Name.Attribute: "#c4a000", # class: 'na' - to be revised - Name.Builtin: "#004461", # class: 'nb' - Name.Builtin.Pseudo: "#3465a4", # class: 'bp' - Name.Class: "#000000", # class: 'nc' - to be revised - Name.Constant: "#000000", # class: 'no' - to be revised - Name.Decorator: "#888", # class: 'nd' - to be revised - Name.Entity: "#ce5c00", # class: 'ni' - Name.Exception: "bold #cc0000", # class: 'ne' - Name.Function: "#000000", # class: 'nf' - Name.Property: "#000000", # class: 'py' - Name.Label: "#f57900", # class: 'nl' - Name.Namespace: "#000000", # class: 'nn' - to be revised - Name.Other: "#000000", # class: 'nx' - Name.Tag: "bold #004461", # class: 'nt' - like a keyword - Name.Variable: "#000000", # class: 'nv' - to be revised - Name.Variable.Class: "#000000", # class: 'vc' - to be revised - Name.Variable.Global: "#000000", # class: 'vg' - to be revised - Name.Variable.Instance: "#000000", # class: 'vi' - to be revised - - Number: "#990000", # class: 'm' - - Literal: "#000000", # class: 'l' - Literal.Date: "#000000", # class: 'ld' - - String: "#4e9a06", # class: 's' - String.Backtick: "#4e9a06", # class: 'sb' - String.Char: "#4e9a06", # class: 'sc' - String.Doc: "italic #8f5902", # class: 'sd' - like a comment - String.Double: "#4e9a06", # class: 's2' - String.Escape: "#4e9a06", # class: 'se' - String.Heredoc: "#4e9a06", # class: 'sh' - String.Interpol: "#4e9a06", # class: 'si' - String.Other: "#4e9a06", # class: 'sx' - String.Regex: "#4e9a06", # class: 'sr' - String.Single: "#4e9a06", # class: 's1' - String.Symbol: "#4e9a06", # class: 'ss' - - Generic: "#000000", # class: 'g' - Generic.Deleted: "#a40000", # class: 'gd' - Generic.Emph: "italic #000000", # class: 'ge' - Generic.Error: "#ef2929", # class: 'gr' - Generic.Heading: "bold #000080", # class: 'gh' - Generic.Inserted: "#00A000", # class: 'gi' - Generic.Output: "#888", # class: 'go' - Generic.Prompt: "#745334", # class: 'gp' - Generic.Strong: "bold #000000", # class: 'gs' - Generic.Subheading: "bold #800080", # class: 'gu' - Generic.Traceback: "bold #a40000", # class: 'gt' - } diff --git a/docs/flaskstyle.sty b/docs/flaskstyle.sty deleted file mode 100644 index 8a3f75c34f..0000000000 --- a/docs/flaskstyle.sty +++ /dev/null @@ -1,118 +0,0 @@ -\definecolor{TitleColor}{rgb}{0,0,0} -\definecolor{InnerLinkColor}{rgb}{0,0,0} - -\renewcommand{\maketitle}{% - \begin{titlepage}% - \let\footnotesize\small - \let\footnoterule\relax - \ifsphinxpdfoutput - \begingroup - % This \def is required to deal with multi-line authors; it - % changes \\ to ', ' (comma-space), making it pass muster for - % generating document info in the PDF file. - \def\\{, } - \pdfinfo{ - /Author (\@author) - /Title (\@title) - } - \endgroup - \fi - \begin{flushright}% - %\sphinxlogo% - {\center - \vspace*{3cm} - \includegraphics{logo.pdf} - \vspace{3cm} - \par - {\rm\Huge \@title \par}% - {\em\LARGE \py@release\releaseinfo \par} - {\large - \@date \par - \py@authoraddress \par - }}% - \end{flushright}%\par - \@thanks - \end{titlepage}% - \cleardoublepage% - \setcounter{footnote}{0}% - \let\thanks\relax\let\maketitle\relax - %\gdef\@thanks{}\gdef\@author{}\gdef\@title{} -} - -\fancypagestyle{normal}{ - \fancyhf{} - \fancyfoot[LE,RO]{{\thepage}} - \fancyfoot[LO]{{\nouppercase{\rightmark}}} - \fancyfoot[RE]{{\nouppercase{\leftmark}}} - \fancyhead[LE,RO]{{ \@title, \py@release}} - \renewcommand{\headrulewidth}{0.4pt} - \renewcommand{\footrulewidth}{0.4pt} -} - -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[LE,RO]{{\thepage}} - \renewcommand{\headrulewidth}{0pt} - \renewcommand{\footrulewidth}{0.4pt} -} - -\titleformat{\section}{\Large}% - {\py@TitleColor\thesection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\subsection}{\large}% - {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\subsubsection}{}% - {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\paragraph}{\large}% - {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor} - -\ChNameVar{\raggedleft\normalsize} -\ChNumVar{\raggedleft \bfseries\Large} -\ChTitleVar{\raggedleft \rm\Huge} - -\renewcommand\thepart{\@Roman\c@part} -\renewcommand\part{% - \pagestyle{plain} - \if@noskipsec \leavevmode \fi - \cleardoublepage - \vspace*{6cm}% - \@afterindentfalse - \secdef\@part\@spart} - -\def\@part[#1]#2{% - \ifnum \c@secnumdepth >\m@ne - \refstepcounter{part}% - \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}% - \else - \addcontentsline{toc}{part}{#1}% - \fi - {\parindent \z@ %\center - \interlinepenalty \@M - \normalfont - \ifnum \c@secnumdepth >\m@ne - \rm\Large \partname~\thepart - \par\nobreak - \fi - \MakeUppercase{\rm\Huge #2}% - \markboth{}{}\par}% - \nobreak - \vskip 8ex - \@afterheading} -\def\@spart#1{% - {\parindent \z@ %\center - \interlinepenalty \@M - \normalfont - \huge \bfseries #1\par}% - \nobreak - \vskip 3ex - \@afterheading} - -% use inconsolata font -\usepackage{inconsolata} - -% fix single quotes, for inconsolata. (does not work) -%%\usepackage{textcomp} -%%\begingroup -%% \catcode`'=\active -%% \g@addto@macro\@noligs{\let'\textsinglequote} -%% \endgroup -%%\endinput diff --git a/docs/foreword.rst b/docs/foreword.rst deleted file mode 100644 index 4142cb8337..0000000000 --- a/docs/foreword.rst +++ /dev/null @@ -1,57 +0,0 @@ -Foreword -======== - -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`. diff --git a/docs/htmlfaq.rst b/docs/htmlfaq.rst deleted file mode 100644 index 0b6ff5048b..0000000000 --- a/docs/htmlfaq.rst +++ /dev/null @@ -1,207 +0,0 @@ -HTML/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]_ | -+-----------------------------------------+----------+----------+----------+ -| `` + +A less common pattern is to add the data to a ``data-`` attribute on an +HTML tag. In this case, you must use single quotes around the value, not +double quotes, otherwise you will produce invalid or unsafe HTML. + +.. code-block:: jinja + +

+ + +Generating URLs +--------------- + +The other way to get data from the server to JavaScript is to make a +request for it. First, you need to know the URL to request. + +The simplest way to generate URLs is to continue to use +:func:`~flask.url_for` when rendering the template. For example: + +.. code-block:: javascript + + const user_url = {{ url_for("user", id=current_user.id)|tojson }} + fetch(user_url).then(...) + +However, you might need to generate a URL based on information you only +know in JavaScript. As discussed above, JavaScript runs in the user's +browser, not as part of the template rendering, so you can't use +``url_for`` at that point. + +In this case, you need to know the "root URL" under which your +application is served. In simple setups, this is ``/``, but it might +also be something else, like ``https://example.com/myapp/``. + +A simple way to tell your JavaScript code about this root is to set it +as a global variable when rendering the template. Then you can use it +when generating URLs from JavaScript. + +.. code-block:: javascript + + const SCRIPT_ROOT = {{ request.script_root|tojson }} + let user_id = ... // do something to get a user id from the page + let user_url = `${SCRIPT_ROOT}/user/${user_id}` + fetch(user_url).then(...) + + +Making a Request with ``fetch`` +------------------------------- + +|fetch|_ takes two arguments, a URL and an object with other options, +and returns a |Promise|_. We won't cover all the available options, and +will only use ``then()`` on the promise, not other callbacks or +``await`` syntax. Read the linked MDN docs for more information about +those features. + +By default, the GET method is used. If the response contains JSON, it +can be used with a ``then()`` callback chain. + +.. code-block:: javascript + + const room_url = {{ url_for("room_detail", id=room.id)|tojson }} + fetch(room_url) + .then(response => response.json()) + .then(data => { + // data is a parsed JSON object + }) + +To send data, use a data method such as POST, and pass the ``body`` +option. The most common types for data are form data or JSON data. + +To send form data, pass a populated |FormData|_ object. This uses the +same format as an HTML form, and would be accessed with ``request.form`` +in a Flask view. + +.. code-block:: javascript + + let data = new FormData() + data.append("name", "Flask Room") + data.append("description", "Talk about Flask here.") + fetch(room_url, { + "method": "POST", + "body": data, + }).then(...) + +In general, prefer sending request data as form data, as would be used +when submitting an HTML form. JSON can represent more complex data, but +unless you need that it's better to stick with the simpler format. When +sending JSON data, the ``Content-Type: application/json`` header must be +sent as well, otherwise Flask will return a 400 error. + +.. code-block:: javascript + + let data = { + "name": "Flask Room", + "description": "Talk about Flask here.", + } + fetch(room_url, { + "method": "POST", + "headers": {"Content-Type": "application/json"}, + "body": JSON.stringify(data), + }).then(...) + +.. |Promise| replace:: ``Promise`` +.. _Promise: https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/Promise +.. |FormData| replace:: ``FormData`` +.. _FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData + + +Following Redirects +------------------- + +A response might be a redirect, for example if you logged in with +JavaScript instead of a traditional HTML form, and your view returned +a redirect instead of JSON. JavaScript requests do follow redirects, but +they don't change the page. If you want to make the page change you can +inspect the response and apply the redirect manually. + +.. code-block:: javascript + + fetch("http://github.com/login", {"body": ...}).then( + response => { + if (response.redirected) { + window.location = response.url + } else { + showLoginError() + } + } + ) + + +Replacing Content +----------------- + +A response might be new HTML, either a new section of the page to add or +replace, or an entirely new page. In general, if you're returning the +entire page, it would be better to handle that with a redirect as shown +in the previous section. The following example shows how to replace a +``
`` with the HTML returned by a request. + +.. code-block:: html + +
+ {{ include "geology_fact.html" }} +
+ + + +Return JSON from Views +---------------------- + +To return a JSON object from your API view, you can directly return a +dict from the view. It will be serialized to JSON automatically. + +.. code-block:: python + + @app.route("/user/") + def user_detail(id): + user = User.query.get_or_404(id) + return { + "username": User.username, + "email": User.email, + "picture": url_for("static", filename=f"users/{id}/profile.png"), + } + +If you want to return another JSON type, use the +:func:`~flask.json.jsonify` function, which creates a response object +with the given data serialized to JSON. + +.. code-block:: python + + from flask import jsonify + + @app.route("/users") + def user_list(): + users = User.query.order_by(User.name).all() + return jsonify([u.to_json() for u in users]) + +It is usually not a good idea to return file data in a JSON response. +JSON cannot represent binary data directly, so it must be base64 +encoded, which can be slow, takes more bandwidth to send, and is not as +easy to cache. Instead, serve files using one view, and generate a URL +to the desired file to include in the JSON. Then the client can make a +separate request to get the linked resource after getting the JSON. + + +Receiving JSON in Views +----------------------- + +Use the :attr:`~flask.Request.json` property of the +:data:`~flask.request` object to decode the request's body as JSON. If +the body is not valid JSON, or the ``Content-Type`` header is not set to +``application/json``, a 400 Bad Request error will be raised. + +.. code-block:: python + + from flask import request + + @app.post("/user/") + def user_update(id): + user = User.query.get_or_404(id) + user.update_from_json(request.json) + db.session.commit() + return user.to_json() diff --git a/docs/patterns/jquery.rst b/docs/patterns/jquery.rst index d136d5b42d..7ac6856eac 100644 --- a/docs/patterns/jquery.rst +++ b/docs/patterns/jquery.rst @@ -1,168 +1,6 @@ +:orphan: + AJAX with jQuery ================ -`jQuery`_ is a small JavaScript library commonly used to simplify working -with the DOM and JavaScript in general. It is the perfect tool to make -web applications more dynamic by exchanging JSON between server and -client. - -JSON itself is a very lightweight transport format, very similar to how -Python primitives (numbers, strings, dicts and lists) look like which is -widely supported and very easy to parse. It became popular a few years -ago and quickly replaced XML as transport format in web applications. - -.. _jQuery: http://jquery.com/ - -Loading jQuery --------------- - -In order to use jQuery, you have to download it first and place it in the -static folder of your application and then ensure it's loaded. Ideally -you have a layout template that is used for all pages where you just have -to add a script statement to the bottom of your ```` to load jQuery: - -.. sourcecode:: html - - - -Another method is using Google's `AJAX Libraries API -`_ to load jQuery: - -.. sourcecode:: html - - - - -In this case you have to put jQuery into your static folder as a fallback, but it will -first try to load it directly from Google. This has the advantage that your -website will probably load faster for users if they went to at least one -other website before using the same jQuery version from Google because it -will already be in the browser cache. - -Where is My Site? ------------------ - -Do you know where your application is? If you are developing the answer -is quite simple: it's on localhost port something and directly on the root -of that server. But what if you later decide to move your application to -a different location? For example to ``http://example.com/myapp``? On -the server side this never was a problem because we were using the handy -:func:`~flask.url_for` function that could answer that question for -us, but if we are using jQuery we should not hardcode the path to -the application but make that dynamic, so how can we do that? - -A simple method would be to add a script tag to our page that sets a -global variable to the prefix to the root of the application. Something -like this: - -.. sourcecode:: html+jinja - - - -The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not -escape the JSON encoded string with HTML rules. Usually this would be -necessary, but we are inside a ``script`` block here where different rules -apply. - -.. admonition:: Information for Pros - - In HTML the ``script`` tag is declared ``CDATA`` which means that entities - will not be parsed. Everything until ```` is handled as script. - This also means that there must never be any ``"|tojson|safe }}`` is rendered as - ``"<\/script>"``). - - In Flask 0.10 it goes a step further and escapes all HTML tags with - unicode escapes. This makes it possible for Flask to automatically - mark the result as HTML safe. - - -JSON View Functions -------------------- - -Now let's create a server side function that accepts two URL arguments of -numbers which should be added together and then sent back to the -application in a JSON object. This is a really ridiculous example and is -something you usually would do on the client side alone, but a simple -example that shows how you would use jQuery and Flask nonetheless:: - - from flask import Flask, jsonify, render_template, request - app = Flask(__name__) - - @app.route('/_add_numbers') - def add_numbers(): - a = request.args.get('a', 0, type=int) - b = request.args.get('b', 0, type=int) - return jsonify(result=a + b) - - @app.route('/') - def index(): - return render_template('index.html') - -As you can see I also added an `index` method here that renders a -template. This template will load jQuery as above and have a little form -we can add two numbers and a link to trigger the function on the server -side. - -Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here -which will never fail. If the key is missing a default value (here ``0``) -is returned. Furthermore it can convert values to a specific type (like -in our case `int`). This is especially handy for code that is -triggered by a script (APIs, JavaScript etc.) because you don't need -special error reporting in that case. - -The HTML --------- - -Your index.html template either has to extend a :file:`layout.html` template with -jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top. -Here's the HTML code needed for our little application (:file:`index.html`). -Notice that we also drop the script directly into the HTML here. It is -usually a better idea to have that in a separate script file: - -.. sourcecode:: html - - -

jQuery Example

-

+ - = - ? -

calculate server side - -I won't go into detail here about how jQuery works, just a very quick -explanation of the little bit of code above: - -1. ``$(function() { ... })`` specifies code that should run once the - browser is done loading the basic parts of the page. -2. ``$('selector')`` selects an element and lets you operate on it. -3. ``element.bind('event', func)`` specifies a function that should run - when the user clicked on the element. If that function returns - `false`, the default behavior will not kick in (in this case, navigate - to the `#` URL). -4. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will - send the contents of the `data` object as query parameters. Once the - data arrived, it will call the given function with the return value as - argument. Note that we can use the `$SCRIPT_ROOT` variable here that - we set earlier. - -If you don't get the whole picture, download the `sourcecode -for this example -`_ -from GitHub. +Obsolete, see :doc:`/patterns/javascript` instead. diff --git a/docs/patterns/lazyloading.rst b/docs/patterns/lazyloading.rst index acb77f943a..658a1cd43c 100644 --- a/docs/patterns/lazyloading.rst +++ b/docs/patterns/lazyloading.rst @@ -58,7 +58,7 @@ 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 + from werkzeug.utils import import_string, cached_property class LazyView(object): @@ -93,7 +93,7 @@ write this by having a function that calls into name and a dot, and by wrapping `view_func` in a `LazyView` as needed. :: def url(http://github.com/import_name,%20url_rules=[],%20**options): - view = LazyView('yourapplication.' + import_name) + view = LazyView(f"yourapplication.{import_name}") for url_rule in url_rules: app.add_url_rule(url_rule, view_func=view, **options) diff --git a/docs/patterns/methodoverrides.rst b/docs/patterns/methodoverrides.rst index d5c187b67c..45dbb87e20 100644 --- a/docs/patterns/methodoverrides.rst +++ b/docs/patterns/methodoverrides.rst @@ -2,14 +2,14 @@ Adding 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 (such as PATCH). In that case it's possible to "proxy" HTTP methods through another HTTP method in total violation of the protocol. The way this works is by letting the client do an HTTP POST request and -set the ``X-HTTP-Method-Override`` header and set the value to the -intended HTTP method (such as ``PATCH``). +set the ``X-HTTP-Method-Override`` header. Then the method is replaced +with the header value before being passed to Flask. -This can easily be accomplished with an HTTP middleware:: +This can be accomplished with an HTTP middleware:: class HTTPMethodOverrideMiddleware(object): allowed_methods = frozenset([ @@ -29,13 +29,12 @@ This can easily be accomplished with an HTTP middleware:: def __call__(self, environ, start_response): method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper() if method in self.allowed_methods: - method = method.encode('ascii', 'replace') environ['REQUEST_METHOD'] = method if method in self.bodyless_methods: environ['CONTENT_LENGTH'] = '0' return self.app(environ, start_response) -To use this with Flask this is all that is necessary:: +To use this with Flask, wrap the app object with the middleware:: from flask import Flask diff --git a/docs/patterns/mongoengine.rst b/docs/patterns/mongoengine.rst new file mode 100644 index 0000000000..624988e423 --- /dev/null +++ b/docs/patterns/mongoengine.rst @@ -0,0 +1,103 @@ +MongoDB 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 = Movie.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. diff --git a/docs/patterns/mongokit.rst b/docs/patterns/mongokit.rst deleted file mode 100644 index 9d1b3e2a96..0000000000 --- a/docs/patterns/mongokit.rst +++ /dev/null @@ -1,144 +0,0 @@ -.. mongokit-pattern: - -MongoKit in Flask -================= - -Using a document database rather than a full DBMS gets more common these days. -This pattern shows how to use MongoKit, a document mapper library, to -integrate with MongoDB. - -This pattern requires a running MongoDB server and the MongoKit library -installed. - -There are two very common ways to use MongoKit. I will outline each of them -here: - - -Declarative ------------ - -The default behavior of MongoKit is the declarative one that is based on -common ideas from Django or the SQLAlchemy declarative extension. - -Here an example :file:`app.py` module for your application:: - - from flask import Flask - from mongokit import Connection, Document - - # configuration - MONGODB_HOST = 'localhost' - MONGODB_PORT = 27017 - - # create the little application object - app = Flask(__name__) - app.config.from_object(__name__) - - # connect to the database - connection = Connection(app.config['MONGODB_HOST'], - app.config['MONGODB_PORT']) - - -To define your models, just subclass the `Document` class that is imported -from MongoKit. If you've seen the SQLAlchemy pattern you may wonder why we do -not have a session and even do not define a `init_db` function here. On the -one hand, MongoKit does not have something like a session. This sometimes -makes it more to type but also makes it blazingly fast. On the other hand, -MongoDB is schemaless. This means you can modify the data structure from one -insert query to the next without any problem. MongoKit is just schemaless -too, but implements some validation to ensure data integrity. - -Here is an example document (put this also into :file:`app.py`, e.g.):: - - from mongokit import ValidationError - - def max_length(length): - def validate(value): - if len(value) <= length: - return True - # must have %s in error format string to have mongokit place key in there - raise ValidationError('%s must be at most {} characters long'.format(length)) - return validate - - class User(Document): - structure = { - 'name': unicode, - 'email': unicode, - } - validators = { - 'name': max_length(50), - 'email': max_length(120) - } - use_dot_notation = True - def __repr__(self): - return '' % (self.name) - - # register the User document with our current connection - connection.register([User]) - - -This example shows you how to define your schema (named structure), a -validator for the maximum character length and uses a special MongoKit feature -called `use_dot_notation`. Per default MongoKit behaves like a python -dictionary but with `use_dot_notation` set to ``True`` you can use your -documents like you use models in nearly any other ORM by using dots to -separate between attributes. - -You can insert entries into the database like this: - ->>> from yourapplication.database import connection ->>> from yourapplication.models import User ->>> collection = connection['test'].users ->>> user = collection.User() ->>> user['name'] = u'admin' ->>> user['email'] = u'admin@localhost' ->>> user.save() - -Note that MongoKit is kinda strict with used column types, you must not use a -common `str` type for either `name` or `email` but unicode. - -Querying is simple as well: - ->>> list(collection.User.find()) -[] ->>> collection.User.find_one({'name': u'admin'}) - - -.. _MongoKit: http://bytebucket.org/namlook/mongokit/ - - -PyMongo Compatibility Layer ---------------------------- - -If you just want to use PyMongo, you can do that with MongoKit as well. You -may use this process if you need the best performance to get. Note that this -example does not show how to couple it with Flask, see the above MongoKit code -for examples:: - - from MongoKit import Connection - - connection = Connection() - -To insert data you can use the `insert` method. We have to get a -collection first, this is somewhat the same as a table in the SQL world. - ->>> collection = connection['test'].users ->>> user = {'name': u'admin', 'email': u'admin@localhost'} ->>> collection.insert(user) - -MongoKit will automatically commit for us. - -To query your database, you use the collection directly: - ->>> list(collection.find()) -[{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}] ->>> collection.find_one({'name': u'admin'}) -{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'} - -These results are also dict-like objects: - ->>> r = collection.find_one({'name': u'admin'}) ->>> r['email'] -u'admin@localhost' - -For more information about MongoKit, head over to the -`website `_. diff --git a/docs/patterns/packages.rst b/docs/patterns/packages.rst index 1cd7797420..90fa8a8f49 100644 --- a/docs/patterns/packages.rst +++ b/docs/patterns/packages.rst @@ -1,11 +1,7 @@ -.. _larger-applications: +Large Applications as Packages +============================== -Larger Applications -=================== - -For larger applications it's a good idea to use a package instead of a -module. That is quite simple. Imagine a small application looks like -this:: +Imagine a simple flask application structure that looks like this:: /yourapplication yourapplication.py @@ -17,6 +13,11 @@ this:: 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 :doc:`/tutorial/index` is structured to use the package pattern, +see the :gh:`example code `. + Simple Packages --------------- @@ -41,36 +42,34 @@ You should then end up with something like that:: 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:: +a big problem, just add a new file called :file:`pyproject.toml` next to the inner +:file:`yourapplication` folder with the following contents: + +.. code-block:: toml - from setuptools import setup + [project] + name = "yourapplication" + dependencies = [ + "flask", + ] - setup( - name='yourapplication', - packages=['yourapplication'], - include_package_data=True, - install_requires=[ - 'flask', - ], - ) + [build-system] + requires = ["flit_core<4"] + build-backend = "flit_core.buildapi" -In order to run the application you need to export an environment variable -that tells Flask where to find the application instance:: +Install your application so it is importable: - export FLASK_APP=yourapplication +.. code-block:: text -If you are outside of the project directory make sure to provide the exact -path to your application directory. Similiarly you can turn on "debug -mode" with this environment variable:: + $ pip install -e . - export FLASK_DEBUG=true +To use the ``flask`` command and run your application you need to set +the ``--app`` option that tells Flask where to find the application +instance: -In order to install and run the application you need to issue the following -commands:: +.. code-block:: text - pip install -e . - flask run + $ flask --app yourapplication 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 @@ -102,7 +101,7 @@ And this is what :file:`views.py` would look like:: You should then end up with something like that:: /yourapplication - setup.py + pyproject.toml /yourapplication __init__.py views.py @@ -124,12 +123,6 @@ You should then end up with something like that:: 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 ----------------------- @@ -137,4 +130,4 @@ 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. +:doc:`/blueprints` chapter of the documentation. diff --git a/docs/patterns/requestchecksum.rst b/docs/patterns/requestchecksum.rst index 902be64ab8..25bc38b2a4 100644 --- a/docs/patterns/requestchecksum.rst +++ b/docs/patterns/requestchecksum.rst @@ -52,4 +52,4 @@ Example usage:: files = request.files # At this point the hash is fully constructed. checksum = hash.hexdigest() - return 'Hash was: %s' % checksum + return f"Hash was: {checksum}" diff --git a/docs/patterns/singlepageapplications.rst b/docs/patterns/singlepageapplications.rst new file mode 100644 index 0000000000..1cb779b33b --- /dev/null +++ b/docs/patterns/singlepageapplications.rst @@ -0,0 +1,24 @@ +Single-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', static_url_path="/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") diff --git a/docs/patterns/sqlalchemy.rst b/docs/patterns/sqlalchemy.rst index 40e048e003..7e4108d068 100644 --- a/docs/patterns/sqlalchemy.rst +++ b/docs/patterns/sqlalchemy.rst @@ -1,12 +1,10 @@ -.. _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. +and drop the models into a separate module (:doc:`packages`). 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: @@ -20,9 +18,9 @@ there is a Flask extension that handles that for you. This is recommended if you want to get started quickly. You can download `Flask-SQLAlchemy`_ from `PyPI -`_. +`_. -.. _Flask-SQLAlchemy: http://pythonhosted.org/Flask-SQLAlchemy/ +.. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/ Declarative @@ -36,10 +34,9 @@ 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 + from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base - engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) + engine = create_engine('sqlite:////tmp/test.db') db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) @@ -86,7 +83,7 @@ Here is an example model (put this into :file:`models.py`, e.g.):: self.email = email def __repr__(self): - return '' % (self.name) + return f'' To create the database you can use the `init_db` function: @@ -104,13 +101,12 @@ You can insert entries into the database like this: Querying is simple as well: >>> User.query.all() -[] +[] >>> User.query.filter(User.name == 'admin').first() - + -.. _SQLAlchemy: http://www.sqlalchemy.org/ -.. _declarative: - http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/ +.. _SQLAlchemy: https://www.sqlalchemy.org/ +.. _declarative: https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/ Manual Object Relational Mapping -------------------------------- @@ -127,7 +123,7 @@ 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) + engine = create_engine('sqlite:////tmp/test.db') metadata = MetaData() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, @@ -135,7 +131,7 @@ Here is an example :file:`database.py` module for your application:: def init_db(): metadata.create_all(bind=engine) -As for the declarative approach you need to close the session after +As in the declarative approach, you need to close the session after each request or application context shutdown. Put this into your application module:: @@ -159,7 +155,7 @@ Here is an example table and model (put this into :file:`models.py`):: self.email = email def __repr__(self): - return '' % (self.name) + return f'' users = Table('users', metadata, Column('id', Integer, primary_key=True), @@ -179,7 +175,7 @@ you basically only need the engine:: from sqlalchemy import create_engine, MetaData, Table - engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) + engine = create_engine('sqlite:////tmp/test.db') metadata = MetaData(bind=engine) Then you can either declare the tables in your code like in the examples @@ -200,19 +196,19 @@ 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') +(1, 'admin', 'admin@localhost') These results are also dict-like tuples: >>> r = users.select(users.c.id == 1).execute().first() >>> r['name'] -u'admin' +'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') +(1, 'admin', 'admin@localhost') For more information about SQLAlchemy, head over to the -`website `_. +`website `_. diff --git a/docs/patterns/sqlite3.rst b/docs/patterns/sqlite3.rst index 66a7c4c45f..5932589ffa 100644 --- a/docs/patterns/sqlite3.rst +++ b/docs/patterns/sqlite3.rst @@ -1,10 +1,8 @@ -.. _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 +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:: @@ -32,10 +30,6 @@ 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('/') @@ -62,16 +56,15 @@ the application context by hand:: with app.app_context(): # now you can use get_db() -.. _easy-querying: Easy Querying ------------- -Now in each request handling function you can access `g.db` to get the +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`` +dictionaries instead of tuples, this could be inserted into the ``get_db`` function we created above:: def make_dicts(cursor, row): @@ -102,36 +95,36 @@ This would use Row objects rather than dicts to return the results of queries. T 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 +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'] + 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' + print('No such user') else: - print the_username, 'has the id', user['user_id'] + 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 --------------- diff --git a/docs/patterns/streaming.rst b/docs/patterns/streaming.rst index f5bff3ca01..c9e6ef22be 100644 --- a/docs/patterns/streaming.rst +++ b/docs/patterns/streaming.rst @@ -15,14 +15,12 @@ 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') + yield f"{','.join(row)}\n" + return generate(), {"Content-Type": "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 @@ -31,54 +29,57 @@ 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. +The Jinja2 template engine supports rendering a template piece by +piece, returning an iterator of strings. Flask provides the +:func:`~flask.stream_template` and :func:`~flask.stream_template_string` +functions to make this easier to use. + +.. code-block:: python + + from flask import stream_template + + @app.get("/timeline") + def timeline(): + return stream_template("timeline.html") + +The parts yielded by the render stream tend to match statement blocks in +the template. + Streaming with Context ---------------------- -.. versionadded:: 0.9 +The :data:`~flask.request` will not be active while the generator is +running, because the view has already returned at that point. If you try +to access ``request``, you'll get a ``RuntimeError``. -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:: +If your generator function relies on data in ``request``, use the +:func:`~flask.stream_with_context` wrapper. This will keep the request +context active during the generator. - from flask import stream_with_context, request, Response +.. code-block:: python + + from flask import stream_with_context, request + from markupsafe import escape @app.route('/stream') def streamed_response(): def generate(): - yield 'Hello ' - yield request.args['name'] - yield '!' - return Response(stream_with_context(generate())) + yield '

Hello ' + yield escape(request.args['name']) + yield '!

' + return stream_with_context(generate()) + +It can also be used as a decorator. + +.. code-block:: python + + @stream_with_context + def generate(): + ... + + return generate() -Without the :func:`~flask.stream_with_context` function you would get a -:class:`RuntimeError` at that point. +The :func:`~flask.stream_template` and +:func:`~flask.stream_template_string` functions automatically +use :func:`~flask.stream_with_context` if a request is active. diff --git a/docs/patterns/templateinheritance.rst b/docs/patterns/templateinheritance.rst index dbcb4163c7..bb5cba2706 100644 --- a/docs/patterns/templateinheritance.rst +++ b/docs/patterns/templateinheritance.rst @@ -1,5 +1,3 @@ -.. _template-inheritance: - Template Inheritance ==================== diff --git a/docs/patterns/urlprocessors.rst b/docs/patterns/urlprocessors.rst index 3f65d75876..0d743205fd 100644 --- a/docs/patterns/urlprocessors.rst +++ b/docs/patterns/urlprocessors.rst @@ -39,8 +39,8 @@ 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 +come in. They can automatically inject values into a call to +:func:`~flask.url_for`. 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'``:: diff --git a/docs/patterns/viewdecorators.rst b/docs/patterns/viewdecorators.rst index 7fd97dca4f..0b0479ef81 100644 --- a/docs/patterns/viewdecorators.rst +++ b/docs/patterns/viewdecorators.rst @@ -59,7 +59,7 @@ 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`. +assuming you have set up a cache like mentioned in :doc:`caching`. 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 @@ -70,7 +70,7 @@ 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 +1. get the unique cache key for the current request based on the current path. 2. get the value for that key from the cache. If the cache returned something we will return that value. @@ -82,11 +82,11 @@ Here the code:: from functools import wraps from flask import request - def cached(timeout=5 * 60, key='view/%s'): + def cached(timeout=5 * 60, key='view/{}'): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): - cache_key = key % request.path + cache_key = key.format(request.path) rv = cache.get(cache_key) if rv is not None: return rv @@ -96,8 +96,8 @@ Here the code:: return decorated_function return decorator -Notice that this assumes an instantiated `cache` object is available, see -:ref:`caching-pattern` for more information. +Notice that this assumes an instantiated ``cache`` object is available, see +:doc:`caching`. Templating Decorator @@ -142,8 +142,7 @@ Here is the code for that decorator:: def decorated_function(*args, **kwargs): template_name = template if template_name is None: - template_name = request.endpoint \ - .replace('.', '/') + '.html' + template_name = f"{request.endpoint.replace('.', '/')}.html" ctx = f(*args, **kwargs) if ctx is None: ctx = {} diff --git a/docs/patterns/wtforms.rst b/docs/patterns/wtforms.rst index 2649cad699..3d626f5084 100644 --- a/docs/patterns/wtforms.rst +++ b/docs/patterns/wtforms.rst @@ -9,7 +9,7 @@ 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 +(:doc:`packages`) for that and adding a separate module for the forms. .. admonition:: Getting the most out of WTForms with an Extension @@ -17,9 +17,9 @@ forms. 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: http://pythonhosted.org/Flask-WTF/ +.. _Flask-WTF: https://flask-wtf.readthedocs.io/ The Forms --------- @@ -55,7 +55,7 @@ In the view function, the usage of this form looks like this:: 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 +(:doc:`sqlalchemy`), but that's not a requirement, of course. Adapt the code as necessary. Things to remember: @@ -98,9 +98,9 @@ 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. +the input element. Note that WTForms returns standard Python 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: diff --git a/docs/python3.rst b/docs/python3.rst deleted file mode 100644 index a7a4f1651e..0000000000 --- a/docs/python3.rst +++ /dev/null @@ -1,23 +0,0 @@ -.. _python3-support: - -Python 3 Support -================ - -Flask, its dependencies, and most Flask extensions support Python 3. -You should start using Python 3 for your next project, -but there are a few things to be aware of. - -You need to use Python 3.3 or higher. 3.2 and older are *not* supported. - -You should use the latest versions of all Flask-related packages. -Flask 0.10 and Werkzeug 0.9 were the first versions to introduce Python 3 support. - -Python 3 changed how unicode and bytes are handled, which complicates how low -level code handles HTTP data. This mainly affects WSGI middleware interacting -with the WSGI ``environ`` data. Werkzeug wraps that information in high-level -helpers, so encoding issues should not affect you. - -The majority of the upgrade work is in the lower-level libraries like -Flask and Werkzeug, not the high-level application code. -For example, all of the examples in the Flask repository work on both Python 2 and 3 -and did not require a single line of code changed. diff --git a/docs/quickstart.rst b/docs/quickstart.rst index b444e080b5..f763bb1e06 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -1,69 +1,70 @@ -.. _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. +Eager to get started? This page gives a good introduction to Flask. +Follow :doc:`installation` to set up a project and install Flask first. A Minimal Application --------------------- -A minimal Flask application looks something like this:: +A minimal Flask application looks something like this: + +.. code-block:: python from flask import Flask + app = Flask(__name__) - @app.route('/') + @app.route("/") def hello_world(): - return '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 +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. ``__name__`` is a + convenient shortcut for this that is appropriate for most cases. + This is needed so that Flask knows where to look for resources such + as templates and static files. +3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask + what URL should trigger our function. +4. The function returns the message we want to display in the user's + browser. The default content type is HTML, so HTML in the string + will be rendered by the browser. + +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:: +To run the application, use the ``flask`` command or +``python -m flask``. You need to tell the Flask where your application +is with the ``--app`` option. + +.. code-block:: text - $ export FLASK_APP=hello.py - $ flask run - * Running on http://127.0.0.1:5000/ + $ flask --app hello run + * Serving Flask app 'hello' + * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) -If you are on Windows you need to use ``set`` instead of ``export``. +.. admonition:: Application Discovery Behavior -Alternatively you can use :command:`python -m flask`:: + As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you + don't have to use ``--app``. See :doc:`/cli` for more details. - $ 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 :doc:`deploying/index`. -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. -Now head over to `http://127.0.0.1:5000/ `_, and you -should see your hello world greeting. +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. .. _public-server: @@ -78,95 +79,88 @@ should see your hello world greeting. 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 + $ 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. +Debug Mode +---------- -Invalid Import Name -``````````````````` +The ``flask run`` command can do more than just start the development +server. By enabling debug mode, the server will automatically reload if +code changes, and will show an interactive debugger in the browser if an +error occurs during a request. -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. +.. image:: _static/debugger.png + :align: center + :class: screenshot + :alt: The interactive debugger in action. -The most common reason is a typo or because you did not actually create an -``app`` object. +.. warning:: -.. _debug-mode: + The debugger allows executing arbitrary Python code from the + browser. It is protected by a pin, but still represents a major + security risk. Do not run the development server or debugger in a + production environment. -Debug Mode ----------- +To enable debug mode, use the ``--debug`` option. -(Want to just log errors and stack traces? See :ref:`application-errors`) +.. code-block:: text -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. + $ flask --app hello run --debug + * Serving Flask app 'hello' + * Debug mode: on + * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) + * Restarting with stat + * Debugger is active! + * Debugger PIN: nnn-nnn-nnn -To enable debug mode you can export the ``FLASK_DEBUG`` environment variable -before running the server:: +See also: - $ export FLASK_DEBUG=1 - $ flask run +- :doc:`/server` and :doc:`/cli` for information about running in debug mode. +- :doc:`/debugging` for information about using the built-in debugger + and other debuggers. +- :doc:`/logging` and :doc:`/errorhandling` to log errors and display + nice error pages. -(On Windows you need to use ``set`` instead of ``export``). -This does the following things: +HTML Escaping +------------- -1. it activates the debugger -2. it activates the automatic reloader -3. it enables the debug mode on the Flask application. +When returning HTML (the default response type in Flask), any +user-provided values rendered in the output must be escaped to protect +from injection attacks. HTML templates rendered with Jinja, introduced +later, will do this automatically. -There are more parameters that are explained in the :ref:`server` docs. +:func:`~markupsafe.escape`, shown here, can be used manually. It is +omitted in most examples for brevity, but you should always be aware of +how you're using untrusted data. -.. admonition:: Attention +.. code-block:: python - 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**. + from markupsafe import escape -Screenshot of the debugger in action: + @app.route("/") + def hello(name): + return f"Hello, {escape(name)}!" -.. image:: _static/debugger.png - :align: center - :class: screenshot - :alt: screenshot of debugger in action +If a user managed to submit the name ````, +escaping causes it to be rendered as text, rather than running the +script in the user's browser. -Have another debugger in mind? See :ref:`working-with-debuggers`. +```` in the route captures a value from the URL and passes it to +the view function. These variable rules are explained below. Routing ------- -Modern web applications have beautiful URLs. This helps people remember -the URLs, which is especially handy for applications that are used from -mobile devices with slower network connections. If the user can directly -go to the desired page without having to hit the index page it is more -likely they will like the page and come back next time. +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. -As you have seen above, the :meth:`~flask.Flask.route` decorator is used to -bind a function to a URL. Here are some basic examples:: +Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. :: @app.route('/') def index(): @@ -176,68 +170,68 @@ bind a function to a URL. Here are some basic examples:: def hello(): return 'Hello, World' -But there is more to it! You can make certain parts of the URL dynamic and -attach multiple rules to a function. +You can do more! You can make parts of the URL dynamic and attach multiple +rules to a function. Variable Rules `````````````` -To add variable parts to a URL you can mark these special sections as -````. Such a part is then passed as a keyword argument to your -function. Optionally a converter can be used by specifying a rule with -````. Here are some nice examples:: +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 ````. :: + + from markupsafe import escape @app.route('/user/') def show_user_profile(username): # show the user profile for that user - return 'User %s' % username + return f'User {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 + return f'Post {post_id}' -The following converters exist: + @app.route('/path/') + def show_subpath(subpath): + # show the subpath after /path/ + return f'Subpath {escape(subpath)}' -=========== =============================================== -`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 -=========== =============================================== +Converter types: -.. admonition:: Unique URLs / Redirection Behavior +========== ========================================== +``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 +========== ========================================== - Flask's URL rules are based on Werkzeug's routing module. The idea - behind that module is to ensure beautiful and unique URLs based on - precedents laid down by Apache and earlier HTTP servers. - Take these two rules:: +Unique URLs / Redirection Behavior +`````````````````````````````````` - @app.route('/projects/') - def projects(): - return 'The project page' +The following two rules differ in their use of a trailing slash. :: - @app.route('/about') - def about(): - return 'The about page' + @app.route('/projects/') + def projects(): + return 'The project page' - Though they look rather similar, they differ in their use of the trailing - slash in the URL *definition*. In the first case, the canonical URL for the - ``projects`` endpoint has a trailing slash. In that sense, it is similar to - a folder on a filesystem. Accessing it without a trailing slash will cause - Flask to redirect to the canonical URL with the trailing slash. + @app.route('/about') + def about(): + return 'The about page' - In the second case, however, the URL is defined without a trailing slash, - rather like the pathname of a file on UNIX-like systems. Accessing the URL - with a trailing slash will produce a 404 "Not Found" error. +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 (``/projects``), Flask redirects you to the canonical URL +with the trailing slash (``/projects/``). - This behavior allows relative URLs to continue working even if the trailing - slash is omitted, consistent with how Apache and other servers work. Also, - the URLs will stay unique, which helps search engines avoid indexing the - same page twice. +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 (``/about/``) 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: @@ -245,129 +239,100 @@ The following converters exist: URL Building ```````````` -If it can match URLs, can Flask also generate them? Of course it can. To -build a URL to a specific function you can use the :func:`~flask.url_for` -function. It accepts the name of the function as first argument and a number -of keyword arguments, each corresponding to the variable part of the URL rule. -Unknown variable parts are appended to the URL as query parameters. Here are -some examples:: - - >>> from flask import Flask, url_for - >>> app = Flask(__name__) - >>> @app.route('/') - ... def index(): pass - ... - >>> @app.route('/login') - ... def login(): pass - ... - >>> @app.route('/user/') - ... def profile(username): pass - ... - >>> 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') - ... - / - /login - /login?next=/ - /user/John%20Doe - -(This also uses the :meth:`~flask.Flask.test_request_context` method, explained -below. It tells Flask to behave as though it is handling a request, even -though we are interacting with it through a Python shell. Have a look at the -explanation below. :ref:`context-locals`). +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? -There are three good reasons for this: -1. Reversing is often more descriptive than hard-coding the URLs. More - importantly, it allows you to change URLs in one go, without having to - remember to change URLs all over the place. -2. URL building will handle escaping of special characters and Unicode - data transparently for you, so you don't have to deal with them. -3. If your application is placed outside the URL root - say, in - ``/myapplication`` instead of ``/`` - :func:`~flask.url_for` will handle - that properly for you. +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 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 url_for + + @app.route('/') + def index(): + return 'index' + + @app.route('/login') + def login(): + return 'login' + + @app.route('/user/') + def profile(username): + return f'{username}\'s profile' + + 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 ```````````` -HTTP (the protocol web applications are speaking) knows different methods for -accessing URLs. By default, a route only answers to ``GET`` requests, but that -can be changed by providing the ``methods`` argument to the -:meth:`~flask.Flask.route` decorator. Here are some examples:: +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': - do_the_login() + return do_the_login() else: - show_the_login_form() - -If ``GET`` is present, ``HEAD`` will be added automatically for you. You -don't have to deal with that. It will also make sure that ``HEAD`` requests -are handled as the `HTTP RFC`_ (the document describing the HTTP -protocol) demands, so you can completely ignore that part of the HTTP -specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you -automatically as well. - -You have no idea what an HTTP method is? Worry not, here is a quick -introduction to HTTP methods and why they matter: - -The HTTP method (also often called "the verb") tells the server what the -client wants to *do* with the requested page. The following methods are -very common: - -``GET`` - The browser tells the server to just *get* the information stored on - that page and send it. This is probably the most common method. - -``HEAD`` - The browser tells the server to get the information, but it is only - interested in the *headers*, not the content of the page. An - application is supposed to handle that as if a ``GET`` request was - received but to not deliver the actual content. In Flask you don't - have to deal with that at all, the underlying Werkzeug library handles - that for you. - -``POST`` - The browser tells the server that it wants to *post* some new - information to that URL and that the server must ensure the data is - stored and only stored once. This is how HTML forms usually - transmit data to the server. - -``PUT`` - Similar to ``POST`` but the server might trigger the store procedure - multiple times by overwriting the old values more than once. Now you - might be asking why this is useful, but there are some good reasons - to do it this way. Consider that the connection is lost during - transmission: in this situation a system between the browser and the - server might receive the request safely a second time without breaking - things. With ``POST`` that would not be possible because it must only - be triggered once. - -``DELETE`` - Remove the information at the given location. - -``OPTIONS`` - Provides a quick way for a client to figure out which methods are - supported by this URL. Starting with Flask 0.6, this is implemented - for you automatically. - -Now the interesting part is that in HTML4 and XHTML1, the only methods a -form can submit to the server are ``GET`` and ``POST``. But with JavaScript -and future HTML standards you can use the other methods as well. Furthermore -HTTP has become quite popular lately and browsers are no longer the only -clients that are using HTTP. For instance, many revision control systems -use it. - -.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt + return show_the_login_form() + +The example above keeps all methods for the route within one function, +which can be useful if each part uses some common data. + +You can also separate views for different methods into different +functions. Flask provides a shortcut for decorating such routes with +:meth:`~flask.Flask.get`, :meth:`~flask.Flask.post`, etc. for each +common HTTP method. + +.. code-block:: python + + @app.get('/login') + def login_get(): + return show_the_login_form() + + @app.post('/login') + def login_post(): + return do_the_login() + +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 ------------ @@ -390,7 +355,15 @@ 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. +`_ template engine for you automatically. + +Templates can be used to generate any type of text file. For web applications, you'll +primarily be generating HTML pages, but you can also generate markdown, plain text for +emails, and anything else. + +For a reference to HTML, CSS, and other web APIs, use the `MDN Web Docs`_. + +.. _MDN Web Docs: https://developer.mozilla.org/ 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 @@ -402,7 +375,7 @@ Here's a simple example of how to render a template:: @app.route('/hello/') @app.route('/hello/') def hello(name=None): - return render_template('hello.html', name=name) + return render_template('hello.html', person=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 @@ -423,7 +396,7 @@ package it's actually inside your package: For templates you can use the full power of Jinja2 templates. Head over to the official `Jinja2 Template Documentation -`_ for more information. +`_ for more information. Here is an example template: @@ -431,37 +404,37 @@ Here is an example template: Hello from Flask - {% if name %} -

Hello {{ name }}!

+ {% if person %} +

Hello {{ person }}!

{% 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. +Inside templates you also have access to the :data:`~flask.Flask.config`, +:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects +as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions. 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). +know how that works, see :doc:`patterns/templateinheritance`. 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 +Automatic escaping is enabled, so if ``person`` 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 +:class:`~markupsafe.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:: +Here is a basic introduction to how the :class:`~markupsafe.Markup` class works:: - >>> from flask import Markup + >>> from markupsafe import Markup >>> Markup('Hello %s!') % 'hacker' - Markup(u'Hello <blink>hacker</blink>!') + Markup('Hello <blink>hacker</blink>!') >>> Markup.escape('hacker') - Markup(u'<blink>hacker</blink>') + Markup('<blink>hacker</blink>') >>> Markup('Marked up » HTML').striptags() - u'Marked up \xbb HTML' + 'Marked up » HTML' .. versionchanged:: 0.5 @@ -471,9 +444,8 @@ Here is a basic introduction to how the :class:`~jinja2.Markup` class works:: 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. + you can store information for your own needs. See the documentation + for :class:`flask.g` and :doc:`patterns/sqlite3`. Accessing Request Data @@ -529,8 +501,6 @@ test request so that you can interact with it. Here is an example:: 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' @@ -538,16 +508,16 @@ 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 +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 +: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 +:attr:`~flask.Request.form` attribute. Here is a full example of the two attributes mentioned above:: @app.route('/login', methods=['POST', 'GET']) @@ -570,7 +540,7 @@ 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:: +:attr:`~flask.Request.args` attribute:: searchword = request.args.get('key', '') @@ -579,7 +549,7 @@ We recommend accessing URL parameters with `get` or by catching the 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. +to the :class:`~flask.Request` documentation. File Uploads @@ -594,9 +564,9 @@ 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:: +: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 @@ -609,23 +579,23 @@ that works:: 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 +: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)) + file = request.files['the_file'] + file.save(f"/var/www/uploads/{secure_filename(file.filename)}") ... -For some better examples, checkout the :ref:`uploading-files` pattern. +For some better examples, see :doc:`patterns/fileuploads`. Cookies ``````` @@ -665,7 +635,7 @@ 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. +:doc:`patterns/deferredcallbacks` pattern. For this also see :ref:`about-responses`. @@ -705,29 +675,36 @@ 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. +See :doc:`errorhandling` 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. The logic that Flask applies to -converting return values into response objects is as follows: +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 or list, :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 a tuple is returned the items in the tuple can provide extra - information. Such tuples have to be in the form ``(response, status, - headers)`` or ``(response, headers)`` where at least one item has - to be in the tuple. The ``status`` value will override the status code - and ``headers`` can be a list or dictionary of additional header values. -4. If none of that works, Flask will assume the return value is a +2. If it's a string, a response object is created with that data and + the default parameters. +3. If it's an iterator or generator returning strings or bytes, it is + treated as a streaming response. +4. If it's a dict or list, a response object is created using + :func:`~flask.json.jsonify`. +5. 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. +6. 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 @@ -735,6 +712,8 @@ you can use the :func:`~flask.make_response` function. Imagine you have a view like this:: + from flask import render_template + @app.errorhandler(404) def not_found(error): return render_template('error.html'), 404 @@ -743,12 +722,49 @@ You just need to wrap the return expression with :func:`~flask.make_response` and get the response object to modify it, then return it:: + from flask import make_response + @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`` or +``list`` 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), + } + + @app.route("/users") + def users_api(): + users = get_all_users() + return [user.to_json() for user in users] + +This is a shortcut to passing the data to the +:func:`~flask.json.jsonify` function, which will serialize any supported +JSON data type. That means that all the data in the dict or list must be +JSON serializable. + +For complex types such as database models, you'll want to use a +serialization library to convert the data to valid JSON types first. +There are many serialization libraries and Flask API extensions +maintained by the community that support more complex applications. + + .. _sessions: Sessions @@ -764,14 +780,15 @@ 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 + from flask import session - 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 f'Logged in as {session["username"]}' return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) @@ -792,24 +809,15 @@ sessions work:: session.pop('username', None) return redirect(url_for('index')) - # set the secret key. keep this really secret: - app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' - -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 - The problem with random is that it's hard to judge what is truly random. And - a secret key should be as random as possible. Your operating system - has ways to generate pretty random stuff based on a cryptographic - random generator which can be used to get such a key:: + 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`):: - >>> import os - >>> os.urandom(24) - '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O`_ for more -information. +:class:`~logging.Logger`, so head over to the official :mod:`logging` +docs for more information. + +See :doc:`errorhandling`. + + +Hooking in WSGI Middleware +-------------------------- -Read more on :ref:`application-errors`. +To add WSGI middleware to your Flask application, wrap the application's +``wsgi_app`` attribute. For example, to apply Werkzeug's +:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running +behind Nginx: -Hooking in WSGI Middlewares ---------------------------- +.. code-block:: python -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.middleware.proxy_fix import ProxyFix + app.wsgi_app = ProxyFix(app.wsgi_app) - from werkzeug.contrib.fixers import LighttpdCGIRootFix - app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app) +Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still +points at your Flask application, not at the middleware, so you can +continue to use and configure ``app`` directly. Using Flask Extensions ---------------------- @@ -885,9 +899,9 @@ 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`. +For more on Flask extensions, see :doc:`extensions`. Deploying to a Web Server ------------------------- -Ready to deploy your new Flask app? Go to :ref:`deployment`. +Ready to deploy your new Flask app? See :doc:`deploying/index`. diff --git a/docs/reqcontext.rst b/docs/reqcontext.rst index 51cd66f6da..4f1846a346 100644 --- a/docs/reqcontext.rst +++ b/docs/reqcontext.rst @@ -1,223 +1,243 @@ -.. _request-context: +.. currentmodule:: flask The Request Context =================== -This document describes the behavior in Flask 0.7 which is mostly in line -with the old behavior but has some small, subtle differences. +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. -It is recommended that you read the :ref:`app-context` chapter first. +This is similar to :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. -Diving into Context Locals --------------------------- -Say you have a utility function that returns the URL the user should be -redirected to. Imagine it would always redirect to the URL's ``next`` -parameter or the HTTP referrer or the index page:: +Purpose of the Context +---------------------- - from flask import request, url_for +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. - def redirect_url(): - return request.args.get('next') or \ - request.referrer or \ - url_for('index') +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. -As you can see, it accesses the request object. If you try to run this -from a plain Python shell, this is the exception you will see: ->>> redirect_url() -Traceback (most recent call last): - File "", line 1, in -AttributeError: 'NoneType' object has no attribute 'request' +Lifetime of the Context +----------------------- -That makes a lot of sense because we currently do not have a request we -could access. So we have to make a request and bind it to the current -context. The :attr:`~flask.Flask.test_request_context` method can create -us a :class:`~flask.ctx.RequestContext`: +When a Flask application begins handling a request, it pushes a request +context, which also pushes an :doc:`app context `. When the +request ends it pops the request context then the application context. ->>> ctx = app.test_request_context('/?next=http://example.com/') +The context is unique to each thread (or other worker type). +:data:`request` cannot be passed to another thread, the other thread has +a different context space and will not know about the request the parent +thread was pointing to. -This context can be used in two ways. Either with the ``with`` statement -or by calling the :meth:`~flask.ctx.RequestContext.push` and -:meth:`~flask.ctx.RequestContext.pop` methods: +Context locals are implemented using Python's :mod:`contextvars` and +Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the +lifetime of context vars automatically, and local proxy wraps that +low-level interface to make the data easier to work with. ->>> ctx.push() -From that point onwards you can work with the request object: +Manually Push a Context +----------------------- ->>> redirect_url() -u'http://example.com/' +If you try to access :data:`request`, or anything that uses it, outside +a request context, you'll get this error message: -Until you call `pop`: +.. code-block:: pytb ->>> ctx.pop() + RuntimeError: Working outside of request context. -Because the request context is internally maintained as a stack you can -push and pop multiple times. This is very handy to implement things like -internal redirects. + 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", query_string={"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`. -For more information of how to utilize the request context from the -interactive Python shell, head over to the :ref:`shell` chapter. How the Context Works --------------------- -If you look into how the Flask WSGI application internally works, you will -find a piece of code that looks very much like this:: - - def wsgi_app(self, environ): - with self.request_context(environ): - try: - response = self.full_dispatch_request() - except Exception as e: - response = self.make_response(self.handle_exception(e)) - return response(environ, start_response) - -The method :meth:`~Flask.request_context` returns a new -:class:`~flask.ctx.RequestContext` object and uses it in combination with -the ``with`` statement to bind the context. Everything that is called from -the same thread from this point onwards until the end of the ``with`` -statement will have access to the request globals (:data:`flask.request` -and others). - -The request context internally works like a stack: The topmost level on -the stack is the current active request. -:meth:`~flask.ctx.RequestContext.push` adds the context to the stack on -the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the -stack again. On popping the application's -:func:`~flask.Flask.teardown_request` functions are also executed. - -Another thing of note is that the request context will automatically also -create an :ref:`application context ` when it's pushed and -there is no application context for that application so far. +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 like stacks. When contexts are pushed, the +proxies that depend on them are available and point at information from +the top item. + +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. + +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 executed. These +execute even if an unhandled exception occurred during dispatch. + .. _callbacks-and-errors: Callbacks and Errors -------------------- -What happens if an error occurs in Flask during request processing? This -particular behavior changed in 0.7 because we wanted to make it easier to -understand what is actually happening. The new behavior is quite simple: +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. -1. Before each request, :meth:`~flask.Flask.before_request` functions are - executed. If one of these functions return a response, the other - functions are no longer called. In any case however the return value - is treated as a replacement for the view's return value. +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. -2. If the :meth:`~flask.Flask.before_request` functions did not return a - response, the regular request handling kicks in and the view function - that was matched has the chance to return a response. +#. 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. -3. The return value of the view is then converted into an actual response - object and handed over to the :meth:`~flask.Flask.after_request` - functions which have the chance to replace it or modify it in place. +#. 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. -4. At the end of the request the :meth:`~flask.Flask.teardown_request` - functions are executed. This always happens, even in case of an - unhandled exception down the road or if a before-request handler was - not executed yet or at all (for example in test environments sometimes - you might want to not execute before-request callbacks). +#. 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. -Now what happens on errors? In production mode if an exception is not -caught, the 500 internal server handler is called. In development mode -however the exception is not further processed and bubbles up to the WSGI -server. That way things like the interactive debugger can provide helpful -debug information. +#. 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. -An important change in 0.7 is that the internal server error is now no -longer post processed by the after request callbacks and after request -callbacks are no longer guaranteed to be executed. This way the internal -dispatching code looks cleaner and is easier to customize and understand. +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. -The new teardown functions are supposed to be used as a replacement for -things that absolutely need to happen at the end of request. Teardown Callbacks ------------------- +~~~~~~~~~~~~~~~~~~ + +The teardown callbacks are 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. +Use the :meth:`~Flask.test_client` as a ``with`` block to preserve the +contexts until the ``with`` block exits. -The teardown callbacks are special callbacks in that they are executed at -a different point. Strictly speaking they are independent of the actual -request handling as they are bound to the lifecycle of the -:class:`~flask.ctx.RequestContext` object. When the request context is -popped, the :meth:`~flask.Flask.teardown_request` functions are called. +.. code-block:: python -This is important to know if the life of the request context is prolonged -by using the test client in a with statement or when using the request -context from the command line:: + 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: - resp = client.get('/foo') - # the teardown functions are still not called at that point - # even though the response ended and you have the response - # object in your hand - - # only when the code reaches this point the teardown functions - # are called. Alternatively the same thing happens if another - # request was triggered from the test client - -It's easy to see the behavior from the command line: - ->>> app = Flask(__name__) ->>> @app.teardown_request -... def teardown_request(exception=None): -... print 'this runs after request' -... ->>> ctx = app.test_request_context() ->>> ctx.push() ->>> ctx.pop() -this runs after request ->>> - -Keep in mind that teardown callbacks are always executed, even if -before-request callbacks were not executed yet but an exception happened. -Certain parts of the test system might also temporarily create a request -context without calling the before-request handlers. Make sure to write -your teardown-request handlers in a way that they will never fail. + 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 exits + +Signals +~~~~~~~ + +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. + .. _notes-on-proxies: Notes On Proxies ---------------- -Some of the objects provided by Flask are proxies to other objects. The -reason behind this is that these proxies are shared between threads and -they have to dispatch to the actual object bound to a thread behind the -scenes as necessary. +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: +exceptions where it is good to know that this object is actually a proxy: -- The proxy objects do not fake their inherited types, so if you want to - perform actual instance checks, you have to do that on the instance - that is being proxied (see `_get_current_object` below). -- if the object reference is important (so for example for sending - :ref:`signals`) +- 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. +- The reference to the proxied object is needed in some situations, + such as sending :doc:`signals` or passing data to a background + thread. -If you need to get access to the underlying object that is proxied, you -can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method:: +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) - -Context Preservation on Error ------------------------------ - -If an error occurs or not, at the end of the request the request context -is popped and all data associated with it is destroyed. During -development however that can be problematic as you might want to have the -information around for a longer time in case an exception occurred. In -Flask 0.6 and earlier in debug mode, if an exception occurred, the -request context was not popped so that the interactive debugger can still -provide you with important information. - -Starting with Flask 0.7 you have finer control over that behavior by -setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By -default it's linked to the setting of ``DEBUG``. If the application is in -debug mode the context is preserved, in production mode it's not. - -Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode -as it will cause your application to leak memory on exceptions. However -it can be useful during development to get the same error preserving -behavior as in development mode when attempting to debug an error that -only occurs under production settings. diff --git a/docs/security.rst b/docs/security.rst deleted file mode 100644 index 587bd4eff2..0000000000 --- a/docs/security.rst +++ /dev/null @@ -1,106 +0,0 @@ -Security Considerations -======================= - -Web applications usually face all kinds of security problems and it's very -hard to get everything right. Flask tries to solve a few of these things -for you, but there are a couple more you have to take care of yourself. - -.. _xss: - -Cross-Site Scripting (XSS) --------------------------- - -Cross site scripting is the concept of injecting arbitrary HTML (and with -it JavaScript) into the context of a website. To remedy this, developers -have to properly escape text so that it cannot include arbitrary HTML -tags. For more information on that have a look at the Wikipedia article -on `Cross-Site Scripting -`_. - -Flask configures Jinja2 to automatically escape all values unless -explicitly told otherwise. This should rule out all XSS problems caused -in templates, but there are still other places where you have to be -careful: - -- generating HTML without the help of Jinja2 -- calling :class:`~flask.Markup` on data submitted by users -- sending out HTML from uploaded files, never do that, use the - ``Content-Disposition: attachment`` header to prevent that problem. -- sending out textfiles from uploaded files. Some browsers are using - content-type guessing based on the first few bytes so users could - trick a browser to execute HTML. - -Another thing that is very important are unquoted attributes. While -Jinja2 can protect you from XSS issues by escaping HTML, there is one -thing it cannot protect you from: XSS by attribute injection. To counter -this possible attack vector, be sure to always quote your attributes with -either double or single quotes when using Jinja expressions in them: - -.. sourcecode:: html+jinja - - the text - -Why is this necessary? Because if you would not be doing that, an -attacker could easily inject custom JavaScript handlers. For example an -attacker could inject this piece of HTML+JavaScript: - -.. sourcecode:: html - - onmouseover=alert(document.cookie) - -When the user would then move with the mouse over the link, the cookie -would be presented to the user in an alert window. But instead of showing -the cookie to the user, a good attacker might also execute any other -JavaScript code. In combination with CSS injections the attacker might -even make the element fill out the entire page so that the user would -just have to have the mouse anywhere on the page to trigger the attack. - -Cross-Site Request Forgery (CSRF) ---------------------------------- - -Another big problem is CSRF. This is a very complex topic and I won't -outline it here in detail just mention what it is and how to theoretically -prevent it. - -If your authentication information is stored in cookies, you have implicit -state management. The state of "being logged in" is controlled by a -cookie, and that cookie is sent with each request to a page. -Unfortunately that includes requests triggered by 3rd party sites. If you -don't keep that in mind, some people might be able to trick your -application's users with social engineering to do stupid things without -them knowing. - -Say you have a specific URL that, when you sent ``POST`` requests to will -delete a user's profile (say ``http://example.com/user/delete``). If an -attacker now creates a page that sends a post request to that page with -some JavaScript they just have to trick some users to load that page and -their profiles will end up being deleted. - -Imagine you were to run Facebook with millions of concurrent users and -someone would send out links to images of little kittens. When users -would go to that page, their profiles would get deleted while they are -looking at images of fluffy cats. - -How can you prevent that? Basically for each request that modifies -content on the server you would have to either use a one-time token and -store that in the cookie **and** also transmit it with the form data. -After receiving the data on the server again, you would then have to -compare the two tokens and ensure they are equal. - -Why does Flask not do that for you? The ideal place for this to happen is -the form validation framework, which does not exist in Flask. - -.. _json-security: - -JSON Security -------------- - -In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level -arrays to JSON. This was because of a security vulnerability in ECMAScript 4. - -ECMAScript 5 closed this vulnerability, so only extremely old browsers are -still vulnerable. All of these browsers have `other more serious -vulnerabilities -`_, so -this behavior was changed and :func:`~flask.jsonify` now supports serializing -arrays. diff --git a/docs/server.rst b/docs/server.rst index f8332ebf04..11e976bc73 100644 --- a/docs/server.rst +++ b/docs/server.rst @@ -1,52 +1,115 @@ -.. _server: +.. currentmodule:: flask Development Server ================== -.. currentmodule:: flask +Flask provides a ``run`` command to run the application with a development server. In +debug mode, this server provides an interactive debugger and will reload when code is +changed. + +.. warning:: + + Do not use the development server when deploying to production. It + is intended for use only during local development. It is not + designed to be particularly efficient, stable, or secure. -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. + See :doc:`/deploying/index` for deployment options. 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:: +The ``flask run`` CLI command is the recommended way to run the development server. Use +the ``--app`` option to point to your application, and the ``--debug`` option to enable +debug mode. + +.. code-block:: text + + $ flask --app hello run --debug + +This enables debug mode, including the interactive debugger and reloader, and then +starts the server on http://localhost:5000/. Use ``flask run --help`` to see the +available options, and :doc:`/cli` for detailed instructions about configuring and using +the CLI. + + +.. _address-already-in-use: + +Address already in use +~~~~~~~~~~~~~~~~~~~~~~ + +If another program is already using port 5000, you'll see an ``OSError`` +when the server tries to start. It may have one of the following +messages: + +- ``OSError: [Errno 98] Address already in use`` +- ``OSError: [WinError 10013] An attempt was made to access a socket + in a way forbidden by its access permissions`` + +Either identify and stop the other program, or use +``flask run --port 5001`` to pick a different port. + +You can use ``netstat`` or ``lsof`` to identify what process id is using +a port, then use other operating system tools stop that process. The +following example shows that process id 6847 is using port 5000. - $ export FLASK_APP=my_application - $ export FLASK_DEBUG=1 - $ flask run +.. tabs:: -This will enable the debugger, the reloader and then start the server on -*http://localhost:5000/*. + .. tab:: ``netstat`` (Linux) -The individual features of the server can be controlled by passing more -arguments to the ``run`` option. For instance the reloader can be -disabled:: + .. code-block:: text + + $ netstat -nlp | grep 5000 + tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 6847/python + + .. tab:: ``lsof`` (macOS / Linux) + + .. code-block:: text + + $ lsof -P -i :5000 + Python 6847 IPv4 TCP localhost:5000 (LISTEN) + + .. tab:: ``netstat`` (Windows) + + .. code-block:: text + + > netstat -ano | findstr 5000 + TCP 127.0.0.1:5000 0.0.0.0:0 LISTENING 6847 + +macOS Monterey and later automatically starts a service that uses port +5000. You can choose to disable this service instead of using a different port by +searching for "AirPlay Receiver" in System Preferences and toggling it off. + + +Deferred Errors on Reload +~~~~~~~~~~~~~~~~~~~~~~~~~ + +When using the ``flask run`` command with the reloader, the server will +continue to run even if you introduce syntax errors or other +initialization errors into the code. Accessing the site will show the +interactive debugger for the error, rather than crashing the server. + +If a syntax error is already present when calling ``flask run``, it will +fail immediately and show the traceback rather than waiting until the +site is accessed. This is intended to make errors more visible initially +while still allowing the server to handle errors on reload. - $ flask run --no-reload In Code ------- -The alternative way to start the application is through the -:meth:`Flask.run` method. This will immediately launch a local server -exactly the same way the :command:`flask` script does. +The development server can also be started from Python with the :meth:`Flask.run` +method. This method takes arguments similar to the CLI options to control the server. +The main difference from the CLI command is that the server will crash if there are +errors when reloading. ``debug=True`` can be passed to enable debug mode. + +Place the call in a main block, otherwise it will interfere when trying to import and +run the application with a production server later. -Example:: +.. code-block:: python - if __name__ == '__main__': - app.run() + if __name__ == "__main__": + app.run(debug=True) -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). +.. code-block:: text -It is however still a perfectly valid method for invoking a non automatic -reloading application. + $ python hello.py diff --git a/docs/shell.rst b/docs/shell.rst index 9d9bb5f9f9..7e42e28515 100644 --- a/docs/shell.rst +++ b/docs/shell.rst @@ -1,5 +1,3 @@ -.. _shell: - Working with the Shell ====================== @@ -20,11 +18,10 @@ can you do? This is where some helper functions come in handy. Keep in mind however that these functions are not only there for interactive shell usage, but -also for unittesting and other situations that require a faked request +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. +Generally it's recommended that you read :doc:`reqcontext` first. Command Line Interface ---------------------- @@ -34,7 +31,7 @@ Starting with Flask 0.11 the recommended way to work with the shell is the For instance the shell is automatically initialized with a loaded application context. -For more information see :ref:`cli`. +For more information see :doc:`/cli`. Creating a Request Context -------------------------- diff --git a/docs/signals.rst b/docs/signals.rst index 2426e920e8..739bb0b548 100644 --- a/docs/signals.rst +++ b/docs/signals.rst @@ -1,35 +1,28 @@ -.. _signals: - Signals ======= -.. versionadded:: 0.6 - -Starting with Flask 0.6, there is integrated support for signalling in -Flask. This support is provided by the excellent `blinker`_ library and -will gracefully fall back if it is not available. - -What are signals? Signals help you decouple applications by sending -notifications when actions occur elsewhere in the core framework or -another Flask extensions. In short, signals allow certain senders to -notify subscribers that something happened. - -Flask comes with a couple of signals and other extensions might provide -more. Also keep in mind that signals are intended to notify subscribers -and should not encourage subscribers to modify data. You will notice that -there are signals that appear to do the same thing like some of the -builtin decorators do (eg: :data:`~flask.request_started` is very similar -to :meth:`~flask.Flask.before_request`). However, there are differences in -how they work. The core :meth:`~flask.Flask.before_request` handler, for -example, is executed in a specific order and is able to abort the request -early by returning a response. In contrast all signal handlers are -executed in undefined order and do not modify any data. - -The big advantage of signals over handlers is that you can safely -subscribe to them for just a split second. These temporary -subscriptions are helpful for unittesting for example. Say you want to -know what templates were rendered as part of a request: signals allow you -to do exactly that. +Signals are a lightweight way to notify subscribers of certain events during the +lifecycle of the application and each request. When an event occurs, it emits the +signal, which calls each subscriber. + +Signals are implemented by the `Blinker`_ library. See its documentation for detailed +information. Flask provides some built-in signals. Extensions may provide their own. + +Many signals mirror Flask's decorator-based callbacks with similar names. For example, +the :data:`.request_started` signal is similar to the :meth:`~.Flask.before_request` +decorator. The advantage of signals over handlers is that they can be subscribed to +temporarily, and can't directly affect the application. This is useful for testing, +metrics, auditing, and more. For example, if you want to know what templates were +rendered at what parts of what requests, there is a signal that will notify you of that +information. + + +Core Signals +------------ + +See :ref:`core-signals-list` for a list of all built-in signals. The :doc:`lifecycle` +page also describes the order that signals and decorators execute. + Subscribing to Signals ---------------------- @@ -45,7 +38,7 @@ signal. When you subscribe to a signal, be sure to also provide a sender unless you really want to listen for signals from all applications. This is especially true if you are developing an extension. -For example, here is a helper context manager that can be used in a unittest +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:: @@ -101,17 +94,12 @@ The example above would then look like this:: ... 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 +custom :class:`~blinker.base.Namespace`. This is what is recommended most of the time:: from blinker import Namespace @@ -125,12 +113,6 @@ 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 @@ -162,7 +144,7 @@ function, you can pass ``current_app._get_current_object()`` as sender. Signals and Flask's Request Context ----------------------------------- -Signals fully support :ref:`request-context` when receiving signals. +Signals fully support :doc:`reqcontext` 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 @@ -172,19 +154,14 @@ 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 +You can also easily subscribe to signals by using the :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. + print(f'Template {template.name} is rendered with {context}') -.. _blinker: https://pypi.python.org/pypi/blinker +.. _blinker: https://pypi.org/project/blinker/ diff --git a/docs/styleguide.rst b/docs/styleguide.rst deleted file mode 100644 index e03e4ef57c..0000000000 --- a/docs/styleguide.rst +++ /dev/null @@ -1,200 +0,0 @@ -Pocoo 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 an 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) diff --git a/docs/templating.rst b/docs/templating.rst index 9ba2223ac2..23cfee4cb3 100644 --- a/docs/templating.rst +++ b/docs/templating.rst @@ -1,7 +1,7 @@ Templates ========= -Flask leverages Jinja2 as template engine. You are obviously free to use +Flask leverages Jinja2 as its 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. @@ -9,7 +9,7 @@ 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 +Documentation `_ for more information. Jinja Setup @@ -18,7 +18,7 @@ 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 + ``.htm``, ``.xml``, ``.xhtml``, as well as ``.svg`` when using :func:`~flask.templating.render_template`. - autoescaping is enabled for all strings when using :func:`~flask.templating.render_template_string`. @@ -37,7 +37,7 @@ by default: .. data:: config :noindex: - The current configuration object (:data:`flask.config`) + The current configuration object (:data:`flask.Flask.config`) .. versionadded:: 0.6 @@ -95,28 +95,6 @@ by default: {% from '_helpers.html' import my_macro with context %} -Standard Filters ----------------- - -These filters are available in Jinja2 additionally to the filters provided -by Jinja2 itself: - -.. function:: tojson - :noindex: - - This function converts the given object into JSON representation. This - is for example very helpful if you try to generate JavaScript on the - fly. - - Note that inside ``script`` tags no escaping must take place, so make - sure to disable escaping with ``|safe`` before Flask 0.10 if you intend - to use it inside ``script`` tags: - - .. sourcecode:: html+jinja - - Controlling Autoescaping ------------------------ @@ -128,7 +106,7 @@ 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`) +:ref:`security-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 @@ -137,7 +115,7 @@ markdown to HTML converter. There are three ways to accomplish that: -- In the Python code, wrap the HTML string in a :class:`~flask.Markup` +- In the Python code, wrap the HTML string in a :class:`~markupsafe.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 @@ -211,8 +189,8 @@ functions):: @app.context_processor def utility_processor(): - def format_price(amount, currency=u'€'): - return u'{0:.2f}{1}'.format(amount, currency) + def format_price(amount, currency="€"): + return f"{amount:.2f}{currency}" return dict(format_price=format_price) The context processor above makes the `format_price` function available to all @@ -223,3 +201,29 @@ templates:: 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. + +Streaming +--------- + +It can be useful to not render the whole template as one complete +string, instead render it as a stream, yielding smaller incremental +strings. This can be used for streaming HTML in chunks to speed up +initial page load, or to save memory when rendering a very large +template. + +The Jinja2 template engine supports rendering a template piece +by piece, returning an iterator of strings. Flask provides the +:func:`~flask.stream_template` and :func:`~flask.stream_template_string` +functions to make this easier to use. + +.. code-block:: python + + from flask import stream_template + + @app.get("/timeline") + def timeline(): + return stream_template("timeline.html") + +These functions automatically apply the +:func:`~flask.stream_with_context` wrapper if a request is active, so +that it remains available in the template. diff --git a/docs/testing.rst b/docs/testing.rst index 0737936e3e..b1d52f9a0d 100644 --- a/docs/testing.rst +++ b/docs/testing.rst @@ -1,355 +1,319 @@ -.. _testing: - Testing Flask Applications ========================== - **Something that is untested is broken.** +Flask provides utilities for testing an application. This documentation +goes over techniques for working with different parts of the application +in tests. + +We will use the `pytest`_ framework to set up and run our tests. -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. +.. code-block:: text -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 :mod:`unittest` package that comes pre-installed with Python. + $ pip install pytest -The Application ---------------- +.. _pytest: https://docs.pytest.org/ -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 -sources from `the examples`_. +The :doc:`tutorial ` goes over how to write tests for +100% coverage of the sample Flaskr blog application. See +:doc:`the tutorial on tests ` for a detailed +explanation of specific tests for an application. -.. _the examples: - https://github.com/pallets/flask/tree/master/examples/flaskr/ -The Testing Skeleton --------------------- +Identifying Tests +----------------- -In order to test the application, we add a second module -(:file:`flaskr_tests.py`) and create a unittest skeleton there:: +Tests are typically located in the ``tests`` folder. Tests are functions +that start with ``test_``, in Python modules that start with ``test_``. +Tests can also be further grouped in classes that start with ``Test``. - import os - import flaskr - import unittest - import tempfile +It can be difficult to know what to test. Generally, try to test the +code that you write, not the code of libraries that you use, since they +are already tested. Try to extract complex behaviors as separate +functions to test individually. - class FlaskrTestCase(unittest.TestCase): - def setUp(self): - self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp() - flaskr.app.config['TESTING'] = True - self.app = flaskr.app.test_client() - with flaskr.app.app_context(): - flaskr.init_db() +Fixtures +-------- - def tearDown(self): - os.close(self.db_fd) - os.unlink(flaskr.app.config['DATABASE']) +Pytest *fixtures* allow writing pieces of code that are reusable across +tests. A simple fixture returns a value, but a fixture can also do +setup, yield a value, then do teardown. Fixtures for the application, +test client, and CLI runner are shown below, they can be placed in +``tests/conftest.py``. - if __name__ == '__main__': - unittest.main() +If you're using an +:doc:`application factory `, define an ``app`` +fixture to create and configure an app instance. You can add code before +and after the ``yield`` to set up and tear down other resources, such as +creating and clearing a database. -The code in the :meth:`~unittest.TestCase.setUp` method creates a new test -client and initializes a new database. This function is called before -each individual test function is run. To delete the database after the -test, we close the file and remove it from the filesystem in the -:meth:`~unittest.TestCase.tearDown` method. Additionally during setup the -``TESTING`` config flag is activated. What it does is disable the error -catching during request handling so that you get better error reports when -performing test requests against the application. +If you're not using a factory, you already have an app object you can +import and configure directly. You can still use an ``app`` fixture to +set up and tear down resources. -This test client will give us a simple interface to the application. We can -trigger test requests to the application, and the client will also keep track -of cookies for us. +.. code-block:: python -Because SQLite3 is filesystem-based we can easily use the 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. + import pytest + from my_project import create_app -If we now run the test suite, we should see the following output:: - - $ python flaskr_tests.py + @pytest.fixture() + def app(): + app = create_app() + app.config.update({ + "TESTING": True, + }) - ---------------------------------------------------------------------- - Ran 0 tests in 0.000s + # other setup can go here - OK + yield app -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. + # clean up / reset resources here -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 method to our class, like this:: + @pytest.fixture() + def client(app): + return app.test_client() - class FlaskrTestCase(unittest.TestCase): - def setUp(self): - self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp() - self.app = flaskr.app.test_client() - flaskr.init_db() + @pytest.fixture() + def runner(app): + return app.test_cli_runner() - def tearDown(self): - os.close(self.db_fd) - os.unlink(flaskr.app.config['DATABASE']) - def test_empty_db(self): - rv = self.app.get('/') - assert b'No entries here so far' in rv.data +Sending Requests with the Test Client +------------------------------------- -Notice that our test functions begin with the word `test`; this allows -:mod:`unittest` to automatically identify the method as a test to run. +The test client makes requests to the application without running a live +server. Flask's client extends +:doc:`Werkzeug's client `, see those docs for additional +information. -By using `self.app.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. +The ``client`` has methods that match the common HTTP request methods, +such as ``client.get()`` and ``client.post()``. They take many arguments +for building the request; you can find the full documentation in +:class:`~werkzeug.test.EnvironBuilder`. Typically you'll use ``path``, +``query_string``, ``headers``, and ``data`` or ``json``. -Run it again and you should see one passing test:: +To make a request, call the method the request should use with the path +to the route to test. A :class:`~werkzeug.test.TestResponse` is returned +to examine the response data. It has all the usual properties of a +response object. You'll usually look at ``response.data``, which is the +bytes returned by the view. If you want to use text, Werkzeug 2.1 +provides ``response.text``, or use ``response.get_data(as_text=True)``. - $ python flaskr_tests.py - . - ---------------------------------------------------------------------- - Ran 1 test in 0.034s +.. code-block:: python - OK + def test_request_example(client): + response = client.get("/posts") + assert b"

Hello, World!

" in response.data -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`. +Pass a dict ``query_string={"key": "value", ...}`` to set arguments in +the query string (after the ``?`` in the URL). Pass a dict +``headers={}`` to set request headers. -Add the following two methods to your `FlaskrTestCase` class:: +To send a request body in a POST or PUT request, pass a value to +``data``. If raw bytes are passed, that exact body is used. Usually, +you'll pass a dict to set form data. - def login(self, username, password): - return self.app.post('/login', data=dict( - username=username, - password=password - ), follow_redirects=True) - def logout(self): - return self.app.get('/logout', follow_redirects=True) +Form Data +~~~~~~~~~ -Now we can easily test that logging in and out works and that it fails with -invalid credentials. Add this new test to the class:: +To send form data, pass a dict to ``data``. The ``Content-Type`` header +will be set to ``multipart/form-data`` or +``application/x-www-form-urlencoded`` automatically. - def test_login_logout(self): - rv = self.login('admin', 'default') - assert b'You were logged in' in rv.data - rv = self.logout() - assert b'You were logged out' in rv.data - rv = self.login('adminx', 'default') - assert b'Invalid username' in rv.data - rv = self.login('admin', 'defaultx') - assert b'Invalid password' in rv.data +If a value is a file object opened for reading bytes (``"rb"`` mode), it +will be treated as an uploaded file. To change the detected filename and +content type, pass a ``(file, filename, content_type)`` tuple. File +objects will be closed after making the request, so they do not need to +use the usual ``with open() as f:`` pattern. -Test Adding Messages --------------------- +It can be useful to store files in a ``tests/resources`` folder, then +use ``pathlib.Path`` to get files relative to the current test file. -We should also test that adding messages works. Add a new test method -like this:: +.. code-block:: python - def test_messages(self): - self.login('admin', 'default') - rv = self.app.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 + from pathlib import Path -Here we check that HTML is allowed in the text but not in the title, -which is the intended behavior. + # get the resources folder in the tests folder + resources = Path(__file__).parent / "resources" -Running that should now give us three passing tests:: + def test_edit_user(client): + response = client.post("/user/2/edit", data={ + "name": "Flask", + "theme": "dark", + "picture": (resources / "picture.png").open("rb"), + }) + assert response.status_code == 200 - $ python flaskr_tests.py - ... - ---------------------------------------------------------------------- - Ran 3 tests in 0.332s - OK +JSON Data +~~~~~~~~~ -For more complex tests with headers and status codes, check out the -`MiniTwit Example`_ from the sources which contains a larger test -suite. +To send JSON data, pass an object to ``json``. The ``Content-Type`` +header will be set to ``application/json`` automatically. +Similarly, if the response contains JSON data, the ``response.json`` +attribute will contain the deserialized object. -.. _MiniTwit Example: - https://github.com/pallets/flask/tree/master/examples/minitwit/ +.. code-block:: python + def test_json_data(client): + response = client.post("/graphql", json={ + "query": """ + query User($id: String!) { + user(id: $id) { + name + theme + picture_url + } + } + """, + variables={"id": 2}, + }) + assert response.json["data"]["user"]["name"] == "Flask" -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:: +Following Redirects +------------------- - import flask - - app = flask.Flask(__name__) +By default, the client does not make additional requests if the response +is a redirect. By passing ``follow_redirects=True`` to a request method, +the client will continue to make requests until a non-redirect response +is returned. - with app.test_request_context('/?name=Peter'): - assert flask.request.path == '/' - assert flask.request.args['name'] == 'Peter' +:attr:`TestResponse.history ` is +a tuple of the responses that led up to the final response. Each +response has a :attr:`~werkzeug.test.TestResponse.request` attribute +which records the request that produced that response. -All the other objects that are context bound can be used in the same -way. +.. code-block:: python -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`). + def test_logout_redirect(client): + response = client.get("/logout", follow_redirects=True) + # Check that there was one redirect response. + assert len(response.history) == 1 + # Check that the second request was to the index page. + assert response.request.path == "/index" -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__) +Accessing and Modifying the Session +----------------------------------- - with app.test_request_context('/?name=Peter'): - app.preprocess_request() - ... +To access Flask's context variables, mainly +:data:`~flask.session`, use the client in a ``with`` statement. +The app and request context will remain active *after* making a request, +until the ``with`` block ends. -This can be necessary to open database connections or something similar -depending on how your application was designed. +.. code-block:: python -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:: + from flask import session - app = flask.Flask(__name__) + def test_access_session(client): + with client: + client.post("/auth/login", data={"username": "flask"}) + # session is still accessible + assert session["user_id"] == 1 - with app.test_request_context('/?name=Peter'): - resp = Response('...') - resp = app.process_response(resp) - ... + # session is no longer accessible -This in general is less useful because at that point you can directly -start using the test client. +If you want to access or set a value in the session *before* making a +request, use the client's +:meth:`~flask.testing.FlaskClient.session_transaction` method in a +``with`` statement. It returns a session object, and will save the +session once the block ends. -.. _faking-resources: +.. code-block:: python -Faking Resources and Context ----------------------------- + from flask import session -.. versionadded:: 0.10 + def test_modify_session(client): + with client.session_transaction() as session: + # set a user id without going through the login route + session["user_id"] = 1 -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:: + # session is saved now - def get_user(): - user = getattr(g, 'user', None) - if user is None: - user = fetch_current_user_from_database() - g.user = user - return user + response = client.get("/users/me") + assert response.json["username"] == "flask" -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 +.. _testing-cli: - @contextmanager - def user_set(app, user): - def handler(sender, **kwargs): - g.user = user - with appcontext_pushed.connected_to(handler, app): - yield +Running Commands with the CLI Runner +------------------------------------ -And then to use it:: +Flask provides :meth:`~flask.Flask.test_cli_runner` to create a +:class:`~flask.testing.FlaskCliRunner`, which runs CLI commands in +isolation and captures the output in a :class:`~click.testing.Result` +object. Flask's runner extends :doc:`Click's runner `, +see those docs for additional information. - from flask import json, jsonify +Use the runner's :meth:`~flask.testing.FlaskCliRunner.invoke` method to +call commands in the same way they would be called with the ``flask`` +command from the command line. - @app.route('/users/me') - def users_me(): - return jsonify(username=g.user.username) +.. code-block:: python - 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) + import click + @app.cli.command("hello") + @click.option("--name", default="World") + def hello_command(name): + click.echo(f"Hello, {name}!") -Keeping the Context Around --------------------------- + def test_hello_command(runner): + result = runner.invoke(args="hello") + assert "World" in result.output -.. versionadded:: 0.4 + result = runner.invoke(args=["hello", "--name", "Flask"]) + assert "Flask" in result.output -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__) +Tests that depend on an Active Context +-------------------------------------- - with app.test_client() as c: - rv = c.get('/?tequila=42') - assert request.args['tequila'] == '42' +You may have functions that are called from views or commands, that +expect an active :doc:`application context ` or +:doc:`request context ` because they access ``request``, +``session``, or ``current_app``. Rather than testing them by making a +request or invoking the command, you can create and activate a context +directly. -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). +Use ``with app.app_context()`` to push an application context. For +example, database extensions usually require an active app context to +make queries. +.. code-block:: python -Accessing and Modifying Sessions --------------------------------- + def test_db_post_model(app): + with app.app_context(): + post = db.session.query(Post).get(1) -.. versionadded:: 0.8 +Use ``with app.test_request_context()`` to push a request context. It +takes the same arguments as the test client's request methods. -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`:: +.. code-block:: python - with app.test_client() as c: - rv = c.get('/') - assert flask.session['foo'] == 42 + def test_validate_user_edit(app): + with app.test_request_context( + "/user/2/edit", method="POST", data={"name": ""} + ): + # call a function that accesses `request` + messages = validate_edit_user() -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. This works -independently of the session backend used:: + assert messages["name"][0] == "Name cannot be empty." - with app.test_client() as c: - with c.session_transaction() as sess: - sess['a_key'] = 'a value' +Creating a test request context doesn't run any of the Flask dispatching +code, so ``before_request`` functions are not called. If you need to +call these, usually it's better to make a full request instead. However, +it's possible to call them manually. - # once this is reached the session was stored +.. code-block:: python -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. + def test_auth_token(app): + with app.test_request_context("/user/2/edit", headers={"X-Auth-Token": "1"}): + app.preprocess_request() + assert g.user.name == "Flask" diff --git a/docs/tutorial/blog.rst b/docs/tutorial/blog.rst new file mode 100644 index 0000000000..b06329eaae --- /dev/null +++ b/docs/tutorial/blog.rst @@ -0,0 +1,336 @@ +.. 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: https://jinja.palletsprojects.com/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, f"Post id {id} doesn't exist.") + + 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`. diff --git a/docs/tutorial/css.rst b/docs/tutorial/css.rst deleted file mode 100644 index 56414657c1..0000000000 --- a/docs/tutorial/css.rst +++ /dev/null @@ -1,31 +0,0 @@ -.. _tutorial-css: - -Step 8: Adding Style -==================== - -Now that everything else works, it's time to add some style to the -application. Just create a stylesheet called :file:`style.css` in the -:file:`static` folder: - -.. sourcecode:: css - - body { font-family: sans-serif; background: #eee; } - a, h1, h2 { color: #377ba8; } - h1, h2 { font-family: 'Georgia', serif; margin: 0; } - h1 { border-bottom: 2px solid #eee; } - h2 { font-size: 1.2em; } - - .page { margin: 2em auto; width: 35em; border: 5px solid #ccc; - padding: 0.8em; background: white; } - .entries { list-style: none; margin: 0; padding: 0; } - .entries li { margin: 0.8em 1.2em; } - .entries li h2 { margin-left: -1em; } - .add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; } - .add-entry dl { font-weight: bold; } - .metanav { text-align: right; font-size: 0.8em; padding: 0.3em; - margin-bottom: 1em; background: #fafafa; } - .flash { background: #cee5F5; padding: 0.5em; - border: 1px solid #aacbe2; } - .error { background: #f0d6d6; padding: 0.5em; } - -Continue with :ref:`tutorial-testing`. diff --git a/docs/tutorial/database.rst b/docs/tutorial/database.rst new file mode 100644 index 0000000000..93abf93a1a --- /dev/null +++ b/docs/tutorial/database.rst @@ -0,0 +1,219 @@ +.. 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 + from datetime import datetime + + import click + from flask import current_app, g + + + 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') + def init_db_command(): + """Clear the existing data and create new tables.""" + init_db() + click.echo('Initialized the database.') + + + sqlite3.register_converter( + "timestamp", lambda v: datetime.fromisoformat(v.decode()) + ) + +: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 :doc:`/cli` to learn more about writing commands. + +The call to :func:`sqlite3.register_converter` tells Python how to +interpret timestamp values in the database. We convert the value to a +:class:`datetime.datetime`. + + +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 :doc:`/installation`. + +Run the ``init-db`` command: + +.. code-block:: none + + $ flask --app flaskr init-db + Initialized the database. + +There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in +your project. + +Continue to :doc:`views`. diff --git a/docs/tutorial/dbcon.rst b/docs/tutorial/dbcon.rst deleted file mode 100644 index 2dd3d7bea0..0000000000 --- a/docs/tutorial/dbcon.rst +++ /dev/null @@ -1,75 +0,0 @@ -.. _tutorial-dbcon: - -Step 4: Database Connections ----------------------------- - -You currently have a function for establishing a database connection with -`connect_db`, but by itself, it is not particularly useful. Creating and -closing database connections all the time is very inefficient, so you will -need to keep it around for longer. Because database connections -encapsulate a transaction, you will need to make sure that only one -request at a time uses the connection. An elegant way to do this is by -utilizing the *application context*. - -Flask provides two contexts: the *application context* and the -*request context*. For the time being, all you have to know is that there -are special variables that use these. For instance, the -:data:`~flask.request` variable is the request object associated with -the current request, whereas :data:`~flask.g` is a general purpose -variable associated with the current application context. The tutorial -will cover some more details of this later on. - -For the time being, all you have to know is that you can store information -safely on the :data:`~flask.g` object. - -So when do you put it on there? To do that you can make a helper -function. The first time the function is called, it will create a database -connection for the current context, and successive calls will return the -already established connection:: - - def get_db(): - """Opens a new database connection if there is none yet for the - current application context. - """ - if not hasattr(g, 'sqlite_db'): - g.sqlite_db = connect_db() - return g.sqlite_db - -Now you know how to connect, but how can you properly disconnect? For -that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext` -decorator. It's executed every time the application context tears down:: - - @app.teardown_appcontext - def close_db(error): - """Closes the database again at the end of the request.""" - if hasattr(g, 'sqlite_db'): - g.sqlite_db.close() - -Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called -every time the app context tears down. What does this mean? -Essentially, the app context is created before the request comes in and is -destroyed (torn down) whenever the request finishes. A teardown can -happen because of two reasons: either everything went well (the error -parameter will be ``None``) or an exception happened, in which case the error -is passed to the teardown function. - -Curious about what these contexts mean? Have a look at the -:ref:`app-context` documentation to learn more. - -Continue to :ref:`tutorial-dbinit`. - -.. hint:: Where do I put this code? - - If you've been following along in this tutorial, you might be wondering - where to put the code from this step and the next. A logical place is to - group these module-level functions together, and put your new - ``get_db`` and ``close_db`` functions below your existing - ``connect_db`` function (following the tutorial line-by-line). - - If you need a moment to find your bearings, take a look at how the `example - source`_ is organized. In Flask, you can put all of your application code - into a single Python module. You don't have to, and if your app :ref:`grows - larger `, it's a good idea not to. - -.. _example source: - https://github.com/pallets/flask/tree/master/examples/flaskr/ diff --git a/docs/tutorial/dbinit.rst b/docs/tutorial/dbinit.rst deleted file mode 100644 index fbbcde0072..0000000000 --- a/docs/tutorial/dbinit.rst +++ /dev/null @@ -1,73 +0,0 @@ -.. _tutorial-dbinit: - -Step 5: Creating The Database -============================= - -As outlined earlier, Flaskr is a database powered application, and more -precisely, it is an application powered by a relational database system. Such -systems need a schema that tells them how to store that information. -Before starting the server for the first time, it's important to create -that schema. - -Such a schema can be created by piping the ``schema.sql`` file into the -`sqlite3` command as follows:: - - sqlite3 /tmp/flaskr.db < schema.sql - -The downside of this is that it requires the ``sqlite3`` command to be -installed, which is not necessarily the case on every system. This also -requires that you provide the path to the database, which can introduce -errors. It's a good idea to add a function that initializes the database -for you, to the application. - -To do this, you can create a function and hook it into a :command:`flask` -command that initializes the database. For now just take a look at the -code segment below. A good place to add this function, and command, is -just below the `connect_db` function in :file:`flaskr.py`:: - - def init_db(): - db = get_db() - with app.open_resource('schema.sql', mode='r') as f: - db.cursor().executescript(f.read()) - db.commit() - - @app.cli.command('initdb') - def initdb_command(): - """Initializes the database.""" - init_db() - print('Initialized the database.') - -The ``app.cli.command()`` decorator registers a new command with the -:command:`flask` script. When the command executes, Flask will automatically -create an application context which is bound to the right application. -Within the function, you can then access :attr:`flask.g` and other things as -you might expect. When the script ends, the application context tears down -and the database connection is released. - -You will want to keep an actual function around that initializes the database, -though, so that we can easily create databases in unit tests later on. (For -more information see :ref:`testing`.) - -The :func:`~flask.Flask.open_resource` method of the application object -is a convenient helper function that will open a resource that the -application provides. This function opens a file from the resource -location (the :file:`flaskr/flaskr` folder) and allows you to read from it. -It is used in this example to execute a script on the database connection. - -The connection object provided by SQLite can give you a cursor object. -On that cursor, there is a method to execute a complete script. Finally, you -only have to commit the changes. SQLite3 and other transactional -databases will not commit unless you explicitly tell it to. - -Now, it is possible to create a database with the :command:`flask` script:: - - flask initdb - Initialized the database. - -.. admonition:: Troubleshooting - - If you get an exception later on stating that a table cannot be found, check - that you did execute the ``initdb`` command and that your table names are - correct (singular vs. plural, for example). - -Continue with :ref:`tutorial-views` diff --git a/docs/tutorial/deploy.rst b/docs/tutorial/deploy.rst new file mode 100644 index 0000000000..eb3a53ac5e --- /dev/null +++ b/docs/tutorial/deploy.rst @@ -0,0 +1,111 @@ +Deploy 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 *wheel* +(``.whl``) file. Install and use the ``build`` tool to do this. + +.. code-block:: none + + $ pip install build + $ python -m build --wheel + +You can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The +file name is in the format of {project name}-{version}-{python tag} +-{abi tag}-{platform tag}. + +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:: text + + $ flask --app flaskr 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 secrets; print(secrets.token_hex())' + + '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + +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 = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + +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 +``--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`. diff --git a/docs/tutorial/factory.rst b/docs/tutorial/factory.rst new file mode 100644 index 0000000000..39febd135f --- /dev/null +++ b/docs/tutorial/factory.rst @@ -0,0 +1,162 @@ +.. 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 +debug mode. Remember, you should still be in the top-level +``flask-tutorial`` directory, not the ``flaskr`` package. + +Debug 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. + +.. code-block:: text + + $ flask --app flaskr run --debug + +You'll see output similar to this: + +.. code-block:: text + + * Serving Flask app "flaskr" + * Debug mode: on + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) + * Restarting with stat + * Debugger is active! + * Debugger PIN: nnn-nnn-nnn + +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! + +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. + +Continue to :doc:`database`. diff --git a/docs/tutorial/flaskr_edit.png b/docs/tutorial/flaskr_edit.png new file mode 100644 index 0000000000..6cd6e3980f Binary files /dev/null and b/docs/tutorial/flaskr_edit.png differ diff --git a/docs/tutorial/flaskr_index.png b/docs/tutorial/flaskr_index.png new file mode 100644 index 0000000000..aa2b50f552 Binary files /dev/null and b/docs/tutorial/flaskr_index.png differ diff --git a/docs/tutorial/flaskr_login.png b/docs/tutorial/flaskr_login.png new file mode 100644 index 0000000000..d482c64541 Binary files /dev/null and b/docs/tutorial/flaskr_login.png differ diff --git a/docs/tutorial/folders.rst b/docs/tutorial/folders.rst deleted file mode 100644 index ba62b3b75e..0000000000 --- a/docs/tutorial/folders.rst +++ /dev/null @@ -1,27 +0,0 @@ -.. _tutorial-folders: - -Step 0: Creating The Folders -============================ - -Before getting started, you will need to create the folders needed for this -application:: - - /flaskr - /flaskr - /static - /templates - -The application will be installed and run as Python package. This is the -recommended way to install and run Flask applications. You will see exactly -how to run ``flaskr`` later on in this tutorial. For now go ahead and create -the applications directory structure. In the next few steps you will be -creating the database schema as well as the main module. - -As a quick side note, the files inside of the :file:`static` folder are -available to users of the application via HTTP. This is the place where CSS and -JavaScript files go. Inside the :file:`templates` folder, Flask will look for -`Jinja2`_ templates. You will see examples of this later on. - -For now you should continue with :ref:`tutorial-schema`. - -.. _Jinja2: http://jinja.pocoo.org/ diff --git a/docs/tutorial/index.rst b/docs/tutorial/index.rst index f0a583e09a..d5dc5b3c39 100644 --- a/docs/tutorial/index.rst +++ b/docs/tutorial/index.rst @@ -1,33 +1,64 @@ -.. _tutorial: - Tutorial ======== -You want to develop an application with Python and Flask? Here you have -the chance to learn by example. In this tutorial, we will create a simple -microblogging application. It only supports one user that can create -text-only entries and there are no feeds or comments, but it still -features everything you need to get started. We will use Flask and SQLite -as a database (which comes out of the box with Python) so there is nothing -else you need. +.. toctree:: + :caption: Contents: + :maxdepth: 1 -If you want the full source code in advance or for comparison, check out -the `example source`_. + layout + factory + database + views + templates + static + blog + install + tests + deploy + next -.. _example source: - https://github.com/pallets/flask/tree/master/examples/flaskr/ +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. -.. toctree:: - :maxdepth: 2 - - introduction - folders - schema - setup - packaging - dbcon - dbinit - views - templates - css - testing +.. 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 :doc:`/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 :doc:`/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 edit 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`. diff --git a/docs/tutorial/install.rst b/docs/tutorial/install.rst new file mode 100644 index 0000000000..db83e106f6 --- /dev/null +++ b/docs/tutorial/install.rst @@ -0,0 +1,89 @@ +Make the Project Installable +============================ + +Making your project installable means that you can build a *wheel* 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 ``pyproject.toml`` file describes your project and how to build it. + +.. code-block:: toml + :caption: ``pyproject.toml`` + + [project] + name = "flaskr" + version = "1.0.0" + description = "The basic blog app built in the Flask tutorial." + dependencies = [ + "flask", + ] + + [build-system] + requires = ["flit_core<4"] + build-backend = "flit_core.buildapi" + +See the official `Packaging tutorial `_ for more +explanation of the files and options used. + +.. _packaging tutorial: 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 ``pyproject.toml`` in the current directory and install the +project 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 + Werkzeug 0.14.1 + +Nothing changes from how you've been running your project so far. +``--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`. diff --git a/docs/tutorial/introduction.rst b/docs/tutorial/introduction.rst deleted file mode 100644 index dd46628b39..0000000000 --- a/docs/tutorial/introduction.rst +++ /dev/null @@ -1,34 +0,0 @@ -.. _tutorial-introduction: - -Introducing Flaskr -================== - -This tutorial will demonstrate a blogging application named Flaskr, but feel -free to choose your own less Web-2.0-ish name ;) Essentially, it will do the -following things: - -1. Let the user sign in and out with credentials specified in the - configuration. Only one user is supported. -2. When the user is logged in, they can add new entries to the page - consisting of a text-only title and some HTML for the text. This HTML - is not sanitized because we trust the user here. -3. The index page shows all entries so far in reverse chronological order - (newest on top) and the user can add new ones from there if logged in. - -SQLite3 will be used directly for this application because it's good enough -for an application of this size. For larger applications, however, -it makes a lot of sense to use `SQLAlchemy`_, as it handles database -connections in a more intelligent way, allowing you to target different -relational databases at once and more. You might also want to consider -one of the popular NoSQL databases if your data is more suited for those. - -Here a screenshot of the final application: - -.. image:: ../_static/flaskr.png - :align: center - :class: screenshot - :alt: screenshot of the final application - -Continue with :ref:`tutorial-folders`. - -.. _SQLAlchemy: http://www.sqlalchemy.org/ diff --git a/docs/tutorial/layout.rst b/docs/tutorial/layout.rst new file mode 100644 index 0000000000..6f8e59f44d --- /dev/null +++ b/docs/tutorial/layout.rst @@ -0,0 +1,110 @@ +Project 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/ + ├── pyproject.toml + └── 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`. diff --git a/docs/tutorial/next.rst b/docs/tutorial/next.rst new file mode 100644 index 0000000000..d41e8ef21f --- /dev/null +++ b/docs/tutorial/next.rst @@ -0,0 +1,38 @@ +Keep 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 :doc:`/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 +:doc:`/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/ diff --git a/docs/tutorial/packaging.rst b/docs/tutorial/packaging.rst deleted file mode 100644 index 8db6531eea..0000000000 --- a/docs/tutorial/packaging.rst +++ /dev/null @@ -1,108 +0,0 @@ -.. _tutorial-packaging: - -Step 3: Installing flaskr as a Package -====================================== - -Flask is now shipped with built-in support for `Click`_. Click provides -Flask with enhanced and extensible command line utilities. Later in this -tutorial you will see exactly how to extend the ``flask`` command line -interface (CLI). - -A useful pattern to manage a Flask application is to install your app -following the `Python Packaging Guide`_. Presently this involves -creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the -projects root directory. You also need to add an :file:`__init__.py` -file to make the :file:`flaskr/flaskr` directory a package. After these -changes, your code structure should be:: - - /flaskr - /flaskr - __init__.py - /static - /templates - flaskr.py - schema.sql - setup.py - MANIFEST.in - -The content of the ``setup.py`` file for ``flaskr`` is: - -.. sourcecode:: python - - from setuptools import setup - - setup( - name='flaskr', - packages=['flaskr'], - include_package_data=True, - install_requires=[ - 'flask', - ], - ) - -When using setuptools, it is also necessary to specify any special files -that should be included in your package (in the :file:`MANIFEST.in`). -In this case, the static and templates directories need to be included, -as well as the schema. Create the :file:`MANIFEST.in` and add the -following lines:: - - graft flaskr/templates - graft flaskr/static - include flaskr/schema.sql - -To simplify locating the application, add the following import statement -into this file, :file:`flaskr/__init__.py`: - -.. sourcecode:: python - - from flaskr import app - -This import statement brings the application instance into the top-level -of the application package. When it is time to run the application, the -Flask development server needs the location of the app instance. This -import statement simplifies the location process. Without it the export -statement a few steps below would need to be -``export FLASK_APP=flaskr.flaskr``. - -At this point you should be able to install the application. As usual, it -is recommended to install your Flask application within a `virtualenv`_. -With that said, go ahead and install the application with:: - - pip install --editable . - -The above installation command assumes that it is run within the projects -root directory, `flaskr/`. The `editable` flag allows editing -source code without having to reinstall the Flask app each time you make -changes. The flaskr app is now installed in your virtualenv (see output -of ``pip freeze``). - -With that out of the way, you should be able to start up the application. -Do this with the following commands:: - - export FLASK_APP=flaskr - export FLASK_DEBUG=true - flask run - -(In case you are on Windows you need to use `set` instead of `export`). -The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger. -*Never leave debug mode activated in a production system*, because it will -allow users to execute code on the server! - -You will see a message telling you that server has started along with -the address at which you can access it. - -When you head over to the server in your browser, you will get a 404 error -because we don't have any views yet. That will be addressed a little later, -but first, you should get the database working. - -.. admonition:: Externally Visible Server - - Want your server to be publicly available? Check out the - :ref:`externally visible server ` section for more - information. - -Continue with :ref:`tutorial-dbcon`. - -.. _Click: http://click.pocoo.org -.. _Python Packaging Guide: https://packaging.python.org -.. _virtualenv: https://virtualenv.pypa.io diff --git a/docs/tutorial/schema.rst b/docs/tutorial/schema.rst deleted file mode 100644 index 00f56f0911..0000000000 --- a/docs/tutorial/schema.rst +++ /dev/null @@ -1,25 +0,0 @@ -.. _tutorial-schema: - -Step 1: Database Schema -======================= - -In this step, you will create the database schema. Only a single table is -needed for this application and it will only support SQLite. All you need to do -is put the following contents into a file named :file:`schema.sql` in the -:file:`flaskr/flaskr` folder: - -.. sourcecode:: sql - - drop table if exists entries; - create table entries ( - id integer primary key autoincrement, - title text not null, - 'text' text not null - ); - -This schema consists of a single table called ``entries``. Each row in -this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an -automatically incrementing integer and a primary key, the other two are -strings that must not be null. - -Continue with :ref:`tutorial-setup`. diff --git a/docs/tutorial/setup.rst b/docs/tutorial/setup.rst deleted file mode 100644 index 4bedb54c0e..0000000000 --- a/docs/tutorial/setup.rst +++ /dev/null @@ -1,97 +0,0 @@ -.. _tutorial-setup: - -Step 2: Application Setup Code -============================== - -Now that the schema is in place, you can create the application module, -:file:`flaskr.py`. This file should be placed inside of the -:file:`flaskr/flaskr` folder. The first several lines of code in the -application module are the needed import statements. After that there will be a -few lines of configuration code. For small applications like ``flaskr``, it is -possible to drop the configuration directly into the module. However, a cleaner -solution is to create a separate ``.ini`` or ``.py`` file, load that, and -import the values from there. - -Here are the import statements (in :file:`flaskr.py`):: - - # all the imports - import os - import sqlite3 - from flask import Flask, request, session, g, redirect, url_for, abort, \ - render_template, flash - -The next couple lines will create the actual application instance and -initialize it with the config from the same file in :file:`flaskr.py`: - -.. sourcecode:: python - - app = Flask(__name__) # create the application instance :) - app.config.from_object(__name__) # load config from this file , flaskr.py - - # Load default config and override config from an environment variable - app.config.update(dict( - DATABASE=os.path.join(app.root_path, 'flaskr.db'), - SECRET_KEY='development key', - USERNAME='admin', - PASSWORD='default' - )) - app.config.from_envvar('FLASKR_SETTINGS', silent=True) - -The :class:`~flask.Config` object works similarly to a dictionary, so it can be -updated with new values. - -.. admonition:: Database Path - - Operating systems know the concept of a current working directory for - each process. Unfortunately, you cannot depend on this in web - applications because you might have more than one application in the - same process. - - For this reason the ``app.root_path`` attribute can be used to - get the path to the application. Together with the ``os.path`` module, - files can then easily be found. In this example, we place the - database right next to it. - - For a real-world application, it's recommended to use - :ref:`instance-folders` instead. - -Usually, it is a good idea to load a separate, environment-specific -configuration file. Flask allows you to import multiple configurations and it -will use the setting defined in the last import. This enables robust -configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this. - -.. sourcecode:: python - - app.config.from_envvar('FLASKR_SETTINGS', silent=True) - -Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to -a config file to be loaded. The silent switch just tells Flask to not complain -if no such environment key is set. - -In addition to that, you can use the :meth:`~flask.Config.from_object` -method on the config object and provide it with an import name of a -module. Flask will then initialize the variable from that module. Note -that in all cases, only variable names that are uppercase are considered. - -The ``SECRET_KEY`` is needed to keep the client-side sessions secure. -Choose that key wisely and as hard to guess and complex as possible. - -Lastly, you will add a method that allows for easy connections to the -specified database. This can be used to open a connection on request and -also from the interactive Python shell or a script. This will come in -handy later. You can create a simple database connection through SQLite and -then tell it to use the :class:`sqlite3.Row` object to represent rows. -This allows the rows to be treated as if they were dictionaries instead of -tuples. - -.. sourcecode:: python - - def connect_db(): - """Connects to the specific database.""" - rv = sqlite3.connect(app.config['DATABASE']) - rv.row_factory = sqlite3.Row - return rv - -In the next section you will see how to run the application. - -Continue with :ref:`tutorial-packaging`. diff --git a/docs/tutorial/static.rst b/docs/tutorial/static.rst new file mode 100644 index 0000000000..8e76c409b5 --- /dev/null +++ b/docs/tutorial/static.rst @@ -0,0 +1,72 @@ +Static 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`. diff --git a/docs/tutorial/templates.rst b/docs/tutorial/templates.rst index 269e8df1b1..1a5535cc4d 100644 --- a/docs/tutorial/templates.rst +++ b/docs/tutorial/templates.rst @@ -1,112 +1,187 @@ -.. _tutorial-templates: +.. 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: https://jinja.palletsprojects.com/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`` -Step 7: The Templates -===================== + + {% block title %}{% endblock %} - Flaskr + + +
+
+ {% block header %}{% endblock %} +
+ {% for message in get_flashed_messages() %} +
{{ message }}
+ {% endfor %} + {% block content %}{% endblock %} +
-Now it is time to start working on the templates. As you may have -noticed, if you make requests with the app running, you will get -an exception that Flask cannot find the templates. The templates -are using `Jinja2`_ syntax and have autoescaping enabled by -default. This means that unless you mark a value in the code with -:class:`~flask.Markup` or with the ``|safe`` filter in the template, -Jinja2 will ensure that special characters such as ``<`` or ``>`` are -escaped with their XML equivalents. +: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. -We are also using template inheritance which makes it possible to reuse -the layout of the website in all pages. +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. -Put the following templates into the :file:`templates` folder: +There are three blocks defined here that will be overridden in the other +templates: -.. _Jinja2: http://jinja.pocoo.org/docs/templates +#. ``{% block title %}`` will change the title displayed in the + browser's tab and window title. -layout.html ------------ +#. ``{% block header %}`` is similar to ``title`` but will change the + title displayed on the page. -This template contains the HTML skeleton, the header and a link to log in -(or log out if the user was already logged in). It also displays the -flashed messages if there are any. The ``{% block body %}`` block can be -replaced by a block of the same name (``body``) in a child template. +#. ``{% block content %}`` is where the content of each page goes, such + as the login form or a blog post. -The :class:`~flask.session` dict is available in the template as well and -you can use that to check if the user is logged in or not. Note that in -Jinja you can access missing attributes and items of objects / dicts which -makes the following code work, even if there is no ``'logged_in'`` key in -the session: +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. -.. sourcecode:: html+jinja - - Flaskr - -
-

Flaskr

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

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

Login

- {% if error %}

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

-
-
Username: -
-
Password: -
-
-
+ {% block content %} + + + + + +
{% endblock %} -Continue with :ref:`tutorial-css`. + +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`. diff --git a/docs/tutorial/testing.rst b/docs/tutorial/testing.rst deleted file mode 100644 index dcf3659466..0000000000 --- a/docs/tutorial/testing.rst +++ /dev/null @@ -1,96 +0,0 @@ -.. _tutorial-testing: - -Bonus: Testing the Application -============================== - -Now that you have finished the application and everything works as -expected, it's probably not a bad idea to add automated tests to simplify -modifications in the future. The application above is used as a basic -example of how to perform unit testing in the :ref:`testing` section of the -documentation. Go there to see how easy it is to test Flask applications. - -Adding tests to flaskr ----------------------- - -Assuming you have seen the :ref:`testing` section and have either written -your own tests for ``flaskr`` or have followed along with the examples -provided, you might be wondering about ways to organize the project. - -One possible and recommended project structure is:: - - flaskr/ - flaskr/ - __init__.py - static/ - templates/ - tests/ - test_flaskr.py - setup.py - MANIFEST.in - -For now go ahead a create the :file:`tests/` directory as well as the -:file:`test_flaskr.py` file. - -Running the tests ------------------ - -At this point you can run the tests. Here ``pytest`` will be used. - -.. note:: Make sure that ``pytest`` is installed in the same virtualenv - as flaskr. Otherwise ``pytest`` test will not be able to import the - required components to test the application:: - - pip install -e . - pip install pytest - -Run and watch the tests pass, within the top-level :file:`flaskr/` -directory as:: - - py.test - -Testing + setuptools --------------------- - -One way to handle testing is to integrate it with ``setuptools``. Here -that requires adding a couple of lines to the :file:`setup.py` file and -creating a new file :file:`setup.cfg`. One benefit of running the tests -this way is that you do not have to install ``pytest``. Go ahead and -update the :file:`setup.py` file to contain:: - - from setuptools import setup - - setup( - name='flaskr', - packages=['flaskr'], - include_package_data=True, - install_requires=[ - 'flask', - ], - setup_requires=[ - 'pytest-runner', - ], - tests_require=[ - 'pytest', - ], - ) - -Now create :file:`setup.cfg` in the project root (alongside -:file:`setup.py`):: - - [aliases] - test=pytest - -Now you can run:: - - python setup.py test - -This calls on the alias created in :file:`setup.cfg` which in turn runs -``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has -been called. (Recall the `setup_requires` argument in :file:`setup.py`) -Following the standard rules of test-discovery your tests will be -found, run, and hopefully pass. - -This is one possible way to run and manage testing. Here ``pytest`` is -used, but there are other options such as ``nose``. Integrating testing -with ``setuptools`` is convenient because it is not necessary to actually -download ``pytest`` or any other testing framework one might use. diff --git a/docs/tutorial/tests.rst b/docs/tutorial/tests.rst new file mode 100644 index 0000000000..f4744cda27 --- /dev/null +++ b/docs/tutorial/tests.rst @@ -0,0 +1,559 @@ +.. 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 descriptor 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 response.headers["Location"] == "/auth/login" + + 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 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"] == "/" + + 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="http://github.com/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"] == "/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="http://github.com/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"] == "/" + + 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 ``pyproject.toml`` file. + +.. code-block:: toml + :caption: ``pyproject.toml`` + + [tool.pytest.ini_options] + testpaths = ["tests"] + + [tool.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 + 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`. diff --git a/docs/tutorial/views.rst b/docs/tutorial/views.rst index 4364d97382..7092dbc28f 100644 --- a/docs/tutorial/views.rst +++ b/docs/tutorial/views.rst @@ -1,117 +1,305 @@ -.. _tutorial-views: - -Step 6: The View Functions -========================== - -Now that the database connections are working, you can start writing the -view functions. You will need four of them: - -Show Entries ------------- - -This view shows all the entries stored in the database. It listens on the -root of the application and will select title and text from the database. -The one with the highest id (the newest entry) will be on top. The rows -returned from the cursor look a bit like dictionaries because we are using -the :class:`sqlite3.Row` row factory. - -The view function will pass the entries to the :file:`show_entries.html` -template and return the rendered one:: - - @app.route('/') - def show_entries(): - db = get_db() - cur = db.execute('select title, text from entries order by id desc') - entries = cur.fetchall() - return render_template('show_entries.html', entries=entries) - -Add New Entry -------------- - -This view lets the user add new entries if they are logged in. This only -responds to ``POST`` requests; the actual form is shown on the -`show_entries` page. If everything worked out well, it will -:func:`~flask.flash` an information message to the next request and -redirect back to the `show_entries` page:: - - @app.route('/add', methods=['POST']) - def add_entry(): - if not session.get('logged_in'): - abort(401) - db = get_db() - db.execute('insert into entries (title, text) values (?, ?)', - [request.form['title'], request.form['text']]) - db.commit() - flash('New entry was successfully posted') - return redirect(url_for('show_entries')) - -Note that this view checks that the user is logged in (that is, if the -`logged_in` key is present in the session and ``True``). - -.. admonition:: Security Note - - Be sure to use question marks when building SQL statements, as done in the - example above. Otherwise, your app will be vulnerable to SQL injection when - you use string formatting to build SQL statements. - See :ref:`sqlite3` for more. - -Login and Logout ----------------- - -These functions are used to sign the user in and out. Login checks the -username and password against the ones from the configuration and sets the -`logged_in` key for the session. If the user logged in successfully, that -key is set to ``True``, and the user is redirected back to the `show_entries` -page. In addition, a message is flashed that informs the user that he or -she was logged in successfully. If an error occurred, the template is -notified about that, and the user is asked again:: - - @app.route('/login', methods=['GET', 'POST']) +.. 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.' + + if error is None: + try: + db.execute( + "INSERT INTO user (username, password) VALUES (?, ?)", + (username, generate_password_hash(password)), + ) + db.commit() + except db.IntegrityError: + error = f"User {username} is already registered." + else: + 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. + +#. If validation succeeds, insert the new user data into the database. + + - :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*. + + - 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. + + - An :exc:`sqlite3.IntegrityError` will occur if the username + already exists, which should be shown to the user as another + validation error. + +#. 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(): - error = None if request.method == 'POST': - if request.form['username'] != app.config['USERNAME']: - error = 'Invalid username' - elif request.form['password'] != app.config['PASSWORD']: - error = 'Invalid password' - else: - session['logged_in'] = True - flash('You were logged in') - return redirect(url_for('show_entries')) - return render_template('login.html', error=error) - -The `logout` function, on the other hand, removes that key from the session -again. There is a neat trick here: if you use the :meth:`~dict.pop` method -of the dict and pass a second parameter to it (the default), the method -will delete the key from the dictionary if present or do nothing when that -key is not in there. This is helpful because now it is not necessary to -check if the user was logged in. - -:: - - @app.route('/logout') + 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. + + :meth:`~sqlite3.Cursor.fetchone` returns one row from the query. + If the query returned no results, it returns ``None``. Later, + :meth:`~sqlite3.Cursor.fetchall` will be used, which returns a list + of all results. + +#. :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.pop('logged_in', None) - flash('You were logged out') - return redirect(url_for('show_entries')) + 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) -.. admonition:: Security Note + return wrapped_view - Passwords should never be stored in plain text in a production - system. This tutorial uses plain text passwords for simplicity. If you - plan to release a project based off this tutorial out into the world, - passwords should be both `hashed and salted`_ before being stored in a - database or file. +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. - Fortunately, there are Flask extensions for the purpose of - hashing passwords and verifying passwords against hashes, so adding - this functionality is fairly straight forward. There are also - many general python libraries that can be used for hashing. +Endpoints and URLs +------------------ - You can find a list of recommended Flask extensions - `here `_ +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')``. -Continue with :ref:`tutorial-templates`. +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. -.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/ +Continue to :doc:`templates`. diff --git a/docs/unicode.rst b/docs/unicode.rst deleted file mode 100644 index 5aa6e25def..0000000000 --- a/docs/unicode.rst +++ /dev/null @@ -1,107 +0,0 @@ -Unicode 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 charpoints 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. diff --git a/docs/upgrading.rst b/docs/upgrading.rst deleted file mode 100644 index 41b70f03ed..0000000000 --- a/docs/upgrading.rst +++ /dev/null @@ -1,472 +0,0 @@ -Upgrading to Newer Releases -=========================== - -Flask itself is changing like any software is changing over time. Most of -the changes are the nice kind, the kind where you don't have to change -anything in your code to profit from a new release. - -However every once in a while there are changes that do require some -changes in your code or there are changes that make it possible for you to -improve your own code quality by taking advantage of new features in -Flask. - -This section of the documentation enumerates all the changes in Flask from -release to release and how you can change your code to have a painless -updating experience. - -Use the :command:`pip` command to upgrade your existing Flask installation by -providing the ``--upgrade`` parameter:: - - $ pip install --upgrade Flask - -.. _upgrading-to-012: - -Version 0.12 ------------- - -Changes to send_file -```````````````````` - -The ``filename`` is no longer automatically inferred from file-like objects. -This means that the following code will no longer automatically have -``X-Sendfile`` support, etag generation or MIME-type guessing:: - - response = send_file(open('/path/to/file.txt')) - -Any of the following is functionally equivalent:: - - fname = '/path/to/file.txt' - - # Just pass the filepath directly - response = send_file(fname) - - # Set the MIME-type and ETag explicitly - response = send_file(open(fname), mimetype='text/plain') - response.set_etag(...) - - # Set `attachment_filename` for MIME-type guessing - # ETag still needs to be manually set - response = send_file(open(fname), attachment_filename=fname) - response.set_etag(...) - -The reason for this is that some file-like objects have a invalid or even -misleading ``name`` attribute. Silently swallowing errors in such cases was not -a satisfying solution. - -Additionally the default of falling back to ``application/octet-stream`` has -been restricted. If Flask can't guess one or the user didn't provide one, the -function fails if no filename information was provided. - -.. _upgrading-to-011: - -Version 0.11 ------------- - -0.11 is an odd release in the Flask release cycle because it was supposed -to be the 1.0 release. However because there was such a long lead time up -to the release we decided to push out a 0.11 release first with some -changes removed to make the transition easier. If you have been tracking -the master branch which was 1.0 you might see some unexpected changes. - -In case you did track the master branch you will notice that :command:`flask --app` -is removed now. You need to use the environment variable to specify an -application. - -Debugging -````````` - -Flask 0.11 removed the ``debug_log_format`` attribute from Flask -applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can -be used to disable the default log handlers and custom log handlers can be -set up. - -Error handling -`````````````` - -The behavior of error handlers was changed. -The precedence of handlers used to be based on the decoration/call order of -:meth:`~flask.Flask.errorhandler` and -:meth:`~flask.Flask.register_error_handler`, respectively. -Now the inheritance hierarchy takes precedence and handlers for more -specific exception classes are executed instead of more general ones. -See :ref:`error-handlers` for specifics. - -Trying to register a handler on an instance now raises :exc:`ValueError`. - -.. note:: - - There used to be a logic error allowing you to register handlers - only for exception *instances*. This was unintended and plain wrong, - and therefore was replaced with the intended behavior of registering - handlers only using exception classes and HTTP error codes. - -Templating -`````````` - -The :func:`~flask.templating.render_template_string` function has changed to -autoescape template variables by default. This better matches the behavior -of :func:`~flask.templating.render_template`. - -Extension imports -````````````````` - -Extension imports of the form ``flask.ext.foo`` are deprecated, you should use -``flask_foo``. - -The old form still works, but Flask will issue a -``flask.exthook.ExtDeprecationWarning`` for each extension you import the old -way. We also provide a migration utility called `flask-ext-migrate -`_ that is supposed to -automatically rewrite your imports for this. - -.. _upgrading-to-010: - -Version 0.10 ------------- - -The biggest change going from 0.9 to 0.10 is that the cookie serialization -format changed from pickle to a specialized JSON format. This change has -been done in order to avoid the damage an attacker can do if the secret -key is leaked. When you upgrade you will notice two major changes: all -sessions that were issued before the upgrade are invalidated and you can -only store a limited amount of types in the session. The new sessions are -by design much more restricted to only allow JSON with a few small -extensions for tuples and strings with HTML markup. - -In order to not break people's sessions it is possible to continue using -the old session system by using the `Flask-OldSessions`_ extension. - -Flask also started storing the :data:`flask.g` object on the application -context instead of the request context. This change should be transparent -for you but it means that you now can store things on the ``g`` object -when there is no request context yet but an application context. The old -``flask.Flask.request_globals_class`` attribute was renamed to -:attr:`flask.Flask.app_ctx_globals_class`. - -.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/ - -Version 0.9 ------------ - -The behavior of returning tuples from a function was simplified. If you -return a tuple it no longer defines the arguments for the response object -you're creating, it's now always a tuple in the form ``(response, status, -headers)`` where at least one item has to be provided. If you depend on -the old behavior, you can add it easily by subclassing Flask:: - - class TraditionalFlask(Flask): - def make_response(self, rv): - if isinstance(rv, tuple): - return self.response_class(*rv) - return Flask.make_response(self, rv) - -If you maintain an extension that was using :data:`~flask._request_ctx_stack` -before, please consider changing to :data:`~flask._app_ctx_stack` if it makes -sense for your extension. For instance, the app context stack makes sense for -extensions which connect to databases. Using the app context stack instead of -the request context stack will make extensions more readily handle use cases -outside of requests. - -Version 0.8 ------------ - -Flask introduced a new session interface system. We also noticed that -there was a naming collision between ``flask.session`` the module that -implements sessions and :data:`flask.session` which is the global session -object. With that introduction we moved the implementation details for -the session system into a new module called :mod:`flask.sessions`. If you -used the previously undocumented session support we urge you to upgrade. - -If invalid JSON data was submitted Flask will now raise a -:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the -default :exc:`ValueError` bubble up. This has the advantage that you no -longer have to handle that error to avoid an internal server error showing -up for the user. If you were catching this down explicitly in the past -as :exc:`ValueError` you will need to change this. - -Due to a bug in the test client Flask 0.7 did not trigger teardown -handlers when the test client was used in a with statement. This was -since fixed but might require some changes in your test suites if you -relied on this behavior. - -Version 0.7 ------------ - -In Flask 0.7 we cleaned up the code base internally a lot and did some -backwards incompatible changes that make it easier to implement larger -applications with Flask. Because we want to make upgrading as easy as -possible we tried to counter the problems arising from these changes by -providing a script that can ease the transition. - -The script scans your whole application and generates an unified diff with -changes it assumes are safe to apply. However as this is an automated -tool it won't be able to find all use cases and it might miss some. We -internally spread a lot of deprecation warnings all over the place to make -it easy to find pieces of code that it was unable to upgrade. - -We strongly recommend that you hand review the generated patchfile and -only apply the chunks that look good. - -If you are using git as version control system for your project we -recommend applying the patch with ``path -p1 < patchfile.diff`` and then -using the interactive commit feature to only apply the chunks that look -good. - -To apply the upgrade script do the following: - -1. Download the script: `flask-07-upgrade.py - `_ -2. Run it in the directory of your application:: - - python flask-07-upgrade.py > patchfile.diff - -3. Review the generated patchfile. -4. Apply the patch:: - - patch -p1 < patchfile.diff - -5. If you were using per-module template folders you need to move some - templates around. Previously if you had a folder named :file:`templates` - next to a blueprint named ``admin`` the implicit template path - automatically was :file:`admin/index.html` for a template file called - :file:`templates/index.html`. This no longer is the case. Now you need - to name the template :file:`templates/admin/index.html`. The tool will - not detect this so you will have to do that on your own. - -Please note that deprecation warnings are disabled by default starting -with Python 2.7. In order to see the deprecation warnings that might be -emitted you have to enabled them with the :mod:`warnings` module. - -If you are working with windows and you lack the ``patch`` command line -utility you can get it as part of various Unix runtime environments for -windows including cygwin, msysgit or ming32. Also source control systems -like svn, hg or git have builtin support for applying unified diffs as -generated by the tool. Check the manual of your version control system -for more information. - -Bug in Request Locals -````````````````````` - -Due to a bug in earlier implementations the request local proxies now -raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they -are unbound. If you caught these exceptions with :exc:`AttributeError` -before, you should catch them with :exc:`RuntimeError` now. - -Additionally the :func:`~flask.send_file` function is now issuing -deprecation warnings if you depend on functionality that will be removed -in Flask 0.11. Previously it was possible to use etags and mimetypes -when file objects were passed. This was unreliable and caused issues -for a few setups. If you get a deprecation warning, make sure to -update your application to work with either filenames there or disable -etag attaching and attach them yourself. - -Old code:: - - return send_file(my_file_object) - return send_file(my_file_object) - -New code:: - - return send_file(my_file_object, add_etags=False) - -.. _upgrading-to-new-teardown-handling: - -Upgrading to new Teardown Handling -`````````````````````````````````` - -We streamlined the behavior of the callbacks for request handling. For -things that modify the response the :meth:`~flask.Flask.after_request` -decorators continue to work as expected, but for things that absolutely -must happen at the end of request we introduced the new -:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that -change also made after-request work differently under error conditions. -It's not consistently skipped if exceptions happen whereas previously it -might have been called twice to ensure it is executed at the end of the -request. - -If you have database connection code that looks like this:: - - @app.after_request - def after_request(response): - g.db.close() - return response - -You are now encouraged to use this instead:: - - @app.teardown_request - def after_request(exception): - if hasattr(g, 'db'): - g.db.close() - -On the upside this change greatly improves the internal code flow and -makes it easier to customize the dispatching and error handling. This -makes it now a lot easier to write unit tests as you can prevent closing -down of database connections for a while. You can take advantage of the -fact that the teardown callbacks are called when the response context is -removed from the stack so a test can query the database after request -handling:: - - with app.test_client() as client: - resp = client.get('/') - # g.db is still bound if there is such a thing - - # and here it's gone - -Manual Error Handler Attaching -`````````````````````````````` - -While it is still possible to attach error handlers to -:attr:`Flask.error_handlers` it's discouraged to do so and in fact -deprecated. In general we no longer recommend custom error handler -attaching via assignments to the underlying dictionary due to the more -complex internal handling to support arbitrary exception classes and -blueprints. See :meth:`Flask.errorhandler` for more information. - -The proper upgrade is to change this:: - - app.error_handlers[403] = handle_error - -Into this:: - - app.register_error_handler(403, handle_error) - -Alternatively you should just attach the function with a decorator:: - - @app.errorhandler(403) - def handle_error(e): - ... - -(Note that :meth:`register_error_handler` is new in Flask 0.7) - -Blueprint Support -````````````````` - -Blueprints replace the previous concept of “Modules” in Flask. They -provide better semantics for various features and work better with large -applications. The update script provided should be able to upgrade your -applications automatically, but there might be some cases where it fails -to upgrade. What changed? - -- Blueprints need explicit names. Modules had an automatic name - guessing scheme where the shortname for the module was taken from the - last part of the import module. The upgrade script tries to guess - that name but it might fail as this information could change at - runtime. -- Blueprints have an inverse behavior for :meth:`url_for`. Previously - ``.foo`` told :meth:`url_for` that it should look for the endpoint - ``foo`` on the application. Now it means “relative to current module”. - The script will inverse all calls to :meth:`url_for` automatically for - you. It will do this in a very eager way so you might end up with - some unnecessary leading dots in your code if you're not using - modules. -- Blueprints do not automatically provide static folders. They will - also no longer automatically export templates from a folder called - :file:`templates` next to their location however but it can be enabled from - the constructor. Same with static files: if you want to continue - serving static files you need to tell the constructor explicitly the - path to the static folder (which can be relative to the blueprint's - module path). -- Rendering templates was simplified. Now the blueprints can provide - template folders which are added to a general template searchpath. - This means that you need to add another subfolder with the blueprint's - name into that folder if you want :file:`blueprintname/template.html` as - the template name. - -If you continue to use the ``Module`` object which is deprecated, Flask will -restore the previous behavior as good as possible. However we strongly -recommend upgrading to the new blueprints as they provide a lot of useful -improvement such as the ability to attach a blueprint multiple times, -blueprint specific error handlers and a lot more. - - -Version 0.6 ------------ - -Flask 0.6 comes with a backwards incompatible change which affects the -order of after-request handlers. Previously they were called in the order -of the registration, now they are called in reverse order. This change -was made so that Flask behaves more like people expected it to work and -how other systems handle request pre- and post-processing. If you -depend on the order of execution of post-request functions, be sure to -change the order. - -Another change that breaks backwards compatibility is that context -processors will no longer override values passed directly to the template -rendering function. If for example ``request`` is as variable passed -directly to the template, the default context processor will not override -it with the current request object. This makes it easier to extend -context processors later to inject additional variables without breaking -existing template not expecting them. - -Version 0.5 ------------ - -Flask 0.5 is the first release that comes as a Python package instead of a -single module. There were a couple of internal refactoring so if you -depend on undocumented internal details you probably have to adapt the -imports. - -The following changes may be relevant to your application: - -- autoescaping no longer happens for all templates. Instead it is - configured to only happen on files ending with ``.html``, ``.htm``, - ``.xml`` and ``.xhtml``. If you have templates with different - extensions you should override the - :meth:`~flask.Flask.select_jinja_autoescape` method. -- Flask no longer supports zipped applications in this release. This - functionality might come back in future releases if there is demand - for this feature. Removing support for this makes the Flask internal - code easier to understand and fixes a couple of small issues that make - debugging harder than necessary. -- The ``create_jinja_loader`` function is gone. If you want to customize - the Jinja loader now, use the - :meth:`~flask.Flask.create_jinja_environment` method instead. - -Version 0.4 ------------ - -For application developers there are no changes that require changes in -your code. In case you are developing on a Flask extension however, and -that extension has a unittest-mode you might want to link the activation -of that mode to the new ``TESTING`` flag. - -Version 0.3 ------------ - -Flask 0.3 introduces configuration support and logging as well as -categories for flashing messages. All these are features that are 100% -backwards compatible but you might want to take advantage of them. - -Configuration Support -````````````````````` - -The configuration support makes it easier to write any kind of application -that requires some sort of configuration. (Which most likely is the case -for any application out there). - -If you previously had code like this:: - - app.debug = DEBUG - app.secret_key = SECRET_KEY - -You no longer have to do that, instead you can just load a configuration -into the config object. How this works is outlined in :ref:`config`. - -Logging Integration -``````````````````` - -Flask now configures a logger for you with some basic and useful defaults. -If you run your application in production and want to profit from -automatic error logging, you might be interested in attaching a proper log -handler. Also you can start logging warnings and errors into the logger -when appropriately. For more information on that, read -:ref:`application-errors`. - -Categories for Flash Messages -````````````````````````````` - -Flash messages can now have categories attached. This makes it possible -to render errors, warnings or regular messages differently for example. -This is an opt-in feature because it requires some rethinking in the code. - -Read all about that in the :ref:`message-flashing-pattern` pattern. diff --git a/docs/views.rst b/docs/views.rst index 68e8824154..f221027067 100644 --- a/docs/views.rst +++ b/docs/views.rst @@ -1,237 +1,324 @@ -.. _views: +Class-based Views +================= -Pluggable Views -=============== +.. currentmodule:: flask.views -.. versionadded:: 0.7 +This page introduces using the :class:`View` and :class:`MethodView` +classes to write class-based views. -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. +A class-based view is a class that acts as a view function. Because it +is a class, different instances of the class can be created with +different arguments, to change the behavior of the view. This is also +known as generic, reusable, or pluggable views. -Basic Principle ---------------- +An example of where this is useful is defining a class that creates an +API based on the database model it is initialized with. + +For more complex API behavior and customization, look into the various +API extensions for Flask. + + +Basic Reusable View +------------------- -Consider you have a function that loads a list of objects from the -database and renders into a template:: +Let's walk through an example converting a view function to a view +class. We start with a view function that queries a list of users then +renders a template to show the list. - @app.route('/users/') - def show_users(page): +.. code-block:: python + + @app.route("/users/") + def user_list(): users = User.query.all() - return render_template('users.html', users=users) + 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:: +This works for the user model, but let's say you also had more models +that needed list pages. You'd need to write another view function for +each model, even though the only thing that would change is the model +and template name. +Instead, you can write a :class:`View` subclass that will query a model +and render a template. As the first step, we'll convert the view to a +class without any customization. - from flask.views import View +.. code-block:: python - class ShowUsers(View): + from flask.views import View + class UserList(View): def dispatch_request(self): users = User.query.all() - return render_template('users.html', objects=users) + return render_template("users.html", objects=users) - app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users')) + app.add_url_rule("/users/", view_func=UserList.as_view("user_list")) -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:: +The :meth:`View.dispatch_request` method is the equivalent of the view +function. Calling :meth:`View.as_view` method will create a view +function that can be registered on the app with its +:meth:`~flask.Flask.add_url_rule` method. The first argument to +``as_view`` is the name to use to refer to the view with +:func:`~flask.url_for`. +.. note:: - from flask.views import View + You can't decorate the class with ``@app.route()`` the way you'd + do with a basic view function. - class ListView(View): +Next, we need to be able to register the same view class for different +models and templates, to make it more useful than the original function. +The class will take two arguments, the model and template, and store +them on ``self``. Then ``dispatch_request`` can reference these instead +of hard-coded values. - def get_template_name(self): - raise NotImplementedError() +.. code-block:: python - def render_template(self, context): - return render_template(self.get_template_name(), **context) + class ListView(View): + def __init__(self, model, template): + self.model = model + self.template = template def dispatch_request(self): - context = {'objects': self.get_objects()} - return self.render_template(context) + items = self.model.query.all() + return render_template(self.template, items=items) + +Remember, we create the view function with ``View.as_view()`` instead of +creating the class directly. Any extra arguments passed to ``as_view`` +are then passed when creating the class. Now we can register the same +view to handle multiple models. + +.. code-block:: python + + app.add_url_rule( + "/users/", + view_func=ListView.as_view("user_list", User, "users.html"), + ) + app.add_url_rule( + "/stories/", + view_func=ListView.as_view("story_list", Story, "stories.html"), + ) - class UserView(ListView): - def get_template_name(self): - return 'users.html' +URL Variables +------------- - def get_objects(self): - return User.query.all() +Any variables captured by the URL are passed as keyword arguments to the +``dispatch_request`` method, as they would be for a regular view +function. + +.. code-block:: python + + class DetailView(View): + def __init__(self, model): + self.model = model + self.template = f"{model.__name__.lower()}/detail.html" + + def dispatch_request(self, id) + item = self.model.query.get_or_404(id) + return render_template(self.template, item=item) + + app.add_url_rule( + "/users/", + view_func=DetailView.as_view("user_detail", User) + ) + + +View Lifetime and ``self`` +-------------------------- + +By default, a new instance of the view class is created every time a +request is handled. This means that it is safe to write other data to +``self`` during the request, since the next request will not see it, +unlike other forms of global state. + +However, if your view class needs to do a lot of complex initialization, +doing it for every request is unnecessary and can be inefficient. To +avoid this, set :attr:`View.init_every_request` to ``False``, which will +only create one instance of the class and use it for every request. In +this case, writing to ``self`` is not safe. If you need to store data +during the request, use :data:`~flask.g` instead. + +In the ``ListView`` example, nothing writes to ``self`` during the +request, so it is more efficient to create a single instance. + +.. code-block:: python + + class ListView(View): + init_every_request = False -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:: + def __init__(self, model, template): + self.model = model + self.template = template - class RenderTemplateView(View): - def __init__(self, template_name): - self.template_name = template_name def dispatch_request(self): - return render_template(self.template_name) + items = self.model.query.all() + return render_template(self.template, items=items) -And then you can register it like this:: +Different instances will still be created each for each ``as_view`` +call, but not for each request to those views. + + +View Decorators +--------------- + +The view class itself is not the view function. View decorators need to +be applied to the view function returned by ``as_view``, not the class +itself. Set :attr:`View.decorators` to a list of decorators to apply. + +.. code-block:: python + + class UserList(View): + decorators = [cache(minutes=2), login_required] + + app.add_url_rule('/users/', view_func=UserList.as_view()) + +If you didn't set ``decorators``, you could apply them manually instead. +This is equivalent to: + +.. code-block:: python + + view = UserList.as_view("users_list") + view = cache(minutes=2)(view) + view = login_required(view) + app.add_url_rule('/users/', view_func=view) + +Keep in mind that order matters. If you're used to ``@decorator`` style, +this is equivalent to: + +.. code-block:: python + + @app.route("/users/") + @login_required + @cache(minutes=2) + def user_list(): + ... - 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:: +A common pattern is to register a view with ``methods=["GET", "POST"]``, +then check ``request.method == "POST"`` to decide what to do. Setting +:attr:`View.methods` is equivalent to passing the list of methods to +``add_url_rule`` or ``route``. + +.. code-block:: python class MyView(View): - methods = ['GET', 'POST'] + methods = ["GET", "POST"] def dispatch_request(self): - if request.method == 'POST': + if request.method == "POST": ... ... - app.add_url_rule('/myview', view_func=MyView.as_view('myview')) - -Method Based Dispatching ------------------------- + app.add_url_rule('/my-view', view_func=MyView.as_view('my-view')) -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):: +This is equivalent to the following, except further subclasses can +inherit or change the methods. - from flask.views import MethodView +.. code-block:: python - class UserAPI(MethodView): + app.add_url_rule( + "/my-view", + view_func=MyView.as_view("my-view"), + methods=["GET", "POST"], + ) - def get(self): - users = User.query.all() - ... - def post(self): - user = User.from_form_data(request.form) - ... +Method Dispatching and APIs +--------------------------- - app.add_url_rule('/users/', view_func=UserAPI.as_view('users')) +For APIs it can be helpful to use a different function for each HTTP +method. :class:`MethodView` extends the basic :class:`View` to dispatch +to different methods of the class based on the request method. Each HTTP +method maps to a method of the class with the same (lowercase) name. -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. +:class:`MethodView` automatically sets :attr:`View.methods` based on the +methods defined by the class. It even knows how to handle subclasses +that override or define other methods. -Decorating Views ----------------- +We can make a generic ``ItemAPI`` class that provides get (detail), +patch (edit), and delete methods for a given model. A ``GroupAPI`` can +provide get (list) and post (create) methods. -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:: +.. code-block:: python - 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 + from flask.views import MethodView - view = user_required(UserAPI.as_view('users')) - app.add_url_rule('/users/', view_func=view) + class ItemAPI(MethodView): + init_every_request = False -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:: + def __init__(self, model): + self.model = model + self.validator = generate_validator(model) - class UserAPI(MethodView): - decorators = [user_required] + def _get_item(self, id): + return self.model.query.get_or_404(id) -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. + def get(self, id): + item = self._get_item(id) + return jsonify(item.to_json()) -Method Views for APIs ---------------------- + def patch(self, id): + item = self._get_item(id) + errors = self.validator.validate(item, request.json) -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: + if errors: + return jsonify(errors), 400 -=============== =============== ====================================== -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 -=============== =============== ====================================== + item.update_from_json(request.json) + db.session.commit() + return jsonify(item.to_json()) -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. + def delete(self, id): + item = self._get_item(id) + db.session.delete(item) + db.session.commit() + return "", 204 -Let's assume for the moment the view would look like this:: + class GroupAPI(MethodView): + init_every_request = False - class UserAPI(MethodView): + def __init__(self, model): + self.model = model + self.validator = generate_validator(model, create=True) - def get(self, user_id): - if user_id is None: - # return a list of users - pass - else: - # expose a single user - pass + def get(self): + items = self.model.query.all() + return jsonify([item.to_json() for item in items]) 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') + errors = self.validator.validate(request.json) + + if errors: + return jsonify(errors), 400 + + db.session.add(self.model.from_json(request.json)) + db.session.commit() + return jsonify(item.to_json()) + + def register_api(app, model, name): + item = ItemAPI.as_view(f"{name}-item", model) + group = GroupAPI.as_view(f"{name}-group", model) + app.add_url_rule(f"/{name}/", view_func=item) + app.add_url_rule(f"/{name}/", view_func=group) + + register_api(app, User, "users") + register_api(app, Story, "stories") + +This produces the following views, a standard REST API! + +================= ========== =================== +URL Method Description +----------------- ---------- ------------------- +``/users/`` ``GET`` List all users +``/users/`` ``POST`` Create a new user +``/users/`` ``GET`` Show a single user +``/users/`` ``PATCH`` Update a user +``/users/`` ``DELETE`` Delete a user +``/stories/`` ``GET`` List all stories +``/stories/`` ``POST`` Create a new story +``/stories/`` ``GET`` Show a single story +``/stories/`` ``PATCH`` Update a story +``/stories/`` ``DELETE`` Delete a story +================= ========== =================== diff --git a/docs/web-security.rst b/docs/web-security.rst new file mode 100644 index 0000000000..d742056fea --- /dev/null +++ b/docs/web-security.rst @@ -0,0 +1,295 @@ +Security Considerations +======================= + +Web applications face many types of potential security problems, and it can be +hard to get everything right, or even to know what "right" is in general. Flask +tries to solve a few of these things by default, but there are other parts you +may have to take care of yourself. Many of these solutions are tradeoffs, and +will depend on each application's specific needs and threat model. Many hosting +platforms may take care of certain types of problems without the need for the +Flask application to handle them. + +Resource Use +------------ + +A common category of attacks is "Denial of Service" (DoS or DDoS). This is a +very broad category, and different variants target different layers in a +deployed application. In general, something is done to increase how much +processing time or memory is used to handle each request, to the point where +there are not enough resources to handle legitimate requests. + +Flask provides a few configuration options to handle resource use. They can +also be set on individual requests to customize only that request. The +documentation for each goes into more detail. + +- :data:`MAX_CONTENT_LENGTH` or :attr:`.Request.max_content_length` controls + how much data will be read from a request. It is not set by default, + although it will still block truly unlimited streams unless the WSGI server + indicates support. +- :data:`MAX_FORM_MEMORY_SIZE` or :attr:`.Request.max_form_memory_size` + controls how large any non-file ``multipart/form-data`` field can be. It is + set to 500kB by default. +- :data:`MAX_FORM_PARTS` or :attr:`.Request.max_form_parts` controls how many + ``multipart/form-data`` fields can be parsed. It is set to 1000 by default. + Combined with the default `max_form_memory_size`, this means that a form + will occupy at most 500MB of memory. + +Regardless of these settings, you should also review what settings are available +from your operating system, container deployment (Docker etc), WSGI server, HTTP +server, and hosting platform. They typically have ways to set process resource +limits, timeouts, and other checks regardless of how Flask is configured. + +.. _security-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:`~markupsafe.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. + +.. _security-json: + +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 + +.. _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 + + +Copy/Paste to Terminal +---------------------- + +Hidden characters such as the backspace character (``\b``, ``^H``) can +cause text to render differently in HTML than how it is interpreted if +`pasted into a terminal `__. + +For example, ``import y\bose\bm\bi\bt\be\b`` renders as +``import yosemite`` in HTML, but the backspaces are applied when pasted +into a terminal, and it becomes ``import os``. + +If you expect users to copy and paste untrusted code from your site, +such as from comments posted by users on a technical blog, consider +applying extra filtering, such as replacing all ``\b`` characters. + +.. code-block:: python + + body = body.replace("\b", "") + +Most modern terminals will warn about and remove hidden characters when +pasting, so this isn't strictly necessary. It's also possible to craft +dangerous commands in other ways that aren't possible to filter. +Depending on your site's use case, it may be good to show a warning +about copying code in general. diff --git a/examples/blueprintexample/blueprintexample.py b/examples/blueprintexample/blueprintexample.py deleted file mode 100644 index 78ee3a5b83..0000000000 --- a/examples/blueprintexample/blueprintexample.py +++ /dev/null @@ -1,10 +0,0 @@ -from flask import Flask -from simple_page.simple_page import simple_page - -app = Flask(__name__) -app.register_blueprint(simple_page) -# Blueprint can be registered many times -app.register_blueprint(simple_page, url_prefix='/pages') - -if __name__=='__main__': - app.run() diff --git a/examples/blueprintexample/simple_page/simple_page.py b/examples/blueprintexample/simple_page/simple_page.py deleted file mode 100644 index cb82cc372c..0000000000 --- a/examples/blueprintexample/simple_page/simple_page.py +++ /dev/null @@ -1,13 +0,0 @@ -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) diff --git a/examples/blueprintexample/simple_page/templates/pages/hello.html b/examples/blueprintexample/simple_page/templates/pages/hello.html deleted file mode 100644 index 7e4a624d79..0000000000 --- a/examples/blueprintexample/simple_page/templates/pages/hello.html +++ /dev/null @@ -1,5 +0,0 @@ -{% extends "pages/layout.html" %} - -{% block body %} - Hello -{% endblock %} diff --git a/examples/blueprintexample/simple_page/templates/pages/index.html b/examples/blueprintexample/simple_page/templates/pages/index.html deleted file mode 100644 index b8d92da42d..0000000000 --- a/examples/blueprintexample/simple_page/templates/pages/index.html +++ /dev/null @@ -1,5 +0,0 @@ -{% extends "pages/layout.html" %} - -{% block body %} - Blueprint example page -{% endblock %} diff --git a/examples/blueprintexample/simple_page/templates/pages/layout.html b/examples/blueprintexample/simple_page/templates/pages/layout.html deleted file mode 100644 index f312d44be8..0000000000 --- a/examples/blueprintexample/simple_page/templates/pages/layout.html +++ /dev/null @@ -1,20 +0,0 @@ - -Simple Page Blueprint -
-

This is blueprint example

-

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

-

- Also you can register the same blueprint under another path -

- - {% block body %}{% endblock %} -
diff --git a/examples/blueprintexample/simple_page/templates/pages/world.html b/examples/blueprintexample/simple_page/templates/pages/world.html deleted file mode 100644 index 9fa2880a8c..0000000000 --- a/examples/blueprintexample/simple_page/templates/pages/world.html +++ /dev/null @@ -1,4 +0,0 @@ -{% extends "pages/layout.html" %} -{% block body %} - World -{% endblock %} diff --git a/examples/blueprintexample/test_blueprintexample.py b/examples/blueprintexample/test_blueprintexample.py deleted file mode 100644 index 2f3dd93fbe..0000000000 --- a/examples/blueprintexample/test_blueprintexample.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Blueprint Example Tests - ~~~~~~~~~~~~~~ - - Tests the Blueprint example app -""" -import pytest - -import blueprintexample - - -@pytest.fixture -def client(): - return blueprintexample.app.test_client() - - -def test_urls(client): - r = client.get('/') - assert r.status_code == 200 - - r = client.get('/hello') - assert r.status_code == 200 - - r = client.get('/world') - assert r.status_code == 200 - - # second blueprint instance - r = client.get('/pages/hello') - assert r.status_code == 200 - - r = client.get('/pages/world') - assert r.status_code == 200 diff --git a/examples/celery/README.md b/examples/celery/README.md new file mode 100644 index 0000000000..038eb51eb6 --- /dev/null +++ b/examples/celery/README.md @@ -0,0 +1,27 @@ +Background Tasks with Celery +============================ + +This example shows how to configure Celery with Flask, how to set up an API for +submitting tasks and polling results, and how to use that API with JavaScript. See +[Flask's documentation about Celery](https://flask.palletsprojects.com/patterns/celery/). + +From this directory, create a virtualenv and install the application into it. Then run a +Celery worker. + +```shell +$ python3 -m venv .venv +$ . ./.venv/bin/activate +$ pip install -r requirements.txt && pip install -e . +$ celery -A make_celery worker --loglevel INFO +``` + +In a separate terminal, activate the virtualenv and run the Flask development server. + +```shell +$ . ./.venv/bin/activate +$ flask -A task_app run --debug +``` + +Go to http://localhost:5000/ and use the forms to submit tasks. You can see the polling +requests in the browser dev tools and the Flask logs. You can see the tasks submitting +and completing in the Celery logs. diff --git a/examples/celery/make_celery.py b/examples/celery/make_celery.py new file mode 100644 index 0000000000..f7d138e642 --- /dev/null +++ b/examples/celery/make_celery.py @@ -0,0 +1,4 @@ +from task_app import create_app + +flask_app = create_app() +celery_app = flask_app.extensions["celery"] diff --git a/examples/celery/pyproject.toml b/examples/celery/pyproject.toml new file mode 100644 index 0000000000..cca36d8c97 --- /dev/null +++ b/examples/celery/pyproject.toml @@ -0,0 +1,17 @@ +[project] +name = "flask-example-celery" +version = "1.0.0" +description = "Example Flask application with Celery background tasks." +readme = "README.md" +classifiers = ["Private :: Do Not Upload"] +dependencies = ["flask", "celery[redis]"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.module] +name = "task_app" + +[tool.ruff] +src = ["src"] diff --git a/examples/celery/requirements.txt b/examples/celery/requirements.txt new file mode 100644 index 0000000000..29075ab5b6 --- /dev/null +++ b/examples/celery/requirements.txt @@ -0,0 +1,58 @@ +# +# This file is autogenerated by pip-compile with Python 3.11 +# by the following command: +# +# pip-compile --resolver=backtracking pyproject.toml +# +amqp==5.1.1 + # via kombu +async-timeout==4.0.2 + # via redis +billiard==3.6.4.0 + # via celery +blinker==1.6.2 + # via flask +celery[redis]==5.2.7 + # via flask-example-celery (pyproject.toml) +click==8.1.3 + # via + # celery + # click-didyoumean + # click-plugins + # click-repl + # flask +click-didyoumean==0.3.0 + # via celery +click-plugins==1.1.1 + # via celery +click-repl==0.2.0 + # via celery +flask==2.3.2 + # via flask-example-celery (pyproject.toml) +itsdangerous==2.1.2 + # via flask +jinja2==3.1.2 + # via flask +kombu==5.2.4 + # via celery +markupsafe==2.1.2 + # via + # jinja2 + # werkzeug +prompt-toolkit==3.0.38 + # via click-repl +pytz==2023.3 + # via celery +redis==4.5.4 + # via celery +six==1.16.0 + # via click-repl +vine==5.0.0 + # via + # amqp + # celery + # kombu +wcwidth==0.2.6 + # via prompt-toolkit +werkzeug==2.3.3 + # via flask diff --git a/examples/celery/src/task_app/__init__.py b/examples/celery/src/task_app/__init__.py new file mode 100644 index 0000000000..dafff8aad8 --- /dev/null +++ b/examples/celery/src/task_app/__init__.py @@ -0,0 +1,39 @@ +from celery import Celery +from celery import Task +from flask import Flask +from flask import render_template + + +def create_app() -> Flask: + app = Flask(__name__) + app.config.from_mapping( + CELERY=dict( + broker_url="redis://localhost", + result_backend="redis://localhost", + task_ignore_result=True, + ), + ) + app.config.from_prefixed_env() + celery_init_app(app) + + @app.route("/") + def index() -> str: + return render_template("index.html") + + from . import views + + app.register_blueprint(views.bp) + return app + + +def celery_init_app(app: Flask) -> Celery: + class FlaskTask(Task): + def __call__(self, *args: object, **kwargs: object) -> object: + with app.app_context(): + return self.run(*args, **kwargs) + + celery_app = Celery(app.name, task_cls=FlaskTask) + celery_app.config_from_object(app.config["CELERY"]) + celery_app.set_default() + app.extensions["celery"] = celery_app + return celery_app diff --git a/examples/celery/src/task_app/tasks.py b/examples/celery/src/task_app/tasks.py new file mode 100644 index 0000000000..b6b3595d22 --- /dev/null +++ b/examples/celery/src/task_app/tasks.py @@ -0,0 +1,23 @@ +import time + +from celery import shared_task +from celery import Task + + +@shared_task(ignore_result=False) +def add(a: int, b: int) -> int: + return a + b + + +@shared_task() +def block() -> None: + time.sleep(5) + + +@shared_task(bind=True, ignore_result=False) +def process(self: Task, total: int) -> object: + for i in range(total): + self.update_state(state="PROGRESS", meta={"current": i + 1, "total": total}) + time.sleep(1) + + return {"current": total, "total": total} diff --git a/examples/celery/src/task_app/templates/index.html b/examples/celery/src/task_app/templates/index.html new file mode 100644 index 0000000000..4e1145cb8f --- /dev/null +++ b/examples/celery/src/task_app/templates/index.html @@ -0,0 +1,108 @@ + + + + + Celery Example + + +

Celery Example

+Execute background tasks with Celery. Submits tasks and shows results using JavaScript. + +
+

Add

+

Start a task to add two numbers, then poll for the result. +

+
+
+ +
+

Result:

+ +
+

Block

+

Start a task that takes 5 seconds. However, the response will return immediately. +

+ +
+

+ +
+

Process

+

Start a task that counts, waiting one second each time, showing progress. +

+
+ +
+

+ + + + diff --git a/examples/celery/src/task_app/views.py b/examples/celery/src/task_app/views.py new file mode 100644 index 0000000000..99cf92dc20 --- /dev/null +++ b/examples/celery/src/task_app/views.py @@ -0,0 +1,38 @@ +from celery.result import AsyncResult +from flask import Blueprint +from flask import request + +from . import tasks + +bp = Blueprint("tasks", __name__, url_prefix="/tasks") + + +@bp.get("/result/") +def result(id: str) -> dict[str, object]: + result = AsyncResult(id) + ready = result.ready() + return { + "ready": ready, + "successful": result.successful() if ready else None, + "value": result.get() if ready else result.result, + } + + +@bp.post("/add") +def add() -> dict[str, object]: + a = request.form.get("a", type=int) + b = request.form.get("b", type=int) + result = tasks.add.delay(a, b) + return {"result_id": result.id} + + +@bp.post("/block") +def block() -> dict[str, object]: + result = tasks.block.delay() + return {"result_id": result.id} + + +@bp.post("/process") +def process() -> dict[str, object]: + result = tasks.process.delay(total=request.form.get("total", type=int)) + return {"result_id": result.id} diff --git a/examples/flaskr/.gitignore b/examples/flaskr/.gitignore deleted file mode 100644 index 8d567f84e1..0000000000 --- a/examples/flaskr/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -flaskr.db -.eggs/ diff --git a/examples/flaskr/MANIFEST.in b/examples/flaskr/MANIFEST.in deleted file mode 100644 index efbd93df6a..0000000000 --- a/examples/flaskr/MANIFEST.in +++ /dev/null @@ -1,3 +0,0 @@ -graft flaskr/templates -graft flaskr/static -include flaskr/schema.sql diff --git a/examples/flaskr/README b/examples/flaskr/README deleted file mode 100644 index 90860ff2c9..0000000000 --- a/examples/flaskr/README +++ /dev/null @@ -1,38 +0,0 @@ - / Flaskr / - - a minimal blog application - - - ~ What is Flaskr? - - A sqlite powered thumble blog application - - ~ How do I use it? - - 1. edit the configuration in the flaskr.py file or - export an FLASKR_SETTINGS environment variable - pointing to a configuration file. - - 2. install the app from the root of the project directory - - pip install --editable . - - 3. Instruct flask to use the right application - - export FLASK_APP=flaskr - - 4. initialize the database with this command: - - flask initdb - - 5. now you can run flaskr: - - flask run - - the application will greet you on - http://localhost:5000/ - - ~ Is it tested? - - You betcha. Run `python setup.py test` to see - the tests pass. diff --git a/examples/flaskr/flaskr/__init__.py b/examples/flaskr/flaskr/__init__.py deleted file mode 100644 index 37a7b5ccdc..0000000000 --- a/examples/flaskr/flaskr/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from flaskr.flaskr import app \ No newline at end of file diff --git a/examples/flaskr/flaskr/flaskr.py b/examples/flaskr/flaskr/flaskr.py deleted file mode 100644 index b4c1d6bd93..0000000000 --- a/examples/flaskr/flaskr/flaskr.py +++ /dev/null @@ -1,110 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Flaskr - ~~~~~~ - - A microblog example application written as Flask tutorial with - Flask and sqlite3. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - -import os -from sqlite3 import dbapi2 as sqlite3 -from flask import Flask, request, session, g, redirect, url_for, abort, \ - render_template, flash - - -# create our little application :) -app = Flask(__name__) - -# Load default config and override config from an environment variable -app.config.update(dict( - DATABASE=os.path.join(app.root_path, 'flaskr.db'), - DEBUG=True, - SECRET_KEY='development key', - USERNAME='admin', - PASSWORD='default' -)) -app.config.from_envvar('FLASKR_SETTINGS', silent=True) - - -def connect_db(): - """Connects to the specific database.""" - rv = sqlite3.connect(app.config['DATABASE']) - rv.row_factory = sqlite3.Row - return rv - - -def init_db(): - """Initializes the database.""" - db = get_db() - with app.open_resource('schema.sql', mode='r') as f: - db.cursor().executescript(f.read()) - db.commit() - - -@app.cli.command('initdb') -def initdb_command(): - """Creates the database tables.""" - init_db() - print('Initialized the database.') - - -def get_db(): - """Opens a new database connection if there is none yet for the - current application context. - """ - if not hasattr(g, 'sqlite_db'): - g.sqlite_db = connect_db() - return g.sqlite_db - - -@app.teardown_appcontext -def close_db(error): - """Closes the database again at the end of the request.""" - if hasattr(g, 'sqlite_db'): - g.sqlite_db.close() - - -@app.route('/') -def show_entries(): - db = get_db() - cur = db.execute('select title, text from entries order by id desc') - entries = cur.fetchall() - return render_template('show_entries.html', entries=entries) - - -@app.route('/add', methods=['POST']) -def add_entry(): - if not session.get('logged_in'): - abort(401) - db = get_db() - db.execute('insert into entries (title, text) values (?, ?)', - [request.form['title'], request.form['text']]) - db.commit() - flash('New entry was successfully posted') - return redirect(url_for('show_entries')) - - -@app.route('/login', methods=['GET', 'POST']) -def login(): - error = None - if request.method == 'POST': - if request.form['username'] != app.config['USERNAME']: - error = 'Invalid username' - elif request.form['password'] != app.config['PASSWORD']: - error = 'Invalid password' - else: - session['logged_in'] = True - flash('You were logged in') - return redirect(url_for('show_entries')) - return render_template('login.html', error=error) - - -@app.route('/logout') -def logout(): - session.pop('logged_in', None) - flash('You were logged out') - return redirect(url_for('show_entries')) diff --git a/examples/flaskr/flaskr/schema.sql b/examples/flaskr/flaskr/schema.sql deleted file mode 100644 index 25b2cadd1d..0000000000 --- a/examples/flaskr/flaskr/schema.sql +++ /dev/null @@ -1,6 +0,0 @@ -drop table if exists entries; -create table entries ( - id integer primary key autoincrement, - title text not null, - 'text' text not null -); diff --git a/examples/flaskr/flaskr/static/style.css b/examples/flaskr/flaskr/static/style.css deleted file mode 100644 index 4f3b71d8ae..0000000000 --- a/examples/flaskr/flaskr/static/style.css +++ /dev/null @@ -1,18 +0,0 @@ -body { font-family: sans-serif; background: #eee; } -a, h1, h2 { color: #377BA8; } -h1, h2 { font-family: 'Georgia', serif; margin: 0; } -h1 { border-bottom: 2px solid #eee; } -h2 { font-size: 1.2em; } - -.page { margin: 2em auto; width: 35em; border: 5px solid #ccc; - padding: 0.8em; background: white; } -.entries { list-style: none; margin: 0; padding: 0; } -.entries li { margin: 0.8em 1.2em; } -.entries li h2 { margin-left: -1em; } -.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; } -.add-entry dl { font-weight: bold; } -.metanav { text-align: right; font-size: 0.8em; padding: 0.3em; - margin-bottom: 1em; background: #fafafa; } -.flash { background: #CEE5F5; padding: 0.5em; - border: 1px solid #AACBE2; } -.error { background: #F0D6D6; padding: 0.5em; } diff --git a/examples/flaskr/flaskr/templates/layout.html b/examples/flaskr/flaskr/templates/layout.html deleted file mode 100644 index 737b51b2f0..0000000000 --- a/examples/flaskr/flaskr/templates/layout.html +++ /dev/null @@ -1,17 +0,0 @@ - -Flaskr - -
-

Flaskr

-
- {% if not session.logged_in %} - log in - {% else %} - log out - {% endif %} -
- {% for message in get_flashed_messages() %} -
{{ message }}
- {% endfor %} - {% block body %}{% endblock %} -
diff --git a/examples/flaskr/flaskr/templates/login.html b/examples/flaskr/flaskr/templates/login.html deleted file mode 100644 index ed09aebae8..0000000000 --- a/examples/flaskr/flaskr/templates/login.html +++ /dev/null @@ -1,14 +0,0 @@ -{% extends "layout.html" %} -{% block body %} -

Login

- {% if error %}

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

-
-
Username: -
-
Password: -
-
-
-
-{% endblock %} diff --git a/examples/flaskr/flaskr/templates/show_entries.html b/examples/flaskr/flaskr/templates/show_entries.html deleted file mode 100644 index 2f68b9d3d6..0000000000 --- a/examples/flaskr/flaskr/templates/show_entries.html +++ /dev/null @@ -1,21 +0,0 @@ -{% extends "layout.html" %} -{% block body %} - {% if session.logged_in %} -
-
-
Title: -
-
Text: -
-
-
-
- {% endif %} -
    - {% for entry in entries %} -
  • {{ entry.title }}

    {{ entry.text|safe }}
  • - {% else %} -
  • Unbelievable. No entries here so far
  • - {% endfor %} -
-{% endblock %} diff --git a/examples/flaskr/setup.cfg b/examples/flaskr/setup.cfg deleted file mode 100644 index b7e478982c..0000000000 --- a/examples/flaskr/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[aliases] -test=pytest diff --git a/examples/flaskr/setup.py b/examples/flaskr/setup.py deleted file mode 100644 index 910f23aca4..0000000000 --- a/examples/flaskr/setup.py +++ /dev/null @@ -1,16 +0,0 @@ -from setuptools import setup - -setup( - name='flaskr', - packages=['flaskr'], - include_package_data=True, - install_requires=[ - 'flask', - ], - setup_requires=[ - 'pytest-runner', - ], - tests_require=[ - 'pytest', - ], -) diff --git a/examples/flaskr/tests/test_flaskr.py b/examples/flaskr/tests/test_flaskr.py deleted file mode 100644 index 663e92e039..0000000000 --- a/examples/flaskr/tests/test_flaskr.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Flaskr Tests - ~~~~~~~~~~~~ - - Tests the Flaskr application. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - -import os -import tempfile -import pytest -from flaskr import flaskr - - -@pytest.fixture -def client(request): - db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp() - flaskr.app.config['TESTING'] = True - client = flaskr.app.test_client() - with flaskr.app.app_context(): - flaskr.init_db() - - def teardown(): - os.close(db_fd) - os.unlink(flaskr.app.config['DATABASE']) - request.addfinalizer(teardown) - - return client - - -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) - - -def test_empty_db(client): - """Start with a blank database.""" - rv = client.get('/') - assert b'No entries here so far' in rv.data - - -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 - - -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 diff --git a/examples/javascript/.gitignore b/examples/javascript/.gitignore new file mode 100644 index 0000000000..a306afbc08 --- /dev/null +++ b/examples/javascript/.gitignore @@ -0,0 +1,14 @@ +.venv/ +*.pyc +__pycache__/ +instance/ +.cache/ +.pytest_cache/ +.coverage +htmlcov/ +dist/ +build/ +*.egg-info/ +.idea/ +*.swp +*~ diff --git a/examples/javascript/LICENSE.txt b/examples/javascript/LICENSE.txt new file mode 100644 index 0000000000..9d227a0cc4 --- /dev/null +++ b/examples/javascript/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 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. diff --git a/examples/javascript/README.rst b/examples/javascript/README.rst new file mode 100644 index 0000000000..f5f66912f8 --- /dev/null +++ b/examples/javascript/README.rst @@ -0,0 +1,48 @@ +JavaScript 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 |fetch|_, |XMLHttpRequest|_, and +|jQuery.ajax|_. See the `Flask docs`_ about JavaScript and Ajax. + +.. |fetch| replace:: ``fetch`` +.. _fetch: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch + +.. |XMLHttpRequest| replace:: ``XMLHttpRequest`` +.. _XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest + +.. |jQuery.ajax| replace:: ``jQuery.ajax`` +.. _jQuery.ajax: https://api.jquery.com/jQuery.ajax/ + +.. _Flask docs: https://flask.palletsprojects.com/patterns/javascript/ + + +Install +------- + +.. code-block:: text + + $ python3 -m venv .venv + $ . .venv/bin/activate + $ pip install -e . + + +Run +--- + +.. code-block:: text + + $ flask --app js_example run + +Open http://127.0.0.1:5000 in a browser. + + +Test +---- + +.. code-block:: text + + $ pip install -e '.[test]' + $ coverage run -m pytest + $ coverage report diff --git a/examples/javascript/js_example/__init__.py b/examples/javascript/js_example/__init__.py new file mode 100644 index 0000000000..0ec3ca215a --- /dev/null +++ b/examples/javascript/js_example/__init__.py @@ -0,0 +1,5 @@ +from flask import Flask + +app = Flask(__name__) + +from js_example import views # noqa: E402, F401 diff --git a/examples/javascript/js_example/templates/base.html b/examples/javascript/js_example/templates/base.html new file mode 100644 index 0000000000..a4d35bd7d7 --- /dev/null +++ b/examples/javascript/js_example/templates/base.html @@ -0,0 +1,33 @@ + +JavaScript Example + + + + +
+

{% block intro %}{% endblock %}

+
+
+ + + + + +
+= +{% block script %}{% endblock %} diff --git a/examples/javascript/js_example/templates/fetch.html b/examples/javascript/js_example/templates/fetch.html new file mode 100644 index 0000000000..e2944b8575 --- /dev/null +++ b/examples/javascript/js_example/templates/fetch.html @@ -0,0 +1,33 @@ +{% extends 'base.html' %} + +{% block intro %} + fetch + is the modern plain JavaScript way to make requests. It's + supported in all modern browsers. +{% endblock %} + +{% block script %} + +{% endblock %} diff --git a/examples/javascript/js_example/templates/jquery.html b/examples/javascript/js_example/templates/jquery.html new file mode 100644 index 0000000000..48f0c11ca2 --- /dev/null +++ b/examples/javascript/js_example/templates/jquery.html @@ -0,0 +1,27 @@ +{% 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 %} diff --git a/examples/javascript/js_example/templates/xhr.html b/examples/javascript/js_example/templates/xhr.html new file mode 100644 index 0000000000..1672d4d6fd --- /dev/null +++ b/examples/javascript/js_example/templates/xhr.html @@ -0,0 +1,29 @@ +{% extends 'base.html' %} + +{% block intro %} + XMLHttpRequest + is the original JavaScript way to make requests. It's natively supported + by all browsers, but has been superseded by + fetch. +{% endblock %} + +{% block script %} + +{% endblock %} diff --git a/examples/javascript/js_example/views.py b/examples/javascript/js_example/views.py new file mode 100644 index 0000000000..9f0d26c5e1 --- /dev/null +++ b/examples/javascript/js_example/views.py @@ -0,0 +1,18 @@ +from flask import jsonify +from flask import render_template +from flask import request + +from . import app + + +@app.route("/", defaults={"js": "fetch"}) +@app.route("/") +def index(js): + return render_template(f"{js}.html", 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) diff --git a/examples/javascript/pyproject.toml b/examples/javascript/pyproject.toml new file mode 100644 index 0000000000..ea0efabd27 --- /dev/null +++ b/examples/javascript/pyproject.toml @@ -0,0 +1,33 @@ +[project] +name = "js_example" +version = "1.1.0" +description = "Demonstrates making AJAX requests to Flask." +readme = "README.rst" +license = {file = "LICENSE.txt"} +maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}] +classifiers = ["Private :: Do Not Upload"] +dependencies = ["flask"] + +[project.urls] +Documentation = "https://flask.palletsprojects.com/patterns/javascript/" + +[project.optional-dependencies] +test = ["pytest"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.module] +name = "js_example" + +[tool.pytest.ini_options] +testpaths = ["tests"] +filterwarnings = ["error"] + +[tool.coverage.run] +branch = true +source = ["js_example", "tests"] + +[tool.ruff] +src = ["src"] diff --git a/examples/javascript/tests/conftest.py b/examples/javascript/tests/conftest.py new file mode 100644 index 0000000000..e0cabbfd1d --- /dev/null +++ b/examples/javascript/tests/conftest.py @@ -0,0 +1,15 @@ +import 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() diff --git a/examples/javascript/tests/test_js_example.py b/examples/javascript/tests/test_js_example.py new file mode 100644 index 0000000000..856f5f7725 --- /dev/null +++ b/examples/javascript/tests/test_js_example.py @@ -0,0 +1,27 @@ +import pytest +from flask import template_rendered + + +@pytest.mark.parametrize( + ("path", "template_name"), + ( + ("/", "fetch.html"), + ("/plain", "xhr.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 diff --git a/examples/jqueryexample/jqueryexample.py b/examples/jqueryexample/jqueryexample.py deleted file mode 100644 index 39b81951d1..0000000000 --- a/examples/jqueryexample/jqueryexample.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -""" - jQuery Example - ~~~~~~~~~~~~~~ - - A simple application that shows how Flask and jQuery get along. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -from flask import Flask, jsonify, render_template, request -app = Flask(__name__) - - -@app.route('/_add_numbers') -def add_numbers(): - """Add two numbers server side, ridiculous but well...""" - 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') - -if __name__ == '__main__': - app.run() diff --git a/examples/jqueryexample/templates/index.html b/examples/jqueryexample/templates/index.html deleted file mode 100644 index b6118cf4d6..0000000000 --- a/examples/jqueryexample/templates/index.html +++ /dev/null @@ -1,33 +0,0 @@ -{% extends "layout.html" %} -{% block body %} - -

jQuery Example

-

- + - = - ? -

calculate server side -{% endblock %} diff --git a/examples/jqueryexample/templates/layout.html b/examples/jqueryexample/templates/layout.html deleted file mode 100644 index 8be7606e16..0000000000 --- a/examples/jqueryexample/templates/layout.html +++ /dev/null @@ -1,8 +0,0 @@ - -jQuery Example - - -{% block body %}{% endblock %} diff --git a/examples/minitwit/.gitignore b/examples/minitwit/.gitignore deleted file mode 100644 index c3accd8238..0000000000 --- a/examples/minitwit/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -minitwit.db -.eggs/ diff --git a/examples/minitwit/MANIFEST.in b/examples/minitwit/MANIFEST.in deleted file mode 100644 index 973d65863a..0000000000 --- a/examples/minitwit/MANIFEST.in +++ /dev/null @@ -1,3 +0,0 @@ -graft minitwit/templates -graft minitwit/static -include minitwit/schema.sql \ No newline at end of file diff --git a/examples/minitwit/README b/examples/minitwit/README deleted file mode 100644 index 4561d836c1..0000000000 --- a/examples/minitwit/README +++ /dev/null @@ -1,35 +0,0 @@ - - / MiniTwit / - - because writing todo lists is not fun - - - ~ What is MiniTwit? - - A SQLite and Flask powered twitter clone - - ~ How do I use it? - - 1. edit the configuration in the minitwit.py file or - export an MINITWIT_SETTINGS environment variable - pointing to a configuration file. - - 2. tell flask about the right application: - - export FLASK_APP=minitwit - - 2. fire up a shell and run this: - - flask initdb - - 3. now you can run minitwit: - - flask run - - the application will greet you on - http://localhost:5000/ - - ~ Is it tested? - - You betcha. Run the `python setup.py test` file to - see the tests pass. diff --git a/examples/minitwit/minitwit/__init__.py b/examples/minitwit/minitwit/__init__.py deleted file mode 100644 index 0b8bd697a7..0000000000 --- a/examples/minitwit/minitwit/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from minitwit import app \ No newline at end of file diff --git a/examples/minitwit/minitwit/minitwit.py b/examples/minitwit/minitwit/minitwit.py deleted file mode 100644 index bbc3b48301..0000000000 --- a/examples/minitwit/minitwit/minitwit.py +++ /dev/null @@ -1,256 +0,0 @@ -# -*- coding: utf-8 -*- -""" - MiniTwit - ~~~~~~~~ - - A microblogging application written with Flask and sqlite3. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - -import time -from sqlite3 import dbapi2 as sqlite3 -from hashlib import md5 -from datetime import datetime -from flask import Flask, request, session, url_for, redirect, \ - render_template, abort, g, flash, _app_ctx_stack -from werkzeug import check_password_hash, generate_password_hash - - -# configuration -DATABASE = '/tmp/minitwit.db' -PER_PAGE = 30 -DEBUG = True -SECRET_KEY = 'development key' - -# create our little application :) -app = Flask(__name__) -app.config.from_object(__name__) -app.config.from_envvar('MINITWIT_SETTINGS', silent=True) - - -def get_db(): - """Opens a new database connection if there is none yet for the - current application context. - """ - top = _app_ctx_stack.top - if not hasattr(top, 'sqlite_db'): - top.sqlite_db = sqlite3.connect(app.config['DATABASE']) - top.sqlite_db.row_factory = sqlite3.Row - return top.sqlite_db - - -@app.teardown_appcontext -def close_database(exception): - """Closes the database again at the end of the request.""" - top = _app_ctx_stack.top - if hasattr(top, 'sqlite_db'): - top.sqlite_db.close() - - -def init_db(): - """Initializes the database.""" - db = get_db() - with app.open_resource('schema.sql', mode='r') as f: - db.cursor().executescript(f.read()) - db.commit() - - -@app.cli.command('initdb') -def initdb_command(): - """Creates the database tables.""" - init_db() - print('Initialized the database.') - - -def query_db(query, args=(), one=False): - """Queries the database and returns a list of dictionaries.""" - cur = get_db().execute(query, args) - rv = cur.fetchall() - return (rv[0] if rv else None) if one else rv - - -def get_user_id(username): - """Convenience method to look up the id for a username.""" - rv = query_db('select user_id from user where username = ?', - [username], one=True) - return rv[0] if rv else None - - -def format_datetime(timestamp): - """Format a timestamp for display.""" - return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M') - - -def gravatar_url(http://github.com/email,%20size=80): - """Return the gravatar image for the given email address.""" - return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \ - (md5(email.strip().lower().encode('utf-8')).hexdigest(), size) - - -@app.before_request -def before_request(): - g.user = None - if 'user_id' in session: - g.user = query_db('select * from user where user_id = ?', - [session['user_id']], one=True) - - -@app.route('/') -def timeline(): - """Shows a users timeline or if no user is logged in it will - redirect to the public timeline. This timeline shows the user's - messages as well as all the messages of followed users. - """ - if not g.user: - return redirect(url_for('public_timeline')) - return render_template('timeline.html', messages=query_db(''' - select message.*, user.* from message, user - where message.author_id = user.user_id and ( - user.user_id = ? or - user.user_id in (select whom_id from follower - where who_id = ?)) - order by message.pub_date desc limit ?''', - [session['user_id'], session['user_id'], PER_PAGE])) - - -@app.route('/public') -def public_timeline(): - """Displays the latest messages of all users.""" - return render_template('timeline.html', messages=query_db(''' - select message.*, user.* from message, user - where message.author_id = user.user_id - order by message.pub_date desc limit ?''', [PER_PAGE])) - - -@app.route('/') -def user_timeline(username): - """Display's a users tweets.""" - profile_user = query_db('select * from user where username = ?', - [username], one=True) - if profile_user is None: - abort(404) - followed = False - if g.user: - followed = query_db('''select 1 from follower where - follower.who_id = ? and follower.whom_id = ?''', - [session['user_id'], profile_user['user_id']], - one=True) is not None - return render_template('timeline.html', messages=query_db(''' - select message.*, user.* from message, user where - user.user_id = message.author_id and user.user_id = ? - order by message.pub_date desc limit ?''', - [profile_user['user_id'], PER_PAGE]), followed=followed, - profile_user=profile_user) - - -@app.route('//follow') -def follow_user(username): - """Adds the current user as follower of the given user.""" - if not g.user: - abort(401) - whom_id = get_user_id(username) - if whom_id is None: - abort(404) - db = get_db() - db.execute('insert into follower (who_id, whom_id) values (?, ?)', - [session['user_id'], whom_id]) - db.commit() - flash('You are now following "%s"' % username) - return redirect(url_for('user_timeline', username=username)) - - -@app.route('//unfollow') -def unfollow_user(username): - """Removes the current user as follower of the given user.""" - if not g.user: - abort(401) - whom_id = get_user_id(username) - if whom_id is None: - abort(404) - db = get_db() - db.execute('delete from follower where who_id=? and whom_id=?', - [session['user_id'], whom_id]) - db.commit() - flash('You are no longer following "%s"' % username) - return redirect(url_for('user_timeline', username=username)) - - -@app.route('/add_message', methods=['POST']) -def add_message(): - """Registers a new message for the user.""" - if 'user_id' not in session: - abort(401) - if request.form['text']: - db = get_db() - db.execute('''insert into message (author_id, text, pub_date) - values (?, ?, ?)''', (session['user_id'], request.form['text'], - int(time.time()))) - db.commit() - flash('Your message was recorded') - return redirect(url_for('timeline')) - - -@app.route('/login', methods=['GET', 'POST']) -def login(): - """Logs the user in.""" - if g.user: - return redirect(url_for('timeline')) - error = None - if request.method == 'POST': - user = query_db('''select * from user where - username = ?''', [request.form['username']], one=True) - if user is None: - error = 'Invalid username' - elif not check_password_hash(user['pw_hash'], - request.form['password']): - error = 'Invalid password' - else: - flash('You were logged in') - session['user_id'] = user['user_id'] - return redirect(url_for('timeline')) - return render_template('login.html', error=error) - - -@app.route('/register', methods=['GET', 'POST']) -def register(): - """Registers the user.""" - if g.user: - return redirect(url_for('timeline')) - error = None - if request.method == 'POST': - if not request.form['username']: - error = 'You have to enter a username' - elif not request.form['email'] or \ - '@' not in request.form['email']: - error = 'You have to enter a valid email address' - elif not request.form['password']: - error = 'You have to enter a password' - elif request.form['password'] != request.form['password2']: - error = 'The two passwords do not match' - elif get_user_id(request.form['username']) is not None: - error = 'The username is already taken' - else: - db = get_db() - db.execute('''insert into user ( - username, email, pw_hash) values (?, ?, ?)''', - [request.form['username'], request.form['email'], - generate_password_hash(request.form['password'])]) - db.commit() - flash('You were successfully registered and can login now') - return redirect(url_for('login')) - return render_template('register.html', error=error) - - -@app.route('/logout') -def logout(): - """Logs the user out.""" - flash('You were logged out') - session.pop('user_id', None) - return redirect(url_for('public_timeline')) - - -# add some filters to jinja -app.jinja_env.filters['datetimeformat'] = format_datetime -app.jinja_env.filters['gravatar'] = gravatar_url diff --git a/examples/minitwit/minitwit/schema.sql b/examples/minitwit/minitwit/schema.sql deleted file mode 100644 index b272adc894..0000000000 --- a/examples/minitwit/minitwit/schema.sql +++ /dev/null @@ -1,21 +0,0 @@ -drop table if exists user; -create table user ( - user_id integer primary key autoincrement, - username text not null, - email text not null, - pw_hash text not null -); - -drop table if exists follower; -create table follower ( - who_id integer, - whom_id integer -); - -drop table if exists message; -create table message ( - message_id integer primary key autoincrement, - author_id integer not null, - text text not null, - pub_date integer -); diff --git a/examples/minitwit/minitwit/static/style.css b/examples/minitwit/minitwit/static/style.css deleted file mode 100644 index ebbed8c9c9..0000000000 --- a/examples/minitwit/minitwit/static/style.css +++ /dev/null @@ -1,178 +0,0 @@ -body { - background: #CAECE9; - font-family: 'Trebuchet MS', sans-serif; - font-size: 14px; -} - -a { - color: #26776F; -} - -a:hover { - color: #333; -} - -input[type="text"], -input[type="password"] { - background: white; - border: 1px solid #BFE6E2; - padding: 2px; - font-family: 'Trebuchet MS', sans-serif; - font-size: 14px; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - color: #105751; -} - -input[type="submit"] { - background: #105751; - border: 1px solid #073B36; - padding: 1px 3px; - font-family: 'Trebuchet MS', sans-serif; - font-size: 14px; - font-weight: bold; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - color: white; -} - -div.page { - background: white; - border: 1px solid #6ECCC4; - width: 700px; - margin: 30px auto; -} - -div.page h1 { - background: #6ECCC4; - margin: 0; - padding: 10px 14px; - color: white; - letter-spacing: 1px; - text-shadow: 0 0 3px #24776F; - font-weight: normal; -} - -div.page div.navigation { - background: #DEE9E8; - padding: 4px 10px; - border-top: 1px solid #ccc; - border-bottom: 1px solid #eee; - color: #888; - font-size: 12px; - letter-spacing: 0.5px; -} - -div.page div.navigation a { - color: #444; - font-weight: bold; -} - -div.page h2 { - margin: 0 0 15px 0; - color: #105751; - text-shadow: 0 1px 2px #ccc; -} - -div.page div.body { - padding: 10px; -} - -div.page div.footer { - background: #eee; - color: #888; - padding: 5px 10px; - font-size: 12px; -} - -div.page div.followstatus { - border: 1px solid #ccc; - background: #E3EBEA; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - padding: 3px; - font-size: 13px; -} - -div.page ul.messages { - list-style: none; - margin: 0; - padding: 0; -} - -div.page ul.messages li { - margin: 10px 0; - padding: 5px; - background: #F0FAF9; - border: 1px solid #DBF3F1; - -moz-border-radius: 5px; - -webkit-border-radius: 5px; - min-height: 48px; -} - -div.page ul.messages p { - margin: 0; -} - -div.page ul.messages li img { - float: left; - padding: 0 10px 0 0; -} - -div.page ul.messages li small { - font-size: 0.9em; - color: #888; -} - -div.page div.twitbox { - margin: 10px 0; - padding: 5px; - background: #F0FAF9; - border: 1px solid #94E2DA; - -moz-border-radius: 5px; - -webkit-border-radius: 5px; -} - -div.page div.twitbox h3 { - margin: 0; - font-size: 1em; - color: #2C7E76; -} - -div.page div.twitbox p { - margin: 0; -} - -div.page div.twitbox input[type="text"] { - width: 585px; -} - -div.page div.twitbox input[type="submit"] { - width: 70px; - margin-left: 5px; -} - -ul.flashes { - list-style: none; - margin: 10px 10px 0 10px; - padding: 0; -} - -ul.flashes li { - background: #B9F3ED; - border: 1px solid #81CEC6; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - padding: 4px; - font-size: 13px; -} - -div.error { - margin: 10px 0; - background: #FAE4E4; - border: 1px solid #DD6F6F; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - padding: 4px; - font-size: 13px; -} diff --git a/examples/minitwit/minitwit/templates/layout.html b/examples/minitwit/minitwit/templates/layout.html deleted file mode 100644 index 5a43df61dc..0000000000 --- a/examples/minitwit/minitwit/templates/layout.html +++ /dev/null @@ -1,32 +0,0 @@ - -{% block title %}Welcome{% endblock %} | MiniTwit - -

-

MiniTwit

- - {% with flashes = get_flashed_messages() %} - {% if flashes %} -
    - {% for message in flashes %} -
  • {{ message }} - {% endfor %} -
- {% endif %} - {% endwith %} -
- {% block body %}{% endblock %} -
- -
diff --git a/examples/minitwit/minitwit/templates/login.html b/examples/minitwit/minitwit/templates/login.html deleted file mode 100644 index f15bf1098d..0000000000 --- a/examples/minitwit/minitwit/templates/login.html +++ /dev/null @@ -1,16 +0,0 @@ -{% extends "layout.html" %} -{% block title %}Sign In{% endblock %} -{% block body %} -

Sign In

- {% if error %}
Error: {{ error }}
{% endif %} -
-
-
Username: -
-
Password: -
-
-
-
-{% endblock %} - diff --git a/examples/minitwit/minitwit/templates/register.html b/examples/minitwit/minitwit/templates/register.html deleted file mode 100644 index f28cd9f0c8..0000000000 --- a/examples/minitwit/minitwit/templates/register.html +++ /dev/null @@ -1,19 +0,0 @@ -{% extends "layout.html" %} -{% block title %}Sign Up{% endblock %} -{% block body %} -

Sign Up

- {% if error %}
Error: {{ error }}
{% endif %} -
-
-
Username: -
-
E-Mail: -
-
Password: -
-
Password (repeat): -
-
-
-
-{% endblock %} diff --git a/examples/minitwit/minitwit/templates/timeline.html b/examples/minitwit/minitwit/templates/timeline.html deleted file mode 100644 index bf655634e5..0000000000 --- a/examples/minitwit/minitwit/templates/timeline.html +++ /dev/null @@ -1,49 +0,0 @@ -{% extends "layout.html" %} -{% block title %} - {% if request.endpoint == 'public_timeline' %} - Public Timeline - {% elif request.endpoint == 'user_timeline' %} - {{ profile_user.username }}'s Timeline - {% else %} - My Timeline - {% endif %} -{% endblock %} -{% block body %} -

{{ self.title() }}

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

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

-
-

-

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

  • There's no message so far. - {% endfor %} -
-{% endblock %} diff --git a/examples/minitwit/setup.cfg b/examples/minitwit/setup.cfg deleted file mode 100644 index b7e478982c..0000000000 --- a/examples/minitwit/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[aliases] -test=pytest diff --git a/examples/minitwit/setup.py b/examples/minitwit/setup.py deleted file mode 100644 index 1e5802167f..0000000000 --- a/examples/minitwit/setup.py +++ /dev/null @@ -1,16 +0,0 @@ -from setuptools import setup - -setup( - name='minitwit', - packages=['minitwit'], - include_package_data=True, - install_requires=[ - 'flask', - ], - setup_requires=[ - 'pytest-runner', - ], - tests_require=[ - 'pytest', - ], -) \ No newline at end of file diff --git a/examples/minitwit/tests/test_minitwit.py b/examples/minitwit/tests/test_minitwit.py deleted file mode 100644 index 50ca26d94b..0000000000 --- a/examples/minitwit/tests/test_minitwit.py +++ /dev/null @@ -1,151 +0,0 @@ -# -*- coding: utf-8 -*- -""" - MiniTwit Tests - ~~~~~~~~~~~~~~ - - Tests the MiniTwit application. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -import os -import tempfile -import pytest -from minitwit import minitwit - - -@pytest.fixture -def client(request): - db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp() - client = minitwit.app.test_client() - with minitwit.app.app_context(): - minitwit.init_db() - - def teardown(): - """Get rid of the database again after each test.""" - os.close(db_fd) - os.unlink(minitwit.app.config['DATABASE']) - request.addfinalizer(teardown) - return client - - -def register(client, username, password, password2=None, email=None): - """Helper function to register a user""" - if password2 is None: - password2 = password - if email is None: - email = username + '@example.com' - return client.post('/register', data={ - 'username': username, - 'password': password, - 'password2': password2, - 'email': email, - }, follow_redirects=True) - - -def login(client, username, password): - """Helper function to login""" - return client.post('/login', data={ - 'username': username, - 'password': password - }, follow_redirects=True) - - -def register_and_login(client, username, password): - """Registers and logs in in one go""" - register(client, username, password) - return login(client, username, password) - - -def logout(client): - """Helper function to logout""" - return client.get('/logout', follow_redirects=True) - - -def add_message(client, text): - """Records a message""" - rv = client.post('/add_message', data={'text': text}, - follow_redirects=True) - if text: - assert b'Your message was recorded' in rv.data - return rv - - -def test_register(client): - """Make sure registering works""" - rv = register(client, 'user1', 'default') - assert b'You were successfully registered ' \ - b'and can login now' in rv.data - rv = register(client, 'user1', 'default') - assert b'The username is already taken' in rv.data - rv = register(client, '', 'default') - assert b'You have to enter a username' in rv.data - rv = register(client, 'meh', '') - assert b'You have to enter a password' in rv.data - rv = register(client, 'meh', 'x', 'y') - assert b'The two passwords do not match' in rv.data - rv = register(client, 'meh', 'foo', email='broken') - assert b'You have to enter a valid email address' in rv.data - - -def test_login_logout(client): - """Make sure logging in and logging out works""" - rv = register_and_login(client, 'user1', 'default') - assert b'You were logged in' in rv.data - rv = logout(client) - assert b'You were logged out' in rv.data - rv = login(client, 'user1', 'wrongpassword') - assert b'Invalid password' in rv.data - rv = login(client, 'user2', 'wrongpassword') - assert b'Invalid username' in rv.data - - -def test_message_recording(client): - """Check if adding messages works""" - register_and_login(client, 'foo', 'default') - add_message(client, 'test message 1') - add_message(client, '') - rv = client.get('/') - assert b'test message 1' in rv.data - assert b'<test message 2>' in rv.data - - -def test_timelines(client): - """Make sure that timelines work""" - register_and_login(client, 'foo', 'default') - add_message(client, 'the message by foo') - logout(client) - register_and_login(client, 'bar', 'default') - add_message(client, 'the message by bar') - rv = client.get('/public') - assert b'the message by foo' in rv.data - assert b'the message by bar' in rv.data - - # bar's timeline should just show bar's message - rv = client.get('/') - assert b'the message by foo' not in rv.data - assert b'the message by bar' in rv.data - - # now let's follow foo - rv = client.get('/foo/follow', follow_redirects=True) - assert b'You are now following "foo"' in rv.data - - # we should now see foo's message - rv = client.get('/') - assert b'the message by foo' in rv.data - assert b'the message by bar' in rv.data - - # but on the user's page we only want the user's message - rv = client.get('/bar') - assert b'the message by foo' not in rv.data - assert b'the message by bar' in rv.data - rv = client.get('/foo') - assert b'the message by foo' in rv.data - assert b'the message by bar' not in rv.data - - # now unfollow and check if that worked - rv = client.get('/foo/unfollow', follow_redirects=True) - assert b'You are no longer following "foo"' in rv.data - rv = client.get('/') - assert b'the message by foo' not in rv.data - assert b'the message by bar' in rv.data diff --git a/examples/tutorial/.gitignore b/examples/tutorial/.gitignore new file mode 100644 index 0000000000..a306afbc08 --- /dev/null +++ b/examples/tutorial/.gitignore @@ -0,0 +1,14 @@ +.venv/ +*.pyc +__pycache__/ +instance/ +.cache/ +.pytest_cache/ +.coverage +htmlcov/ +dist/ +build/ +*.egg-info/ +.idea/ +*.swp +*~ diff --git a/examples/tutorial/LICENSE.txt b/examples/tutorial/LICENSE.txt new file mode 100644 index 0000000000..9d227a0cc4 --- /dev/null +++ b/examples/tutorial/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 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. diff --git a/examples/tutorial/README.rst b/examples/tutorial/README.rst new file mode 100644 index 0000000000..653c216729 --- /dev/null +++ b/examples/tutorial/README.rst @@ -0,0 +1,68 @@ +Flaskr +====== + +The basic blog app built in the Flask `tutorial`_. + +.. _tutorial: https://flask.palletsprojects.com/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 main 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 main branch, install Flask from source before +installing Flaskr:: + + $ pip install -e ../.. + $ pip install -e . + + +Run +--- + +.. code-block:: text + + $ flask --app flaskr init-db + $ flask --app flaskr run --debug + +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 diff --git a/examples/tutorial/flaskr/__init__.py b/examples/tutorial/flaskr/__init__.py new file mode 100644 index 0000000000..e35934d676 --- /dev/null +++ b/examples/tutorial/flaskr/__init__.py @@ -0,0 +1,51 @@ +import 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 . import db + + db.init_app(app) + + # apply the blueprints to the app + from . import auth + from . import 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 diff --git a/examples/tutorial/flaskr/auth.py b/examples/tutorial/flaskr/auth.py new file mode 100644 index 0000000000..34c03a204f --- /dev/null +++ b/examples/tutorial/flaskr/auth.py @@ -0,0 +1,116 @@ +import 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 .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." + + if error is None: + try: + db.execute( + "INSERT INTO user (username, password) VALUES (?, ?)", + (username, generate_password_hash(password)), + ) + db.commit() + except db.IntegrityError: + # The username was already taken, which caused the + # commit to fail. Show a validation error. + error = f"User {username} is already registered." + else: + # Success, go to the login page. + 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")) diff --git a/examples/tutorial/flaskr/blog.py b/examples/tutorial/flaskr/blog.py new file mode 100644 index 0000000000..be0d92c435 --- /dev/null +++ b/examples/tutorial/flaskr/blog.py @@ -0,0 +1,125 @@ +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 url_for +from werkzeug.exceptions import abort + +from .auth import login_required +from .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, f"Post id {id} doesn't exist.") + + 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")) diff --git a/examples/tutorial/flaskr/db.py b/examples/tutorial/flaskr/db.py new file mode 100644 index 0000000000..dec22fde2d --- /dev/null +++ b/examples/tutorial/flaskr/db.py @@ -0,0 +1,56 @@ +import sqlite3 +from datetime import datetime + +import click +from flask import current_app +from flask import g + + +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") +def init_db_command(): + """Clear existing data and create new tables.""" + init_db() + click.echo("Initialized the database.") + + +sqlite3.register_converter("timestamp", lambda v: datetime.fromisoformat(v.decode())) + + +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) diff --git a/examples/tutorial/flaskr/schema.sql b/examples/tutorial/flaskr/schema.sql new file mode 100644 index 0000000000..dd4c86600a --- /dev/null +++ b/examples/tutorial/flaskr/schema.sql @@ -0,0 +1,20 @@ +-- 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) +); diff --git a/examples/tutorial/flaskr/static/style.css b/examples/tutorial/flaskr/static/style.css new file mode 100644 index 0000000000..2f1f4d0c3c --- /dev/null +++ b/examples/tutorial/flaskr/static/style.css @@ -0,0 +1,134 @@ +html { + 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; +} diff --git a/examples/tutorial/flaskr/templates/auth/login.html b/examples/tutorial/flaskr/templates/auth/login.html new file mode 100644 index 0000000000..b326b5a6b8 --- /dev/null +++ b/examples/tutorial/flaskr/templates/auth/login.html @@ -0,0 +1,15 @@ +{% extends 'base.html' %} + +{% block header %} +

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

+{% endblock %} + +{% block content %} +
+ + + + + +
+{% endblock %} diff --git a/examples/tutorial/flaskr/templates/auth/register.html b/examples/tutorial/flaskr/templates/auth/register.html new file mode 100644 index 0000000000..4320e17e84 --- /dev/null +++ b/examples/tutorial/flaskr/templates/auth/register.html @@ -0,0 +1,15 @@ +{% extends 'base.html' %} + +{% block header %} +

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

+{% endblock %} + +{% block content %} +
+ + + + + +
+{% endblock %} diff --git a/examples/tutorial/flaskr/templates/base.html b/examples/tutorial/flaskr/templates/base.html new file mode 100644 index 0000000000..f09e92687c --- /dev/null +++ b/examples/tutorial/flaskr/templates/base.html @@ -0,0 +1,24 @@ + +{% block title %}{% endblock %} - Flaskr + + +
+
+ {% block header %}{% endblock %} +
+ {% for message in get_flashed_messages() %} +
{{ message }}
+ {% endfor %} + {% block content %}{% endblock %} +
diff --git a/examples/tutorial/flaskr/templates/blog/create.html b/examples/tutorial/flaskr/templates/blog/create.html new file mode 100644 index 0000000000..88e31e44bd --- /dev/null +++ b/examples/tutorial/flaskr/templates/blog/create.html @@ -0,0 +1,15 @@ +{% extends 'base.html' %} + +{% block header %} +

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

+{% endblock %} + +{% block content %} +
+ + + + + +
+{% endblock %} diff --git a/examples/tutorial/flaskr/templates/blog/index.html b/examples/tutorial/flaskr/templates/blog/index.html new file mode 100644 index 0000000000..3481b8e18d --- /dev/null +++ b/examples/tutorial/flaskr/templates/blog/index.html @@ -0,0 +1,28 @@ +{% 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 %} diff --git a/examples/tutorial/flaskr/templates/blog/update.html b/examples/tutorial/flaskr/templates/blog/update.html new file mode 100644 index 0000000000..2c405e6303 --- /dev/null +++ b/examples/tutorial/flaskr/templates/blog/update.html @@ -0,0 +1,19 @@ +{% extends 'base.html' %} + +{% block header %} +

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

+{% endblock %} + +{% block content %} +
+ + + + + +
+
+
+ +
+{% endblock %} diff --git a/examples/tutorial/pyproject.toml b/examples/tutorial/pyproject.toml new file mode 100644 index 0000000000..ca31e53d19 --- /dev/null +++ b/examples/tutorial/pyproject.toml @@ -0,0 +1,40 @@ +[project] +name = "flaskr" +version = "1.0.0" +description = "The basic blog app built in the Flask tutorial." +readme = "README.rst" +license = {file = "LICENSE.txt"} +maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}] +classifiers = ["Private :: Do Not Upload"] +dependencies = [ + "flask", +] + +[project.urls] +Documentation = "https://flask.palletsprojects.com/tutorial/" + +[project.optional-dependencies] +test = ["pytest"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.module] +name = "flaskr" + +[tool.flit.sdist] +include = [ + "tests/", +] + +[tool.pytest.ini_options] +testpaths = ["tests"] +filterwarnings = ["error"] + +[tool.coverage.run] +branch = true +source = ["flaskr", "tests"] + +[tool.ruff] +src = ["src"] diff --git a/examples/tutorial/tests/conftest.py b/examples/tutorial/tests/conftest.py new file mode 100644 index 0000000000..6bf62f0a8f --- /dev/null +++ b/examples/tutorial/tests/conftest.py @@ -0,0 +1,62 @@ +import 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: + 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) diff --git a/examples/tutorial/tests/data.sql b/examples/tutorial/tests/data.sql new file mode 100644 index 0000000000..9b68006510 --- /dev/null +++ b/examples/tutorial/tests/data.sql @@ -0,0 +1,8 @@ +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'); diff --git a/examples/tutorial/tests/test_auth.py b/examples/tutorial/tests/test_auth.py new file mode 100644 index 0000000000..76db62f79d --- /dev/null +++ b/examples/tutorial/tests/test_auth.py @@ -0,0 +1,69 @@ +import 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 response.headers["Location"] == "/auth/login" + + # 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"] == "/" + + # 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 diff --git a/examples/tutorial/tests/test_blog.py b/examples/tutorial/tests/test_blog.py new file mode 100644 index 0000000000..55c769d817 --- /dev/null +++ b/examples/tutorial/tests/test_blog.py @@ -0,0 +1,83 @@ +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"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="http://github.com/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"] == "/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="http://github.com/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"] == "/" + + with app.app_context(): + db = get_db() + post = db.execute("SELECT * FROM post WHERE id = 1").fetchone() + assert post is None diff --git a/examples/tutorial/tests/test_db.py b/examples/tutorial/tests/test_db.py new file mode 100644 index 0000000000..2363bf8163 --- /dev/null +++ b/examples/tutorial/tests/test_db.py @@ -0,0 +1,29 @@ +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) + + +def test_init_db_command(runner, monkeypatch): + class Recorder: + 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 diff --git a/examples/tutorial/tests/test_factory.py b/examples/tutorial/tests/test_factory.py new file mode 100644 index 0000000000..9b7ca57fd4 --- /dev/null +++ b/examples/tutorial/tests/test_factory.py @@ -0,0 +1,12 @@ +from 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!" diff --git a/flask/__init__.py b/flask/__init__.py deleted file mode 100644 index 509b944f48..0000000000 --- a/flask/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask - ~~~~~ - - A microframework based on Werkzeug. It's extensively documented - and follows best practice patterns. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - -__version__ = '0.11.2-dev' - -# utilities we import from Werkzeug and Jinja2 that are unused -# in the module but are exported as public interface. -from werkzeug.exceptions import abort -from werkzeug.utils import redirect -from jinja2 import Markup, escape - -from .app import Flask, Request, Response -from .config import Config -from .helpers import url_for, flash, send_file, send_from_directory, \ - get_flashed_messages, get_template_attribute, make_response, safe_join, \ - stream_with_context -from .globals import current_app, g, request, session, _request_ctx_stack, \ - _app_ctx_stack -from .ctx import has_request_context, has_app_context, \ - after_this_request, copy_current_request_context -from .blueprints import Blueprint -from .templating import render_template, render_template_string - -# the signals -from .signals import signals_available, template_rendered, request_started, \ - request_finished, got_request_exception, request_tearing_down, \ - appcontext_tearing_down, appcontext_pushed, \ - appcontext_popped, message_flashed, before_render_template - -# We're not exposing the actual json module but a convenient wrapper around -# it. -from . import json - -# This was the only thing that flask used to export at one point and it had -# a more generic name. -jsonify = json.jsonify - -# backwards compat, goes away in 1.0 -from .sessions import SecureCookieSession as Session -json_available = True diff --git a/flask/__main__.py b/flask/__main__.py deleted file mode 100644 index cbefccd27d..0000000000 --- a/flask/__main__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.__main__ - ~~~~~~~~~~~~~~ - - Alias for flask.run for the command line. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - - -if __name__ == '__main__': - from .cli import main - main(as_module=True) diff --git a/flask/_compat.py b/flask/_compat.py deleted file mode 100644 index 071628fc11..0000000000 --- a/flask/_compat.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask._compat - ~~~~~~~~~~~~~ - - Some py2/py3 compatibility support based on a stripped down - version of six so we don't have to depend on a specific version - of it. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -import sys - -PY2 = sys.version_info[0] == 2 -_identity = lambda x: x - - -if not PY2: - text_type = str - string_types = (str,) - integer_types = (int,) - - iterkeys = lambda d: iter(d.keys()) - itervalues = lambda d: iter(d.values()) - iteritems = lambda d: iter(d.items()) - - from io import StringIO - - def reraise(tp, value, tb=None): - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - - implements_to_string = _identity - -else: - text_type = unicode - string_types = (str, unicode) - integer_types = (int, long) - - iterkeys = lambda d: d.iterkeys() - itervalues = lambda d: d.itervalues() - iteritems = lambda d: d.iteritems() - - from cStringIO import StringIO - - exec('def reraise(tp, value, tb=None):\n raise tp, value, tb') - - def implements_to_string(cls): - cls.__unicode__ = cls.__str__ - cls.__str__ = lambda x: x.__unicode__().encode('utf-8') - return cls - - -def with_metaclass(meta, *bases): - """Create a base class with a metaclass.""" - # This requires a bit of explanation: the basic idea is to make a - # dummy metaclass for one level of class instantiation that replaces - # itself with the actual metaclass. - class metaclass(type): - def __new__(cls, name, this_bases, d): - return meta(name, bases, d) - return type.__new__(metaclass, 'temporary_class', (), {}) - - -# Certain versions of pypy have a bug where clearing the exception stack -# breaks the __exit__ function in a very peculiar way. The second level of -# exception blocks is necessary because pypy seems to forget to check if an -# exception happened until the next bytecode instruction? -# -# Relevant PyPy bugfix commit: -# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df4003301 -# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later -# versions. -# -# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug. -BROKEN_PYPY_CTXMGR_EXIT = False -if hasattr(sys, 'pypy_version_info'): - class _Mgr(object): - def __enter__(self): - return self - def __exit__(self, *args): - if hasattr(sys, 'exc_clear'): - # Python 3 (PyPy3) doesn't have exc_clear - sys.exc_clear() - try: - try: - with _Mgr(): - raise AssertionError() - except: - raise - except TypeError: - BROKEN_PYPY_CTXMGR_EXIT = True - except AssertionError: - pass diff --git a/flask/app.py b/flask/app.py deleted file mode 100644 index 59c77a1587..0000000000 --- a/flask/app.py +++ /dev/null @@ -1,2011 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.app - ~~~~~~~~~ - - This module implements the central WSGI application object. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -import os -import sys -from threading import Lock -from datetime import timedelta -from itertools import chain -from functools import update_wrapper -from collections import deque - -from werkzeug.datastructures import ImmutableDict -from werkzeug.routing import Map, Rule, RequestRedirect, BuildError -from werkzeug.exceptions import HTTPException, InternalServerError, \ - MethodNotAllowed, BadRequest, default_exceptions - -from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \ - locked_cached_property, _endpoint_from_view_func, find_package, \ - get_debug_flag -from . import json, cli -from .wrappers import Request, Response -from .config import ConfigAttribute, Config -from .ctx import RequestContext, AppContext, _AppCtxGlobals -from .globals import _request_ctx_stack, request, session, g -from .sessions import SecureCookieSessionInterface -from .templating import DispatchingJinjaLoader, Environment, \ - _default_template_ctx_processor -from .signals import request_started, request_finished, got_request_exception, \ - request_tearing_down, appcontext_tearing_down -from ._compat import reraise, string_types, text_type, integer_types - -# a lock used for logger initialization -_logger_lock = Lock() - -# a singleton sentinel value for parameter defaults -_sentinel = object() - - -def _make_timedelta(value): - if not isinstance(value, timedelta): - return timedelta(seconds=value) - return value - - -def setupmethod(f): - """Wraps a method so that it performs a check in debug mode if the - first request was already handled. - """ - def wrapper_func(self, *args, **kwargs): - if self.debug and self._got_first_request: - raise AssertionError('A setup function was called after the ' - 'first request was handled. This usually indicates a bug ' - 'in the application where a module was not imported ' - 'and decorators or other functionality was called too late.\n' - 'To fix this make sure to import all your view modules, ' - 'database models and everything related at a central place ' - 'before the application starts serving requests.') - return f(self, *args, **kwargs) - return update_wrapper(wrapper_func, f) - - -class Flask(_PackageBoundObject): - """The flask object implements a WSGI application and acts as the central - object. It is passed the name of the module or package of the - application. Once it is created it will act as a central registry for - the view functions, the URL rules, template configuration and much more. - - The name of the package is used to resolve resources from inside the - package or the folder the module is contained in depending on if the - package parameter resolves to an actual python package (a folder with - an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file). - - For more information about resource loading, see :func:`open_resource`. - - Usually you create a :class:`Flask` instance in your main module or - in the :file:`__init__.py` file of your package like this:: - - from flask import Flask - app = Flask(__name__) - - .. admonition:: About the First Parameter - - The idea of the first parameter is to give Flask an idea of what - belongs to your application. This name is used to find resources - on the filesystem, can be used by extensions to improve debugging - information and a lot more. - - So it's important what you provide there. If you are using a single - module, `__name__` is always the correct value. If you however are - using a package, it's usually recommended to hardcode the name of - your package there. - - For example if your application is defined in :file:`yourapplication/app.py` - you should create it with one of the two versions below:: - - app = Flask('yourapplication') - app = Flask(__name__.split('.')[0]) - - Why is that? The application will work even with `__name__`, thanks - to how resources are looked up. However it will make debugging more - painful. Certain extensions can make assumptions based on the - import name of your application. For example the Flask-SQLAlchemy - extension will look for the code in your application that triggered - an SQL query in debug mode. If the import name is not properly set - up, that debugging information is lost. (For example it would only - pick up SQL queries in `yourapplication.app` and not - `yourapplication.views.frontend`) - - .. versionadded:: 0.7 - The `static_url_path`, `static_folder`, and `template_folder` - parameters were added. - - .. versionadded:: 0.8 - The `instance_path` and `instance_relative_config` parameters were - added. - - .. versionadded:: 0.11 - The `root_path` parameter was added. - - :param import_name: the name of the application package - :param static_url_path: can be used to specify a different path for the - static files on the web. Defaults to the name - of the `static_folder` folder. - :param static_folder: the folder with static files that should be served - at `static_url_path`. Defaults to the ``'static'`` - folder in the root path of the application. - :param template_folder: the folder that contains the templates that should - be used by the application. Defaults to - ``'templates'`` folder in the root path of the - application. - :param instance_path: An alternative instance path for the application. - By default the folder ``'instance'`` next to the - package or module is assumed to be the instance - path. - :param instance_relative_config: if set to ``True`` relative filenames - for loading the config are assumed to - be relative to the instance path instead - of the application root. - :param root_path: Flask by default will automatically calculate the path - to the root of the application. In certain situations - this cannot be achieved (for instance if the package - is a Python 3 namespace package) and needs to be - manually defined. - """ - - #: The class that is used for request objects. See :class:`~flask.Request` - #: for more information. - request_class = Request - - #: The class that is used for response objects. See - #: :class:`~flask.Response` for more information. - response_class = Response - - #: The class that is used for the Jinja environment. - #: - #: .. versionadded:: 0.11 - jinja_environment = Environment - - #: The class that is used for the :data:`~flask.g` instance. - #: - #: Example use cases for a custom class: - #: - #: 1. Store arbitrary attributes on flask.g. - #: 2. Add a property for lazy per-request database connectors. - #: 3. Return None instead of AttributeError on unexpected attributes. - #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g. - #: - #: In Flask 0.9 this property was called `request_globals_class` but it - #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the - #: flask.g object is now application context scoped. - #: - #: .. versionadded:: 0.10 - app_ctx_globals_class = _AppCtxGlobals - - # Backwards compatibility support - def _get_request_globals_class(self): - return self.app_ctx_globals_class - def _set_request_globals_class(self, value): - from warnings import warn - warn(DeprecationWarning('request_globals_class attribute is now ' - 'called app_ctx_globals_class')) - self.app_ctx_globals_class = value - request_globals_class = property(_get_request_globals_class, - _set_request_globals_class) - del _get_request_globals_class, _set_request_globals_class - - #: The class that is used for the ``config`` attribute of this app. - #: Defaults to :class:`~flask.Config`. - #: - #: Example use cases for a custom class: - #: - #: 1. Default values for certain config options. - #: 2. Access to config values through attributes in addition to keys. - #: - #: .. versionadded:: 0.11 - config_class = Config - - #: The debug flag. Set this to ``True`` to enable debugging of the - #: application. In debug mode the debugger will kick in when an unhandled - #: exception occurs and the integrated server will automatically reload - #: the application if changes in the code are detected. - #: - #: This attribute can also be configured from the config with the ``DEBUG`` - #: configuration key. Defaults to ``False``. - debug = ConfigAttribute('DEBUG') - - #: The testing flag. Set this to ``True`` to enable the test mode of - #: Flask extensions (and in the future probably also Flask itself). - #: For example this might activate unittest helpers that have an - #: additional runtime cost which should not be enabled by default. - #: - #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the - #: default it's implicitly enabled. - #: - #: This attribute can also be configured from the config with the - #: ``TESTING`` configuration key. Defaults to ``False``. - testing = ConfigAttribute('TESTING') - - #: If a secret key is set, cryptographic components can use this to - #: sign cookies and other things. Set this to a complex random value - #: when you want to use the secure cookie for instance. - #: - #: This attribute can also be configured from the config with the - #: ``SECRET_KEY`` configuration key. Defaults to ``None``. - secret_key = ConfigAttribute('SECRET_KEY') - - #: The secure cookie uses this for the name of the session cookie. - #: - #: This attribute can also be configured from the config with the - #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'`` - session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME') - - #: A :class:`~datetime.timedelta` which is used to set the expiration - #: date of a permanent session. The default is 31 days which makes a - #: permanent session survive for roughly one month. - #: - #: This attribute can also be configured from the config with the - #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to - #: ``timedelta(days=31)`` - permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME', - get_converter=_make_timedelta) - - #: A :class:`~datetime.timedelta` which is used as default cache_timeout - #: for the :func:`send_file` functions. The default is 12 hours. - #: - #: This attribute can also be configured from the config with the - #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration - #: variable can also be set with an integer value used as seconds. - #: Defaults to ``timedelta(hours=12)`` - send_file_max_age_default = ConfigAttribute('SEND_FILE_MAX_AGE_DEFAULT', - get_converter=_make_timedelta) - - #: Enable this if you want to use the X-Sendfile feature. Keep in - #: mind that the server has to support this. This only affects files - #: sent with the :func:`send_file` method. - #: - #: .. versionadded:: 0.2 - #: - #: This attribute can also be configured from the config with the - #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``. - use_x_sendfile = ConfigAttribute('USE_X_SENDFILE') - - #: The name of the logger to use. By default the logger name is the - #: package name passed to the constructor. - #: - #: .. versionadded:: 0.4 - logger_name = ConfigAttribute('LOGGER_NAME') - - #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`. - #: - #: .. versionadded:: 0.10 - json_encoder = json.JSONEncoder - - #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`. - #: - #: .. versionadded:: 0.10 - json_decoder = json.JSONDecoder - - #: Options that are passed directly to the Jinja2 environment. - jinja_options = ImmutableDict( - extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'] - ) - - #: Default configuration parameters. - default_config = ImmutableDict({ - 'DEBUG': get_debug_flag(default=False), - 'TESTING': False, - 'PROPAGATE_EXCEPTIONS': None, - 'PRESERVE_CONTEXT_ON_EXCEPTION': None, - 'SECRET_KEY': None, - 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), - 'USE_X_SENDFILE': False, - 'LOGGER_NAME': None, - 'LOGGER_HANDLER_POLICY': 'always', - 'SERVER_NAME': None, - 'APPLICATION_ROOT': None, - 'SESSION_COOKIE_NAME': 'session', - 'SESSION_COOKIE_DOMAIN': None, - 'SESSION_COOKIE_PATH': None, - 'SESSION_COOKIE_HTTPONLY': True, - 'SESSION_COOKIE_SECURE': False, - 'SESSION_REFRESH_EACH_REQUEST': True, - 'MAX_CONTENT_LENGTH': None, - 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), - 'TRAP_BAD_REQUEST_ERRORS': False, - 'TRAP_HTTP_EXCEPTIONS': False, - 'EXPLAIN_TEMPLATE_LOADING': False, - 'PREFERRED_URL_SCHEME': 'http', - 'JSON_AS_ASCII': True, - 'JSON_SORT_KEYS': True, - 'JSONIFY_PRETTYPRINT_REGULAR': True, - 'JSONIFY_MIMETYPE': 'application/json', - 'TEMPLATES_AUTO_RELOAD': None, - }) - - #: The rule object to use for URL rules created. This is used by - #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`. - #: - #: .. versionadded:: 0.7 - url_rule_class = Rule - - #: the test client that is used with when `test_client` is used. - #: - #: .. versionadded:: 0.7 - test_client_class = None - - #: the session interface to use. By default an instance of - #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here. - #: - #: .. versionadded:: 0.8 - session_interface = SecureCookieSessionInterface() - - def __init__(self, import_name, static_path=None, static_url_path=None, - static_folder='static', template_folder='templates', - instance_path=None, instance_relative_config=False, - root_path=None): - _PackageBoundObject.__init__(self, import_name, - template_folder=template_folder, - root_path=root_path) - if static_path is not None: - from warnings import warn - warn(DeprecationWarning('static_path is now called ' - 'static_url_path'), stacklevel=2) - static_url_path = static_path - - if static_url_path is not None: - self.static_url_path = static_url_path - if static_folder is not None: - self.static_folder = static_folder - if instance_path is None: - instance_path = self.auto_find_instance_path() - elif not os.path.isabs(instance_path): - raise ValueError('If an instance path is provided it must be ' - 'absolute. A relative path was given instead.') - - #: Holds the path to the instance folder. - #: - #: .. versionadded:: 0.8 - self.instance_path = instance_path - - #: The configuration dictionary as :class:`Config`. This behaves - #: exactly like a regular dictionary but supports additional methods - #: to load a config from files. - self.config = self.make_config(instance_relative_config) - - # Prepare the deferred setup of the logger. - self._logger = None - self.logger_name = self.import_name - - #: A dictionary of all view functions registered. The keys will - #: be function names which are also used to generate URLs and - #: the values are the function objects themselves. - #: To register a view function, use the :meth:`route` decorator. - self.view_functions = {} - - # support for the now deprecated `error_handlers` attribute. The - # :attr:`error_handler_spec` shall be used now. - self._error_handlers = {} - - #: A dictionary of all registered error handlers. The key is ``None`` - #: for error handlers active on the application, otherwise the key is - #: the name of the blueprint. Each key points to another dictionary - #: where the key is the status code of the http exception. The - #: special key ``None`` points to a list of tuples where the first item - #: is the class for the instance check and the second the error handler - #: function. - #: - #: To register a error handler, use the :meth:`errorhandler` - #: decorator. - self.error_handler_spec = {None: self._error_handlers} - - #: A list of functions that are called when :meth:`url_for` raises a - #: :exc:`~werkzeug.routing.BuildError`. Each function registered here - #: is called with `error`, `endpoint` and `values`. If a function - #: returns ``None`` or raises a :exc:`BuildError` the next function is - #: tried. - #: - #: .. versionadded:: 0.9 - self.url_build_error_handlers = [] - - #: A dictionary with lists of functions that should be called at the - #: beginning of the request. The key of the dictionary is the name of - #: the blueprint this function is active for, ``None`` for all requests. - #: This can for example be used to open database connections or - #: getting hold of the currently logged in user. To register a - #: function here, use the :meth:`before_request` decorator. - self.before_request_funcs = {} - - #: A lists of functions that should be called at the beginning of the - #: first request to this instance. To register a function here, use - #: the :meth:`before_first_request` decorator. - #: - #: .. versionadded:: 0.8 - self.before_first_request_funcs = [] - - #: A dictionary with lists of functions that should be called after - #: each request. The key of the dictionary is the name of the blueprint - #: this function is active for, ``None`` for all requests. This can for - #: example be used to close database connections. To register a function - #: here, use the :meth:`after_request` decorator. - self.after_request_funcs = {} - - #: A dictionary with lists of functions that are called after - #: each request, even if an exception has occurred. The key of the - #: dictionary is the name of the blueprint this function is active for, - #: ``None`` for all requests. These functions are not allowed to modify - #: the request, and their return values are ignored. If an exception - #: occurred while processing the request, it gets passed to each - #: teardown_request function. To register a function here, use the - #: :meth:`teardown_request` decorator. - #: - #: .. versionadded:: 0.7 - self.teardown_request_funcs = {} - - #: A list of functions that are called when the application context - #: is destroyed. Since the application context is also torn down - #: if the request ends this is the place to store code that disconnects - #: from databases. - #: - #: .. versionadded:: 0.9 - self.teardown_appcontext_funcs = [] - - #: A dictionary with lists of functions that can be used as URL - #: value processor functions. Whenever a URL is built these functions - #: are called to modify the dictionary of values in place. The key - #: ``None`` here is used for application wide - #: callbacks, otherwise the key is the name of the blueprint. - #: Each of these functions has the chance to modify the dictionary - #: - #: .. versionadded:: 0.7 - self.url_value_preprocessors = {} - - #: A dictionary with lists of functions that can be used as URL value - #: preprocessors. The key ``None`` here is used for application wide - #: callbacks, otherwise the key is the name of the blueprint. - #: Each of these functions has the chance to modify the dictionary - #: of URL values before they are used as the keyword arguments of the - #: view function. For each function registered this one should also - #: provide a :meth:`url_defaults` function that adds the parameters - #: automatically again that were removed that way. - #: - #: .. versionadded:: 0.7 - self.url_default_functions = {} - - #: A dictionary with list of functions that are called without argument - #: to populate the template context. The key of the dictionary is the - #: name of the blueprint this function is active for, ``None`` for all - #: requests. Each returns a dictionary that the template context is - #: updated with. To register a function here, use the - #: :meth:`context_processor` decorator. - self.template_context_processors = { - None: [_default_template_ctx_processor] - } - - #: A list of shell context processor functions that should be run - #: when a shell context is created. - #: - #: .. versionadded:: 0.11 - self.shell_context_processors = [] - - #: all the attached blueprints in a dictionary by name. Blueprints - #: can be attached multiple times so this dictionary does not tell - #: you how often they got attached. - #: - #: .. versionadded:: 0.7 - self.blueprints = {} - self._blueprint_order = [] - - #: a place where extensions can store application specific state. For - #: example this is where an extension could store database engines and - #: similar things. For backwards compatibility extensions should register - #: themselves like this:: - #: - #: if not hasattr(app, 'extensions'): - #: app.extensions = {} - #: app.extensions['extensionname'] = SomeObject() - #: - #: The key must match the name of the extension module. For example in - #: case of a "Flask-Foo" extension in `flask_foo`, the key would be - #: ``'foo'``. - #: - #: .. versionadded:: 0.7 - self.extensions = {} - - #: The :class:`~werkzeug.routing.Map` for this instance. You can use - #: this to change the routing converters after the class was created - #: but before any routes are connected. Example:: - #: - #: from werkzeug.routing import BaseConverter - #: - #: class ListConverter(BaseConverter): - #: def to_python(self, value): - #: return value.split(',') - #: def to_url(http://github.com/self,%20values): - #: return ','.join(super(ListConverter, self).to_url(http://github.com/value) - #: for value in values) - #: - #: app = Flask(__name__) - #: app.url_map.converters['list'] = ListConverter - self.url_map = Map() - - # tracks internally if the application already handled at least one - # request. - self._got_first_request = False - self._before_request_lock = Lock() - - # register the static folder for the application. Do that even - # if the folder does not exist. First of all it might be created - # while the server is running (usually happens during development) - # but also because google appengine stores static files somewhere - # else when mapped with the .yml file. - if self.has_static_folder: - self.add_url_rule(self.static_url_path + '/', - endpoint='static', - view_func=self.send_static_file) - - #: The click command line context for this application. Commands - #: registered here show up in the :command:`flask` command once the - #: application has been discovered. The default commands are - #: provided by Flask itself and can be overridden. - #: - #: This is an instance of a :class:`click.Group` object. - self.cli = cli.AppGroup(self.name) - - def _get_error_handlers(self): - from warnings import warn - warn(DeprecationWarning('error_handlers is deprecated, use the ' - 'new error_handler_spec attribute instead.'), stacklevel=1) - return self._error_handlers - def _set_error_handlers(self, value): - self._error_handlers = value - self.error_handler_spec[None] = value - error_handlers = property(_get_error_handlers, _set_error_handlers) - del _get_error_handlers, _set_error_handlers - - @locked_cached_property - def name(self): - """The name of the application. This is usually the import name - with the difference that it's guessed from the run file if the - import name is main. This name is used as a display name when - Flask needs the name of the application. It can be set and overridden - to change the value. - - .. versionadded:: 0.8 - """ - if self.import_name == '__main__': - fn = getattr(sys.modules['__main__'], '__file__', None) - if fn is None: - return '__main__' - return os.path.splitext(os.path.basename(fn))[0] - return self.import_name - - @property - def propagate_exceptions(self): - """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration - value in case it's set, otherwise a sensible default is returned. - - .. versionadded:: 0.7 - """ - rv = self.config['PROPAGATE_EXCEPTIONS'] - if rv is not None: - return rv - return self.testing or self.debug - - @property - def preserve_context_on_exception(self): - """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION`` - configuration value in case it's set, otherwise a sensible default - is returned. - - .. versionadded:: 0.7 - """ - rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION'] - if rv is not None: - return rv - return self.debug - - @property - def logger(self): - """A :class:`logging.Logger` object for this application. The - default configuration is to log to stderr if the application is - in debug mode. This logger can be used to (surprise) log messages. - Here some examples:: - - app.logger.debug('A value for debugging') - app.logger.warning('A warning occurred (%d apples)', 42) - app.logger.error('An error occurred') - - .. versionadded:: 0.3 - """ - if self._logger and self._logger.name == self.logger_name: - return self._logger - with _logger_lock: - if self._logger and self._logger.name == self.logger_name: - return self._logger - from flask.logging import create_logger - self._logger = rv = create_logger(self) - return rv - - @locked_cached_property - def jinja_env(self): - """The Jinja2 environment used to load templates.""" - return self.create_jinja_environment() - - @property - def got_first_request(self): - """This attribute is set to ``True`` if the application started - handling the first request. - - .. versionadded:: 0.8 - """ - return self._got_first_request - - def make_config(self, instance_relative=False): - """Used to create the config attribute by the Flask constructor. - The `instance_relative` parameter is passed in from the constructor - of Flask (there named `instance_relative_config`) and indicates if - the config should be relative to the instance path or the root path - of the application. - - .. versionadded:: 0.8 - """ - root_path = self.root_path - if instance_relative: - root_path = self.instance_path - return self.config_class(root_path, self.default_config) - - def auto_find_instance_path(self): - """Tries to locate the instance path if it was not provided to the - constructor of the application class. It will basically calculate - the path to a folder named ``instance`` next to your main file or - the package. - - .. versionadded:: 0.8 - """ - prefix, package_path = find_package(self.import_name) - if prefix is None: - return os.path.join(package_path, 'instance') - return os.path.join(prefix, 'var', self.name + '-instance') - - def open_instance_resource(self, resource, mode='rb'): - """Opens a resource from the application's instance folder - (:attr:`instance_path`). Otherwise works like - :meth:`open_resource`. Instance resources can also be opened for - writing. - - :param resource: the name of the resource. To access resources within - subfolders use forward slashes as separator. - :param mode: resource file opening mode, default is 'rb'. - """ - return open(os.path.join(self.instance_path, resource), mode) - - def create_jinja_environment(self): - """Creates the Jinja2 environment based on :attr:`jinja_options` - and :meth:`select_jinja_autoescape`. Since 0.7 this also adds - the Jinja2 globals and filters after initialization. Override - this function to customize the behavior. - - .. versionadded:: 0.5 - .. versionchanged:: 0.11 - ``Environment.auto_reload`` set in accordance with - ``TEMPLATES_AUTO_RELOAD`` configuration option. - """ - options = dict(self.jinja_options) - if 'autoescape' not in options: - options['autoescape'] = self.select_jinja_autoescape - if 'auto_reload' not in options: - if self.config['TEMPLATES_AUTO_RELOAD'] is not None: - options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD'] - else: - options['auto_reload'] = self.debug - rv = self.jinja_environment(self, **options) - rv.globals.update( - url_for=url_for, - get_flashed_messages=get_flashed_messages, - config=self.config, - # request, session and g are normally added with the - # context processor for efficiency reasons but for imported - # templates we also want the proxies in there. - request=request, - session=session, - g=g - ) - rv.filters['tojson'] = json.tojson_filter - return rv - - def create_global_jinja_loader(self): - """Creates the loader for the Jinja2 environment. Can be used to - override just the loader and keeping the rest unchanged. It's - discouraged to override this function. Instead one should override - the :meth:`jinja_loader` function instead. - - The global loader dispatches between the loaders of the application - and the individual blueprints. - - .. versionadded:: 0.7 - """ - return DispatchingJinjaLoader(self) - - def init_jinja_globals(self): - """Deprecated. Used to initialize the Jinja2 globals. - - .. versionadded:: 0.5 - .. versionchanged:: 0.7 - This method is deprecated with 0.7. Override - :meth:`create_jinja_environment` instead. - """ - - def select_jinja_autoescape(self, filename): - """Returns ``True`` if autoescaping should be active for the given - template name. If no template name is given, returns `True`. - - .. versionadded:: 0.5 - """ - if filename is None: - return True - return filename.endswith(('.html', '.htm', '.xml', '.xhtml')) - - def update_template_context(self, context): - """Update the template context with some commonly used variables. - This injects request, session, config and g into the template - context as well as everything template context processors want - to inject. Note that the as of Flask 0.6, the original values - in the context will not be overridden if a context processor - decides to return a value with the same key. - - :param context: the context as a dictionary that is updated in place - to add extra variables. - """ - funcs = self.template_context_processors[None] - reqctx = _request_ctx_stack.top - if reqctx is not None: - bp = reqctx.request.blueprint - if bp is not None and bp in self.template_context_processors: - funcs = chain(funcs, self.template_context_processors[bp]) - orig_ctx = context.copy() - for func in funcs: - context.update(func()) - # make sure the original values win. This makes it possible to - # easier add new variables in context processors without breaking - # existing views. - context.update(orig_ctx) - - def make_shell_context(self): - """Returns the shell context for an interactive shell for this - application. This runs all the registered shell context - processors. - - .. versionadded:: 0.11 - """ - rv = {'app': self, 'g': g} - for processor in self.shell_context_processors: - rv.update(processor()) - return rv - - def run(self, host=None, port=None, debug=None, **options): - """Runs the application on a local development server. - - Do not use ``run()`` in a production setting. It is not intended to - meet security and performance requirements for a production server. - Instead, see :ref:`deployment` for WSGI server recommendations. - - If the :attr:`debug` flag is set the server will automatically reload - for code changes and show a debugger in case an exception happened. - - If you want to run the application in debug mode, but disable the - code execution on the interactive debugger, you can pass - ``use_evalex=False`` as parameter. This will keep the debugger's - traceback screen active, but disable code execution. - - It is not recommended to use this function for development with - automatic reloading as this is badly supported. Instead you should - be using the :command:`flask` command line script's ``run`` support. - - .. admonition:: Keep in Mind - - Flask will suppress any server error with a generic error page - unless it is in debug mode. As such to enable just the - interactive debugger without the code reloading, you have to - invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``. - Setting ``use_debugger`` to ``True`` without being in debug mode - won't catch any exceptions because there won't be any to - catch. - - .. versionchanged:: 0.10 - The default port is now picked from the ``SERVER_NAME`` variable. - - :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to - have the server available externally as well. Defaults to - ``'127.0.0.1'``. - :param port: the port of the webserver. Defaults to ``5000`` or the - port defined in the ``SERVER_NAME`` config variable if - present. - :param debug: if given, enable or disable debug mode. - See :attr:`debug`. - :param options: the options to be forwarded to the underlying - Werkzeug server. See - :func:`werkzeug.serving.run_simple` for more - information. - """ - from werkzeug.serving import run_simple - if host is None: - host = '127.0.0.1' - if port is None: - server_name = self.config['SERVER_NAME'] - if server_name and ':' in server_name: - port = int(server_name.rsplit(':', 1)[1]) - else: - port = 5000 - if debug is not None: - self.debug = bool(debug) - options.setdefault('use_reloader', self.debug) - options.setdefault('use_debugger', self.debug) - try: - run_simple(host, port, self, **options) - finally: - # reset the first request information if the development server - # reset normally. This makes it possible to restart the server - # without reloader and that stuff from an interactive shell. - self._got_first_request = False - - def test_client(self, use_cookies=True, **kwargs): - """Creates a test client for this application. For information - about unit testing head over to :ref:`testing`. - - Note that if you are testing for assertions or exceptions in your - application code, you must set ``app.testing = True`` in order for the - exceptions to propagate to the test client. Otherwise, the exception - will be handled by the application (not visible to the test client) and - the only indication of an AssertionError or other exception will be a - 500 status code response to the test client. See the :attr:`testing` - attribute. For example:: - - app.testing = True - client = app.test_client() - - The test client can be used in a ``with`` block to defer the closing down - of the context until the end of the ``with`` block. This is useful if - you want to access the context locals for testing:: - - with app.test_client() as c: - rv = c.get('/?vodka=42') - assert request.args['vodka'] == '42' - - Additionally, you may pass optional keyword arguments that will then - be passed to the application's :attr:`test_client_class` constructor. - For example:: - - from flask.testing import FlaskClient - - class CustomClient(FlaskClient): - def __init__(self, *args, **kwargs): - self._authentication = kwargs.pop("authentication") - super(CustomClient,self).__init__( *args, **kwargs) - - app.test_client_class = CustomClient - client = app.test_client(authentication='Basic ....') - - See :class:`~flask.testing.FlaskClient` for more information. - - .. versionchanged:: 0.4 - added support for ``with`` block usage for the client. - - .. versionadded:: 0.7 - The `use_cookies` parameter was added as well as the ability - to override the client to be used by setting the - :attr:`test_client_class` attribute. - - .. versionchanged:: 0.11 - Added `**kwargs` to support passing additional keyword arguments to - the constructor of :attr:`test_client_class`. - """ - cls = self.test_client_class - if cls is None: - from flask.testing import FlaskClient as cls - return cls(self, self.response_class, use_cookies=use_cookies, **kwargs) - - def open_session(self, request): - """Creates or opens a new session. Default implementation stores all - session data in a signed cookie. This requires that the - :attr:`secret_key` is set. Instead of overriding this method - we recommend replacing the :class:`session_interface`. - - :param request: an instance of :attr:`request_class`. - """ - return self.session_interface.open_session(self, request) - - def save_session(self, session, response): - """Saves the session if it needs updates. For the default - implementation, check :meth:`open_session`. Instead of overriding this - method we recommend replacing the :class:`session_interface`. - - :param session: the session to be saved (a - :class:`~werkzeug.contrib.securecookie.SecureCookie` - object) - :param response: an instance of :attr:`response_class` - """ - return self.session_interface.save_session(self, session, response) - - def make_null_session(self): - """Creates a new instance of a missing session. Instead of overriding - this method we recommend replacing the :class:`session_interface`. - - .. versionadded:: 0.7 - """ - return self.session_interface.make_null_session(self) - - @setupmethod - def register_blueprint(self, blueprint, **options): - """Registers a blueprint on the application. - - .. versionadded:: 0.7 - """ - first_registration = False - if blueprint.name in self.blueprints: - assert self.blueprints[blueprint.name] is blueprint, \ - 'A blueprint\'s name collision occurred between %r and ' \ - '%r. Both share the same name "%s". Blueprints that ' \ - 'are created on the fly need unique names.' % \ - (blueprint, self.blueprints[blueprint.name], blueprint.name) - else: - self.blueprints[blueprint.name] = blueprint - self._blueprint_order.append(blueprint) - first_registration = True - blueprint.register(self, options, first_registration) - - def iter_blueprints(self): - """Iterates over all blueprints by the order they were registered. - - .. versionadded:: 0.11 - """ - return iter(self._blueprint_order) - - @setupmethod - def add_url_rule(self, rule, endpoint=None, view_func=None, **options): - """Connects a URL rule. Works exactly like the :meth:`route` - decorator. If a view_func is provided it will be registered with the - endpoint. - - Basically this example:: - - @app.route('/') - def index(): - pass - - Is equivalent to the following:: - - def index(): - pass - app.add_url_rule('/', 'index', index) - - If the view_func is not provided you will need to connect the endpoint - to a view function like so:: - - app.view_functions['index'] = index - - Internally :meth:`route` invokes :meth:`add_url_rule` so if you want - to customize the behavior via subclassing you only need to change - this method. - - For more information refer to :ref:`url-route-registrations`. - - .. versionchanged:: 0.2 - `view_func` parameter added. - - .. versionchanged:: 0.6 - ``OPTIONS`` is added automatically as method. - - :param rule: the URL rule as string - :param endpoint: the endpoint for the registered URL rule. Flask - itself assumes the name of the view function as - endpoint - :param view_func: the function to call when serving a request to the - provided endpoint - :param options: the options to be forwarded to the underlying - :class:`~werkzeug.routing.Rule` object. A change - to Werkzeug is handling of method options. methods - is a list of methods this rule should be limited - to (``GET``, ``POST`` etc.). By default a rule - just listens for ``GET`` (and implicitly ``HEAD``). - Starting with Flask 0.6, ``OPTIONS`` is implicitly - added and handled by the standard request handling. - """ - if endpoint is None: - endpoint = _endpoint_from_view_func(view_func) - options['endpoint'] = endpoint - methods = options.pop('methods', None) - - # if the methods are not given and the view_func object knows its - # methods we can use that instead. If neither exists, we go with - # a tuple of only ``GET`` as default. - if methods is None: - methods = getattr(view_func, 'methods', None) or ('GET',) - if isinstance(methods, string_types): - raise TypeError('Allowed methods have to be iterables of strings, ' - 'for example: @app.route(..., methods=["POST"])') - methods = set(item.upper() for item in methods) - - # Methods that should always be added - required_methods = set(getattr(view_func, 'required_methods', ())) - - # starting with Flask 0.8 the view_func object can disable and - # force-enable the automatic options handling. - provide_automatic_options = getattr(view_func, - 'provide_automatic_options', None) - - if provide_automatic_options is None: - if 'OPTIONS' not in methods: - provide_automatic_options = True - required_methods.add('OPTIONS') - else: - provide_automatic_options = False - - # Add the required methods now. - methods |= required_methods - - rule = self.url_rule_class(rule, methods=methods, **options) - rule.provide_automatic_options = provide_automatic_options - - self.url_map.add(rule) - if view_func is not None: - old_func = self.view_functions.get(endpoint) - if old_func is not None and old_func != view_func: - raise AssertionError('View function mapping is overwriting an ' - 'existing endpoint function: %s' % endpoint) - self.view_functions[endpoint] = view_func - - def route(self, rule, **options): - """A decorator that is used to register a view function for a - given URL rule. This does the same thing as :meth:`add_url_rule` - but is intended for decorator usage:: - - @app.route('/') - def index(): - return 'Hello World' - - For more information refer to :ref:`url-route-registrations`. - - :param rule: the URL rule as string - :param endpoint: the endpoint for the registered URL rule. Flask - itself assumes the name of the view function as - endpoint - :param options: the options to be forwarded to the underlying - :class:`~werkzeug.routing.Rule` object. A change - to Werkzeug is handling of method options. methods - is a list of methods this rule should be limited - to (``GET``, ``POST`` etc.). By default a rule - just listens for ``GET`` (and implicitly ``HEAD``). - Starting with Flask 0.6, ``OPTIONS`` is implicitly - added and handled by the standard request handling. - """ - def decorator(f): - endpoint = options.pop('endpoint', None) - self.add_url_rule(rule, endpoint, f, **options) - return f - return decorator - - @setupmethod - def endpoint(self, endpoint): - """A decorator to register a function as an endpoint. - Example:: - - @app.endpoint('example.endpoint') - def example(): - return "example" - - :param endpoint: the name of the endpoint - """ - def decorator(f): - self.view_functions[endpoint] = f - return f - return decorator - - @staticmethod - def _get_exc_class_and_code(exc_class_or_code): - """Ensure that we register only exceptions as handler keys""" - if isinstance(exc_class_or_code, integer_types): - exc_class = default_exceptions[exc_class_or_code] - else: - exc_class = exc_class_or_code - - assert issubclass(exc_class, Exception) - - if issubclass(exc_class, HTTPException): - return exc_class, exc_class.code - else: - return exc_class, None - - @setupmethod - def errorhandler(self, code_or_exception): - """A decorator that is used to register a function given an - error code. Example:: - - @app.errorhandler(404) - def page_not_found(error): - return 'This page does not exist', 404 - - You can also register handlers for arbitrary exceptions:: - - @app.errorhandler(DatabaseError) - def special_exception_handler(error): - return 'Database connection failed', 500 - - You can also register a function as error handler without using - the :meth:`errorhandler` decorator. The following example is - equivalent to the one above:: - - def page_not_found(error): - return 'This page does not exist', 404 - app.error_handler_spec[None][404] = page_not_found - - Setting error handlers via assignments to :attr:`error_handler_spec` - however is discouraged as it requires fiddling with nested dictionaries - and the special case for arbitrary exception types. - - The first ``None`` refers to the active blueprint. If the error - handler should be application wide ``None`` shall be used. - - .. versionadded:: 0.7 - Use :meth:`register_error_handler` instead of modifying - :attr:`error_handler_spec` directly, for application wide error - handlers. - - .. versionadded:: 0.7 - One can now additionally also register custom exception types - that do not necessarily have to be a subclass of the - :class:`~werkzeug.exceptions.HTTPException` class. - - :param code: the code as integer for the handler - """ - def decorator(f): - self._register_error_handler(None, code_or_exception, f) - return f - return decorator - - def register_error_handler(self, code_or_exception, f): - """Alternative error attach function to the :meth:`errorhandler` - decorator that is more straightforward to use for non decorator - usage. - - .. versionadded:: 0.7 - """ - self._register_error_handler(None, code_or_exception, f) - - @setupmethod - def _register_error_handler(self, key, code_or_exception, f): - """ - :type key: None|str - :type code_or_exception: int|T<=Exception - :type f: callable - """ - if isinstance(code_or_exception, HTTPException): # old broken behavior - raise ValueError( - 'Tried to register a handler for an exception instance {0!r}. ' - 'Handlers can only be registered for exception classes or HTTP error codes.' - .format(code_or_exception)) - - exc_class, code = self._get_exc_class_and_code(code_or_exception) - - handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {}) - handlers[exc_class] = f - - @setupmethod - def template_filter(self, name=None): - """A decorator that is used to register custom template filter. - You can specify a name for the filter, otherwise the function - name will be used. Example:: - - @app.template_filter() - def reverse(s): - return s[::-1] - - :param name: the optional name of the filter, otherwise the - function name will be used. - """ - def decorator(f): - self.add_template_filter(f, name=name) - return f - return decorator - - @setupmethod - def add_template_filter(self, f, name=None): - """Register a custom template filter. Works exactly like the - :meth:`template_filter` decorator. - - :param name: the optional name of the filter, otherwise the - function name will be used. - """ - self.jinja_env.filters[name or f.__name__] = f - - @setupmethod - def template_test(self, name=None): - """A decorator that is used to register custom template test. - You can specify a name for the test, otherwise the function - name will be used. Example:: - - @app.template_test() - def is_prime(n): - if n == 2: - return True - for i in range(2, int(math.ceil(math.sqrt(n))) + 1): - if n % i == 0: - return False - return True - - .. versionadded:: 0.10 - - :param name: the optional name of the test, otherwise the - function name will be used. - """ - def decorator(f): - self.add_template_test(f, name=name) - return f - return decorator - - @setupmethod - def add_template_test(self, f, name=None): - """Register a custom template test. Works exactly like the - :meth:`template_test` decorator. - - .. versionadded:: 0.10 - - :param name: the optional name of the test, otherwise the - function name will be used. - """ - self.jinja_env.tests[name or f.__name__] = f - - @setupmethod - def template_global(self, name=None): - """A decorator that is used to register a custom template global function. - You can specify a name for the global function, otherwise the function - name will be used. Example:: - - @app.template_global() - def double(n): - return 2 * n - - .. versionadded:: 0.10 - - :param name: the optional name of the global function, otherwise the - function name will be used. - """ - def decorator(f): - self.add_template_global(f, name=name) - return f - return decorator - - @setupmethod - def add_template_global(self, f, name=None): - """Register a custom template global function. Works exactly like the - :meth:`template_global` decorator. - - .. versionadded:: 0.10 - - :param name: the optional name of the global function, otherwise the - function name will be used. - """ - self.jinja_env.globals[name or f.__name__] = f - - @setupmethod - def before_request(self, f): - """Registers a function to run before each request. - - The function will be called without any arguments. - If the function returns a non-None value, it's handled as - if it was the return value from the view and further - request handling is stopped. - """ - self.before_request_funcs.setdefault(None, []).append(f) - return f - - @setupmethod - def before_first_request(self, f): - """Registers a function to be run before the first request to this - instance of the application. - - The function will be called without any arguments and its return - value is ignored. - - .. versionadded:: 0.8 - """ - self.before_first_request_funcs.append(f) - return f - - @setupmethod - def after_request(self, f): - """Register a function to be run after each request. - - Your function must take one parameter, an instance of - :attr:`response_class` and return a new response object or the - same (see :meth:`process_response`). - - As of Flask 0.7 this function might not be executed at the end of the - request in case an unhandled exception occurred. - """ - self.after_request_funcs.setdefault(None, []).append(f) - return f - - @setupmethod - def teardown_request(self, f): - """Register a function to be run at the end of each request, - regardless of whether there was an exception or not. These functions - are executed when the request context is popped, even if not an - actual request was performed. - - Example:: - - ctx = app.test_request_context() - ctx.push() - ... - ctx.pop() - - When ``ctx.pop()`` is executed in the above example, the teardown - functions are called just before the request context moves from the - stack of active contexts. This becomes relevant if you are using - such constructs in tests. - - Generally teardown functions must take every necessary step to avoid - that they will fail. If they do execute code that might fail they - will have to surround the execution of these code by try/except - statements and log occurring errors. - - When a teardown function was called because of a exception it will - be passed an error object. - - The return values of teardown functions are ignored. - - .. admonition:: Debug Note - - In debug mode Flask will not tear down a request on an exception - immediately. Instead it will keep it alive so that the interactive - debugger can still access it. This behavior can be controlled - by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. - """ - self.teardown_request_funcs.setdefault(None, []).append(f) - return f - - @setupmethod - def teardown_appcontext(self, f): - """Registers a function to be called when the application context - ends. These functions are typically also called when the request - context is popped. - - Example:: - - ctx = app.app_context() - ctx.push() - ... - ctx.pop() - - When ``ctx.pop()`` is executed in the above example, the teardown - functions are called just before the app context moves from the - stack of active contexts. This becomes relevant if you are using - such constructs in tests. - - Since a request context typically also manages an application - context it would also be called when you pop a request context. - - When a teardown function was called because of an exception it will - be passed an error object. - - The return values of teardown functions are ignored. - - .. versionadded:: 0.9 - """ - self.teardown_appcontext_funcs.append(f) - return f - - @setupmethod - def context_processor(self, f): - """Registers a template context processor function.""" - self.template_context_processors[None].append(f) - return f - - @setupmethod - def shell_context_processor(self, f): - """Registers a shell context processor function. - - .. versionadded:: 0.11 - """ - self.shell_context_processors.append(f) - return f - - @setupmethod - def url_value_preprocessor(self, f): - """Registers a function as URL value preprocessor for all view - functions of the application. It's called before the view functions - are called and can modify the url values provided. - """ - self.url_value_preprocessors.setdefault(None, []).append(f) - return f - - @setupmethod - def url_defaults(self, f): - """Callback function for URL defaults for all view functions of the - application. It's called with the endpoint and values and should - update the values passed in place. - """ - self.url_default_functions.setdefault(None, []).append(f) - return f - - def _find_error_handler(self, e): - """Finds a registered error handler for the request’s blueprint. - Otherwise falls back to the app, returns None if not a suitable - handler is found. - """ - exc_class, code = self._get_exc_class_and_code(type(e)) - - def find_handler(handler_map): - if not handler_map: - return - queue = deque(exc_class.__mro__) - # Protect from geniuses who might create circular references in - # __mro__ - done = set() - - while queue: - cls = queue.popleft() - if cls in done: - continue - done.add(cls) - handler = handler_map.get(cls) - if handler is not None: - # cache for next time exc_class is raised - handler_map[exc_class] = handler - return handler - - queue.extend(cls.__mro__) - - # try blueprint handlers - handler = find_handler(self.error_handler_spec - .get(request.blueprint, {}) - .get(code)) - if handler is not None: - return handler - - # fall back to app handlers - return find_handler(self.error_handler_spec[None].get(code)) - - def handle_http_exception(self, e): - """Handles an HTTP exception. By default this will invoke the - registered error handlers and fall back to returning the - exception as response. - - .. versionadded:: 0.3 - """ - # Proxy exceptions don't have error codes. We want to always return - # those unchanged as errors - if e.code is None: - return e - - handler = self._find_error_handler(e) - if handler is None: - return e - return handler(e) - - def trap_http_exception(self, e): - """Checks if an HTTP exception should be trapped or not. By default - this will return ``False`` for all exceptions except for a bad request - key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It - also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``. - - This is called for all HTTP exceptions raised by a view function. - If it returns ``True`` for any exception the error handler for this - exception is not called and it shows up as regular exception in the - traceback. This is helpful for debugging implicitly raised HTTP - exceptions. - - .. versionadded:: 0.8 - """ - if self.config['TRAP_HTTP_EXCEPTIONS']: - return True - if self.config['TRAP_BAD_REQUEST_ERRORS']: - return isinstance(e, BadRequest) - return False - - def handle_user_exception(self, e): - """This method is called whenever an exception occurs that should be - handled. A special case are - :class:`~werkzeug.exception.HTTPException`\s which are forwarded by - this function to the :meth:`handle_http_exception` method. This - function will either return a response value or reraise the - exception with the same traceback. - - .. versionadded:: 0.7 - """ - exc_type, exc_value, tb = sys.exc_info() - assert exc_value is e - - # ensure not to trash sys.exc_info() at that point in case someone - # wants the traceback preserved in handle_http_exception. Of course - # we cannot prevent users from trashing it themselves in a custom - # trap_http_exception method so that's their fault then. - - if isinstance(e, HTTPException) and not self.trap_http_exception(e): - return self.handle_http_exception(e) - - handler = self._find_error_handler(e) - - if handler is None: - reraise(exc_type, exc_value, tb) - return handler(e) - - def handle_exception(self, e): - """Default exception handling that kicks in when an exception - occurs that is not caught. In debug mode the exception will - be re-raised immediately, otherwise it is logged and the handler - for a 500 internal server error is used. If no such handler - exists, a default 500 internal server error message is displayed. - - .. versionadded:: 0.3 - """ - exc_type, exc_value, tb = sys.exc_info() - - got_request_exception.send(self, exception=e) - handler = self._find_error_handler(InternalServerError()) - - if self.propagate_exceptions: - # if we want to repropagate the exception, we can attempt to - # raise it with the whole traceback in case we can do that - # (the function was actually called from the except part) - # otherwise, we just raise the error again - if exc_value is e: - reraise(exc_type, exc_value, tb) - else: - raise e - - self.log_exception((exc_type, exc_value, tb)) - if handler is None: - return InternalServerError() - return self.finalize_request(handler(e), from_error_handler=True) - - def log_exception(self, exc_info): - """Logs an exception. This is called by :meth:`handle_exception` - if debugging is disabled and right before the handler is called. - The default implementation logs the exception as error on the - :attr:`logger`. - - .. versionadded:: 0.8 - """ - self.logger.error('Exception on %s [%s]' % ( - request.path, - request.method - ), exc_info=exc_info) - - def raise_routing_exception(self, request): - """Exceptions that are recording during routing are reraised with - this method. During debug we are not reraising redirect requests - for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising - a different error instead to help debug situations. - - :internal: - """ - if not self.debug \ - or not isinstance(request.routing_exception, RequestRedirect) \ - or request.method in ('GET', 'HEAD', 'OPTIONS'): - raise request.routing_exception - - from .debughelpers import FormDataRoutingRedirect - raise FormDataRoutingRedirect(request) - - def dispatch_request(self): - """Does the request dispatching. Matches the URL and returns the - return value of the view or error handler. This does not have to - be a response object. In order to convert the return value to a - proper response object, call :func:`make_response`. - - .. versionchanged:: 0.7 - This no longer does the exception handling, this code was - moved to the new :meth:`full_dispatch_request`. - """ - req = _request_ctx_stack.top.request - if req.routing_exception is not None: - self.raise_routing_exception(req) - rule = req.url_rule - # if we provide automatic options for this URL and the - # request came with the OPTIONS method, reply automatically - if getattr(rule, 'provide_automatic_options', False) \ - and req.method == 'OPTIONS': - return self.make_default_options_response() - # otherwise dispatch to the handler for that endpoint - return self.view_functions[rule.endpoint](**req.view_args) - - def full_dispatch_request(self): - """Dispatches the request and on top of that performs request - pre and postprocessing as well as HTTP exception catching and - error handling. - - .. versionadded:: 0.7 - """ - self.try_trigger_before_first_request_functions() - try: - request_started.send(self) - rv = self.preprocess_request() - if rv is None: - rv = self.dispatch_request() - except Exception as e: - rv = self.handle_user_exception(e) - return self.finalize_request(rv) - - def finalize_request(self, rv, from_error_handler=False): - """Given the return value from a view function this finalizes - the request by converting it into a response and invoking the - postprocessing functions. This is invoked for both normal - request dispatching as well as error handlers. - - Because this means that it might be called as a result of a - failure a special safe mode is available which can be enabled - with the `from_error_handler` flag. If enabled, failures in - response processing will be logged and otherwise ignored. - - :internal: - """ - response = self.make_response(rv) - try: - response = self.process_response(response) - request_finished.send(self, response=response) - except Exception: - if not from_error_handler: - raise - self.logger.exception('Request finalizing failed with an ' - 'error while handling an error') - return response - - def try_trigger_before_first_request_functions(self): - """Called before each request and will ensure that it triggers - the :attr:`before_first_request_funcs` and only exactly once per - application instance (which means process usually). - - :internal: - """ - if self._got_first_request: - return - with self._before_request_lock: - if self._got_first_request: - return - for func in self.before_first_request_funcs: - func() - self._got_first_request = True - - def make_default_options_response(self): - """This method is called to create the default ``OPTIONS`` response. - This can be changed through subclassing to change the default - behavior of ``OPTIONS`` responses. - - .. versionadded:: 0.7 - """ - adapter = _request_ctx_stack.top.url_adapter - if hasattr(adapter, 'allowed_methods'): - methods = adapter.allowed_methods() - else: - # fallback for Werkzeug < 0.7 - methods = [] - try: - adapter.match(method='--') - except MethodNotAllowed as e: - methods = e.valid_methods - except HTTPException as e: - pass - rv = self.response_class() - rv.allow.update(methods) - return rv - - def should_ignore_error(self, error): - """This is called to figure out if an error should be ignored - or not as far as the teardown system is concerned. If this - function returns ``True`` then the teardown handlers will not be - passed the error. - - .. versionadded:: 0.10 - """ - return False - - def make_response(self, rv): - """Converts the return value from a view function to a real - response object that is an instance of :attr:`response_class`. - - The following types are allowed for `rv`: - - .. tabularcolumns:: |p{3.5cm}|p{9.5cm}| - - ======================= =========================================== - :attr:`response_class` the object is returned unchanged - :class:`str` a response object is created with the - string as body - :class:`unicode` a response object is created with the - string encoded to utf-8 as body - a WSGI function the function is called as WSGI application - and buffered as response object - :class:`tuple` A tuple in the form ``(response, status, - headers)`` or ``(response, headers)`` - where `response` is any of the - types defined here, `status` is a string - or an integer and `headers` is a list or - a dictionary with header values. - ======================= =========================================== - - :param rv: the return value from the view function - - .. versionchanged:: 0.9 - Previously a tuple was interpreted as the arguments for the - response object. - """ - status_or_headers = headers = None - if isinstance(rv, tuple): - rv, status_or_headers, headers = rv + (None,) * (3 - len(rv)) - - if rv is None: - raise ValueError('View function did not return a response') - - if isinstance(status_or_headers, (dict, list)): - headers, status_or_headers = status_or_headers, None - - if not isinstance(rv, self.response_class): - # When we create a response object directly, we let the constructor - # set the headers and status. We do this because there can be - # some extra logic involved when creating these objects with - # specific values (like default content type selection). - if isinstance(rv, (text_type, bytes, bytearray)): - rv = self.response_class(rv, headers=headers, - status=status_or_headers) - headers = status_or_headers = None - else: - rv = self.response_class.force_type(rv, request.environ) - - if status_or_headers is not None: - if isinstance(status_or_headers, string_types): - rv.status = status_or_headers - else: - rv.status_code = status_or_headers - if headers: - rv.headers.extend(headers) - - return rv - - def create_url_adapter(self, request): - """Creates a URL adapter for the given request. The URL adapter - is created at a point where the request context is not yet set up - so the request is passed explicitly. - - .. versionadded:: 0.6 - - .. versionchanged:: 0.9 - This can now also be called without a request object when the - URL adapter is created for the application context. - """ - if request is not None: - return self.url_map.bind_to_environ(request.environ, - server_name=self.config['SERVER_NAME']) - # We need at the very least the server name to be set for this - # to work. - if self.config['SERVER_NAME'] is not None: - return self.url_map.bind( - self.config['SERVER_NAME'], - script_name=self.config['APPLICATION_ROOT'] or '/', - url_scheme=self.config['PREFERRED_URL_SCHEME']) - - def inject_url_defaults(self, endpoint, values): - """Injects the URL defaults for the given endpoint directly into - the values dictionary passed. This is used internally and - automatically called on URL building. - - .. versionadded:: 0.7 - """ - funcs = self.url_default_functions.get(None, ()) - if '.' in endpoint: - bp = endpoint.rsplit('.', 1)[0] - funcs = chain(funcs, self.url_default_functions.get(bp, ())) - for func in funcs: - func(endpoint, values) - - def handle_url_build_error(self, error, endpoint, values): - """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`. - """ - exc_type, exc_value, tb = sys.exc_info() - for handler in self.url_build_error_handlers: - try: - rv = handler(error, endpoint, values) - if rv is not None: - return rv - except BuildError as e: - # make error available outside except block (py3) - error = e - - # At this point we want to reraise the exception. If the error is - # still the same one we can reraise it with the original traceback, - # otherwise we raise it from here. - if error is exc_value: - reraise(exc_type, exc_value, tb) - raise error - - def preprocess_request(self): - """Called before the actual request dispatching and will - call each :meth:`before_request` decorated function, passing no - arguments. - If any of these functions returns a value, it's handled as - if it was the return value from the view and further - request handling is stopped. - - This also triggers the :meth:`url_value_preprocessor` functions before - the actual :meth:`before_request` functions are called. - """ - bp = _request_ctx_stack.top.request.blueprint - - funcs = self.url_value_preprocessors.get(None, ()) - if bp is not None and bp in self.url_value_preprocessors: - funcs = chain(funcs, self.url_value_preprocessors[bp]) - for func in funcs: - func(request.endpoint, request.view_args) - - funcs = self.before_request_funcs.get(None, ()) - if bp is not None and bp in self.before_request_funcs: - funcs = chain(funcs, self.before_request_funcs[bp]) - for func in funcs: - rv = func() - if rv is not None: - return rv - - def process_response(self, response): - """Can be overridden in order to modify the response object - before it's sent to the WSGI server. By default this will - call all the :meth:`after_request` decorated functions. - - .. versionchanged:: 0.5 - As of Flask 0.5 the functions registered for after request - execution are called in reverse order of registration. - - :param response: a :attr:`response_class` object. - :return: a new response object or the same, has to be an - instance of :attr:`response_class`. - """ - ctx = _request_ctx_stack.top - bp = ctx.request.blueprint - funcs = ctx._after_request_functions - if bp is not None and bp in self.after_request_funcs: - funcs = chain(funcs, reversed(self.after_request_funcs[bp])) - if None in self.after_request_funcs: - funcs = chain(funcs, reversed(self.after_request_funcs[None])) - for handler in funcs: - response = handler(response) - if not self.session_interface.is_null_session(ctx.session): - self.save_session(ctx.session, response) - return response - - def do_teardown_request(self, exc=_sentinel): - """Called after the actual request dispatching and will - call every as :meth:`teardown_request` decorated function. This is - not actually called by the :class:`Flask` object itself but is always - triggered when the request context is popped. That way we have a - tighter control over certain resources under testing environments. - - .. versionchanged:: 0.9 - Added the `exc` argument. Previously this was always using the - current exception information. - """ - if exc is _sentinel: - exc = sys.exc_info()[1] - funcs = reversed(self.teardown_request_funcs.get(None, ())) - bp = _request_ctx_stack.top.request.blueprint - if bp is not None and bp in self.teardown_request_funcs: - funcs = chain(funcs, reversed(self.teardown_request_funcs[bp])) - for func in funcs: - func(exc) - request_tearing_down.send(self, exc=exc) - - def do_teardown_appcontext(self, exc=_sentinel): - """Called when an application context is popped. This works pretty - much the same as :meth:`do_teardown_request` but for the application - context. - - .. versionadded:: 0.9 - """ - if exc is _sentinel: - exc = sys.exc_info()[1] - for func in reversed(self.teardown_appcontext_funcs): - func(exc) - appcontext_tearing_down.send(self, exc=exc) - - def app_context(self): - """Binds the application only. For as long as the application is bound - to the current context the :data:`flask.current_app` points to that - application. An application context is automatically created when a - request context is pushed if necessary. - - Example usage:: - - with app.app_context(): - ... - - .. versionadded:: 0.9 - """ - return AppContext(self) - - def request_context(self, environ): - """Creates a :class:`~flask.ctx.RequestContext` from the given - environment and binds it to the current context. This must be used in - combination with the ``with`` statement because the request is only bound - to the current context for the duration of the ``with`` block. - - Example usage:: - - with app.request_context(environ): - do_something_with(request) - - The object returned can also be used without the ``with`` statement - which is useful for working in the shell. The example above is - doing exactly the same as this code:: - - ctx = app.request_context(environ) - ctx.push() - try: - do_something_with(request) - finally: - ctx.pop() - - .. versionchanged:: 0.3 - Added support for non-with statement usage and ``with`` statement - is now passed the ctx object. - - :param environ: a WSGI environment - """ - return RequestContext(self, environ) - - def test_request_context(self, *args, **kwargs): - """Creates a WSGI environment from the given values (see - :class:`werkzeug.test.EnvironBuilder` for more information, this - function accepts the same arguments). - """ - from flask.testing import make_test_environ_builder - builder = make_test_environ_builder(self, *args, **kwargs) - try: - return self.request_context(builder.get_environ()) - finally: - builder.close() - - def wsgi_app(self, environ, start_response): - """The actual WSGI application. This is not implemented in - `__call__` so that middlewares can be applied without losing a - reference to the class. So instead of doing this:: - - app = MyMiddleware(app) - - It's a better idea to do this instead:: - - app.wsgi_app = MyMiddleware(app.wsgi_app) - - Then you still have the original application object around and - can continue to call methods on it. - - .. versionchanged:: 0.7 - The behavior of the before and after request callbacks was changed - under error conditions and a new callback was added that will - always execute at the end of the request, independent on if an - error occurred or not. See :ref:`callbacks-and-errors`. - - :param environ: a WSGI environment - :param start_response: a callable accepting a status code, - a list of headers and an optional - exception context to start the response - """ - ctx = self.request_context(environ) - ctx.push() - error = None - try: - try: - response = self.full_dispatch_request() - except Exception as e: - error = e - response = self.handle_exception(e) - return response(environ, start_response) - finally: - if self.should_ignore_error(error): - error = None - ctx.auto_pop(error) - - def __call__(self, environ, start_response): - """Shortcut for :attr:`wsgi_app`.""" - return self.wsgi_app(environ, start_response) - - def __repr__(self): - return '<%s %r>' % ( - self.__class__.__name__, - self.name, - ) diff --git a/flask/blueprints.py b/flask/blueprints.py deleted file mode 100644 index 586a1b0b11..0000000000 --- a/flask/blueprints.py +++ /dev/null @@ -1,413 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.blueprints - ~~~~~~~~~~~~~~~~ - - Blueprints are the recommended way to implement larger or more - pluggable applications in Flask 0.7 and later. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -from functools import update_wrapper - -from .helpers import _PackageBoundObject, _endpoint_from_view_func - - -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: - rule = self.url_prefix + rule - 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 blueprint is an object that records - functions that will be called with the - :class:`~flask.blueprints.BlueprintSetupState` later to register functions - or other things on the main application. See :ref:`blueprints` for more - information. - - .. versionadded:: 0.7 - """ - - warn_on_modifications = False - _got_registered_once = False - - 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): - _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 - - 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 a blueprint - on the application. This can be overridden to customize the register - behavior. Keyword arguments from - :func:`~flask.Flask.register_blueprint` are directly forwarded to this - method in the `options` dictionary. - """ - 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) - - 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" - 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)) diff --git a/flask/cli.py b/flask/cli.py deleted file mode 100644 index 6c8cf32dc0..0000000000 --- a/flask/cli.py +++ /dev/null @@ -1,511 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.cli - ~~~~~~~~~ - - A simple command line application to run flask apps. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - -import os -import sys -from threading import Lock, Thread -from functools import update_wrapper - -import click - -from ._compat import iteritems, reraise -from .helpers import get_debug_flag -from . import __version__ - -class NoAppException(click.UsageError): - """Raised if an application cannot be found or loaded.""" - - -def find_best_app(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 app is not None and isinstance(app, Flask): - return app - - # Otherwise find the only object that is a Flask instance. - matches = [v for k, v in iteritems(module.__dict__) - if isinstance(v, Flask)] - - if len(matches) == 1: - return matches[0] - raise NoAppException('Failed to find application in module "%s". Are ' - 'you sure it contains a Flask application? Maybe ' - 'you wrapped it in a WSGI middleware or you are ' - 'using a factory function.' % module.__name__) - - -def prepare_exec_for_file(filename): - """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. - """ - module = [] - - # Chop off file extensions or package markers - if os.path.split(filename)[1] == '__init__.py': - filename = os.path.dirname(filename) - elif filename.endswith('.py'): - filename = filename[:-3] - else: - raise NoAppException('The file provided (%s) does exist but is not a ' - 'valid Python file. This means that it cannot ' - 'be used as application. Please change the ' - 'extension to .py' % filename) - filename = os.path.realpath(filename) - - dirpath = filename - while 1: - dirpath, extra = os.path.split(dirpath) - module.append(extra) - if not os.path.isfile(os.path.join(dirpath, '__init__.py')): - break - - sys.path.insert(0, dirpath) - return '.'.join(module[::-1]) - - -def locate_app(app_id): - """Attempts to locate the application.""" - __traceback_hide__ = True - if ':' in app_id: - module, app_obj = app_id.split(':', 1) - else: - module = app_id - app_obj = None - - try: - __import__(module) - except ImportError: - raise NoAppException('The file/path provided (%s) does not appear to ' - 'exist. Please verify the path is correct. If ' - 'app is not on PYTHONPATH, ensure the extension ' - 'is .py' % module) - mod = sys.modules[module] - if app_obj is None: - app = find_best_app(mod) - else: - app = getattr(mod, app_obj, None) - if app is None: - raise RuntimeError('Failed to find application in module "%s"' - % module) - - return app - - -def find_default_import_path(): - app = os.environ.get('FLASK_APP') - if app is None: - return - if os.path.isfile(app): - return prepare_exec_for_file(app) - return app - - -def get_version(ctx, param, value): - if not value or ctx.resilient_parsing: - return - message = 'Flask %(version)s\nPython %(python_version)s' - click.echo(message % { - 'version': __version__, - 'python_version': sys.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 is recorded and shows 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 - 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 - 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 - self._app = rv = self.loader() - self._bg_loading_exc_info = None - return rv - - def __call__(self, environ, start_response): - __traceback_hide__ = True - 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): - """Help 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): - if create_app is None: - if app_import_path is None: - app_import_path = find_default_import_path() - self.app_import_path = app_import_path - else: - app_import_path = None - - #: Optionally the import path for the Flask application. - self.app_import_path = app_import_path - #: 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._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 - if self._loaded_app is not None: - return self._loaded_app - if self.create_app is not None: - rv = self.create_app(self) - else: - if not self.app_import_path: - raise NoAppException( - 'Could not locate Flask application. You did not provide ' - 'the FLASK_APP environment variable.\n\nFor more ' - 'information see ' - 'http://flask.pocoo.org/docs/latest/quickstart/') - rv = locate_app(self.app_import_path) - debug = get_debug_flag() - if debug is not None: - rv.debug = debug - self._loaded_app = rv - return rv - - -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 wil 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. - """ - - def __init__(self, add_default_commands=True, create_app=None, - add_version_option=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 - - if add_default_commands: - self.add_command(run_command) - self.add_command(shell_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. - pass - return sorted(rv) - - def main(self, *args, **kwargs): - obj = kwargs.get('obj') - if obj is None: - obj = ScriptInfo(create_app=self.create_app) - kwargs['obj'] = obj - kwargs.setdefault('auto_envvar_prefix', 'FLASK') - return AppGroup.main(self, *args, **kwargs) - - -@click.command('run', short_help='Runs 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('--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=False, - help='Enable or disable multithreading.') -@pass_script_info -def run_command(info, host, port, reload, debugger, eager_loading, - with_threads): - """Runs a local development server for the Flask application. - - This local server is recommended for development purposes only but it - can also be used for simple intranet deployments. By default it will - not support any sort of concurrency at all to simplify debugging. This - can be changed with the --with-threads option which will enable basic - multithreading. - - The reloader and debugger are by default enabled if the debug flag of - Flask is enabled and disabled otherwise. - """ - from werkzeug.serving import run_simple - - debug = get_debug_flag() - if reload is None: - reload = bool(debug) - if debugger is None: - debugger = bool(debug) - if eager_loading is None: - eager_loading = not reload - - app = DispatchingApp(info.load_app, use_eager_loading=eager_loading) - - # Extra startup messages. This depends a bit on Werkzeug internals to - # not double execute when the reloader kicks in. - if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': - # If we have an import path we can print it out now which can help - # people understand what's being served. If we do not have an - # import path because the app was loaded through a callback then - # we won't print anything. - if info.app_import_path is not None: - print(' * Serving Flask app "%s"' % info.app_import_path) - if debug is not None: - print(' * Forcing debug mode %s' % (debug and 'on' or 'off')) - - run_simple(host, port, app, use_reloader=reload, - use_debugger=debugger, threaded=with_threads) - - -@click.command('shell', short_help='Runs a shell in the app context.') -@with_appcontext -def shell_command(): - """Runs 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 configuring the application. - """ - import code - from flask.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.debug and ' [debug]' or '', - 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) - - -cli = FlaskGroup(help="""\ -This shell command acts as general utility script for Flask applications. - -It loads the application configured (through the FLASK_APP environment -variable) and then provides commands either provided by the application or -Flask itself. - -The most useful commands are the "run" and "shell" command. - -Example usage: - -\b - %(prefix)s%(cmd)s FLASK_APP=hello.py - %(prefix)s%(cmd)s FLASK_DEBUG=1 - %(prefix)sflask run -""" % { - 'cmd': os.name == 'posix' and 'export' or 'set', - 'prefix': os.name == 'posix' and '$ ' or '', -}) - - -def main(as_module=False): - this_module = __package__ + '.cli' - args = sys.argv[1:] - - if as_module: - if sys.version_info >= (2, 7): - name = 'python -m ' + this_module.rsplit('.', 1)[0] - else: - name = 'python -m ' + this_module - - # This module is always executed as "python -m flask.run" and as such - # we need to ensure that we restore the actual command line so that - # the reloader can properly operate. - sys.argv = ['-m', this_module] + sys.argv[1:] - else: - name = None - - cli.main(args=args, prog_name=name) - - -if __name__ == '__main__': - main(as_module=True) diff --git a/flask/ctx.py b/flask/ctx.py deleted file mode 100644 index 480d9c5c42..0000000000 --- a/flask/ctx.py +++ /dev/null @@ -1,410 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.ctx - ~~~~~~~~~ - - Implements the objects required to keep the context. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - -import sys -from functools import update_wrapper - -from werkzeug.exceptions import HTTPException - -from .globals import _request_ctx_stack, _app_ctx_stack -from .signals import appcontext_pushed, appcontext_popped -from ._compat import BROKEN_PYPY_CTXMGR_EXIT, reraise - - -# a singleton sentinel value for parameter defaults -_sentinel = object() - - -class _AppCtxGlobals(object): - """A plain object.""" - - def get(self, name, default=None): - return self.__dict__.get(name, default) - - def pop(self, name, default=_sentinel): - if default is _sentinel: - return self.__dict__.pop(name) - else: - return self.__dict__.pop(name, default) - - def setdefault(self, name, default=None): - return self.__dict__.setdefault(name, default) - - def __contains__(self, item): - return item in self.__dict__ - - def __iter__(self): - return iter(self.__dict__) - - def __repr__(self): - top = _app_ctx_stack.top - if top is not None: - return '' % top.app.name - return object.__repr__(self) - - -def after_this_request(f): - """Executes a function after this request. This is useful to modify - response objects. The function is passed the response object and has - to return the same or a new one. - - Example:: - - @app.route('/') - def index(): - @after_this_request - def add_header(response): - response.headers['X-Foo'] = 'Parachute' - return response - return 'Hello World!' - - This is more useful if a function other than the view function wants to - modify a response. For instance think of a decorator that wants to add - some headers without converting the return value into a response object. - - .. versionadded:: 0.9 - """ - _request_ctx_stack.top._after_request_functions.append(f) - return f - - -def copy_current_request_context(f): - """A helper function that decorates a function to retain the current - request context. This is useful when working with greenlets. The moment - the function is decorated a copy of the request context is created and - then pushed when the function is called. - - Example:: - - import gevent - from flask import copy_current_request_context - - @app.route('/') - def index(): - @copy_current_request_context - def do_some_work(): - # do some work here, it can access flask.request like you - # would otherwise in the view function. - ... - gevent.spawn(do_some_work) - return 'Regular response' - - .. versionadded:: 0.10 - """ - top = _request_ctx_stack.top - if top is None: - raise RuntimeError('This decorator can only be used at local scopes ' - 'when a request context is on the stack. For instance within ' - 'view functions.') - reqctx = top.copy() - def wrapper(*args, **kwargs): - with reqctx: - return f(*args, **kwargs) - return update_wrapper(wrapper, f) - - -def has_request_context(): - """If you have code that wants to test if a request context is there or - not this function can be used. For instance, you may want to take advantage - of request information if the request object is available, but fail - silently if it is unavailable. - - :: - - class User(db.Model): - - def __init__(self, username, remote_addr=None): - self.username = username - if remote_addr is None and has_request_context(): - remote_addr = request.remote_addr - self.remote_addr = remote_addr - - Alternatively you can also just test any of the context bound objects - (such as :class:`request` or :class:`g` for truthness):: - - class User(db.Model): - - def __init__(self, username, remote_addr=None): - self.username = username - if remote_addr is None and request: - remote_addr = request.remote_addr - self.remote_addr = remote_addr - - .. versionadded:: 0.7 - """ - return _request_ctx_stack.top is not None - - -def has_app_context(): - """Works like :func:`has_request_context` but for the application - context. You can also just do a boolean check on the - :data:`current_app` object instead. - - .. versionadded:: 0.9 - """ - return _app_ctx_stack.top is not None - - -class AppContext(object): - """The application context binds an application object implicitly - to the current thread or greenlet, similar to how the - :class:`RequestContext` binds request information. The application - context is also implicitly created if a request context is created - but the application is not on top of the individual application - context. - """ - - def __init__(self, app): - self.app = app - self.url_adapter = app.create_url_adapter(None) - self.g = app.app_ctx_globals_class() - - # Like request context, app contexts can be pushed multiple times - # but there a basic "refcount" is enough to track them. - self._refcnt = 0 - - def push(self): - """Binds the app context to the current context.""" - self._refcnt += 1 - if hasattr(sys, 'exc_clear'): - sys.exc_clear() - _app_ctx_stack.push(self) - appcontext_pushed.send(self.app) - - def pop(self, exc=_sentinel): - """Pops the app context.""" - try: - self._refcnt -= 1 - if self._refcnt <= 0: - if exc is _sentinel: - exc = sys.exc_info()[1] - self.app.do_teardown_appcontext(exc) - finally: - rv = _app_ctx_stack.pop() - assert rv is self, 'Popped wrong app context. (%r instead of %r)' \ - % (rv, self) - appcontext_popped.send(self.app) - - def __enter__(self): - self.push() - return self - - def __exit__(self, exc_type, exc_value, tb): - self.pop(exc_value) - - if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None: - reraise(exc_type, exc_value, tb) - - -class RequestContext(object): - """The request context contains all request relevant information. It is - created at the beginning of the request and pushed to the - `_request_ctx_stack` and removed at the end of it. It will create the - URL adapter and request object for the WSGI environment provided. - - Do not attempt to use this class directly, instead use - :meth:`~flask.Flask.test_request_context` and - :meth:`~flask.Flask.request_context` to create this object. - - When the request context is popped, it will evaluate all the - functions registered on the application for teardown execution - (:meth:`~flask.Flask.teardown_request`). - - The request context is automatically popped at the end of the request - for you. In debug mode the request context is kept around if - exceptions happen so that interactive debuggers have a chance to - introspect the data. With 0.4 this can also be forced for requests - that did not fail and outside of ``DEBUG`` mode. By setting - ``'flask._preserve_context'`` to ``True`` on the WSGI environment the - context will not pop itself at the end of the request. This is used by - the :meth:`~flask.Flask.test_client` for example to implement the - deferred cleanup functionality. - - You might find this helpful for unittests where you need the - information from the context local around for a little longer. Make - sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in - that situation, otherwise your unittests will leak memory. - """ - - def __init__(self, app, environ, request=None): - self.app = app - if request is None: - request = app.request_class(environ) - self.request = request - self.url_adapter = app.create_url_adapter(self.request) - self.flashes = None - self.session = None - - # Request contexts can be pushed multiple times and interleaved with - # other request contexts. Now only if the last level is popped we - # get rid of them. Additionally if an application context is missing - # one is created implicitly so for each level we add this information - self._implicit_app_ctx_stack = [] - - # indicator if the context was preserved. Next time another context - # is pushed the preserved context is popped. - self.preserved = False - - # remembers the exception for pop if there is one in case the context - # preservation kicks in. - self._preserved_exc = None - - # Functions that should be executed after the request on the response - # object. These will be called before the regular "after_request" - # functions. - self._after_request_functions = [] - - self.match_request() - - def _get_g(self): - return _app_ctx_stack.top.g - def _set_g(self, value): - _app_ctx_stack.top.g = value - g = property(_get_g, _set_g) - del _get_g, _set_g - - def copy(self): - """Creates a copy of this request context with the same request object. - This can be used to move a request context to a different greenlet. - Because the actual request object is the same this cannot be used to - move a request context to a different thread unless access to the - request object is locked. - - .. versionadded:: 0.10 - """ - return self.__class__(self.app, - environ=self.request.environ, - request=self.request - ) - - def match_request(self): - """Can be overridden by a subclass to hook into the matching - of the request. - """ - try: - url_rule, self.request.view_args = \ - self.url_adapter.match(return_rule=True) - self.request.url_rule = url_rule - except HTTPException as e: - self.request.routing_exception = e - - def push(self): - """Binds the request context to the current context.""" - # If an exception occurs in debug mode or if context preservation is - # activated under exception situations exactly one context stays - # on the stack. The rationale is that you want to access that - # information under debug situations. However if someone forgets to - # pop that context again we want to make sure that on the next push - # it's invalidated, otherwise we run at risk that something leaks - # memory. This is usually only a problem in test suite since this - # functionality is not active in production environments. - top = _request_ctx_stack.top - if top is not None and top.preserved: - top.pop(top._preserved_exc) - - # Before we push the request context we have to ensure that there - # is an application context. - app_ctx = _app_ctx_stack.top - if app_ctx is None or app_ctx.app != self.app: - app_ctx = self.app.app_context() - app_ctx.push() - self._implicit_app_ctx_stack.append(app_ctx) - else: - self._implicit_app_ctx_stack.append(None) - - if hasattr(sys, 'exc_clear'): - sys.exc_clear() - - _request_ctx_stack.push(self) - - # Open the session at the moment that the request context is - # available. This allows a custom open_session method to use the - # request context (e.g. code that access database information - # stored on `g` instead of the appcontext). - self.session = self.app.open_session(self.request) - if self.session is None: - self.session = self.app.make_null_session() - - def pop(self, exc=_sentinel): - """Pops the request context and unbinds it by doing that. This will - also trigger the execution of functions registered by the - :meth:`~flask.Flask.teardown_request` decorator. - - .. versionchanged:: 0.9 - Added the `exc` argument. - """ - app_ctx = self._implicit_app_ctx_stack.pop() - - try: - clear_request = False - if not self._implicit_app_ctx_stack: - self.preserved = False - self._preserved_exc = None - if exc is _sentinel: - exc = sys.exc_info()[1] - self.app.do_teardown_request(exc) - - # If this interpreter supports clearing the exception information - # we do that now. This will only go into effect on Python 2.x, - # on 3.x it disappears automatically at the end of the exception - # stack. - if hasattr(sys, 'exc_clear'): - sys.exc_clear() - - request_close = getattr(self.request, 'close', None) - if request_close is not None: - request_close() - clear_request = True - finally: - rv = _request_ctx_stack.pop() - - # get rid of circular dependencies at the end of the request - # so that we don't require the GC to be active. - if clear_request: - rv.request.environ['werkzeug.request'] = None - - # Get rid of the app as well if necessary. - if app_ctx is not None: - app_ctx.pop(exc) - - assert rv is self, 'Popped wrong request context. ' \ - '(%r instead of %r)' % (rv, self) - - def auto_pop(self, exc): - if self.request.environ.get('flask._preserve_context') or \ - (exc is not None and self.app.preserve_context_on_exception): - self.preserved = True - self._preserved_exc = exc - else: - self.pop(exc) - - def __enter__(self): - self.push() - return self - - def __exit__(self, exc_type, exc_value, tb): - # do not pop the request stack if we are in debug mode and an - # exception happened. This will allow the debugger to still - # access the request object in the interactive shell. Furthermore - # the context can be force kept alive for the test client. - # See flask.testing for how this works. - self.auto_pop(exc_value) - - if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None: - reraise(exc_type, exc_value, tb) - - def __repr__(self): - return '<%s \'%s\' [%s] of %s>' % ( - self.__class__.__name__, - self.request.url, - self.request.method, - self.app.name, - ) diff --git a/flask/debughelpers.py b/flask/debughelpers.py deleted file mode 100644 index 90710dd353..0000000000 --- a/flask/debughelpers.py +++ /dev/null @@ -1,155 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.debughelpers - ~~~~~~~~~~~~~~~~~~ - - Various helpers to make the development experience better. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -from ._compat import implements_to_string, text_type -from .app import Flask -from .blueprints import Blueprint -from .globals import _request_ctx_stack - - -class UnexpectedUnicodeError(AssertionError, UnicodeError): - """Raised in places where we want some better error reporting for - unexpected unicode or binary data. - """ - - -@implements_to_string -class DebugFilesKeyError(KeyError, AssertionError): - """Raised from request.files during debugging. The idea is that it can - provide a better error message than just a generic KeyError/BadRequest. - """ - - def __init__(self, request, key): - form_matches = request.form.getlist(key) - buf = ['You tried to access the file "%s" in the request.files ' - 'dictionary but it does not exist. The mimetype for the request ' - 'is "%s" instead of "multipart/form-data" which means that no ' - 'file contents were transmitted. To fix this error you should ' - 'provide enctype="multipart/form-data" in your form.' % - (key, request.mimetype)] - if form_matches: - buf.append('\n\nThe browser instead transmitted some file names. ' - 'This was submitted: %s' % ', '.join('"%s"' % x - for x in form_matches)) - self.msg = ''.join(buf) - - def __str__(self): - return self.msg - - -class FormDataRoutingRedirect(AssertionError): - """This exception is raised by Flask in debug mode if it detects a - redirect caused by the routing system when the request method is not - GET, HEAD or OPTIONS. Reasoning: form data will be dropped. - """ - - def __init__(self, request): - exc = request.routing_exception - buf = ['A request was sent to this URL (%s) but a redirect was ' - 'issued automatically by the routing system to "%s".' - % (request.url, exc.new_url)] - - # In case just a slash was appended we can be extra helpful - if request.base_url + '/' == exc.new_url.split('?')[0]: - buf.append(' The URL was defined with a trailing slash so ' - 'Flask will automatically redirect to the URL ' - 'with the trailing slash if it was accessed ' - 'without one.') - - buf.append(' Make sure to directly send your %s-request to this URL ' - 'since we can\'t make browsers or HTTP clients redirect ' - 'with form data reliably or without user interaction.' % - request.method) - buf.append('\n\nNote: this exception is only raised in debug mode') - AssertionError.__init__(self, ''.join(buf).encode('utf-8')) - - -def attach_enctype_error_multidict(request): - """Since Flask 0.8 we're monkeypatching the files object in case a - request is detected that does not use multipart form data but the files - object is accessed. - """ - oldcls = request.files.__class__ - class newcls(oldcls): - def __getitem__(self, key): - try: - return oldcls.__getitem__(self, key) - except KeyError: - if key not in request.form: - raise - raise DebugFilesKeyError(request, key) - newcls.__name__ = oldcls.__name__ - newcls.__module__ = oldcls.__module__ - request.files.__class__ = newcls - - -def _dump_loader_info(loader): - yield 'class: %s.%s' % (type(loader).__module__, type(loader).__name__) - for key, value in sorted(loader.__dict__.items()): - if key.startswith('_'): - continue - if isinstance(value, (tuple, list)): - if not all(isinstance(x, (str, text_type)) for x in value): - continue - yield '%s:' % key - for item in value: - yield ' - %s' % item - continue - elif not isinstance(value, (str, text_type, int, float, bool)): - continue - yield '%s: %r' % (key, value) - - -def explain_template_loading_attempts(app, template, attempts): - """This should help developers understand what failed""" - info = ['Locating template "%s":' % template] - total_found = 0 - blueprint = None - reqctx = _request_ctx_stack.top - if reqctx is not None and reqctx.request.blueprint is not None: - blueprint = reqctx.request.blueprint - - for idx, (loader, srcobj, triple) in enumerate(attempts): - if isinstance(srcobj, Flask): - src_info = 'application "%s"' % srcobj.import_name - elif isinstance(srcobj, Blueprint): - src_info = 'blueprint "%s" (%s)' % (srcobj.name, - srcobj.import_name) - else: - src_info = repr(srcobj) - - info.append('% 5d: trying loader of %s' % ( - idx + 1, src_info)) - - for line in _dump_loader_info(loader): - info.append(' %s' % line) - - if triple is None: - detail = 'no match' - else: - detail = 'found (%r)' % (triple[1] or '') - total_found += 1 - info.append(' -> %s' % detail) - - seems_fishy = False - if total_found == 0: - info.append('Error: the template could not be found.') - seems_fishy = True - elif total_found > 1: - info.append('Warning: multiple loaders returned a match for the template.') - seems_fishy = True - - if blueprint is not None and seems_fishy: - info.append(' The template was looked up from an endpoint that ' - 'belongs to the blueprint "%s".' % blueprint) - info.append(' Maybe you did not place a template in the right folder?') - info.append(' See http://flask.pocoo.org/docs/blueprints/#templates') - - app.logger.info('\n'.join(info)) diff --git a/flask/ext/__init__.py b/flask/ext/__init__.py deleted file mode 100644 index 051f44ac40..0000000000 --- a/flask/ext/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.ext - ~~~~~~~~~ - - Redirect imports for extensions. This module basically makes it possible - for us to transition from flaskext.foo to flask_foo without having to - force all extensions to upgrade at the same time. - - When a user does ``from flask.ext.foo import bar`` it will attempt to - import ``from flask_foo import bar`` first and when that fails it will - try to import ``from flaskext.foo import bar``. - - We're switching from namespace packages because it was just too painful for - everybody involved. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - - -def setup(): - from ..exthook import ExtensionImporter - importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], __name__) - importer.install() - - -setup() -del setup diff --git a/flask/exthook.py b/flask/exthook.py deleted file mode 100644 index d88428027a..0000000000 --- a/flask/exthook.py +++ /dev/null @@ -1,143 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.exthook - ~~~~~~~~~~~~~ - - Redirect imports for extensions. This module basically makes it possible - for us to transition from flaskext.foo to flask_foo without having to - force all extensions to upgrade at the same time. - - When a user does ``from flask.ext.foo import bar`` it will attempt to - import ``from flask_foo import bar`` first and when that fails it will - try to import ``from flaskext.foo import bar``. - - We're switching from namespace packages because it was just too painful for - everybody involved. - - This is used by `flask.ext`. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -import sys -import os -import warnings -from ._compat import reraise - - -class ExtDeprecationWarning(DeprecationWarning): - pass - -warnings.simplefilter('always', ExtDeprecationWarning) - - -class ExtensionImporter(object): - """This importer redirects imports from this submodule to other locations. - This makes it possible to transition from the old flaskext.name to the - newer flask_name without people having a hard time. - """ - - def __init__(self, module_choices, wrapper_module): - self.module_choices = module_choices - self.wrapper_module = wrapper_module - self.prefix = wrapper_module + '.' - self.prefix_cutoff = wrapper_module.count('.') + 1 - - def __eq__(self, other): - return self.__class__.__module__ == other.__class__.__module__ and \ - self.__class__.__name__ == other.__class__.__name__ and \ - self.wrapper_module == other.wrapper_module and \ - self.module_choices == other.module_choices - - def __ne__(self, other): - return not self.__eq__(other) - - def install(self): - sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self] - - def find_module(self, fullname, path=None): - if fullname.startswith(self.prefix) and \ - fullname != 'flask.ext.ExtDeprecationWarning': - return self - - def load_module(self, fullname): - if fullname in sys.modules: - return sys.modules[fullname] - - modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff] - - warnings.warn( - "Importing flask.ext.{x} is deprecated, use flask_{x} instead." - .format(x=modname), ExtDeprecationWarning, stacklevel=2 - ) - - for path in self.module_choices: - realname = path % modname - try: - __import__(realname) - except ImportError: - exc_type, exc_value, tb = sys.exc_info() - # since we only establish the entry in sys.modules at the - # very this seems to be redundant, but if recursive imports - # happen we will call into the move import a second time. - # On the second invocation we still don't have an entry for - # fullname in sys.modules, but we will end up with the same - # fake module name and that import will succeed since this - # one already has a temporary entry in the modules dict. - # Since this one "succeeded" temporarily that second - # invocation now will have created a fullname entry in - # sys.modules which we have to kill. - sys.modules.pop(fullname, None) - - # If it's an important traceback we reraise it, otherwise - # we swallow it and try the next choice. The skipped frame - # is the one from __import__ above which we don't care about - if self.is_important_traceback(realname, tb): - reraise(exc_type, exc_value, tb.tb_next) - continue - module = sys.modules[fullname] = sys.modules[realname] - if '.' not in modname: - setattr(sys.modules[self.wrapper_module], modname, module) - - if realname.startswith('flaskext.'): - warnings.warn( - "Detected extension named flaskext.{x}, please rename it " - "to flask_{x}. The old form is deprecated." - .format(x=modname), ExtDeprecationWarning - ) - - return module - raise ImportError('No module named %s' % fullname) - - def is_important_traceback(self, important_module, tb): - """Walks a traceback's frames and checks if any of the frames - originated in the given important module. If that is the case then we - were able to import the module itself but apparently something went - wrong when the module was imported. (Eg: import of an import failed). - """ - while tb is not None: - if self.is_important_frame(important_module, tb): - return True - tb = tb.tb_next - return False - - def is_important_frame(self, important_module, tb): - """Checks a single frame if it's important.""" - g = tb.tb_frame.f_globals - if '__name__' not in g: - return False - - module_name = g['__name__'] - - # Python 2.7 Behavior. Modules are cleaned up late so the - # name shows up properly here. Success! - if module_name == important_module: - return True - - # Some python versions will clean up modules so early that the - # module name at that point is no longer set. Try guessing from - # the filename then. - filename = os.path.abspath(tb.tb_frame.f_code.co_filename) - test_string = os.path.sep + important_module.replace('.', os.path.sep) - return test_string + '.py' in filename or \ - test_string + os.path.sep + '__init__.py' in filename diff --git a/flask/globals.py b/flask/globals.py deleted file mode 100644 index 0b70a3ef92..0000000000 --- a/flask/globals.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.globals - ~~~~~~~~~~~~~ - - Defines all the global objects that are proxies to the current - active context. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - -from functools import partial -from werkzeug.local import LocalStack, LocalProxy - - -_request_ctx_err_msg = '''\ -Working outside of request context. - -This typically means that you attempted to use functionality that needed -an active HTTP request. Consult the documentation on testing for -information about how to avoid this problem.\ -''' -_app_ctx_err_msg = '''\ -Working outside of application context. - -This typically means that you attempted to use functionality that needed -to interface with the current application object in a way. To solve -this set up an application context with app.app_context(). See the -documentation for more information.\ -''' - - -def _lookup_req_object(name): - top = _request_ctx_stack.top - if top is None: - raise RuntimeError(_request_ctx_err_msg) - return getattr(top, name) - - -def _lookup_app_object(name): - top = _app_ctx_stack.top - if top is None: - raise RuntimeError(_app_ctx_err_msg) - return getattr(top, name) - - -def _find_app(): - top = _app_ctx_stack.top - if top is None: - raise RuntimeError(_app_ctx_err_msg) - return top.app - - -# context locals -_request_ctx_stack = LocalStack() -_app_ctx_stack = LocalStack() -current_app = LocalProxy(_find_app) -request = LocalProxy(partial(_lookup_req_object, 'request')) -session = LocalProxy(partial(_lookup_req_object, 'session')) -g = LocalProxy(partial(_lookup_app_object, 'g')) diff --git a/flask/helpers.py b/flask/helpers.py deleted file mode 100644 index c6c2cddc50..0000000000 --- a/flask/helpers.py +++ /dev/null @@ -1,960 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.helpers - ~~~~~~~~~~~~~ - - Implements various helpers. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" - -import os -import sys -import pkgutil -import posixpath -import mimetypes -from time import time -from zlib import adler32 -from threading import RLock -from werkzeug.routing import BuildError -from functools import update_wrapper - -try: - from werkzeug.urls import url_quote -except ImportError: - from urlparse import quote as url_quote - -from werkzeug.datastructures import Headers, Range -from werkzeug.exceptions import BadRequest, NotFound, \ - RequestedRangeNotSatisfiable - -# this was moved in 0.7 -try: - from werkzeug.wsgi import wrap_file -except ImportError: - from werkzeug.utils import wrap_file - -from jinja2 import FileSystemLoader - -from .signals import message_flashed -from .globals import session, _request_ctx_stack, _app_ctx_stack, \ - current_app, request -from ._compat import string_types, text_type - - -# 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_debug_flag(default=None): - val = os.environ.get('FLASK_DEBUG') - if not val: - return default - return val not 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 `. - - 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(http://github.com/endpoint,%20**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 - defaults to `localhost`. - :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 not reqctx.request._is_old_module: - if endpoint[:1] == '.': - if blueprint_name is not None: - endpoint = blueprint_name + endpoint - else: - endpoint = endpoint[1:] - else: - # TODO: get rid of this deprecated functionality in 1.0 - if '.' not in endpoint: - if blueprint_name is not None: - endpoint = blueprint_name + '.' + endpoint - elif endpoint.startswith('.'): - 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 - 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 - # 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. - - :param filename_or_fp: the filename of the file to send in `latin-1`. - 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 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') - headers.add('Content-Disposition', 'attachment', - filename=attachment_filename) - - 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 - 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: - if callable(getattr(Range, 'to_content_range_header', None)): - # Werkzeug supports Range Requests - # Remove this test when support for Werkzeug <0.12 is dropped - try: - rv = rv.make_conditional(request, accept_ranges=True, - complete_length=fsize) - except RequestedRangeNotSatisfiable: - file.close() - raise - else: - rv = rv.make_conditional(request) - # 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. - """ - for filename in pathnames: - if filename != '': - filename = posixpath.normpath(filename) - for sep in _os_alt_seps: - if sep in filename: - raise NotFound() - if os.path.isabs(filename) or \ - filename == '..' or \ - filename.startswith('../'): - raise NotFound() - directory = os.path.join(directory, filename) - return directory - - -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 = 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(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.split('.')[0] - loader = pkgutil.get_loader(root_mod_name) - if loader is None or import_name == '__main__': - # import name is not found, or interactive/main module - package_path = 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__(import_name) - filename = sys.modules[import_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) - - 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): - - def __init__(self, import_name, template_folder=None, root_path=None): - #: The name of the package or module. Do not change this once - #: it was set by the constructor. - self.import_name = import_name - - #: location of the templates. ``None`` if templates should not be - #: exposed. - self.template_folder = template_folder - - if root_path is None: - root_path = get_root_path(self.import_name) - - #: Where is the app root located? - self.root_path = root_path - - self._static_folder = None - self._static_url_path = None - - def _get_static_folder(self): - if self._static_folder is not None: - return os.path.join(self.root_path, self._static_folder) - def _set_static_folder(self, value): - self._static_folder = value - static_folder = property(_get_static_folder, _set_static_folder, doc=''' - The absolute path to the configured static folder. - ''') - del _get_static_folder, _set_static_folder - - def _get_static_url_path(self): - if self._static_url_path is not None: - return self._static_url_path - if self.static_folder is not None: - return '/' + os.path.basename(self.static_folder) - def _set_static_url_path(self, value): - self._static_url_path = value - static_url_path = property(_get_static_url_path, _set_static_url_path) - del _get_static_url_path, _set_static_url_path - - @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: resource file opening mode, default is 'rb'. - """ - if mode not in ('r', '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 diff --git a/flask/json.py b/flask/json.py deleted file mode 100644 index 16e0c29561..0000000000 --- a/flask/json.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.jsonimpl - ~~~~~~~~~~~~~~ - - Implementation helpers for the JSON support in Flask. - - :copyright: (c) 2015 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -import io -import uuid -from datetime import date -from .globals import current_app, request -from ._compat import text_type, PY2 - -from werkzeug.http import http_date -from jinja2 import Markup - -# Use the same json implementation as itsdangerous on which we -# depend anyways. -from itsdangerous import json as _json - - -# Figure out if simplejson escapes slashes. This behavior was changed -# from one version to another without reason. -_slash_escape = '\\/' not in _json.dumps('/') - - -__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump', - 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder', - 'jsonify'] - - -def _wrap_reader_for_text(fp, encoding): - if isinstance(fp.read(0), bytes): - fp = io.TextIOWrapper(io.BufferedReader(fp), encoding) - return fp - - -def _wrap_writer_for_text(fp, encoding): - try: - fp.write('') - except TypeError: - fp = io.TextIOWrapper(fp, encoding) - return fp - - -class JSONEncoder(_json.JSONEncoder): - """The default Flask JSON encoder. This one extends the default simplejson - encoder by also supporting ``datetime`` objects, ``UUID`` as well as - ``Markup`` objects which are serialized as RFC 822 datetime strings (same - as the HTTP date format). In order to support more data types override the - :meth:`default` method. - """ - - def default(self, o): - """Implement this method in a subclass such that it returns a - serializable object for ``o``, or calls the base implementation (to - raise a :exc:`TypeError`). - - For example, to support arbitrary iterators, you could implement - default like this:: - - def default(self, o): - try: - iterable = iter(o) - except TypeError: - pass - else: - return list(iterable) - return JSONEncoder.default(self, o) - """ - if isinstance(o, date): - return http_date(o.timetuple()) - if isinstance(o, uuid.UUID): - return str(o) - if hasattr(o, '__html__'): - return text_type(o.__html__()) - return _json.JSONEncoder.default(self, o) - - -class JSONDecoder(_json.JSONDecoder): - """The default JSON decoder. This one does not change the behavior from - the default simplejson decoder. Consult the :mod:`json` documentation - for more information. This decoder is not only used for the load - functions of this module but also :attr:`~flask.Request`. - """ - - -def _dump_arg_defaults(kwargs): - """Inject default arguments for dump functions.""" - if current_app: - kwargs.setdefault('cls', current_app.json_encoder) - if not current_app.config['JSON_AS_ASCII']: - kwargs.setdefault('ensure_ascii', False) - kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS']) - else: - kwargs.setdefault('sort_keys', True) - kwargs.setdefault('cls', JSONEncoder) - - -def _load_arg_defaults(kwargs): - """Inject default arguments for load functions.""" - if current_app: - kwargs.setdefault('cls', current_app.json_decoder) - else: - kwargs.setdefault('cls', JSONDecoder) - - -def dumps(obj, **kwargs): - """Serialize ``obj`` to a JSON formatted ``str`` by using the application's - configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an - application on the stack. - - This function can return ``unicode`` strings or ascii-only bytestrings by - default which coerce into unicode strings automatically. That behavior by - default is controlled by the ``JSON_AS_ASCII`` configuration variable - and can be overridden by the simplejson ``ensure_ascii`` parameter. - """ - _dump_arg_defaults(kwargs) - encoding = kwargs.pop('encoding', None) - rv = _json.dumps(obj, **kwargs) - if encoding is not None and isinstance(rv, text_type): - rv = rv.encode(encoding) - return rv - - -def dump(obj, fp, **kwargs): - """Like :func:`dumps` but writes into a file object.""" - _dump_arg_defaults(kwargs) - encoding = kwargs.pop('encoding', None) - if encoding is not None: - fp = _wrap_writer_for_text(fp, encoding) - _json.dump(obj, fp, **kwargs) - - -def loads(s, **kwargs): - """Unserialize a JSON object from a string ``s`` by using the application's - configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an - application on the stack. - """ - _load_arg_defaults(kwargs) - if isinstance(s, bytes): - s = s.decode(kwargs.pop('encoding', None) or 'utf-8') - return _json.loads(s, **kwargs) - - -def load(fp, **kwargs): - """Like :func:`loads` but reads from a file object. - """ - _load_arg_defaults(kwargs) - if not PY2: - fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8') - return _json.load(fp, **kwargs) - - -def htmlsafe_dumps(obj, **kwargs): - """Works exactly like :func:`dumps` but is safe for use in ``') - 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('{{ "