diff --git a/.appveyor.yml b/.appveyor.yml new file mode 100644 index 00000000..3a7d2f63 --- /dev/null +++ b/.appveyor.yml @@ -0,0 +1,23 @@ +environment: + global: + TOXENV: py + + matrix: + - PYTHON: C:\Python36 + - PYTHON: C:\Python27 + +init: + - SET PATH=%PYTHON%;%PATH% + +install: + - python -m pip install -U pip setuptools wheel tox + +build: false + +test_script: + - python -m tox + +branches: + only: + - master + - /^.*-maintenance$/ diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 45198266..00000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100755 index eaebea61..00000000 --- a/.devcontainer/on-create-command.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/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 deleted file mode 100644 index 2ff985a6..00000000 --- a/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -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 new file mode 100644 index 00000000..6f9ff673 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +CHANGES.rst merge=union diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..8b6910fb --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,33 @@ +**This issue tracker is a tool to address bugs in Flask itself. +Please use the #pocoo IRC channel on freenode or Stack Overflow for general +questions about using Flask or issues not related to Flask.** + +If you'd like to report a bug in Flask, fill out the template below. Provide +any any extra information that may be useful / related to your problem. +Ideally, create an [MCVE](http://stackoverflow.com/help/mcve), which helps us +understand the problem and helps check that it is not caused by something in +your code. + +--- + +### Expected Behavior + +Tell us what should happen. + +```python +Paste a minimal example that causes the problem. +``` + +### Actual Behavior + +Tell us what happens instead. + +```pytb +Paste the full traceback if there was an exception. +``` + +### Environment + +* Python version: +* Flask version: +* Werkzeug version: diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md deleted file mode 100644 index 0917c797..00000000 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -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 deleted file mode 100644 index a8f9f0b7..00000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 52c2aed4..00000000 --- a/.github/ISSUE_TEMPLATE/feature-request.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -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 00000000..9dda856c --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,16 @@ +Describe what this patch does to fix the issue. + +Link to any relevant issues or pull requests. + + diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index eb124d25..00000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,25 +0,0 @@ - - - - - diff --git a/.github/workflows/lock.yaml b/.github/workflows/lock.yaml deleted file mode 100644 index 533151a8..00000000 --- a/.github/workflows/lock.yaml +++ /dev/null @@ -1,26 +0,0 @@ -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: {} -concurrency: - group: lock - cancel-in-progress: true -jobs: - lock: - runs-on: ubuntu-latest - permissions: - issues: write - pull-requests: write - discussions: write - steps: - - uses: dessant/lock-threads@7266a7ce5c1df01b1c6db85bf8cd86c737dadbe7 # v6.0.0 - 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 deleted file mode 100644 index eff10995..00000000 --- a/.github/workflows/pre-commit.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: pre-commit -on: - pull_request: - push: - branches: [main, stable] -permissions: {} -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true -jobs: - main: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0 - with: - enable-cache: true - prune-cache: false - - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - id: setup-python - with: - python-version-file: pyproject.toml - - uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 - with: - path: ~/.cache/pre-commit - key: pre-commit|${{ hashFiles('pyproject.toml', '.pre-commit-config.yaml') }} - - run: uv run --locked --no-default-groups --group pre-commit pre-commit run --show-diff-on-failure --color=always --all-files diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml deleted file mode 100644 index 0c4f301a..00000000 --- a/.github/workflows/publish.yaml +++ /dev/null @@ -1,62 +0,0 @@ -name: Publish -on: - push: - tags: ['*'] -permissions: {} -concurrency: - group: publish-${{ github.event.push.ref }} - cancel-in-progress: true -jobs: - build: - runs-on: ubuntu-latest - outputs: - artifact-id: ${{ steps.upload-artifact.outputs.artifact-id }} - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0 - with: - enable-cache: false - prune-cache: false - - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - with: - python-version-file: pyproject.toml - - run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV - - run: uv build - - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - id: upload-artifact - with: - name: dist - path: dist/ - if-no-files-found: error - create-release: - needs: [build] - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - artifact-ids: ${{ needs.build.outputs.artifact-id }} - path: dist/ - - name: create release - run: gh release create --draft --repo ${GITHUB_REPOSITORY} ${GITHUB_REF_NAME} dist/* - env: - GH_TOKEN: ${{ github.token }} - publish-pypi: - needs: [build] - 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@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - artifact-ids: ${{ needs.build.outputs.artifact-id }} - path: dist/ - - uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # v1.13.0 - with: - packages-dir: "dist/" diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml deleted file mode 100644 index 97064c8c..00000000 --- a/.github/workflows/tests.yaml +++ /dev/null @@ -1,63 +0,0 @@ -name: Tests -on: - pull_request: - paths-ignore: ['docs/**', 'README.md'] - push: - branches: [main, stable] - paths-ignore: ['docs/**', 'README.md'] -permissions: {} -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true -jobs: - tests: - name: ${{ matrix.name || matrix.python }} - runs-on: ${{ matrix.os || 'ubuntu-latest' }} - strategy: - fail-fast: false - matrix: - include: - - {python: '3.14'} - - {python: '3.14t'} - - {name: Windows, python: '3.14', os: windows-latest} - - {name: Mac, python: '3.14', os: macos-latest} - - {python: '3.13'} - - {python: '3.12'} - - {python: '3.11'} - - {python: '3.10'} - - {name: PyPy, python: 'pypy-3.11', tox: pypy3.11} - - {name: Minimum Versions, python: '3.14', tox: tests-min} - - {name: Development Versions, python: '3.10', tox: tests-dev} - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0 - with: - enable-cache: true - prune-cache: false - - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - with: - python-version: ${{ matrix.python }} - - run: uv run --locked --no-default-groups --group dev tox run - env: - TOX_ENV: ${{ matrix.tox || format('py{0}', matrix.python) }} - typing: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0 - with: - enable-cache: true - prune-cache: false - - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - with: - python-version-file: pyproject.toml - - name: cache mypy - uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 - with: - path: ./.mypy_cache - key: mypy|${{ hashFiles('pyproject.toml') }} - - run: uv run --locked --no-default-groups --group dev tox run -e typing diff --git a/.github/workflows/zizmor.yaml b/.github/workflows/zizmor.yaml deleted file mode 100644 index 04082427..00000000 --- a/.github/workflows/zizmor.yaml +++ /dev/null @@ -1,22 +0,0 @@ -name: GitHub Actions security analysis with zizmor -on: - pull_request: - paths: ["**/*.yaml?"] - push: - branches: [main, stable] - paths: ["**/*.yaml?"] -permissions: {} -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true -jobs: - zizmor: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - uses: zizmorcore/zizmor-action@71321a20a9ded102f6e9ce5718a2fcec2c4f70d8 # v0.5.2 - with: - advanced-security: false - annotations: true diff --git a/.gitignore b/.gitignore index 8441e5a6..8a323555 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,23 @@ -.idea/ -.vscode/ -__pycache__/ +.DS_Store +.env +.flaskenv +*.pyc +*.pyo +env/ +env* dist/ -.coverage* -htmlcov/ +build/ +*.egg +*.egg-info/ +_mailinglist .tox/ +.cache/ +.pytest_cache/ +.idea/ docs/_build/ + +# Coverage reports +htmlcov/ +.coverage +.coverage.* +*,cover diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 5d1c89cb..00000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,23 +0,0 @@ -repos: - - repo: https://github.com/astral-sh/ruff-pre-commit - rev: 5e2fb545eba1ea9dc051f6f962d52fe8f76a9794 # frozen: v0.15.13 - hooks: - - id: ruff-check - - id: ruff-format - - repo: https://github.com/astral-sh/uv-pre-commit - rev: fa60a193803535a9e2accdb3ca4b1b584b1150cb # frozen: 0.11.15 - hooks: - - id: uv-lock - - repo: https://github.com/codespell-project/codespell - rev: 2ccb47ff45ad361a21071a7eedda4c37e6ae8c5a # frozen: v2.4.2 - hooks: - - id: codespell - args: ['--write-changes'] - - repo: https://github.com/pre-commit/pre-commit-hooks - rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.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 deleted file mode 100644 index acbd83f9..00000000 --- a/.readthedocs.yaml +++ /dev/null @@ -1,10 +0,0 @@ -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 new file mode 100644 index 00000000..0ff95ecd --- /dev/null +++ b/.travis.yml @@ -0,0 +1,55 @@ +os: linux +sudo: false +language: python + +matrix: + include: + - python: 3.6 + env: TOXENV=py,simplejson,devel,lowest,codecov + - python: 3.6 + env: TOXENV=docs-html + - python: 3.5 + env: TOXENV=py,codecov + - python: 3.4 + env: TOXENV=py,codecov + - python: 2.7 + env: TOXENV=py,simplejson,devel,lowest,codecov + - python: pypy + env: TOXENV=py,codecov + - python: nightly + env: TOXENV=py + - os: osx + language: generic + env: TOXENV=py + allow_failures: + - python: nightly + env: TOXENV=py + - os: osx + language: generic + env: TOXENV=py + fast_finish: true + +before_install: + - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then + brew update; + brew install python3 redis memcached; + virtualenv -p python3 ~/py-env; + . ~/py-env/bin/activate; + fi + +install: + - pip install tox + +script: + - tox + +cache: + - pip + +branches: + only: + - master + - /^.*-maintenance$/ + +notifications: + email: false diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 00000000..220046ed --- /dev/null +++ b/AUTHORS @@ -0,0 +1,12 @@ +Flask is developed and maintained by the Pallets team and community +contributors. It was created by Armin Ronacher. The core maintainers +are: + +- David Lord (davidism) +- Adrian Mönnich (ThiefMaster) +- Armin Ronacher (mitsuhiko) +- Marcus Unterwaditzer (untitaker) + +A full list of contributors is available from git with:: + + git shortlog -sne diff --git a/CHANGES.rst b/CHANGES.rst index 232b144a..5bf4c9d2 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,1665 +1,888 @@ -Version 3.2.0 -------------- +.. currentmodule:: flask -Unreleased - -- Drop support for Python 3.9. :pr:`5730` -- Remove previously deprecated code: ``__version__``. :pr:`5648` -- ``RequestContext`` has merged with ``AppContext``. ``RequestContext`` is now - a deprecated alias. If an app context is already pushed, it is not reused - when dispatching a request. This greatly simplifies the internal code for tracking - the active context. :issue:`5639` -- Many ``Flask`` methods involved in request dispatch now take the current - ``AppContext`` as the first parameter, instead of using the proxy objects. - If subclasses were overriding these methods, the old signature is detected, - shows a deprecation warning, and will continue to work during the - deprecation period. :issue:`5815` -- All teardown callbacks are called, even if any raise an error. :pr:`5928` -- The ``should_ignore_error`` is deprecated. Handle errors as needed in - teardown handlers instead. :issue:`5816` -- ``template_filter``, ``template_test``, and ``template_global`` decorators - can be used without parentheses. :issue:`5729` -- ``redirect`` returns a ``303`` status code by default instead of ``302``. - This tells the client to always switch to ``GET``, rather than only - switching ``POST`` to ``GET``. This preserves the current behavior of - ``GET`` and ``POST`` redirects, and is also correct for frontend libraries - such as HTMX. :issue:`5895` -- ``provide_automatic_options=True`` can be used to enable it for a view when - it's disabled in config. Previously, only disabling worked. :issue:`5916` -- ``Flask.select_jinja_autoescape`` uses case-insensitive comparison instead - of only lower case file extensions. :pr:`6012` - - -Version 3.1.3 -------------- - -Released 2026-02-18 - -- The session is marked as accessed for operations that only access the keys - but not the values, such as ``in`` and ``len``. :ghsa:`68rp-wp8r-4726` - - -Version 3.1.2 -------------- - -Released 2025-08-19 - -- ``stream_with_context`` does not fail inside async views. :issue:`5774` -- When using ``follow_redirects`` in the test client, the final state - of ``session`` is correct. :issue:`5786` -- Relax type hint for passing bytes IO to ``send_file``. :issue:`5776` - - -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` +Flask Changelog +=============== Version 1.0.1 ------------- -Released 2018-04-29 +Released on April 29 2018 - Fix registering partials (with no ``__name__``) as view functions. - :pr:`2730` + (`#2730`_) - Don't treat lists returned from view functions the same as tuples. - Only tuples are interpreted as response data. :issue:`2736` + Only tuples are interpreted as response data. (`#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` + change in 1.0. (`#2731`_, `#2742`_) - Only trap ``BadRequestKeyError`` errors in debug mode, not all ``BadRequest`` errors. This allows ``abort(400)`` to continue - working as expected. :issue:`2735` + working as expected. (`#2735`_) - The ``FLASK_SKIP_DOTENV`` environment variable can be set to ``1`` - to skip automatically loading dotenv files. :issue:`2722` + to skip automatically loading dotenv files. (`#2722`_) + +.. _#2722: https://github.com/pallets/flask/issues/2722 +.. _#2730: https://github.com/pallets/flask/pull/2730 +.. _#2731: https://github.com/pallets/flask/issues/2731 +.. _#2735: https://github.com/pallets/flask/issues/2735 +.. _#2736: https://github.com/pallets/flask/issues/2736 +.. _#2742: https://github.com/pallets/flask/issues/2742 Version 1.0 ----------- -Released 2018-04-26 +Released on April 26th 2018 -- Python 2.6 and 3.3 are no longer supported. +- **Python 2.6 and 3.3 are no longer supported.** (`pallets/meta#24`_) - 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` + (`#2586`_) +- Skip :meth:`app.run ` when a Flask application is run + from the command line. This avoids some behavior that was confusing + to debug. +- Change the default for :data:`JSONIFY_PRETTYPRINT_REGULAR` to + ``False``. :func:`~json.jsonify` returns a compact format by + default, and an indented format in debug mode. (`#2193`_) +- :meth:`Flask.__init__ ` accepts the ``host_matching`` + argument and sets it on :attr:`~Flask.url_map`. (`#1559`_) +- :meth:`Flask.__init__ ` accepts the ``static_host`` argument + and passes it as the ``host`` argument when defining the static + route. (`#1559`_) +- :func:`send_file` supports Unicode in ``attachment_filename``. + (`#2223`_) +- Pass ``_scheme`` argument from :func:`url_for` to + :meth:`~Flask.handle_url_build_error`. (`#2017`_) +- :meth:`~Flask.add_url_rule` accepts the + ``provide_automatic_options`` argument to disable adding the + ``OPTIONS`` method. (`#1489`_) +- :class:`~views.MethodView` subclasses inherit method handlers from + base classes. (`#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 + request are handled by the app's error handlers. (`#2254`_) +- Blueprints gained :attr:`~Blueprint.json_encoder` and + :attr:`~Blueprint.json_decoder` attributes to override the app's + encoder and decoder. (`#1898`_) +- :meth:`Flask.make_response` raises ``TypeError`` instead of ``ValueError`` for bad response types. The error messages have been - improved to describe why the type is invalid. :pr:`2256` + improved to describe why the type is invalid. (`#2256`_) - Add ``routes`` CLI command to output routes registered on the - application. :pr:`2259` + application. (`#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` + Chrome. (`#2282`_) +- Allow IP address as exact session cookie domain. (`#2282`_) - ``SESSION_COOKIE_DOMAIN`` is set if it is detected through - ``SERVER_NAME``. :pr:`2282` + ``SERVER_NAME``. (`#2282`_) - Auto-detect zero-argument app factory called ``create_app`` or - ``make_app`` from ``FLASK_APP``. :pr:`2297` + ``make_app`` from ``FLASK_APP``. (`#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` + parameter or a parameter named ``script_info``, the + :class:`~cli.ScriptInfo` object will be passed. (`#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` + (`#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` + (`#2414`_) +- The :class:`~views.View` class attribute + :attr:`~views.View.provide_automatic_options` is set in + :meth:`~views.View.as_view`, to be detected by + :meth:`~Flask.add_url_rule`. (`#2316`_) - Error handling will try handlers registered for ``blueprint, code``, ``app, code``, ``blueprint, exception``, ``app, exception``. - :pr:`2314` + (`#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 + is accessed at all during the request (and not deleted). (`#2288`_) +- :meth:`~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. + (`#1621`_) +- Set :data:`APPLICATION_ROOT` to ``'/'`` by default. This was already + the implicit default when it was set to ``None``. +- :data:`TRAP_BAD_REQUEST_ERRORS` is enabled by default in debug mode. ``BadRequestKeyError`` has a message with the bad key in debug mode - instead of the generic bad request message. :pr:`2348` -- Allow registering new tags with ``TaggedJSONSerializer`` to support - storing other types in the session cookie. :pr:`2352` + instead of the generic bad request message. (`#2348`_) +- Allow registering new tags with + :class:`~json.tag.TaggedJSONSerializer` to support storing other + types in the session cookie. (`#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` + context stack yet. This allows :func:`~stream_with_context` + generators to access the same session that the containing view uses. + (`#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` + content type. (`#2358`_) +- Extract JSON handling to a mixin applied to both the + :class:`Request` and :class:`Response` classes. This adds the + :meth:`~Response.is_json` and :meth:`~Response.get_json` methods to + the response to make testing JSON response much easier. (`#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` + MRO. (`#2362`_) +- Fix incorrect JSON encoding of aware, non-UTC datetimes. (`#2374`_) +- Template auto reloading will honor debug mode even even if + :attr:`~Flask.jinja_env` was already accessed. (`#2373`_) +- The following old deprecated code was removed. (`#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. + :meth:`Flask.create_jinja_environment` instead. - ``Flask.error_handlers`` - tracked by - ``Flask.error_handler_spec``, use ``Flask.errorhandler`` + :attr:`Flask.error_handler_spec`, use :meth:`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. + :attr:`Flask.app_ctx_globals_class` instead. + - ``Flask.static_path`` - use :attr:`Flask.static_url_path` + instead. + - ``Request.module`` - use :attr:`Request.blueprint` instead. -- The ``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 +- The :attr:`Request.json` property is no longer deprecated. + (`#1421`_) +- Support passing a :class:`~werkzeug.test.EnvironBuilder` or + ``dict`` to :meth:`test_client.open `. + (`#2412`_) +- The ``flask`` command and :meth:`Flask.run` will load environment variables from ``.env`` and ``.flaskenv`` files if python-dotenv is - installed. :pr:`2416` + installed. (`#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 + used instead of :data:`PREFERRED_URL_SCHEME`. (`#2430`_) +- :attr:`Flask.logger` has been simplified. ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` config was removed. The logger is always named ``flask.app``. The level is only set on first access, it - doesn't check ``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` + doesn't check :attr:`Flask.debug` each time. Only one format is + used, not different ones depending on :attr:`Flask.debug`. No + handlers are removed, and a handler is only added if no handlers are + already configured. (`#2436`_) +- Blueprint view function names may not contain dots. (`#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` + cases. (`#2526`_) +- The development server uses threads by default. (`#2529`_) +- Loading config files with ``silent=True`` will ignore + :data:`~errno.ENOTDIR` errors. (`#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` + development server over HTTPS. (`#2606`_) +- Added :data:`SESSION_COOKIE_SAMESITE` to control the ``SameSite`` + attribute on the session cookie. (`#2607`_) +- Added :meth:`~flask.Flask.test_cli_runner` to create a Click runner + that can invoke Flask CLI commands for testing. (`#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` + :data:`SERVER_NAME` does not implicily enable it. It can be enabled + by passing ``subdomain_matching=True`` to the ``Flask`` constructor. + (`#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` + ``url_prefix`` when it is registered with the app. (`#2629`_) +- :meth:`Request.get_json` doesn't cache the + result if parsing fails when ``silent`` is true. (`#2651`_) +- :func:`Request.get_json` no longer accepts arbitrary encodings. + Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but + Flask will autodetect UTF-8, -16, or -32. (`#2691`_) +- Added :data:`MAX_COOKIE_SIZE` and :attr:`Response.max_cookie_size` + to control when Werkzeug warns about large cookies that browsers may + ignore. (`#2693`_) - Updated documentation theme to make docs look better in small - windows. :pr:`2709` + windows. (`#2709`_) - Rewrote the tutorial docs and example project to take a more structured approach to help new users avoid common pitfalls. - :pr:`2676` + (`#2676`_) - -Version 0.12.5 --------------- - -Released 2020-02-10 - -- Pin Werkzeug to < 1.0.0. :issue:`3497` +.. _pallets/meta#24: https://github.com/pallets/meta/issues/24 +.. _#1421: https://github.com/pallets/flask/issues/1421 +.. _#1489: https://github.com/pallets/flask/pull/1489 +.. _#1559: https://github.com/pallets/flask/issues/1559 +.. _#1621: https://github.com/pallets/flask/pull/1621 +.. _#1898: https://github.com/pallets/flask/pull/1898 +.. _#1936: https://github.com/pallets/flask/pull/1936 +.. _#2017: https://github.com/pallets/flask/pull/2017 +.. _#2193: https://github.com/pallets/flask/pull/2193 +.. _#2223: https://github.com/pallets/flask/pull/2223 +.. _#2254: https://github.com/pallets/flask/pull/2254 +.. _#2256: https://github.com/pallets/flask/pull/2256 +.. _#2259: https://github.com/pallets/flask/pull/2259 +.. _#2282: https://github.com/pallets/flask/pull/2282 +.. _#2288: https://github.com/pallets/flask/pull/2288 +.. _#2297: https://github.com/pallets/flask/pull/2297 +.. _#2314: https://github.com/pallets/flask/pull/2314 +.. _#2316: https://github.com/pallets/flask/pull/2316 +.. _#2319: https://github.com/pallets/flask/pull/2319 +.. _#2326: https://github.com/pallets/flask/pull/2326 +.. _#2348: https://github.com/pallets/flask/pull/2348 +.. _#2352: https://github.com/pallets/flask/pull/2352 +.. _#2354: https://github.com/pallets/flask/pull/2354 +.. _#2358: https://github.com/pallets/flask/pull/2358 +.. _#2362: https://github.com/pallets/flask/pull/2362 +.. _#2374: https://github.com/pallets/flask/pull/2374 +.. _#2373: https://github.com/pallets/flask/pull/2373 +.. _#2385: https://github.com/pallets/flask/issues/2385 +.. _#2412: https://github.com/pallets/flask/pull/2412 +.. _#2414: https://github.com/pallets/flask/pull/2414 +.. _#2416: https://github.com/pallets/flask/pull/2416 +.. _#2430: https://github.com/pallets/flask/pull/2430 +.. _#2436: https://github.com/pallets/flask/pull/2436 +.. _#2450: https://github.com/pallets/flask/pull/2450 +.. _#2526: https://github.com/pallets/flask/issues/2526 +.. _#2529: https://github.com/pallets/flask/pull/2529 +.. _#2586: https://github.com/pallets/flask/issues/2586 +.. _#2581: https://github.com/pallets/flask/pull/2581 +.. _#2606: https://github.com/pallets/flask/pull/2606 +.. _#2607: https://github.com/pallets/flask/pull/2607 +.. _#2636: https://github.com/pallets/flask/pull/2636 +.. _#2635: https://github.com/pallets/flask/pull/2635 +.. _#2629: https://github.com/pallets/flask/pull/2629 +.. _#2651: https://github.com/pallets/flask/issues/2651 +.. _#2676: https://github.com/pallets/flask/pull/2676 +.. _#2691: https://github.com/pallets/flask/pull/2691 +.. _#2693: https://github.com/pallets/flask/pull/2693 +.. _#2709: https://github.com/pallets/flask/pull/2709 Version 0.12.4 -------------- -Released 2018-04-29 +Released on April 29 2018 -- Repackage 0.12.3 to fix package layout issue. :issue:`2728` +- Repackage 0.12.3 to fix package layout issue. (`#2728`_) Version 0.12.3 -------------- -Released 2018-04-26 +Released on April 26th 2018 -- ``Request.get_json`` no longer accepts arbitrary encodings. +- :func:`Request.get_json` no longer accepts arbitrary encodings. Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but - Flask will autodetect UTF-8, -16, or -32. :issue:`2692` + Flask will autodetect UTF-8, -16, or -32. (`#2692`_) - Fix a Python warning about imports when using ``python -m flask``. - :issue:`2666` + (`#2666`_) - Fix a ``ValueError`` caused by invalid ``Range`` requests in some cases. +.. _#2666: https://github.com/pallets/flask/issues/2666 +.. _#2692: https://github.com/pallets/flask/issues/2692 + Version 0.12.2 -------------- -Released 2017-05-16 - -- Fix a bug in ``safe_join`` on Windows. +Released on May 16 2017 +- 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. +Bugfix release, released on March 31st 2017 +- Prevent `flask run` from showing a NoAppException when an ImportError occurs + within the imported application module. +- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix + ``#2118``. +- Use the ``SERVER_NAME`` config if it is present as default values for + ``app.run``. ``#2109``, ``#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 +Released on December 21st 2016, codename Punsch. -- The cli command now responds to ``--version``. -- Mimetype guessing and ETag generation for file-like objects in - ``send_file`` has been removed. :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` +- 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 -------------- -Released 2016-06-07 - -- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from - working. :pr:`1872` +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 2016-05-29, codename Absinthe +Released on May 29th 2016, 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``. +- 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``). +- Updated extension dev guidelines. +- ``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 -------------- -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. +(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 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. +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 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. +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 ------------- -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. +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 2011-09-29, codename Rakija +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 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 Jinja environment's ``list_templates`` method not - returning the correct names when blueprints or modules were - involved. +- 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 ------------- -Released 2011-07-06 - -- Fixed an issue with URL processors not properly working on - blueprints. +Bugfix release, released on July 6th 2011 +- 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. +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 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. +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 ------------- -Released 2010-12-31 - -- Fixed an issue where the default ``OPTIONS`` response was not - exposing all valid methods in the ``Allow`` header. -- Jinja 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. +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 2010-07-27, codename Whisky +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. -- ``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. +- after request functions are now called in reverse order of + registration. +- OPTIONS is now automatically implemented by Flask unless the + application explicitly adds 'OPTIONS' as method to the URL rule. + In this case no automatic OPTIONS handling kicks in. +- static rules are now even in place if there is no static folder + for the module. This was implemented to aid GAE which will + remove the static folder if it's part of a mapping in the .yml + file. +- the :attr:`~flask.Flask.config` is now available in the templates + as `config`. +- context processors will no longer override values passed directly + to the render function. +- added the ability to limit the incoming request data with the + new ``MAX_CONTENT_LENGTH`` configuration value. +- the endpoint for the :meth:`flask.Module.add_url_rule` method + is now optional to be consistent with the function of the + same name on the application object. +- added a :func:`flask.make_response` function that simplifies + creating response object instances in views. +- added signalling support based on blinker. This feature is currently + optional and supposed to be used by extensions and applications. If + you want to use it, make sure to have `blinker`_ installed. +- refactored the way URL adapters are created. This process is now + fully customizable with the :meth:`~flask.Flask.create_url_adapter` + method. +- modules can now register for a subdomain instead of just an URL + prefix. This makes it possible to bind a whole module to a + configurable subdomain. +.. _blinker: https://pypi.org/project/blinker/ Version 0.5.2 ------------- -Released 2010-07-15 - -- Fixed another issue with loading templates from directories when - modules were used. +Bugfix Release, released on July 15th 2010 +- 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. +Bugfix Release, released on July 6th 2010 +- 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. +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 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. +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 ------------- -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) +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 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. +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 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. +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 ----------- -Released 2010-04-16 - -- First public preview release. +First public preview release. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 00000000..36b7df3a --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,180 @@ +How to contribute to Flask +========================== + +Thank you for considering contributing to Flask! + +Support questions +----------------- + +Please, don't use the issue tracker for this. Use one of the following +resources for questions about your own code: + +* The IRC channel ``#pocoo`` on FreeNode. +* The IRC channel ``#python`` on FreeNode for more general questions. +* The mailing list flask@python.org for long term discussion or larger issues. +* Ask on `Stack Overflow`_. Search with Google first using: + ``site:stackoverflow.com flask {search term, exception message, etc.}`` + +.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?sort=linked + +Reporting issues +---------------- + +- Describe what you expected to happen. +- If possible, include a `minimal, complete, and verifiable example`_ to help + us identify the issue. This also helps check that the issue is not with your + own code. +- Describe what actually happened. Include the full traceback if there was an + exception. +- List your Python, Flask, and Werkzeug versions. If possible, check if this + issue is already fixed in the repository. + +.. _minimal, complete, and verifiable example: https://stackoverflow.com/help/mcve + +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. + +First time setup +~~~~~~~~~~~~~~~~ + +- Download and install the `latest version of git`_. +- Configure git with your `username`_ and `email`_:: + + git config --global user.name 'your name' + git config --global user.email 'your email' + +- Make sure you have a `GitHub account`_. +- Fork Flask to your GitHub account by clicking the `Fork`_ button. +- `Clone`_ your GitHub fork locally:: + + git clone https://github.com/{username}/flask + cd flask + +- Add the main repository as a remote to update later:: + + git remote add pallets https://github.com/pallets/flask + git fetch pallets + +- Create a virtualenv:: + + python3 -m venv env + . env/bin/activate + # or "env\Scripts\activate" on Windows + +- Install Flask in editable mode with development dependencies:: + + pip install -e ".[dev]" + +.. _GitHub account: https://github.com/join +.. _latest version of git: https://git-scm.com/downloads +.. _username: https://help.github.com/articles/setting-your-username-in-git/ +.. _email: https://help.github.com/articles/setting-your-email-in-git/ +.. _Fork: https://github.com/pallets/flask/fork +.. _Clone: https://help.github.com/articles/fork-a-repo/#step-2-create-a-local-clone-of-your-fork + +Start coding +~~~~~~~~~~~~ + +- Create a branch to identify the issue you would like to work on (e.g. + ``2287-dry-test-suite``) +- Using your favorite editor, make your changes, `committing as you go`_. +- Try to follow `PEP8`_, but you may ignore the line length limit if following + it would make the code uglier. +- Include tests that cover any code changes you make. Make sure the test fails + without your patch. `Run the tests. `_. +- Push your commits to GitHub and `create a pull request`_. +- Celebrate 🎉 + +.. _committing as you go: http://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes +.. _PEP8: https://pep8.org/ +.. _create a pull request: https://help.github.com/articles/creating-a-pull-request/ + +.. _contributing-testsuite: + +Running the tests +~~~~~~~~~~~~~~~~~ + +Run the basic test suite with:: + + pytest + +This only runs the tests for the current environment. Whether this is relevant +depends on which part of Flask you're working on. Travis-CI will run the full +suite when you submit your pull request. + +The full test suite takes a long time to run because it tests multiple +combinations of Python and dependencies. You need to have Python 2.7, 3.4, +3.5 3.6, and PyPy 2.7 installed to run all of the environments. Then run:: + + tox + +Running test coverage +~~~~~~~~~~~~~~~~~~~~~ + +Generating a report of lines that do not have test coverage can indicate +where to start contributing. Run ``pytest`` using ``coverage`` and generate a +report on the terminal and as an interactive HTML document:: + + coverage run -m pytest + coverage report + coverage html + # then open htmlcov/index.html + +Read more about `coverage `_. + +Running the full test suite with ``tox`` will combine the coverage reports +from all runs. + + +Building the docs +~~~~~~~~~~~~~~~~~ + +Build the docs in the ``docs`` directory using Sphinx:: + + cd docs + make html + +Open ``_build/html/index.html`` in your browser to view the docs. + +Read more about `Sphinx `_. + + +make targets +~~~~~~~~~~~~ + +Flask provides a ``Makefile`` with various shortcuts. They will ensure that +all dependencies are installed. + +- ``make test`` runs the basic test suite with ``pytest`` +- ``make cov`` runs the basic test suite with ``coverage`` +- ``make test-all`` runs the full test suite with ``tox`` +- ``make docs`` builds the HTML documentation + +Caution: zero-padded file modes +------------------------------- + +This repository contains several zero-padded file modes that may cause issues +when pushing this repository to git hosts other than GitHub. Fixing this is +destructive to the commit history, so we suggest ignoring these warnings. If it +fails to push and you're using a self-hosted git service like GitLab, you can +turn off repository checks in the admin panel. + +These files can also cause issues while cloning. If you have :: + + [fetch] + fsckobjects = true + +or :: + + [receive] + fsckObjects = true + +set in your git configuration file, cloning this repository will fail. The only +solution is to set both of the above settings to false while cloning, and then +setting them back to true after the cloning is finished. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..8f9252f4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,31 @@ +Copyright © 2010 by the Pallets team. + +Some rights reserved. + +Redistribution and use in source and binary forms of the software as +well as documentation, with or without modification, are permitted +provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF +USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 9d227a0c..00000000 --- a/LICENSE.txt +++ /dev/null @@ -1,28 +0,0 @@ -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 new file mode 100644 index 00000000..d8a725b5 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,11 @@ +include Makefile CHANGES.rst LICENSE AUTHORS tox.ini + +graft artwork +graft tests +graft examples +graft docs + +global-exclude *.py[co] + +prune docs/_build +prune docs/_themes diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..7df5fd00 --- /dev/null +++ b/Makefile @@ -0,0 +1,35 @@ +.PHONY: all install-dev test coverage cov test-all tox docs audit release clean-pyc upload-docs ebook + +all: test + +install-dev: + pip install -q -e .[dev] + +test: clean-pyc install-dev + pytest + +coverage: clean-pyc install-dev + coverage run -m pytest + coverage report + coverage html + +cov: coverage + +test-all: install-dev + tox + +tox: test-all + +docs: clean-pyc install-dev + $(MAKE) -C docs html + +audit: + python setup.py audit + +release: + python scripts/make-release.py + +clean-pyc: + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + diff --git a/README.md b/README.md deleted file mode 100644 index 64f56cac..00000000 --- a/README.md +++ /dev/null @@ -1,53 +0,0 @@ -
- -# 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/README.rst b/README.rst new file mode 100644 index 00000000..6277690e --- /dev/null +++ b/README.rst @@ -0,0 +1,76 @@ +Flask +===== + +Flask is a lightweight `WSGI`_ web application framework. It is designed +to make getting started quick and easy, with the ability to scale up to +complex applications. It began as a simple wrapper around `Werkzeug`_ +and `Jinja`_ and has become one of the most popular Python web +application frameworks. + +Flask offers suggestions, but doesn't enforce any dependencies or +project layout. It is up to the developer to choose the tools and +libraries they want to use. There are many extensions provided by the +community that make adding new functionality easy. + + +Installing +---------- + +Install and update using `pip`_: + +.. code-block:: text + + pip install -U Flask + + +A Simple Example +---------------- + +.. code-block:: python + + from flask import Flask + + app = Flask(__name__) + + @app.route('/') + def hello(): + return 'Hello, World!' + +.. code-block:: text + + $ FLASK_APP=hello.py flask run + * Serving Flask app "hello" + * 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://psfmember.org/civicrm/contribute/transact?reset=1&id=20 + + +Links +----- + +* Website: https://www.palletsprojects.com/p/flask/ +* Documentation: http://flask.pocoo.org/docs/ +* License: `BSD `_ +* Releases: https://pypi.org/project/Flask/ +* Code: https://github.com/pallets/flask +* Issue tracker: https://github.com/pallets/flask/issues +* Test status: + + * Linux, Mac: https://travis-ci.org/pallets/flask + * Windows: https://ci.appveyor.com/project/pallets/flask + +* Test coverage: https://codecov.io/gh/pallets/flask + +.. _WSGI: https://wsgi.readthedocs.io +.. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/ +.. _Jinja: https://www.palletsprojects.com/p/jinja/ +.. _pip: https://pip.pypa.io/en/stable/quickstart/ diff --git a/artwork/LICENSE b/artwork/LICENSE new file mode 100644 index 00000000..c6df416c --- /dev/null +++ b/artwork/LICENSE @@ -0,0 +1,20 @@ +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 new file mode 100644 index 00000000..8c0748a2 --- /dev/null +++ b/artwork/logo-full.svg @@ -0,0 +1,290 @@ + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/artwork/logo-lineart.svg b/artwork/logo-lineart.svg new file mode 100644 index 00000000..615260dc --- /dev/null +++ b/artwork/logo-lineart.svg @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + diff --git a/docs/Makefile b/docs/Makefile index d4bb2cbb..fc19e49d 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -1,10 +1,10 @@ # Minimal makefile for Sphinx documentation # -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= sphinx-build +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = Flask SOURCEDIR = . BUILDDIR = _build @@ -17,4 +17,4 @@ help: # 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) + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/_static/flask-favicon.ico b/docs/_static/flask-favicon.ico new file mode 100644 index 00000000..bf0a9615 Binary files /dev/null and b/docs/_static/flask-favicon.ico differ diff --git a/docs/_static/flask-icon.svg b/docs/_static/flask-icon.svg deleted file mode 100644 index c802da9a..00000000 --- a/docs/_static/flask-icon.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/docs/_static/flask-logo.svg b/docs/_static/flask-logo.svg deleted file mode 100644 index c216b617..00000000 --- a/docs/_static/flask-logo.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/docs/_static/flask-name.svg b/docs/_static/flask-name.svg deleted file mode 100644 index b46782d2..00000000 --- a/docs/_static/flask-name.svg +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/docs/_static/flask.png b/docs/_static/flask.png new file mode 100644 index 00000000..55cb8478 Binary files /dev/null and b/docs/_static/flask.png differ diff --git a/docs/_static/logo-full.png b/docs/_static/logo-full.png new file mode 100644 index 00000000..ce236061 Binary files /dev/null and b/docs/_static/logo-full.png differ diff --git a/docs/_static/no.png b/docs/_static/no.png new file mode 100644 index 00000000..644c3f70 Binary files /dev/null and b/docs/_static/no.png differ diff --git a/docs/_static/pycharm-run-config.png b/docs/_static/pycharm-run-config.png deleted file mode 100644 index ad025545..00000000 Binary files a/docs/_static/pycharm-run-config.png and /dev/null differ diff --git a/docs/_static/pycharm-runconfig.png b/docs/_static/pycharm-runconfig.png new file mode 100644 index 00000000..dff21fa0 Binary files /dev/null and b/docs/_static/pycharm-runconfig.png differ diff --git a/docs/_static/touch-icon.png b/docs/_static/touch-icon.png new file mode 100644 index 00000000..ef151f15 Binary files /dev/null and b/docs/_static/touch-icon.png differ diff --git a/docs/_static/yes.png b/docs/_static/yes.png new file mode 100644 index 00000000..56917ab2 Binary files /dev/null and b/docs/_static/yes.png differ diff --git a/docs/advanced_foreword.rst b/docs/advanced_foreword.rst new file mode 100644 index 00000000..bd56f53c --- /dev/null +++ b/docs/advanced_foreword.rst @@ -0,0 +1,47 @@ +.. _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. diff --git a/docs/api.rst b/docs/api.rst index 52b25376..cdb05638 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,9 +1,11 @@ +.. _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. @@ -27,28 +29,76 @@ Incoming Request Data --------------------- .. autoclass:: Request - :members: - :inherited-members: - :exclude-members: json_module + :members: + :inherited-members: -.. data:: request + .. attribute:: environ - A proxy to the request data for the current request, an instance of - :class:`.Request`. + The underlying WSGI environment. - This is only available when a :doc:`request context ` is - active. + .. attribute:: path + .. attribute:: full_path + .. attribute:: script_root + .. attribute:: url + .. attribute:: base_url + .. attribute:: url_root - This is a proxy. See :ref:`context-visibility` for more information. + Provides different ways to look at the current `IRI + `_. Imagine your application is + listening on the following application root:: + + http://www.example.com/myapplication + + And a user requests the following URI:: + + http://www.example.com/myapplication/%CF%80/page.html?x=y + + In this case the values of the above mentioned attributes would be + the following: + + ============= ====================================================== + `path` ``u'/π/page.html'`` + `full_path` ``u'/π/page.html?x=y'`` + `script_root` ``u'/myapplication'`` + `base_url` ``u'http://www.example.com/myapplication/π/page.html'`` + `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'`` + `url_root` ``u'http://www.example.com/myapplication/'`` + ============= ====================================================== + + +.. attribute:: request + + To access incoming request data, you can use the global `request` + object. Flask parses incoming request data for you and gives you + access to it through that global object. Internally Flask makes + sure that you always get the correct data for the active thread if you + are in a multithreaded environment. + + This is a proxy. See :ref:`notes-on-proxies` for more information. + + The request object is an instance of a :class:`~werkzeug.wrappers.Request` + subclass and provides all of the attributes Werkzeug defines. This + just shows a quick overview of the most important ones. Response Objects ---------------- .. autoclass:: flask.Response - :members: - :inherited-members: - :exclude-members: json_module + :members: set_cookie, max_cookie_size, data, mimetype, is_json, get_json + + .. attribute:: headers + + A :class:`~werkzeug.datastructures.Headers` object representing the response headers. + + .. attribute:: status + + A string with a response status. + + .. attribute:: status_code + + The response status as integer. + Sessions -------- @@ -60,33 +110,40 @@ 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 :data:`.session` proxy. +To access the current session you can use the :class:`session` object: -.. data:: session +.. class:: session - A proxy to the session data for the current request, an instance of - :class:`.SessionMixin`. + The session object works pretty much like an ordinary dict, with the + difference that it keeps track on modifications. - This is only available when a :doc:`request context ` is - active. + This is a proxy. See :ref:`notes-on-proxies` for more information. - This is a proxy. See :ref:`context-visibility` for more information. + The following attributes are interesting: - The session object works like a dict but tracks assignment and access to its - keys. It cannot track modifications to mutable values, you need to set - :attr:`~.SessionMixin.modified` manually when modifying a list, dict, etc. + .. attribute:: new - .. code-block:: python + ``True`` if the session is new, ``False`` otherwise. - # appending to a list is not detected - session["numbers"].append(42) + .. attribute:: modified + + ``True`` if the session object detected a modification. Be advised + that modifications on mutable structures are not picked up + automatically, in that situation you have to explicitly set the + attribute to ``True`` yourself. Here an example:: + + # this change is not picked up because a mutable object (here + # a list) is changed. + session['objects'].append(42) # so mark it as modified yourself session.modified = True - The session is persisted across requests using a cookie. By default the - users's browser will clear the cookie when it is closed. Set - :attr:`~.SessionMixin.permanent` to ``True`` to persist the cookie for - :data:`PERMANENT_SESSION_LIFETIME`. + .. attribute:: permanent + + If set to ``True`` the session lives for + :attr:`~flask.Flask.permanent_session_lifetime` seconds. The + default is 31 days. If set to ``False`` (which is the default) the + session will be deleted when the user closes the browser. Session Interface @@ -116,9 +173,10 @@ implementation that Flask is using. .. admonition:: Notice - The :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``. - The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a - ``timedelta``. + The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer + starting with Flask 0.8. Either catch this down yourself or use + the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the + app which converts the result to an integer automatically. Test Client @@ -146,24 +204,23 @@ 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 -thing, like it does for :data:`.request` and :data:`.session`. +different values for each request. In a nutshell: it does the right +thing, like it does for :class:`request` and :class:`session`. .. data:: g - A proxy to a namespace object used to store data during a single request or - app context. An instance of :attr:`.Flask.app_ctx_globals_class`, which - defaults to :class:`._AppCtxGlobals`. + A namespace object that can store data during an + :doc:`application context `. This is an instance of + :attr:`Flask.app_ctx_globals_class`, which defaults to + :class:`ctx._AppCtxGlobals`. - This is a good place to store resources during a request. For example, a - :meth:`~.Flask.before_request` function could load a user object from a - session id, then set ``g.user`` to be used in the view function. + This is a good place to store resources during a request. During + testing, you can use the :ref:`faking-resources` pattern to + pre-configure such resources. - This is only available when an :doc:`app context ` is active. - - This is a proxy. See :ref:`context-visibility` for more information. + This is a proxy. See :ref:`notes-on-proxies` for more information. .. versionchanged:: 0.10 Bound to the application context instead of the request context. @@ -177,16 +234,17 @@ Useful Functions and Classes .. data:: current_app - A proxy to the :class:`.Flask` application handling the current request or - other activity. + 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 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 only available when an :doc:`app context ` is active. - - This is a proxy. See :ref:`context-visibility` for more information. + This is a proxy. See :ref:`notes-on-proxies` for more information. .. autofunction:: has_request_context @@ -208,6 +266,12 @@ Useful Functions and Classes .. autofunction:: send_from_directory +.. autofunction:: safe_join + +.. autofunction:: escape + +.. autoclass:: Markup + :members: escape, unescape, striptags Message Flashing ---------------- @@ -216,29 +280,58 @@ Message Flashing .. autofunction:: get_flashed_messages - JSON Support ------------ .. module:: flask.json -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. +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. -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 @@ -249,17 +342,14 @@ HTML `` - -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 415 Unsupported Media Type -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("/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, a 400 Bad Request error will be raised. If -the ``Content-Type`` header is not set to ``application/json``, a 415 -Unsupported Media Type 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 7ac6856e..d4e2c92d 100644 --- a/docs/patterns/jquery.rst +++ b/docs/patterns/jquery.rst @@ -1,6 +1,167 @@ -:orphan: - AJAX with jQuery ================ -Obsolete, see :doc:`/patterns/javascript` instead. +`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. + +Check out the :gh:`example source ` for a full +application demonstrating the code on this page, as well as the same +thing using ``XMLHttpRequest`` and ``fetch``. diff --git a/docs/patterns/lazyloading.rst b/docs/patterns/lazyloading.rst index 658a1cd4..acb77f94 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.utils import import_string, cached_property + from werkzeug 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(import_name, url_rules=[], **options): - view = LazyView(f"yourapplication.{import_name}") + view = LazyView('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 45dbb87e..d5c187b6 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. Then the method is replaced -with the header value before being passed to Flask. +set the ``X-HTTP-Method-Override`` header and set the value to the +intended HTTP method (such as ``PATCH``). -This can be accomplished with an HTTP middleware:: +This can easily be accomplished with an HTTP middleware:: class HTTPMethodOverrideMiddleware(object): allowed_methods = frozenset([ @@ -29,12 +29,13 @@ This can 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, wrap the app object with the middleware:: +To use this with Flask this is all that is necessary:: from flask import Flask diff --git a/docs/patterns/mongoengine.rst b/docs/patterns/mongoengine.rst deleted file mode 100644 index 8d49de7c..00000000 --- a/docs/patterns/mongoengine.rst +++ /dev/null @@ -1,102 +0,0 @@ -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://docs.mongoengine.org/projects/flask-mongoengine/en/latest/ - -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 new file mode 100644 index 00000000..9d1b3e2a --- /dev/null +++ b/docs/patterns/mongokit.rst @@ -0,0 +1,144 @@ +.. 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 90fa8a8f..f6b51614 100644 --- a/docs/patterns/packages.rst +++ b/docs/patterns/packages.rst @@ -1,7 +1,11 @@ -Large Applications as Packages -============================== +.. _larger-applications: -Imagine a simple flask application structure that looks like this:: +Larger Applications +=================== + +For larger applications it's a good idea to use a package instead of a +module. That is quite simple. Imagine a small application looks like +this:: /yourapplication yourapplication.py @@ -13,10 +17,8 @@ Imagine a simple flask application structure that looks like 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 `. +The :ref:`tutorial ` is structured this way, see the +:gh:`example code `. Simple Packages --------------- @@ -42,34 +44,36 @@ 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:`pyproject.toml` next to the inner -:file:`yourapplication` folder with the following contents: +a big problem, just add a new file called :file:`setup.py` 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. Similarly you can turn on the +development features like this:: - $ pip install -e . + export FLASK_ENV=development -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 - - $ flask --app yourapplication run + pip install -e . + flask run What did we gain from this? Now we can restructure the application a bit into multiple modules. The only thing you have to remember is the @@ -101,7 +105,7 @@ And this is what :file:`views.py` would look like:: You should then end up with something like that:: /yourapplication - pyproject.toml + setup.py /yourapplication __init__.py views.py @@ -123,6 +127,12 @@ 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 ----------------------- @@ -130,4 +140,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 -:doc:`/blueprints` chapter of the documentation. +:ref:`blueprints` chapter of the documentation. diff --git a/docs/patterns/requestchecksum.rst b/docs/patterns/requestchecksum.rst index 25bc38b2..902be64a 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 f"Hash was: {checksum}" + return 'Hash was: %s' % checksum diff --git a/docs/patterns/singlepageapplications.rst b/docs/patterns/singlepageapplications.rst deleted file mode 100644 index 1cb779b3..00000000 --- a/docs/patterns/singlepageapplications.rst +++ /dev/null @@ -1,24 +0,0 @@ -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 9e9afe48..831d54f0 100644 --- a/docs/patterns/sqlalchemy.rst +++ b/docs/patterns/sqlalchemy.rst @@ -1,10 +1,12 @@ +.. _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 (:doc:`packages`). While that -is not necessary, it makes a lot of sense. +and drop the models into a separate module (:ref:`larger-applications`). +While that is not necessary, it makes a lot of sense. There are four very common ways to use SQLAlchemy. I will outline each of them here: @@ -20,7 +22,7 @@ if you want to get started quickly. You can download `Flask-SQLAlchemy`_ from `PyPI `_. -.. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/ +.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/ Declarative @@ -34,9 +36,10 @@ 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, declarative_base + from sqlalchemy.orm import scoped_session, sessionmaker + from sqlalchemy.ext.declarative import declarative_base - engine = create_engine('sqlite:////tmp/test.db') + engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) @@ -83,7 +86,7 @@ Here is an example model (put this into :file:`models.py`, e.g.):: self.email = email def __repr__(self): - return f'' + return '' % (self.name) To create the database you can use the `init_db` function: @@ -101,12 +104,13 @@ 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: https://www.sqlalchemy.org/ -.. _declarative: https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/ +.. _declarative: + https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/ Manual Object Relational Mapping -------------------------------- @@ -123,7 +127,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') + engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) metadata = MetaData() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, @@ -131,8 +135,9 @@ Here is an example :file:`database.py` module for your application:: def init_db(): metadata.create_all(bind=engine) -As in the declarative approach, you need to close the session after each app -context. Put this into your application module:: +As in the declarative approach, you need to close the session after +each request or application context shutdown. Put this into your +application module:: from yourapplication.database import db_session @@ -154,7 +159,7 @@ Here is an example table and model (put this into :file:`models.py`):: self.email = email def __repr__(self): - return f'' + return '' % (self.name) users = Table('users', metadata, Column('id', Integer, primary_key=True), @@ -174,7 +179,7 @@ you basically only need the engine:: from sqlalchemy import create_engine, MetaData, Table - engine = create_engine('sqlite:////tmp/test.db') + engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) metadata = MetaData(bind=engine) Then you can either declare the tables in your code like in the examples @@ -195,19 +200,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, 'admin', 'admin@localhost') +(1, u'admin', u'admin@localhost') These results are also dict-like tuples: >>> r = users.select(users.c.id == 1).execute().first() >>> r['name'] -'admin' +u'admin' You can also pass strings of SQL statements to the :meth:`~sqlalchemy.engine.base.Connection.execute` method: >>> engine.execute('select * from users where id = :1', [1]).first() -(1, 'admin', 'admin@localhost') +(1, u'admin', u'admin@localhost') For more information about SQLAlchemy, head over to the `website `_. diff --git a/docs/patterns/sqlite3.rst b/docs/patterns/sqlite3.rst index f42e0f8e..eecaaae8 100644 --- a/docs/patterns/sqlite3.rst +++ b/docs/patterns/sqlite3.rst @@ -1,9 +1,11 @@ +.. _sqlite3: + Using SQLite 3 with Flask ========================= -You can implement a few functions to work with a SQLite connection during a -request context. The connection is created the first time it's accessed, -reused on subsequent access, until it is closed when the request context ends. +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:: @@ -30,6 +32,10 @@ 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('/') @@ -56,6 +62,7 @@ the application context by hand:: with app.app_context(): # now you can use get_db() +.. _easy-querying: Easy Querying ------------- @@ -109,16 +116,16 @@ 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 diff --git a/docs/patterns/streaming.rst b/docs/patterns/streaming.rst index fc2f1739..f5bff3ca 100644 --- a/docs/patterns/streaming.rst +++ b/docs/patterns/streaming.rst @@ -8,21 +8,6 @@ roundtrip to the filesystem? The answer is by using generators and direct responses. -HTTP Response Behavior ----------------------- - -**Headers cannot be changed after the streaming response starts.** - -When using streaming, it's important to be aware of the order than an HTTP -response is sent. All headers must be sent first, then the body. More headers -cannot be sent after the body has begun. Therefore, you must make sure all -headers are set before starting the response, outside the generator. - -In particular, if the generator will access ``session``, be sure to do so in the -view as well so that the ``Vary: cookie`` header will be set. Do not modify the -session in the generator, as the ``Set-Cookie`` header will already be sent. - - Basic Usage ----------- @@ -30,12 +15,14 @@ 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 f"{','.join(row)}\n" - return generate(), {"Content-Type": "text/csv"} + yield ','.join(row) + '\n' + return Response(generate(), mimetype='text/csv') Each ``yield`` expression is directly sent to the browser. Note though that some WSGI middlewares might break streaming, so be careful there in @@ -44,57 +31,54 @@ debug environments with profilers and other things you might have enabled. Streaming from Templates ------------------------ -The Jinja 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. +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:: -.. code-block:: python + from flask import Response - from flask import stream_template + 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.get("/timeline") - def timeline(): - return stream_template("timeline.html") - -The parts yielded by the render stream tend to match statement blocks in -the template. + @app.route('/my-large-page.html') + def render_large_template(): + rows = iter_all_rows() + return Response(stream_template('the_template.html', rows=rows)) +The trick here is to get the template object from the Jinja2 environment +on the application and to call :meth:`~jinja2.Template.stream` instead of +:meth:`~jinja2.Template.render` which returns a stream object instead of a +string. Since we're bypassing the Flask template render functions and +using the template object itself we have to make sure to update the render +context ourselves by calling :meth:`~flask.Flask.update_template_context`. +The template is then evaluated as the stream is iterated over. Since each +time you do a yield the server will flush the content to the client you +might want to buffer up a few items in the template which you can do with +``rv.enable_buffering(size)``. ``5`` is a sane default. Streaming with Context ---------------------- -The :data:`.request` proxy will not be active while the generator is -running, because the app has already returned control to the WSGI server at that -point. If you try to access ``request``, you'll get a ``RuntimeError``. +.. versionadded:: 0.9 -If your generator function relies on data in ``request``, use the -:func:`.stream_with_context` wrapper. This will keep the request context active -during the generator. +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:: -.. code-block:: python - - from flask import stream_with_context, request - from markupsafe import escape + from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): def generate(): - yield '

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

' - return stream_with_context(generate()) + yield 'Hello ' + yield request.args['name'] + yield '!' + return Response(stream_with_context(generate())) -It can also be used as a decorator. - -.. code-block:: python - - @stream_with_context - def generate(): - ... - - return generate() - -The :func:`~flask.stream_template` and -:func:`~flask.stream_template_string` functions automatically -use :func:`~flask.stream_with_context` if a request is active. +Without the :func:`~flask.stream_with_context` function you would get a +:class:`RuntimeError` at that point. diff --git a/docs/patterns/templateinheritance.rst b/docs/patterns/templateinheritance.rst index bb5cba27..dbcb4163 100644 --- a/docs/patterns/templateinheritance.rst +++ b/docs/patterns/templateinheritance.rst @@ -1,3 +1,5 @@ +.. _template-inheritance: + Template Inheritance ==================== diff --git a/docs/patterns/urlprocessors.rst b/docs/patterns/urlprocessors.rst index 0d743205..3f65d758 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 to -:func:`~flask.url_for`. The code below checks if the +come in. They can automatically inject values into a call for +:func:`~flask.url_for` automatically. The code below checks if the language code is not yet in the dictionary of URL values and if the endpoint wants a value named ``'lang_code'``:: diff --git a/docs/patterns/viewdecorators.rst b/docs/patterns/viewdecorators.rst index 0b0479ef..7fd97dca 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 :doc:`caching`. +assuming you have set up a cache like mentioned in :ref:`caching-pattern`. Here is an example cache function. It generates the cache key from a specific prefix (actually a format string) and the current path of the @@ -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 based on the current +1. get the unique cache key for the current request base on the current path. 2. get the value for that key from the cache. If the cache returned something we will return that value. @@ -82,11 +82,11 @@ Here the code:: from functools import wraps from flask import request - def cached(timeout=5 * 60, key='view/{}'): + def cached(timeout=5 * 60, key='view/%s'): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): - cache_key = key.format(request.path) + cache_key = key % 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 -:doc:`caching`. +Notice that this assumes an instantiated `cache` object is available, see +:ref:`caching-pattern` for more information. Templating Decorator @@ -142,7 +142,8 @@ Here is the code for that decorator:: def decorated_function(*args, **kwargs): template_name = template if template_name is None: - template_name = f"{request.endpoint.replace('.', '/')}.html" + template_name = 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 cb1208fe..e3fe5723 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 -(:doc:`packages`) for that and adding a separate module for the +(:ref:`larger-applications`) for that and adding a separate module for the forms. .. admonition:: Getting the most out of WTForms with an Extension @@ -19,7 +19,7 @@ forms. fun. You can get it from `PyPI `_. -.. _Flask-WTF: https://flask-wtf.readthedocs.io/ +.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/ 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 -(:doc:`sqlalchemy`), but that's not a requirement, of course. Adapt +(:ref:`sqlalchemy-pattern`), 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 strings, -so we have to tell Jinja that this data is already HTML-escaped with -the ``|safe`` filter. +the input element. Note that WTForms returns standard Python unicode +strings, so we have to tell Jinja2 that this data is already HTML-escaped +with the ``|safe`` filter. Here is the :file:`register.html` template for the function we used above, which takes advantage of the :file:`_formhelpers.html` template: diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 712ba977..8f055d40 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -1,70 +1,76 @@ +.. _quickstart: + Quickstart ========== -Eager to get started? This page gives a good introduction to Flask. -Follow :doc:`installation` to set up a project and install Flask first. +Eager to get started? This page gives a good introduction to Flask. It +assumes you already have Flask installed. If you do not, head over to the +:ref:`installation` section. A Minimal Application --------------------- -A minimal Flask application looks something like this: - -.. code-block:: python +A minimal Flask application looks something like this:: 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. ``__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. +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. -Save it as :file:`hello.py` or something similar. Make sure to not call +Just save it as :file:`hello.py` or something similar. Make sure to not call your application :file:`flask.py` because this would conflict with Flask itself. -To run the application, use the ``flask`` command or -``python -m flask``. You need to tell the Flask where your application -is with the ``--app`` option. +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:: -.. 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, the environment variable syntax depends on command line +interpreter. On Command Prompt:: -.. admonition:: Application Discovery Behavior + C:\path\to\app>set FLASK_APP=hello.py - 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. +And on PowerShell:: -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`. + PS C:\path\to\app> $env:FLASK_APP = "hello.py" -Now head over to http://127.0.0.1:5000/, and you should see your hello -world greeting. +Alternatively you can use :command:`python -m flask`:: -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. + $ export FLASK_APP=hello.py + $ python -m flask run + * Running on http://127.0.0.1:5000/ + +This launches a very simple builtin server, which is good enough for testing +but probably not what you want to use in production. For deployment options see +:ref:`deployment`. + +Now head over to `http://127.0.0.1:5000/ `_, and you +should see your hello world greeting. .. _public-server: @@ -79,76 +85,91 @@ handle that. 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. + +Invalid Import Name +``````````````````` + +The ``FLASK_APP`` environment variable is the name of the module to import at +:command:`flask run`. In case that module is incorrectly named you will get an +import error upon start (or if debug is enabled when you navigate to the +application). It will tell you what it tried to import and why it failed. + +The most common reason is a typo or because you did not actually create an +``app`` object. + +.. _debug-mode: + Debug Mode ---------- -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. +(Want to just log errors and stack traces? See :ref:`application-errors`) + +The :command:`flask` script is nice to start a local development server, but +you would have to restart it manually after each change to your code. +That is not very nice and Flask can do better. If you enable debug +support the server will reload itself on code changes, and it will also +provide you with a helpful debugger if things go wrong. + +To enable all development features (including debug mode) you can export +the ``FLASK_ENV`` environment variable and set it to ``development`` +before running the server:: + + $ export FLASK_ENV=development + $ flask run + +(On Windows you need to use ``set`` instead of ``export``.) + +This does the following things: + +1. it activates the debugger +2. it activates the automatic reloader +3. it enables the debug mode on the Flask application. + +You can also control debug mode separately from the environment by +exporting ``FLASK_DEBUG=1``. + +There are more parameters that are explained in the :ref:`server` docs. + +.. admonition:: Attention + + Even though the interactive debugger does not work in forking environments + (which makes it nearly impossible to use on production servers), it still + allows the execution of arbitrary code. This makes it a major security risk + and therefore it **must never be used on production machines**. + +Screenshot of the debugger in action: .. image:: _static/debugger.png - :align: center - :class: screenshot - :alt: The interactive debugger in action. + :align: center + :class: screenshot + :alt: screenshot of debugger in action -.. warning:: +More information on using the debugger can be found in the `Werkzeug +documentation`_. - 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. +.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger -To enable debug mode, use the ``--debug`` option. - -.. code-block:: text - - $ 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 - -See also: - -- :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. - - -HTML Escaping -------------- - -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. - -: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. - -.. code-block:: python - - from flask import request - from markupsafe import escape - - @app.route("/hello") - def hello(): - name = request.args.get("name", "Flask") - return f"Hello, {escape(name)}!" - -If a user submits ``/hello?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`. Routing @@ -179,22 +200,20 @@ You can add variable sections to a URL by marking sections with 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 f'User {escape(username)}' + return 'User %s' % username @app.route('/post/') def show_post(post_id): # show the post with the given id, the id is an integer - return f'Post {post_id}' + return 'Post %d' % post_id @app.route('/path/') def show_subpath(subpath): # show the subpath after /path/ - return f'Subpath {escape(subpath)}' + return 'Subpath %s' % subpath Converter types: @@ -206,7 +225,6 @@ Converter types: ``uuid`` accepts UUID strings ========== ========================================== - Unique URLs / Redirection Behavior `````````````````````````````````` @@ -222,14 +240,14 @@ The following two rules differ in their use of a trailing slash. :: 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/``). +a trailing slash, Flask redirects you to the canonical URL with the +trailing slash. The canonical URL for the ``about`` endpoint does not have a trailing slash. It's similar to the pathname of a file. Accessing the URL with a -trailing slash (``/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. +trailing slash produces a 404 "Not Found" error. This helps keep URLs +unique for these resources, which helps search engines avoid indexing +the same page twice. .. _url-building: @@ -247,22 +265,23 @@ Why would you want to build URLs using the URL reversing function 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. + manually change hard-coded URLs. +3. URL building handles escaping of special characters and Unicode data + transparently. 4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers. 5. If your application is placed outside the URL root, for example, in - ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly - handles that for you. + ``/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 :doc:`/appcontext`. +Python shell. See :ref:`context-locals`. :: -.. code-block:: python + from flask import Flask, url_for - from flask import url_for + app = Flask(__name__) @app.route('/') def index(): @@ -274,7 +293,7 @@ Python shell. See :doc:`/appcontext`. @app.route('/user/') def profile(username): - return f'{username}\'s profile' + return '{}\'s profile'.format(username) with app.test_request_context(): print(url_for('index')) @@ -282,14 +301,11 @@ Python shell. See :doc:`/appcontext`. print(url_for('login', next='/')) print(url_for('profile', username='John Doe')) -.. code-block:: text - / /login /login?next=/ /user/John%20Doe - HTTP Methods ```````````` @@ -308,24 +324,6 @@ of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods. else: 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. @@ -352,16 +350,8 @@ 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 `Jinja -`_ 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/ +the application secure. Because of that Flask configures the `Jinja2 +`_ template engine for you automatically. To render a template you can use the :func:`~flask.render_template` method. All you have to do is provide the name of the template and the @@ -373,7 +363,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', person=name) + return render_template('hello.html', name=name) Flask will look for templates in the :file:`templates` folder. So if your application is a module, this folder is next to that module, if it's a @@ -392,9 +382,9 @@ package it's actually inside your package: /templates /hello.html -For templates you can use the full power of Jinja templates. Head over -to the official `Jinja Template Documentation -`_ for more information. +For templates you can use the full power of Jinja2 templates. Head over +to the official `Jinja2 Template Documentation +`_ for more information. Here is an example template: @@ -402,37 +392,37 @@ Here is an example template: Hello from Flask - {% if person %} -

Hello {{ person }}!

+ {% if name %} +

Hello {{ name }}!

{% else %}

Hello, World!

{% endif %} -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. +Inside templates you also have access to the :class:`~flask.request`, +:class:`~flask.session` and :class:`~flask.g` [#]_ objects +as well as the :func:`~flask.get_flashed_messages` function. Templates are especially useful if inheritance is used. If you want to -know how that works, see :doc:`patterns/templateinheritance`. Basically -template inheritance makes it possible to keep certain elements on each -page (like header, navigation and footer). +know how that works, head over to the :ref:`template-inheritance` pattern +documentation. Basically template inheritance makes it possible to keep +certain elements on each page (like header, navigation and footer). -Automatic escaping is enabled, so if ``person`` contains HTML it will be escaped +Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the -:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the +:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the template. Head over to the Jinja 2 documentation for more examples. -Here is a basic introduction to how the :class:`~markupsafe.Markup` class works:: +Here is a basic introduction to how the :class:`~jinja2.Markup` class works:: - >>> from markupsafe import Markup + >>> from flask import Markup >>> Markup('Hello %s!') % 'hacker' - Markup('Hello <blink>hacker</blink>!') + Markup(u'Hello <blink>hacker</blink>!') >>> Markup.escape('hacker') - Markup('<blink>hacker</blink>') + Markup(u'<blink>hacker</blink>') >>> Markup('Marked up » HTML').striptags() - 'Marked up » HTML' + u'Marked up \xbb HTML' .. versionchanged:: 0.5 @@ -442,65 +432,115 @@ Here is a basic introduction to how the :class:`~markupsafe.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. See the documentation - for :class:`flask.g` and :doc:`patterns/sqlite3`. + you can store information for your own needs, check the documentation of + that object (:class:`~flask.g`) and the :ref:`sqlite3` for more + information. Accessing Request Data ---------------------- -For web applications it's crucial to react to the data a client sends to the -server. In Flask this information is provided by the global :data:`.request` -object, which is an instance of :class:`.Request`. This object has many -attributes and methods to work with the incoming request data, but here is a -broad overview. First it needs to be imported. +For web applications it's crucial to react to the data a client sends to +the server. In Flask this information is provided by the global +:class:`~flask.request` object. If you have some experience with Python +you might be wondering how that object can be global and how Flask +manages to still be threadsafe. The answer is context locals: -.. code-block:: python + +.. _context-locals: + +Context Locals +`````````````` + +.. admonition:: Insider Information + + If you want to understand how that works and how you can implement + tests with context locals, read this section, otherwise just skip it. + +Certain objects in Flask are global objects, but not of the usual kind. +These objects are actually proxies to objects that are local to a specific +context. What a mouthful. But that is actually quite easy to understand. + +Imagine the context being the handling thread. A request comes in and the +web server decides to spawn a new thread (or something else, the +underlying object is capable of dealing with concurrency systems other +than threads). When Flask starts its internal request handling it +figures out that the current thread is the active context and binds the +current application and the WSGI environments to that context (thread). +It does that in an intelligent way so that one application can invoke another +application without breaking. + +So what does this mean to you? Basically you can completely ignore that +this is the case unless you are doing something like unit testing. You +will notice that code which depends on a request object will suddenly break +because there is no request object. The solution is creating a request +object yourself and binding it to the context. The easiest solution for +unit testing is to use the :meth:`~flask.Flask.test_request_context` +context manager. In combination with the ``with`` statement it will bind a +test request so that you can interact with it. Here is an example:: from flask import request -If you have some experience with Python you might be wondering how that object -can be global when Flask handles multiple requests at a time. The answer is -that :data:`.request` is actually a proxy, pointing at whatever request is -currently being handled by a given worker, which is managed internally by Flask -and Python. See :doc:`/appcontext` for much more information. + with app.test_request_context('/hello', method='POST'): + # now you can do something with the request until the + # end of the with block, such as basic assertions: + assert request.path == '/hello' + assert request.method == 'POST' -The current request method is available in the :attr:`~.Request.method` -attribute. To access form data (data transmitted in a ``POST`` or ``PUT`` -request), use the :attr:`~flask.Request.form` attribute, which behaves like a -dict. +The other possibility is passing a whole WSGI environment to the +:meth:`~flask.Flask.request_context` method:: -.. code-block:: python + from flask import request - @app.route("/login", methods=["GET", "POST"]) + with app.request_context(environ): + assert request.method == 'POST' + +The Request Object +`````````````````` + +The request object is documented in the API section and we will not cover +it here in detail (see :class:`~flask.Request`). Here is a broad overview of +some of the most common operations. First of all you have to import it from +the ``flask`` module:: + + from flask import request + +The current request method is available by using the +:attr:`~flask.Request.method` attribute. To access form data (data +transmitted in a ``POST`` or ``PUT`` request) you can use the +:attr:`~flask.Request.form` attribute. Here is a full example of the two +attributes mentioned above:: + + @app.route('/login', methods=['POST', 'GET']) def login(): error = None - - if request.method == "POST": - if valid_login(request.form["username"], request.form["password"]): - return store_login(request.form["username"]) + if request.method == 'POST': + if valid_login(request.form['username'], + request.form['password']): + return log_the_user_in(request.form['username']) else: - error = "Invalid username or password" + error = 'Invalid username/password' + # the code below is executed if the request method + # was GET or the credentials were invalid + return render_template('login.html', error=error) - # Executed if the request method was GET or the credentials were invalid. - return render_template("login.html", error=error) +What happens if the key does not exist in the ``form`` attribute? In that +case a special :exc:`KeyError` is raised. You can catch it like a +standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request +error page is shown instead. So for many situations you don't have to +deal with that problem. -If the key does not exist in ``form``, a special :exc:`KeyError` is raised. You -can catch it like a normal ``KeyError``, otherwise it will return a HTTP 400 -Bad Request error page. You can also use the -:meth:`~werkzeug.datastructures.MultiDict.get` method to get a default -instead of an error. - -To access parameters submitted in the URL (``?key=value``), use the -:attr:`~.Request.args` attribute. Key errors behave the same as ``form``, -returning a 400 response if not caught. - -.. code-block:: python +To access parameters submitted in the URL (``?key=value``) you can use the +:attr:`~flask.Request.args` attribute:: searchword = request.args.get('key', '') -For a full list of methods and attributes of the request object, see the -:class:`~.Request` documentation. +We recommend accessing URL parameters with `get` or by catching the +:exc:`KeyError` because users might change the URL and presenting them a 400 +bad request page in that case is not user friendly. + +For a full list of methods and attributes of the request object, head over +to the :class:`~flask.Request` documentation. File Uploads @@ -515,9 +555,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 @@ -530,23 +570,23 @@ Here is a simple example showing how 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': - file = request.files['the_file'] - file.save(f"/var/www/uploads/{secure_filename(file.filename)}") + f = request.files['the_file'] + f.save('/var/www/uploads/' + secure_filename(f.filename)) ... -For some better examples, see :doc:`patterns/fileuploads`. +For some better examples, checkout the :ref:`uploading-files` pattern. Cookies ``````` @@ -586,7 +626,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 -:doc:`patterns/deferredcallbacks` pattern. +:ref:`deferred-callbacks` pattern. For this also see :ref:`about-responses`. @@ -626,36 +666,29 @@ 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 :doc:`errorhandling` for more details. +See :ref:`error-handlers` for more details. .. _about-responses: About Responses --------------- -The return value from a view function is automatically converted into -a response object for you. If the return value is a string it's -converted into a response object with the string as response body, a -``200 OK`` status code and a :mimetype:`text/html` mimetype. If the -return value is a dict 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: +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: 1. If a response object of the correct type is returned it's directly returned from the view. -2. If it's a string, a response object is created with that data and - the default parameters. -3. If it's 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 +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 valid WSGI application and convert that into a response object. If you want to get hold of the resulting response object inside the view @@ -663,8 +696,6 @@ 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 @@ -673,49 +704,12 @@ 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 @@ -731,7 +725,9 @@ 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 session + from flask import Flask, session, redirect, url_for, escape, request + + app = Flask(__name__) # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @@ -739,7 +735,7 @@ sessions work:: @app.route('/') def index(): if 'username' in session: - return f'Logged in as {session["username"]}' + return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) @@ -760,6 +756,9 @@ sessions work:: session.pop('username', None) return redirect(url_for('index')) +The :func:`~flask.escape` mentioned here does escaping for you if you are +not using the template engine (as in this example). + .. admonition:: How to generate good secret keys A secret key should be as random as possible. Your operating system has @@ -767,8 +766,8 @@ sessions work:: generator. Use the following command to quickly generate a value for :attr:`Flask.secret_key` (or :data:`SECRET_KEY`):: - $ python -c 'import secrets; print(secrets.token_hex())' - '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + $ python -c 'import os; print(os.urandom(16))' + b'_5#y2L"F4Q8z\n\xec]/' A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some @@ -793,8 +792,8 @@ template to expose the message. To flash a message use the :func:`~flask.flash` method, to get hold of the messages you can use :func:`~flask.get_flashed_messages` which is also -available in the templates. See :doc:`patterns/flashing` for a full -example. +available in the templates. Check out the :ref:`message-flashing-pattern` +for a full example. Logging ------- @@ -802,12 +801,12 @@ Logging .. versionadded:: 0.3 Sometimes you might be in a situation where you deal with data that -should be correct, but actually is not. For example you may have -some client-side code that sends an HTTP request to the server -but it's obviously malformed. This might be caused by a user tampering -with the data, or the client code failing. Most of the time it's okay -to reply with ``400 Bad Request`` in that situation, but sometimes -that won't do and the code has to continue working. +should be correct, but actually is not. For example you may have some client-side +code that sends an HTTP request to the server but it's obviously +malformed. This might be caused by a user tampering with the data, or the +client code failing. Most of the time it's okay to reply with ``400 Bad +Request`` in that situation, but sometimes that won't do and the code has +to continue working. You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you @@ -820,28 +819,22 @@ Here are some example log calls:: app.logger.error('An error occurred') The attached :attr:`~flask.Flask.logger` is a standard logging -:class:`~logging.Logger`, so head over to the official :mod:`logging` -docs for more information. +:class:`~logging.Logger`, so head over to the official `logging +documentation `_ for more +information. -See :doc:`errorhandling`. +Read more on :ref:`application-errors`. +Hooking in WSGI Middlewares +--------------------------- -Hooking in WSGI Middleware --------------------------- +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:: -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: - -.. code-block:: python - - from werkzeug.middleware.proxy_fix import ProxyFix - app.wsgi_app = ProxyFix(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. + from werkzeug.contrib.fixers import LighttpdCGIRootFix + app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app) Using Flask Extensions ---------------------- @@ -850,9 +843,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, see :doc:`extensions`. +For more on Flask extensions, have a look at :ref:`extensions`. Deploying to a Web Server ------------------------- -Ready to deploy your new Flask app? See :doc:`deploying/index`. +Ready to deploy your new Flask app? Go to :ref:`deployment`. diff --git a/docs/reqcontext.rst b/docs/reqcontext.rst index 6660671e..2724fe0c 100644 --- a/docs/reqcontext.rst +++ b/docs/reqcontext.rst @@ -1,6 +1,267 @@ -:orphan: +.. currentmodule:: flask + +.. _request-context: The Request Context =================== -Obsolete, see :doc:`/appcontext` instead. +The request context keeps track of the request-level data during a +request. Rather than passing the request object to each function that +runs during a request, the :data:`request` and :data:`session` proxies +are accessed instead. + +This is similar to the :doc:`/appcontext`, which keeps track of the +application-level data independent of a request. A corresponding +application context is pushed when a request context is pushed. + + +Purpose of the Context +---------------------- + +When the :class:`Flask` application handles a request, it creates a +:class:`Request` object based on the environment it received from the +WSGI server. Because a *worker* (thread, process, or coroutine depending +on the server) handles only one request at a time, the request data can +be considered global to that worker during that request. Flask uses the +term *context local* for this. + +Flask automatically *pushes* a request context when handling a request. +View functions, error handlers, and other functions that run during a +request will have access to the :data:`request` proxy, which points to +the request object for the current request. + + +Lifetime of the Context +----------------------- + +When a Flask application begins handling a request, it pushes a request +context, which also pushes an :doc:`/appcontext`. When the request ends +it pops the request context then the application context. + +The context is unique to each thread (or other worker type). +:data:`request` cannot be passed to another thread, the other thread +will have a different context stack and will not know about the request +the parent thread was pointing to. + +Context locals are implemented in Werkzeug. See :doc:`werkzeug:local` +for more information on how this works internally. + + +Manually Push a Context +----------------------- + +If you try to access :data:`request`, or anything that uses it, outside +a request context, you'll get this error message: + +.. code-block:: pytb + + RuntimeError: Working outside of request context. + + This typically means that you attempted to use functionality that + needed an active HTTP request. Consult the documentation on testing + for information about how to avoid this problem. + +This should typically only happen when testing code that expects an +active request. One option is to use the +:meth:`test client ` to simulate a full request. Or +you can use :meth:`~Flask.test_request_context` in a ``with`` block, and +everything that runs in the block will have access to :data:`request`, +populated with your test data. :: + + def generate_report(year): + format = request.args.get('format') + ... + + with app.test_request_context( + '/make_report/2017', data={'format': 'short'}): + generate_report() + +If you see that error somewhere else in your code not related to +testing, it most likely indicates that you should move that code into a +view function. + +For information on how to use the request context from the interactive +Python shell, see :doc:`/shell`. + + +How the Context Works +--------------------- + +The :meth:`Flask.wsgi_app` method is called to handle each request. It +manages the contexts during the request. Internally, the request and +application contexts work as stacks, :data:`_request_ctx_stack` and +:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the +proxies that depend on them are available and point at information from +the top context on the stack. + +When the request starts, a :class:`~ctx.RequestContext` is created and +pushed, which creates and pushes an :class:`~ctx.AppContext` first if +a context for that application is not already the top context. While +these contexts are pushed, the :data:`current_app`, :data:`g`, +:data:`request`, and :data:`session` proxies are available to the +original thread handling the request. + +Because the contexts are stacks, other contexts may be pushed to change +the proxies during a request. While this is not a common pattern, it +can be used in advanced applications to, for example, do internal +redirects or chain different applications together. + +After the request is dispatched and a response is generated and sent, +the request context is popped, which then pops the application context. +Immediately before they are popped, the :meth:`~Flask.teardown_request` +and :meth:`~Flask.teardown_appcontext` functions are are executed. These +execute even if an unhandled exception occurred during dispatch. + + +.. _callbacks-and-errors: + +Callbacks and Errors +-------------------- + +Flask dispatches a request in multiple stages which can affect the +request, response, and how errors are handled. The contexts are active +during all of these stages. + +A :class:`Blueprint` can add handlers for these events that are specific +to the blueprint. The handlers for a blueprint will run if the blueprint +owns the route that matches the request. + +#. Before each request, :meth:`~Flask.before_request` functions are + called. If one of these functions return a value, the other + functions are skipped. The return value is treated as the response + and the view function is not called. + +#. If the :meth:`~Flask.before_request` functions did not return a + response, the view function for the matched route is called and + returns a response. + +#. The return value of the view is converted into an actual response + object and passed to the :meth:`~Flask.after_request` + functions. Each function returns a modified or new response object. + +#. After the response is returned, the contexts are popped, which calls + the :meth:`~Flask.teardown_request` and + :meth:`~Flask.teardown_appcontext` functions. These functions are + called even if an unhandled exception was raised at any point above. + +If an exception is raised before the teardown functions, Flask tries to +match it with an :meth:`~Flask.errorhandler` function to handle the +exception and return a response. If no error handler is found, or the +handler itself raises an exception, Flask returns a generic +``500 Internal Server Error`` response. The teardown functions are still +called, and are passed the exception object. + +If debug mode is enabled, unhandled exceptions are not converted to a +``500`` response and instead are propagated to the WSGI server. This +allows the development server to present the interactive debugger with +the traceback. + + +Teardown Callbacks +~~~~~~~~~~~~~~~~~~ + +The teardown callbacks are independent of the request dispatch, and are +instead called by the contexts when they are popped. The functions are +called even if there is an unhandled exception during dispatch, and for +manually pushed contexts. This means there is no guarantee that any +other parts of the request dispatch have run first. Be sure to write +these functions in a way that does not depend on other callbacks and +will not fail. + +During testing, it can be useful to defer popping the contexts after the +request ends, so that their data can be accessed in the test function. +Using the :meth:`~Flask.test_client` as a ``with`` block to preserve the +contexts until the with block exits. + +.. code-block:: python + + from flask import Flask, request + + app = Flask(__name__) + + @app.route('/') + def hello(): + print('during view') + return 'Hello, World!' + + @app.teardown_request + def show_teardown(exception): + print('after with block') + + with app.test_request_context(): + print('during with block') + + # teardown functions are called after the context with block exits + + with app.test_client(): + client.get('/') + # the contexts are not popped even though the request ended + print(request.path) + + # the contexts are popped and teardown functions are called after + # the client with block exists + + +Signals +~~~~~~~ + +If :data:`~signals.signals_available` is true, the following signals are +sent: + +#. :data:`request_started` is sent before the + :meth:`~Flask.before_request` functions are called. + +#. :data:`request_finished` is sent after the + :meth:`~Flask.after_request` functions are called. + +#. :data:`got_request_exception` is sent when an exception begins to + be handled, but before an :meth:`~Flask.errorhandler` is looked up or + called. + +#. :data:`request_tearing_down` is sent after the + :meth:`~Flask.teardown_request` functions are called. + + +Context Preservation on Error +----------------------------- + +At the end of a request, the request context is popped and all data +associated with it is destroyed. If an error occurs during development, +it is useful to delay destroying the data for debugging purposes. + +When the development server is running in development mode (the +``FLASK_ENV`` environment variable is set to ``'development'``), the +error and data will be preserved and shown in the interactive debugger. + +This behavior can be controlled with the +:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it +defaults to ``True`` in the development environment. + +Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it +will cause your application to leak memory on exceptions. + + +.. _notes-on-proxies: + +Notes On Proxies +---------------- + +Some of the objects provided by Flask are proxies to other objects. The +proxies are accessed in the same way for each worker thread, but +point to the unique object bound to each worker behind the scenes as +described on this page. + +Most of the time you don't have to care about that, but there are some +exceptions where it is good to know that this object is an actual proxy: + +- The proxy objects cannot fake their type as the actual object types. + If you want to perform instance checks, you have to do that on the + object being proxied. +- If the specific object reference is important, for example for + sending :ref:`signals` or passing data to a background thread. + +If you need to access the underlying object that is proxied, use the +:meth:`~werkzeug.local.LocalProxy._get_current_object` method:: + + app = current_app._get_current_object() + my_signal.send(app) diff --git a/docs/web-security.rst b/docs/security.rst similarity index 66% rename from docs/web-security.rst rename to docs/security.rst index 4118b5ec..44c095ac 100644 --- a/docs/web-security.rst +++ b/docs/security.rst @@ -1,45 +1,11 @@ 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. +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. -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: +.. _xss: Cross-Site Scripting (XSS) -------------------------- @@ -51,13 +17,13 @@ tags. For more information on that have a look at the Wikipedia article on `Cross-Site Scripting `_. -Flask configures Jinja to automatically escape all values unless +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 Jinja -- calling :class:`~markupsafe.Markup` on data submitted by users +- 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 @@ -65,7 +31,7 @@ careful: trick a browser to execute HTML. Another thing that is very important are unquoted attributes. While -Jinja can protect you from XSS issues by escaping HTML, there is one +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: @@ -135,7 +101,7 @@ 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: JSON Security ------------- @@ -158,7 +124,7 @@ 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/wntrblm/flask-talisman +.. _Flask-Talisman: https://github.com/GoogleCloudPlatform/flask-talisman HTTP Strict Transport Security (HSTS) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -207,6 +173,18 @@ invisibly to clicks on your page's elements. This is also known as - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options +X-XSS-Protection +~~~~~~~~~~~~~~~~ + +The browser will try to prevent reflected XSS attacks by not loading the page +if the request contains something that looks like JavaScript and the response +contains the same data. :: + + response.headers['X-XSS-Protection'] = '1; mode=block' + +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection + + .. _security-cookie: Set-Cookie options @@ -269,48 +247,14 @@ values (or any values that need secure signatures). .. _samesite_support: https://caniuse.com/#feat=same-site-cookie-attribute -Host Header Validation ----------------------- +HTTP Public Key Pinning (HPKP) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``Host`` header is used by the client to indicate what host name the request -was made to. This is used, for example, by ``url_for(..., _external=True)`` to -generate full URLs, for use in email or other messages outside the browser -window. +This tells the browser to authenticate with the server using only the specific +certificate key to prevent MITM attacks. -By default the app doesn't know what host(s) it is allowed to be accessed -through, and assumes any host is valid. Although browsers do not allow setting -the ``Host`` header, requests made by attackers in other scenarios could set -the ``Host`` header to a value they want. +.. warning:: + Be careful when enabling this, as it is very difficult to undo if you set up + or upgrade your key incorrectly. -When deploying your application, set :data:`TRUSTED_HOSTS` to restrict what -values the ``Host`` header may be. - -The ``Host`` header may be modified by proxies in between the client and your -application. See :doc:`deploying/proxy_fix` to tell your app which proxy values -to trust. - - -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. +- https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning diff --git a/docs/server.rst b/docs/server.rst index d6beb1d8..db431a6c 100644 --- a/docs/server.rst +++ b/docs/server.rst @@ -1,115 +1,62 @@ -.. currentmodule:: flask +.. _server: Development Server ================== -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. +.. currentmodule:: flask -.. 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. - - See :doc:`/deploying/index` for deployment options. +Starting with Flask 0.11 there are multiple built-in ways to run a +development server. The best one is the :command:`flask` command line utility +but you can also continue using the :meth:`Flask.run` method. Command Line ------------ -The ``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. +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:: -.. code-block:: text + $ export FLASK_APP=my_application + $ export FLASK_ENV=development + $ flask run - $ flask --app hello run --debug +This enables the development environment, including the interactive +debugger and reloader, and then starts the server on +*http://localhost:5000/*. -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. +The individual features of the server can be controlled by passing more +arguments to the ``run`` option. For instance the reloader can be +disabled:: + $ flask run --no-reload -.. _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. - -.. tabs:: - - .. tab:: ``netstat`` (Linux) - - .. 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 Settings 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. +.. note:: + Prior to Flask 1.0 the :envvar:`FLASK_ENV` environment variable was + not supported and you needed to enable debug mode by exporting + ``FLASK_DEBUG=1``. This can still be used to control debug mode, but + you should prefer setting the development environment as shown + above. In Code ------- -The 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. +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. -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 - - $ python hello.py +It is however still a perfectly valid method for invoking a non automatic +reloading application. diff --git a/docs/shell.rst b/docs/shell.rst index d8821e23..9d9bb5f9 100644 --- a/docs/shell.rst +++ b/docs/shell.rst @@ -1,37 +1,59 @@ +.. _shell: + Working with the Shell ====================== -One of the reasons everybody loves Python is the interactive shell. It allows -you to play around with code in real time and immediately get results back. -Flask provides the ``flask shell`` CLI command to start an interactive Python -shell with some setup done to make working with the Flask app easier. +.. versionadded:: 0.3 -.. code-block:: text +One of the reasons everybody loves Python is the interactive shell. It +basically allows you to execute Python commands in real time and +immediately get results back. Flask itself does not come with an +interactive shell, because it does not require any specific setup upfront, +just import your application and start playing around. - $ flask shell +There are however some handy helpers to make playing around in the shell a +more pleasant experience. The main issue with interactive console +sessions is that you're not triggering a request like a browser does which +means that :data:`~flask.g`, :data:`~flask.request` and others are not +available. But the code you want to test might depend on them, so what +can you do? + +This is where some helper functions come in handy. Keep in mind however +that these functions are not only there for interactive shell usage, but +also for unittesting and other situations that require a faked request +context. + +Generally it's recommended that you read the :ref:`request-context` +chapter of the documentation first. + +Command Line Interface +---------------------- + +Starting with Flask 0.11 the recommended way to work with the shell is the +``flask shell`` command which does a lot of this automatically for you. +For instance the shell is automatically initialized with a loaded +application context. + +For more information see :ref:`cli`. Creating a Request Context -------------------------- -``flask shell`` pushes an app context automatically, so :data:`.current_app` and -:data:`.g` are already available. However, there is no HTTP request being -handled in the shell, so :data:`.request` and :data:`.session` are not yet -available. - The easiest way to create a proper request context from the shell is by using the :attr:`~flask.Flask.test_request_context` method which creates us a :class:`~flask.ctx.RequestContext`: >>> ctx = app.test_request_context() -Normally you would use the ``with`` statement to make this context active, but -in the shell it's easier to call :meth:`~.RequestContext.push` and -:meth:`~.RequestContext.pop` manually: +Normally you would use the ``with`` statement to make this request object +active, but in the shell it's easier to use the +:meth:`~flask.ctx.RequestContext.push` and +:meth:`~flask.ctx.RequestContext.pop` methods by hand: >>> ctx.push() -From that point onwards you can work with the request object until you call -``pop``: +From that point onwards you can work with the request object until you +call `pop`: >>> ctx.pop() diff --git a/docs/signals.rst b/docs/signals.rst index 7ca81a9d..2cf3ce60 100644 --- a/docs/signals.rst +++ b/docs/signals.rst @@ -1,28 +1,35 @@ +.. _signals: + Signals ======= -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. +.. versionadded:: 0.6 -Signals are implemented by the `Blinker`_ library. See its documentation for detailed -information. Flask provides some built-in signals. Extensions may provide their own. +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. -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. +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. -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. - +The big advantage of signals over handlers is that you can safely +subscribe to them for just a split second. These temporary +subscriptions are helpful for unit testing for example. Say you want to +know what templates were rendered as part of a request: signals allow you +to do exactly that. Subscribing to Signals ---------------------- @@ -94,12 +101,17 @@ 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 @@ -113,6 +125,12 @@ 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 @@ -144,23 +162,29 @@ function, you can pass ``current_app._get_current_object()`` as sender. Signals and Flask's Request Context ----------------------------------- -Context-local proxies are available between :data:`~flask.request_started` and -:data:`~flask.request_finished`, so you can rely on :class:`flask.g` and others -as needed. Note the limitations described in :ref:`signals-sending` and the -:data:`~flask.request_tearing_down` signal. +Signals fully support :ref:`request-context` when receiving signals. +Context-local variables are consistently available between +:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can +rely on :class:`flask.g` and others as needed. Note the limitations described +in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal. Decorator Based Signal Subscriptions ------------------------------------ -You can also easily subscribe to signals by using the +With Blinker 1.1 you can also easily subscribe to signals by using the new :meth:`~blinker.base.NamedSignal.connect_via` decorator:: from flask import template_rendered @template_rendered.connect_via(app) def when_template_rendered(sender, template, context, **extra): - print(f'Template {template.name} is rendered with {context}') + print 'Template %s is rendered with %s' % (template.name, context) + +Core Signals +------------ + +Take a look at :ref:`core-signals-list` for a list of all builtin signals. .. _blinker: https://pypi.org/project/blinker/ diff --git a/docs/styleguide.rst b/docs/styleguide.rst new file mode 100644 index 00000000..390d5668 --- /dev/null +++ b/docs/styleguide.rst @@ -0,0 +1,200 @@ +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 a utf-8 encoding declaration (if non + ASCII letters are used, but it is recommended all the time) and a + standard docstring:: + + # -*- coding: utf-8 -*- + """ + package.module + ~~~~~~~~~~~~~~ + + A brief description goes here. + + :copyright: (c) YEAR by AUTHOR. + :license: LICENSE_NAME, see LICENSE_FILE for more details. + """ + + Please keep in mind that proper copyrights and license files are a + requirement for approved Flask extensions. + + +Comments +-------- + +Rules for comments are similar to docstrings. Both are formatted with +reStructuredText. If a comment is used to document an attribute, put a +colon after the opening pound sign (``#``):: + + class User(object): + #: the name of the user as unicode string + name = Column(String) + #: the sha1 hash of the password + inline salt + pw_hash = Column(String) diff --git a/docs/templating.rst b/docs/templating.rst index ed4a52ee..c0af6639 100644 --- a/docs/templating.rst +++ b/docs/templating.rst @@ -1,43 +1,45 @@ +.. _templates: + Templates ========= -Flask leverages Jinja as its template engine. You are obviously free to use -a different template engine, but you still have to install Jinja to run +Flask leverages Jinja2 as template engine. You are obviously free to use +a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. -An extension can depend on Jinja being present. +An extension can depend on Jinja2 being present. -This section only gives a very quick introduction into how Jinja +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 `Jinja Template -Documentation `_ for +engine's syntax itself, head over to the official `Jinja2 Template +Documentation `_ for more information. Jinja Setup ----------- -Unless customized, Jinja is configured by Flask as follows: +Unless customized, Jinja2 is configured by Flask as follows: - autoescaping is enabled for all templates ending in ``.html``, - ``.htm``, ``.xml``, ``.xhtml``, as well as ``.svg`` when using + ``.htm``, ``.xml`` as well as ``.xhtml`` when using :func:`~flask.templating.render_template`. - autoescaping is enabled for all strings when using :func:`~flask.templating.render_template_string`. - a template has the ability to opt in/out autoescaping with the ``{% autoescape %}`` tag. - Flask inserts a couple of global functions and helpers into the - Jinja context, additionally to the values that are present by + Jinja2 context, additionally to the values that are present by default. Standard Context ---------------- -The following global variables are available within Jinja templates +The following global variables are available within Jinja2 templates by default: .. data:: config :noindex: - The current configuration object (:data:`flask.Flask.config`) + The current configuration object (:data:`flask.config`) .. versionadded:: 0.6 @@ -95,6 +97,28 @@ 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 ------------------------ @@ -106,7 +130,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:`security-xss`) +:ref:`xss`) Sometimes however you will need to disable autoescaping in templates. This can be the case if you want to explicitly inject HTML into pages, for @@ -115,7 +139,7 @@ markdown to HTML converter. There are three ways to accomplish that: -- In the Python code, wrap the HTML string in a :class:`~markupsafe.Markup` +- In the Python code, wrap the HTML string in a :class:`~flask.Markup` object before passing it to the template. This is in general the recommended way. - Inside the template, use the ``|safe`` filter to explicitly mark a @@ -137,58 +161,32 @@ using in this block. .. _registering-filters: -Registering Filters, Tests, and Globals ---------------------------------------- +Registering Filters +------------------- -The Flask app and blueprints provide decorators and methods to register your own -filters, tests, and global functions for use in Jinja templates. They all follow -the same pattern, so the following examples only discuss filters. +If you want to register your own filters in Jinja2 you have two ways to do +that. You can either put them by hand into the +:attr:`~flask.Flask.jinja_env` of the application or use the +:meth:`~flask.Flask.template_filter` decorator. -Decorate a function with :meth:`~.Flask.template_filter` to register it as a -template filter. +The two following examples work the same and both reverse an object:: -.. code-block:: python + @app.template_filter('reverse') + def reverse_filter(s): + return s[::-1] - @app.template_filter - def reverse(s): - return reversed(s) + def reverse_filter(s): + return s[::-1] + app.jinja_env.filters['reverse'] = reverse_filter -.. code-block:: jinja +In case of the decorator the argument is optional if you want to use the +function name as name of the filter. Once registered, you can use the filter +in your templates in the same way as Jinja2's builtin filters, for example if +you have a Python list in context called `mylist`:: - {% for item in data | reverse %} + {% for x in mylist | reverse %} {% endfor %} -By default it will use the name of the function as the name of the filter, but -that can be changed by passing a name to the decorator. - -.. code-block:: python - - @app.template_filter("reverse") - def reverse_filter(s): - return reversed(s) - -A filter can be registered separately using :meth:`~.Flask.add_template_filter`. -The name is optional and will use the function name if not given. - -.. code-block:: python - - def reverse_filter(s): - return reversed(s) - - app.add_template_filter(reverse_filter, "reverse") - -For template tests, use the :meth:`~.Flask.template_test` decorator or -:meth:`~.Flask.add_template_test` method. For template global functions, use the -:meth:`~.Flask.template_global` decorator or :meth:`~.Flask.add_template_global` -method. - -The same methods also exist on :class:`.Blueprint`, prefixed with ``app_`` to -indicate that the registered functions will be available to all templates, not -only when rendering from within the blueprint. - -The Jinja environment is also available as :attr:`~.Flask.jinja_env`. It may be -modified directly, as you would when using Jinja outside Flask. - Context Processors ------------------ @@ -215,8 +213,8 @@ functions):: @app.context_processor def utility_processor(): - def format_price(amount, currency="€"): - return f"{amount:.2f}{currency}" + def format_price(amount, currency=u'€'): + return u'{0:.2f}{1}'.format(amount, currency) return dict(format_price=format_price) The context processor above makes the `format_price` function available to all @@ -227,35 +225,3 @@ 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 Jinja 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 -:data:`.request`, :data:`.session`, and :data:`.g` remain available in the -template. - -More headers cannot be sent after the body has begun. Therefore, you must -make sure all headers are set before starting the response. In particular, -if the template will access ``session``, be sure to do so in the view as -well so that the ``Vary: cookie`` header will be set. diff --git a/docs/testing.rst b/docs/testing.rst index c171abd6..82e10328 100644 --- a/docs/testing.rst +++ b/docs/testing.rst @@ -1,318 +1,456 @@ +.. _testing: + Testing Flask Applications ========================== -Flask provides utilities for testing an application. This documentation -goes over techniques for working with different parts of the application -in tests. + **Something that is untested is broken.** -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. - $ pip install pytest +In this documentation we will use the `pytest`_ package as the base +framework for our tests. You can install it with ``pip``, like so:: -.. _pytest: https://docs.pytest.org/ + pip install pytest -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. +.. _pytest: + https://pytest.org +The Application +--------------- -Identifying Tests ------------------ +First, we need an application to test; we will use the application from +the :ref:`tutorial`. If you don't have that application yet, get the +source code from :gh:`the examples `. -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``. +The Testing Skeleton +-------------------- -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. +We begin by adding a tests directory under the application root. Then +create a Python file to store our tests (:file:`test_flaskr.py`). When we +format the filename like ``test_*.py``, it will be auto-discoverable by +pytest. +Next, we create a `pytest fixture`_ called +:func:`client` that configures +the application for testing and initializes a new database.:: -Fixtures --------- - -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 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. - -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. - -.. code-block:: python + import os + import tempfile import pytest - from my_project import create_app - @pytest.fixture() - def app(): - app = create_app() - app.config.update({ - "TESTING": True, + from flaskr import flaskr + + + @pytest.fixture + def client(): + 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() + + yield client + + os.close(db_fd) + os.unlink(flaskr.app.config['DATABASE']) + +This client fixture will be called by each individual test. It gives us a +simple interface to the application, where we can trigger test requests to the +application. The client will also keep track of cookies for us. + +During setup, the ``TESTING`` config flag is activated. What +this does is disable error catching during request handling, so that +you get better error reports when performing test requests against the +application. + +Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module +to create a temporary database and initialize it. The +:func:`~tempfile.mkstemp` function does two things for us: it returns a +low-level file handle and a random file name, the latter we use as +database name. We just have to keep the `db_fd` around so that we can use +the :func:`os.close` function to close the file. + +To delete the database after the test, the fixture closes the file and removes +it from the filesystem. + +If we now run the test suite, we should see the following output:: + + $ pytest + + ================ test session starts ================ + rootdir: ./flask/examples/flaskr, inifile: setup.cfg + collected 0 items + + =========== no tests ran in 0.07 seconds ============ + +Even though it did not run any actual tests, we already know that our ``flaskr`` +application is syntactically valid, otherwise the import would have died +with an exception. + +.. _pytest fixture: + https://docs.pytest.org/en/latest/fixture.html + +The First Test +-------------- + +Now it's time to start testing the functionality of the application. +Let's check that the application shows "No entries here so far" if we +access the root of the application (``/``). To do this, we add a new +test function to :file:`test_flaskr.py`, like this:: + + def test_empty_db(client): + """Start with a blank database.""" + + rv = client.get('/') + assert b'No entries here so far' in rv.data + +Notice that our test functions begin with the word `test`; this allows +`pytest`_ to automatically identify the function as a test to run. + +By using ``client.get`` we can send an HTTP ``GET`` request to the application with +the given path. The return value will be a :class:`~flask.Flask.response_class` object. +We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect +the return value (as string) from the application. In this case, we ensure that +``'No entries here so far'`` is part of the output. + +Run it again and you should see one passing test:: + + $ pytest -v + + ================ test session starts ================ + rootdir: ./flask/examples/flaskr, inifile: setup.cfg + collected 1 items + + tests/test_flaskr.py::test_empty_db PASSED + + ============= 1 passed in 0.10 seconds ============== + +Logging In and Out +------------------ + +The majority of the functionality of our application is only available for +the administrative user, so we need a way to log our test client in and out +of the application. To do this, we fire some requests to the login and logout +pages with the required form data (username and password). And because the +login and logout pages redirect, we tell the client to `follow_redirects`. + +Add the following two functions to your :file:`test_flaskr.py` file:: + + def login(client, username, password): + return client.post('/login', data=dict( + username=username, + password=password + ), follow_redirects=True) + + + def logout(client): + return client.get('/logout', follow_redirects=True) + +Now we can easily test that logging in and out works and that it fails with +invalid credentials. Add this new test function:: + + def test_login_logout(client): + """Make sure login and logout works.""" + + rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']) + assert b'You were logged in' in rv.data + + rv = logout(client) + assert b'You were logged out' in rv.data + + rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD']) + assert b'Invalid username' in rv.data + + rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x') + assert b'Invalid password' in rv.data + +Test Adding Messages +-------------------- + +We should also test that adding messages works. Add a new test function +like this:: + + def test_messages(client): + """Test that messages work.""" + + login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']) + rv = client.post('/add', data=dict( + title='', + text='HTML allowed here' + ), follow_redirects=True) + assert b'No entries here so far' not in rv.data + assert b'<Hello>' in rv.data + assert b'HTML allowed here' in rv.data + +Here we check that HTML is allowed in the text but not in the title, +which is the intended behavior. + +Running that should now give us three passing tests:: + + $ pytest -v + + ================ test session starts ================ + rootdir: ./flask/examples/flaskr, inifile: setup.cfg + collected 3 items + + tests/test_flaskr.py::test_empty_db PASSED + tests/test_flaskr.py::test_login_logout PASSED + tests/test_flaskr.py::test_messages PASSED + + ============= 3 passed in 0.23 seconds ============== + + +Other Testing Tricks +-------------------- + +Besides using the test client as shown above, there is also the +:meth:`~flask.Flask.test_request_context` method that can be used +in combination with the ``with`` statement to activate a request context +temporarily. With this you can access the :class:`~flask.request`, +:class:`~flask.g` and :class:`~flask.session` objects like in view +functions. Here is a full example that demonstrates this approach:: + + import flask + + app = flask.Flask(__name__) + + with app.test_request_context('/?name=Peter'): + assert flask.request.path == '/' + assert flask.request.args['name'] == 'Peter' + +All the other objects that are context bound can be used in the same +way. + +If you want to test your application with different configurations and +there does not seem to be a good way to do that, consider switching to +application factories (see :ref:`app-factories`). + +Note however that if you are using a test request context, the +:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request` +functions are not called automatically. However +:meth:`~flask.Flask.teardown_request` functions are indeed executed when +the test request context leaves the ``with`` block. If you do want the +:meth:`~flask.Flask.before_request` functions to be called as well, you +need to call :meth:`~flask.Flask.preprocess_request` yourself:: + + app = flask.Flask(__name__) + + with app.test_request_context('/?name=Peter'): + app.preprocess_request() + ... + +This can be necessary to open database connections or something similar +depending on how your application was designed. + +If you want to call the :meth:`~flask.Flask.after_request` functions you +need to call into :meth:`~flask.Flask.process_response` which however +requires that you pass it a response object:: + + app = flask.Flask(__name__) + + with app.test_request_context('/?name=Peter'): + resp = Response('...') + resp = app.process_response(resp) + ... + +This in general is less useful because at that point you can directly +start using the test client. + +.. _faking-resources: + +Faking Resources and Context +---------------------------- + +.. versionadded:: 0.10 + +A very common pattern is to store user authorization information and +database connections on the application context or the :attr:`flask.g` +object. The general pattern for this is to put the object on there on +first usage and then to remove it on a teardown. Imagine for instance +this code to get the current user:: + + def get_user(): + user = getattr(g, 'user', None) + if user is None: + user = fetch_current_user_from_database() + g.user = user + return user + +For a test it would be nice to override this user from the outside without +having to change some code. This can be accomplished with +hooking the :data:`flask.appcontext_pushed` signal:: + + from contextlib import contextmanager + from flask import appcontext_pushed, g + + @contextmanager + def user_set(app, user): + def handler(sender, **kwargs): + g.user = user + with appcontext_pushed.connected_to(handler, app): + yield + +And then to use it:: + + from flask import json, jsonify + + @app.route('/users/me') + def users_me(): + return jsonify(username=g.user.username) + + with user_set(app, my_user): + with app.test_client() as c: + resp = c.get('/users/me') + data = json.loads(resp.data) + self.assert_equal(data['username'], my_user.username) + + +Keeping the Context Around +-------------------------- + +.. versionadded:: 0.4 + +Sometimes it is helpful to trigger a regular request but still keep the +context around for a little longer so that additional introspection can +happen. With Flask 0.4 this is possible by using the +:meth:`~flask.Flask.test_client` with a ``with`` block:: + + app = flask.Flask(__name__) + + with app.test_client() as c: + rv = c.get('/?tequila=42') + assert request.args['tequila'] == '42' + +If you were to use just the :meth:`~flask.Flask.test_client` without +the ``with`` block, the ``assert`` would fail with an error because `request` +is no longer available (because you are trying to use it outside of the actual request). + + +Accessing and Modifying Sessions +-------------------------------- + +.. versionadded:: 0.8 + +Sometimes it can be very helpful to access or modify the sessions from the +test client. Generally there are two ways for this. If you just want to +ensure that a session has certain keys set to certain values you can just +keep the context around and access :data:`flask.session`:: + + with app.test_client() as c: + rv = c.get('/') + assert flask.session['foo'] == 42 + +This however does not make it possible to also modify the session or to +access the session before a request was fired. Starting with Flask 0.8 we +provide a so called “session transaction” which simulates the appropriate +calls to open a session in the context of the test client and to modify +it. At the end of the transaction the session is stored. This works +independently of the session backend used:: + + with app.test_client() as c: + with c.session_transaction() as sess: + sess['a_key'] = 'a value' + + # once this is reached the session was stored + +Note that in this case you have to use the ``sess`` object instead of the +:data:`flask.session` proxy. The object however itself will provide the +same interface. + + +Testing JSON APIs +----------------- + +.. versionadded:: 1.0 + +Flask has great support for JSON, and is a popular choice for building JSON +APIs. Making requests with JSON data and examining JSON data in responses is +very convenient:: + + from flask import request, jsonify + + @app.route('/api/auth') + def auth(): + json_data = request.get_json() + email = json_data['email'] + password = json_data['password'] + return jsonify(token=generate_token(email, password)) + + with app.test_client() as c: + rv = c.post('/api/auth', json={ + 'username': 'flask', 'password': 'secret' }) + json_data = rv.get_json() + assert verify_token(email, json_data['token']) - # other setup can go here - - yield app - - # clean up / reset resources here - - - @pytest.fixture() - def client(app): - return app.test_client() - - - @pytest.fixture() - def runner(app): - return app.test_cli_runner() - - -Sending Requests with the Test Client -------------------------------------- - -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. - -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``. - -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)``. - -.. code-block:: python - - def test_request_example(client): - response = client.get("/posts") - assert b"

Hello, World!

" in response.data - - -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. - -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. - - -Form Data -~~~~~~~~~ - -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. - -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. - -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. - -.. code-block:: python - - from pathlib import Path - - # get the resources folder in the tests folder - resources = Path(__file__).parent / "resources" - - 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 - - -JSON Data -~~~~~~~~~ - -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. - -.. 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" - - -Following Redirects -------------------- - -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. - -: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. - -.. code-block:: python - - 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" - - -Accessing and Modifying the Session ------------------------------------ - -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. - -.. code-block:: python - - from flask import session - - def test_access_session(client): - with client: - client.post("/auth/login", data={"username": "flask"}) - # session is still accessible - assert session["user_id"] == 1 - - # session is no longer accessible - -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. - -.. code-block:: python - - from flask import session - - 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 - - # session is saved now - - response = client.get("/users/me") - assert response.json["username"] == "flask" +Passing the ``json`` argument in the test client methods sets the request data +to the JSON-serialized object and sets the content type to +``application/json``. You can get the JSON data from the request or response +with ``get_json``. .. _testing-cli: -Running Commands with the CLI Runner ------------------------------------- +Testing CLI Commands +-------------------- + +Click comes with `utilities for testing`_ your CLI commands. A +:class:`~click.testing.CliRunner` runs commands in isolation and +captures the output in a :class:`~click.testing.Result` object. Flask provides :meth:`~flask.Flask.test_cli_runner` to create a -:class:`~flask.testing.FlaskCliRunner`, 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. - -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. - -.. code-block:: python +:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the +CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke` +method to call commands in the same way they would be called from the +command line. :: import click - @app.cli.command("hello") - @click.option("--name", default="World") - def hello_command(name): - click.echo(f"Hello, {name}!") + @app.cli.command('hello') + @click.option('--name', default='World') + def hello_command(name) + click.echo(f'Hello, {name}!') - def test_hello_command(runner): - result = runner.invoke(args="hello") - assert "World" in result.output + def test_hello(): + runner = app.test_cli_runner() - result = runner.invoke(args=["hello", "--name", "Flask"]) - assert "Flask" in result.output + # invoke the command directly + result = runner.invoke(hello_command, ['--name', 'Flask']) + assert 'Hello, Flask' in result.output + # or by name + result = runner.invoke(args=['hello']) + assert 'World' in result.output -Tests that depend on an Active Context --------------------------------------- +In the example above, invoking the command by name is useful because it +verifies that the command was correctly registered with the app. -You may have functions that are called from views or commands, that expect an -active :doc:`app context ` because they access :data:`.request`, -:data:`.session`, :data:`.g`, or :data:`.current_app`. Rather than testing them by -making a request or invoking the command, you can create and activate a context -directly. +If you want to test how your command parses parameters, without running +the command, use its :meth:`~click.BaseCommand.make_context` method. +This is useful for testing complex validation rules and custom types. :: -Use ``with app.app_context()`` to push an application context. For -example, database extensions usually require an active app context to -make queries. + def upper(ctx, param, value): + if value is not None: + return value.upper() -.. code-block:: python + @app.cli.command('hello') + @click.option('--name', default='World', callback=upper) + def hello_command(name) + click.echo(f'Hello, {name}!') - def test_db_post_model(app): - with app.app_context(): - post = db.session.query(Post).get(1) + def test_hello_params(): + context = hello_command.make_context('hello', ['--name', 'flask']) + assert context.params['name'] == 'FLASK' -Use ``with app.test_request_context()`` to push a request context. It -takes the same arguments as the test client's request methods. - -.. code-block:: python - - 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() - - assert messages["name"][0] == "Name cannot be empty." - -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. - -.. code-block:: python - - 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" +.. _click: http://click.pocoo.org/ +.. _utilities for testing: http://click.pocoo.org/testing diff --git a/docs/tutorial/blog.rst b/docs/tutorial/blog.rst index 6418f5ff..4511d61b 100644 --- a/docs/tutorial/blog.rst +++ b/docs/tutorial/blog.rst @@ -125,7 +125,7 @@ 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 +.. _Jinja for loops: http://jinja.pocoo.org/docs/templates/#for Create @@ -207,7 +207,7 @@ it from each view. ).fetchone() if post is None: - abort(404, f"Post id {id} doesn't exist.") + abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post['author_id'] != g.user['id']: abort(403) @@ -305,7 +305,7 @@ 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 +``request.form`` is used instead. :data:`request` is another variable that's automatically available in templates. @@ -314,7 +314,7 @@ 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 +is no template, it will only handle the ``POST`` method then redirect to the ``index`` view. .. code-block:: python diff --git a/docs/tutorial/database.rst b/docs/tutorial/database.rst index cf132603..51f20b61 100644 --- a/docs/tutorial/database.rst +++ b/docs/tutorial/database.rst @@ -37,10 +37,10 @@ response is sent. :caption: ``flaskr/db.py`` import sqlite3 - from datetime import datetime import click from flask import current_app, g + from flask.cli import with_appcontext def get_db(): @@ -60,17 +60,17 @@ response is sent. if db is not None: db.close() -:data:`.g` is a special object that is unique for each request. It is +: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 +: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. +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 @@ -128,16 +128,12 @@ Add the Python functions that will run these SQL commands to the @click.command('init-db') + @with_appcontext def init_db_command(): """Clear the existing data and create new tables.""" init_db() click.echo('Initialized the database.') - - 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`` @@ -146,18 +142,14 @@ 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`. +user. You can read :ref:`cli` to learn more about writing commands. Register with the Application ----------------------------- The ``close_db`` and ``init_db_command`` functions need to be registered -with the application instance; otherwise, they won't be used by the +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. @@ -204,13 +196,15 @@ previous page. 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`. + and activate the env as described in :ref:`install-activate-env`. + You'll also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on + the previous page. Run the ``init-db`` command: .. code-block:: none - $ flask --app flaskr init-db + flask init-db Initialized the database. There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in diff --git a/docs/tutorial/deploy.rst b/docs/tutorial/deploy.rst index eb3a53ac..a0c052ea 100644 --- a/docs/tutorial/deploy.rst +++ b/docs/tutorial/deploy.rst @@ -14,17 +14,26 @@ 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. +When you want to deploy your application elsewhere, you build a +distribution file. The current standard for Python distribution is the +*wheel* format, with the ``.whl`` extension. Make sure the wheel library +is installed first: .. code-block:: none - $ pip install build - $ python -m build --wheel + pip install wheel + +Running ``setup.py`` with Python gives you a command line tool to issue +build-related commands. The ``bdist_wheel`` command will build a wheel +distribution file. + +.. code-block:: none + + python setup.py bdist_wheel You can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The -file name is in the format of {project name}-{version}-{python tag} --{abi tag}-{platform tag}. +file name is the name of the project, the version, and some tags about +the file can install. Copy this file to another machine, :ref:`set up a new virtualenv `, then install the @@ -32,20 +41,21 @@ file with ``pip``. .. code-block:: none - $ pip install flaskr-1.0.0-py3-none-any.whl + 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 +.. code-block:: none - $ flask --app flaskr init-db + export FLASK_APP=flaskr + flask init-db When Flask detects that it's installed (not in editable mode), it uses a different directory for the instance folder. You can find it at -``.venv/var/flaskr-instance`` instead. +``venv/var/flaskr-instance`` instead. Configure the Secret Key @@ -60,17 +70,17 @@ You can use the following command to output a random secret key: .. code-block:: none - $ python -c 'import secrets; print(secrets.token_hex())' + python -c 'import os; print(os.urandom(16))' - '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + b'_5#y2L"F4Q8z\n\xec]/' Create the ``config.py`` file in the instance folder, which the factory will read from if it exists. Copy the generated value into it. .. code-block:: python - :caption: ``.venv/var/flaskr-instance/config.py`` + :caption: ``venv/var/flaskr-instance/config.py`` - SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' + SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/' You can also set any other necessary configuration here, although ``SECRET_KEY`` is the only one needed for Flaskr. @@ -89,15 +99,15 @@ first install it in the virtual environment: .. code-block:: none - $ pip install waitress + 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 +``FLASK_APP`` like ``flask run`` does. You need to tell it to import and call the application factory to get an application object. .. code-block:: none - $ waitress-serve --call 'flaskr:create_app' + waitress-serve --call 'flaskr:create_app' Serving on http://0.0.0.0:8080 @@ -106,6 +116,6 @@ 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/ +.. _Waitress: https://docs.pylonsproject.org/projects/waitress/ Continue to :doc:`next`. diff --git a/docs/tutorial/factory.rst b/docs/tutorial/factory.rst index 381477f9..62462e1c 100644 --- a/docs/tutorial/factory.rst +++ b/docs/tutorial/factory.rst @@ -30,7 +30,7 @@ directory should be treated as a package. .. code-block:: none - $ mkdir flaskr + mkdir flaskr .. code-block:: python :caption: ``flaskr/__init__.py`` @@ -56,7 +56,10 @@ directory should be treated as a package. app.config.from_mapping(test_config) # ensure the instance folder exists - os.makedirs(app.instance_path, exist_ok=True) + try: + os.makedirs(app.instance_path) + except OSError: + pass # a simple page that says hello @app.route('/hello') @@ -124,36 +127,51 @@ 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. +development mode. -Debug mode shows an interactive debugger whenever a page raises an +Development mode shows an interactive debugger whenever a page raises an exception, and restarts the server whenever you make changes to the code. You can leave it running and just reload the browser page as you follow the tutorial. -.. code-block:: text +For Linux and Mac: - $ flask --app flaskr run --debug +.. code-block:: none + + export FLASK_APP=flaskr + export FLASK_ENV=development + flask run + +For Windows cmd, use ``set`` instead of ``export``: + +.. code-block:: none + + set FLASK_APP=flaskr + set FLASK_ENV=development + flask run + +For Windows PowerShell, use ``$env:`` instead of ``export``: + +.. code-block:: none + + $env:FLASK_APP = "flaskr" + $env:FLASK_ENV = "development" + flask run You'll see output similar to this: -.. code-block:: text +.. code-block:: none * Serving Flask app "flaskr" + * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! - * Debugger PIN: nnn-nnn-nnn + * Debugger PIN: 855-212-761 Visit http://127.0.0.1:5000/hello in a browser and you should see the "Hello, World!" message. Congratulations, you're now running your Flask web application! -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/index.rst b/docs/tutorial/index.rst index d5dc5b3c..9b43c510 100644 --- a/docs/tutorial/index.rst +++ b/docs/tutorial/index.rst @@ -1,3 +1,5 @@ +.. _tutorial: + Tutorial ======== @@ -33,11 +35,11 @@ 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 +cover all of Flask's features. Check out the :ref:`quickstart` for an overview of what Flask can do, then dive into the docs to find out more. The tutorial only uses what's provided by Flask and Python. In another -project, you might decide to use :doc:`/extensions` or other libraries -to make some tasks simpler. +project, you might decide to use :ref:`extensions` or other libraries to +make some tasks simpler. .. image:: flaskr_login.png :align: center @@ -55,7 +57,7 @@ this structure and take full advantage of Flask's flexibility. .. image:: flaskr_edit.png :align: center :class: screenshot - :alt: screenshot of edit page + :alt: screenshot of login page :gh:`The tutorial project is available as an example in the Flask repository `, if you want to compare your project diff --git a/docs/tutorial/install.rst b/docs/tutorial/install.rst index db83e106..fff0b52c 100644 --- a/docs/tutorial/install.rst +++ b/docs/tutorial/install.rst @@ -1,10 +1,11 @@ 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. +Making your project installable means that you can build a +*distribution* file and install that in another environment, just like +you installed Flask in your project's environment. This makes deploying +your project the same as installing any other library, so you're using +all the standard Python tools to manage everything. Installing also comes with other benefits that might not be obvious from the tutorial or as a new Python user, including: @@ -27,27 +28,49 @@ the tutorial or as a new Python user, including: Describe the Project -------------------- -The ``pyproject.toml`` file describes your project and how to build it. +The ``setup.py`` file describes your project and the files that belong +to it. -.. code-block:: toml - :caption: ``pyproject.toml`` +.. code-block:: python + :caption: ``setup.py`` - [project] - name = "flaskr" - version = "1.0.0" - description = "The basic blog app built in the Flask tutorial." - dependencies = [ - "flask", - ] + from setuptools import find_packages, setup - [build-system] - requires = ["flit_core<4"] - build-backend = "flit_core.buildapi" + setup( + name='flaskr', + version='1.0.0', + packages=find_packages(), + include_package_data=True, + zip_safe=False, + install_requires=[ + 'flask', + ], + ) -See the official `Packaging tutorial `_ for more -explanation of the files and options used. -.. _packaging tutorial: https://packaging.python.org/tutorials/packaging-projects/ +``packages`` tells Python what package directories (and the Python files +they contain) to include. ``find_packages()`` finds these directories +automatically so you don't have to type them out. To include other +files, such as the static and templates directories, +``include_package_data`` is set. Python needs another file named +``MANIFEST.in`` to tell what this other data is. + +.. code-block:: none + :caption: ``MANIFEST.in`` + + include flaskr/schema.sql + graft flaskr/static + graft flaskr/templates + global-exclude *.pyc + +This tells Python to copy everything in the ``static`` and ``templates`` +directories, and the ``schema.sql`` file, but to exclude all bytecode +files. + +See the `official packaging guide`_ for another explanation of the files +and options used. + +.. _official packaging guide: https://packaging.python.org/tutorials/distributing-packages/ Install the Project @@ -57,18 +80,18 @@ Use ``pip`` to install your project in the virtual environment. .. code-block:: none - $ pip install -e . + 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. +This tells pip to find ``setup.py`` in the current directory and install +it in *editable* or *development* mode. Editable mode means that as you +make changes to your local code, you'll only need to re-install if you +change the metadata about the project, such as its dependencies. You can observe that the project is now installed with ``pip list``. .. code-block:: none - $ pip list + pip list Package Version Location -------------- --------- ---------------------------------- @@ -79,11 +102,12 @@ You can observe that the project is now installed with ``pip list``. Jinja2 2.10 MarkupSafe 1.0 pip 9.0.3 + setuptools 39.0.1 Werkzeug 0.14.1 + wheel 0.30.0 Nothing changes from how you've been running your project so far. -``--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. +``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs +the application. Continue to :doc:`tests`. diff --git a/docs/tutorial/layout.rst b/docs/tutorial/layout.rst index 9f510927..2d7ddebe 100644 --- a/docs/tutorial/layout.rst +++ b/docs/tutorial/layout.rst @@ -5,8 +5,8 @@ Create a project directory and enter it: .. code-block:: none - $ mkdir flask-tutorial - $ cd flask-tutorial + 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. @@ -31,7 +31,7 @@ A Flask application can be as simple as a single file. def hello(): return 'Hello, World!' -However, as a project gets bigger, it becomes overwhelming to keep all +However, as a project get 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. @@ -41,7 +41,7 @@ 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 +* ``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 @@ -57,31 +57,32 @@ By the end, your project layout will look like this: /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 + │   ├── __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 + │   ├── conftest.py + │   ├── data.sql + │   ├── test_factory.py + │   ├── test_db.py + │  ├── test_auth.py + │  └── test_blog.py + ├── venv/ + ├── setup.py + └── MANIFEST.in If you're using version control, the following files that are generated while running your project should be ignored. There may be other files @@ -91,7 +92,7 @@ write. For example, with git: .. code-block:: none :caption: ``.gitignore`` - .venv/ + venv/ *.pyc __pycache__/ @@ -102,4 +103,8 @@ write. For example, with git: .coverage htmlcov/ + dist/ + build/ + *.egg-info/ + Continue to :doc:`factory`. diff --git a/docs/tutorial/next.rst b/docs/tutorial/next.rst index d41e8ef2..07bbc048 100644 --- a/docs/tutorial/next.rst +++ b/docs/tutorial/next.rst @@ -9,11 +9,11 @@ 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 +out the :ref:`quickstart` for an overview of what Flask can do, then dive into the docs to keep learning. Flask uses `Jinja`_, `Click`_, `Werkzeug`_, and `ItsDangerous`_ behind the scenes, and they all have their own documentation too. You'll also be interested in -:doc:`/extensions` which make tasks like working with the database or +:ref:`extensions` which make tasks like working with the database or validating form data easier and more powerful. If you want to keep developing your Flaskr project, here are some ideas diff --git a/docs/tutorial/static.rst b/docs/tutorial/static.rst index 8e76c409..29548e04 100644 --- a/docs/tutorial/static.rst +++ b/docs/tutorial/static.rst @@ -55,7 +55,7 @@ the following into the ``flaskr/static/style.css`` file: 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 +Go to http://127.0.0.1/auth/login and the page should look like the screenshot below. .. image:: flaskr_login.png diff --git a/docs/tutorial/templates.rst b/docs/tutorial/templates.rst index ca9d4b32..226081c9 100644 --- a/docs/tutorial/templates.rst +++ b/docs/tutorial/templates.rst @@ -31,7 +31,7 @@ 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/ +.. _Jinja: http://jinja.pocoo.org/docs/templates/ .. _HTML: https://developer.mozilla.org/docs/Web/HTML @@ -71,9 +71,9 @@ specific sections. {% block content %}{% endblock %} -:data:`.g` is automatically available in templates. Based on if +: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 +and a log out link are displayed, otherwise 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. diff --git a/docs/tutorial/tests.rst b/docs/tutorial/tests.rst index 8958e773..565450f9 100644 --- a/docs/tutorial/tests.rst +++ b/docs/tutorial/tests.rst @@ -28,7 +28,7 @@ Install them both: .. code-block:: none - $ pip install pytest coverage + pip install pytest coverage .. _pytest: https://pytest.readthedocs.io/ .. _coverage: https://coverage.readthedocs.io/ @@ -107,7 +107,7 @@ local development configuration. 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 +the file object and the path to it. The ``DATABASE`` path is overridden so it points to this temporary path instead of the instance folder. After setting the path, the database tables are created and the test data is inserted. After the test is over, the temporary file is @@ -188,7 +188,7 @@ should be closed. with pytest.raises(sqlite3.ProgrammingError) as e: db.execute('SELECT 1') - assert 'closed' in str(e.value) + assert 'closed' in str(e) The ``init-db`` command should call the ``init_db`` function and output a message. @@ -266,11 +266,11 @@ messages. response = client.post( '/auth/register', data={'username': 'a', 'password': 'a'} ) - assert response.headers["Location"] == "/auth/login" + assert 'http://localhost/auth/login' == response.headers['Location'] with app.app_context(): assert get_db().execute( - "SELECT * FROM user WHERE username = 'a'", + "select * from user where username = 'a'", ).fetchone() is not None @@ -301,8 +301,8 @@ 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) ` +``data``. Bytes must be compared to bytes. If you want to compare +Unicode text, use :meth:`get_data(as_text=True) ` instead. ``pytest.mark.parametrize`` tells Pytest to run the same test function @@ -311,7 +311,7 @@ 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. +:data:`session` should have ``user_id`` set after logging in. .. code-block:: python :caption: ``tests/test_auth.py`` @@ -319,7 +319,7 @@ The tests for the ``login`` view are very similar to those for def test_login(client, auth): assert client.get('/auth/login').status_code == 200 response = auth.login() - assert response.headers["Location"] == "/" + assert response.headers['Location'] == 'http://localhost/' with client: client.get('/') @@ -336,10 +336,10 @@ The tests for the ``login`` view are very similar to those for 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, +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 +Testing ``logout`` is the opposite of ``login``. :data:`session` should not contain ``user_id`` after logging out. .. code-block:: python @@ -404,7 +404,7 @@ is returned. If a ``post`` with the given ``id`` doesn't exist, )) def test_login_required(client, path): response = client.post(path) - assert response.headers["Location"] == "/auth/login" + assert response.headers['Location'] == 'http://localhost/auth/login' def test_author_required(app, client, auth): @@ -479,7 +479,7 @@ no longer exist in the database. def test_delete(client, auth, app): auth.login() response = client.post('/1/delete') - assert response.headers["Location"] == "/" + assert response.headers['Location'] == 'http://localhost/' with app.app_context(): db = get_db() @@ -490,29 +490,31 @@ no longer exist in the database. 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. +Some extra configuration, which is not required but makes running +tests with coverage less verbose, can be added to the project's +``setup.cfg`` file. -.. code-block:: toml - :caption: ``pyproject.toml`` +.. code-block:: none + :caption: ``setup.cfg`` - [tool.pytest.ini_options] - testpaths = ["tests"] + [tool:pytest] + testpaths = tests - [tool.coverage.run] - branch = true - source = ["flaskr"] + [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 + 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 + rootdir: /home/user/Projects/flask-tutorial, inifile: setup.cfg collected 23 items tests/test_auth.py ........ [ 34%] @@ -530,13 +532,13 @@ to run pytest instead of running it directly. .. code-block:: none - $ coverage run -m pytest + coverage run -m pytest You can either view a simple coverage report in the terminal: .. code-block:: none - $ coverage report + coverage report Name Stmts Miss Branch BrPart Cover ------------------------------------------------------ @@ -551,7 +553,7 @@ An HTML report allows you to see which lines were covered in each file: .. code-block:: none - $ coverage html + coverage html This generates files in the ``htmlcov`` directory. Open ``htmlcov/index.html`` in your browser to see the report. diff --git a/docs/tutorial/views.rst b/docs/tutorial/views.rst index 6626628a..c9c6a7ca 100644 --- a/docs/tutorial/views.rst +++ b/docs/tutorial/views.rst @@ -91,18 +91,18 @@ write templates to generate the HTML form. error = 'Username is required.' elif not password: error = 'Password is required.' + elif db.execute( + 'SELECT id FROM user WHERE username = ?', (username,) + ).fetchone() is not None: + error = 'User {} is already registered.'.format(username) if error is None: - 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")) + db.execute( + 'INSERT INTO user (username, password) VALUES (?, ?)', + (username, generate_password_hash(password)) + ) + db.commit() + return redirect(url_for('auth.login')) flash(error) @@ -125,25 +125,26 @@ Here's what the ``register`` view function is doing: #. Validate that ``username`` and ``password`` are not empty. +#. Validate that ``username`` is not already registered by querying the + database and checking if a result is returned. + :meth:`db.execute ` takes a SQL query + with ``?`` placeholders for any user input, and a tuple of values + to replace the placeholders with. The database library will take + care of escaping the values so you are not vulnerable to a + *SQL injection attack*. + + :meth:`~sqlite3.Cursor.fetchone` returns one row from the query. + If the query returned no results, it returns ``None``. Later, + :meth:`~sqlite3.Cursor.fetchall` is used, which returns a list of + all results. + #. If validation succeeds, insert the new user data into the database. - - - :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. + For security, passwords should never be stored in the database + directly. Instead, + :func:`~werkzeug.security.generate_password_hash` is used to + securely hash the password, and that hash is stored. Since this + query modifies data, :meth:`db.commit() ` + needs to be called afterwards to save the changes. #. After storing the user, they are redirected to the login page. :func:`url_for` generates the URL for the login view based on its @@ -156,7 +157,7 @@ Here's what the ``register`` view function is doing: 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 + there was an 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. @@ -199,22 +200,17 @@ 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. +#. :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 +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. @@ -236,7 +232,7 @@ available to other views. :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 +: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``. @@ -245,7 +241,7 @@ there is no user id, or if the id doesn't exist, ``g.user`` will be Logout ------ -To log out, you need to remove the user id from the :data:`.session`. +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 diff --git a/docs/unicode.rst b/docs/unicode.rst new file mode 100644 index 00000000..5aa6e25d --- /dev/null +++ b/docs/unicode.rst @@ -0,0 +1,107 @@ +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 new file mode 100644 index 00000000..aae5dd2a --- /dev/null +++ b/docs/upgrading.rst @@ -0,0 +1,472 @@ +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 an invalid or even +misleading ``name`` attribute. Silently swallowing errors in such cases was not +a satisfying solution. + +Additionally the default of falling back to ``application/octet-stream`` has +been restricted. If Flask can't guess one or the user didn't provide one, the +function fails if no filename information was provided. + +.. _upgrading-to-011: + +Version 0.11 +------------ + +0.11 is an odd release in the Flask release cycle because it was supposed +to be the 1.0 release. However because there was such a long lead time up +to the release we decided to push out a 0.11 release first with some +changes removed to make the transition easier. If you have been tracking +the master branch which was 1.0 you might see some unexpected changes. + +In case you did track the master branch you will notice that :command:`flask --app` +is removed now. You need to use the environment variable to specify an +application. + +Debugging +````````` + +Flask 0.11 removed the ``debug_log_format`` attribute from Flask +applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can +be used to disable the default log handlers and custom log handlers can be +set up. + +Error handling +`````````````` + +The behavior of error handlers was changed. +The precedence of handlers used to be based on the decoration/call order of +:meth:`~flask.Flask.errorhandler` and +:meth:`~flask.Flask.register_error_handler`, respectively. +Now the inheritance hierarchy takes precedence and handlers for more +specific exception classes are executed instead of more general ones. +See :ref:`error-handlers` for specifics. + +Trying to register a handler on an instance now raises :exc:`ValueError`. + +.. note:: + + There used to be a logic error allowing you to register handlers + only for exception *instances*. This was unintended and plain wrong, + and therefore was replaced with the intended behavior of registering + handlers only using exception classes and HTTP error codes. + +Templating +`````````` + +The :func:`~flask.templating.render_template_string` function has changed to +autoescape template variables by default. This better matches the behavior +of :func:`~flask.templating.render_template`. + +Extension imports +````````````````` + +Extension imports of the form ``flask.ext.foo`` are deprecated, you should use +``flask_foo``. + +The old form still works, but Flask will issue a +``flask.exthook.ExtDeprecationWarning`` for each extension you import the old +way. We also provide a migration utility called `flask-ext-migrate +`_ that is supposed to +automatically rewrite your imports for this. + +.. _upgrading-to-010: + +Version 0.10 +------------ + +The biggest change going from 0.9 to 0.10 is that the cookie serialization +format changed from pickle to a specialized JSON format. This change has +been done in order to avoid the damage an attacker can do if the secret +key is leaked. When you upgrade you will notice two major changes: all +sessions that were issued before the upgrade are invalidated and you can +only store a limited amount of types in the session. The new sessions are +by design much more restricted to only allow JSON with a few small +extensions for tuples and strings with HTML markup. + +In order to not break people's sessions it is possible to continue using +the old session system by using the `Flask-OldSessions`_ extension. + +Flask also started storing the :data:`flask.g` object on the application +context instead of the request context. This change should be transparent +for you but it means that you now can store things on the ``g`` object +when there is no request context yet but an application context. The old +``flask.Flask.request_globals_class`` attribute was renamed to +:attr:`flask.Flask.app_ctx_globals_class`. + +.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/ + +Version 0.9 +----------- + +The behavior of returning tuples from a function was simplified. If you +return a tuple it no longer defines the arguments for the response object +you're creating, it's now always a tuple in the form ``(response, status, +headers)`` where at least one item has to be provided. If you depend on +the old behavior, you can add it easily by subclassing Flask:: + + class TraditionalFlask(Flask): + def make_response(self, rv): + if isinstance(rv, tuple): + return self.response_class(*rv) + return Flask.make_response(self, rv) + +If you maintain an extension that was using :data:`~flask._request_ctx_stack` +before, please consider changing to :data:`~flask._app_ctx_stack` if it makes +sense for your extension. For instance, the app context stack makes sense for +extensions which connect to databases. Using the app context stack instead of +the request context stack will make extensions more readily handle use cases +outside of requests. + +Version 0.8 +----------- + +Flask introduced a new session interface system. We also noticed that +there was a naming collision between ``flask.session`` the module that +implements sessions and :data:`flask.session` which is the global session +object. With that introduction we moved the implementation details for +the session system into a new module called :mod:`flask.sessions`. If you +used the previously undocumented session support we urge you to upgrade. + +If invalid JSON data was submitted Flask will now raise a +:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the +default :exc:`ValueError` bubble up. This has the advantage that you no +longer have to handle that error to avoid an internal server error showing +up for the user. If you were catching this down explicitly in the past +as :exc:`ValueError` you will need to change this. + +Due to a bug in the test client Flask 0.7 did not trigger teardown +handlers when the test client was used in a with statement. This was +since fixed but might require some changes in your test suites if you +relied on this behavior. + +Version 0.7 +----------- + +In Flask 0.7 we cleaned up the code base internally a lot and did some +backwards incompatible changes that make it easier to implement larger +applications with Flask. Because we want to make upgrading as easy as +possible we tried to counter the problems arising from these changes by +providing a script that can ease the transition. + +The script scans your whole application and generates a unified diff with +changes it assumes are safe to apply. However as this is an automated +tool it won't be able to find all use cases and it might miss some. We +internally spread a lot of deprecation warnings all over the place to make +it easy to find pieces of code that it was unable to upgrade. + +We strongly recommend that you hand review the generated patchfile and +only apply the chunks that look good. + +If you are using git as version control system for your project we +recommend applying the patch with ``path -p1 < patchfile.diff`` and then +using the interactive commit feature to only apply the chunks that look +good. + +To apply the upgrade script do the following: + +1. Download the script: `flask-07-upgrade.py + `_ +2. Run it in the directory of your application:: + + python flask-07-upgrade.py > patchfile.diff + +3. Review the generated patchfile. +4. Apply the patch:: + + patch -p1 < patchfile.diff + +5. If you were using per-module template folders you need to move some + templates around. Previously if you had a folder named :file:`templates` + next to a blueprint named ``admin`` the implicit template path + automatically was :file:`admin/index.html` for a template file called + :file:`templates/index.html`. This no longer is the case. Now you need + to name the template :file:`templates/admin/index.html`. The tool will + not detect this so you will have to do that on your own. + +Please note that deprecation warnings are disabled by default starting +with Python 2.7. In order to see the deprecation warnings that might be +emitted you have to enabled them with the :mod:`warnings` module. + +If you are working with windows and you lack the ``patch`` command line +utility you can get it as part of various Unix runtime environments for +windows including cygwin, msysgit or ming32. Also source control systems +like svn, hg or git have builtin support for applying unified diffs as +generated by the tool. Check the manual of your version control system +for more information. + +Bug in Request Locals +````````````````````` + +Due to a bug in earlier implementations the request local proxies now +raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they +are unbound. If you caught these exceptions with :exc:`AttributeError` +before, you should catch them with :exc:`RuntimeError` now. + +Additionally the :func:`~flask.send_file` function is now issuing +deprecation warnings if you depend on functionality that will be removed +in Flask 0.11. Previously it was possible to use etags and mimetypes +when file objects were passed. This was unreliable and caused issues +for a few setups. If you get a deprecation warning, make sure to +update your application to work with either filenames there or disable +etag attaching and attach them yourself. + +Old code:: + + return send_file(my_file_object) + return send_file(my_file_object) + +New code:: + + return send_file(my_file_object, add_etags=False) + +.. _upgrading-to-new-teardown-handling: + +Upgrading to new Teardown Handling +`````````````````````````````````` + +We streamlined the behavior of the callbacks for request handling. For +things that modify the response the :meth:`~flask.Flask.after_request` +decorators continue to work as expected, but for things that absolutely +must happen at the end of request we introduced the new +:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that +change also made after-request work differently under error conditions. +It's not consistently skipped if exceptions happen whereas previously it +might have been called twice to ensure it is executed at the end of the +request. + +If you have database connection code that looks like this:: + + @app.after_request + def after_request(response): + g.db.close() + return response + +You are now encouraged to use this instead:: + + @app.teardown_request + def after_request(exception): + if hasattr(g, 'db'): + g.db.close() + +On the upside this change greatly improves the internal code flow and +makes it easier to customize the dispatching and error handling. This +makes it now a lot easier to write unit tests as you can prevent closing +down of database connections for a while. You can take advantage of the +fact that the teardown callbacks are called when the response context is +removed from the stack so a test can query the database after request +handling:: + + with app.test_client() as client: + resp = client.get('/') + # g.db is still bound if there is such a thing + + # and here it's gone + +Manual Error Handler Attaching +`````````````````````````````` + +While it is still possible to attach error handlers to +:attr:`Flask.error_handlers` it's discouraged to do so and in fact +deprecated. In general we no longer recommend custom error handler +attaching via assignments to the underlying dictionary due to the more +complex internal handling to support arbitrary exception classes and +blueprints. See :meth:`Flask.errorhandler` for more information. + +The proper upgrade is to change this:: + + app.error_handlers[403] = handle_error + +Into this:: + + app.register_error_handler(403, handle_error) + +Alternatively you should just attach the function with a decorator:: + + @app.errorhandler(403) + def handle_error(e): + ... + +(Note that :meth:`register_error_handler` is new in Flask 0.7) + +Blueprint Support +````````````````` + +Blueprints replace the previous concept of “Modules” in Flask. They +provide better semantics for various features and work better with large +applications. The update script provided should be able to upgrade your +applications automatically, but there might be some cases where it fails +to upgrade. What changed? + +- Blueprints need explicit names. Modules had an automatic name + guessing scheme where the shortname for the module was taken from the + last part of the import module. The upgrade script tries to guess + that name but it might fail as this information could change at + runtime. +- Blueprints have an inverse behavior for :meth:`url_for`. Previously + ``.foo`` told :meth:`url_for` that it should look for the endpoint + ``foo`` on the application. Now it means “relative to current module”. + The script will inverse all calls to :meth:`url_for` automatically for + you. It will do this in a very eager way so you might end up with + some unnecessary leading dots in your code if you're not using + modules. +- Blueprints do not automatically provide static folders. They will + also no longer automatically export templates from a folder called + :file:`templates` next to their location however but it can be enabled from + the constructor. Same with static files: if you want to continue + serving static files you need to tell the constructor explicitly the + path to the static folder (which can be relative to the blueprint's + module path). +- Rendering templates was simplified. Now the blueprints can provide + template folders which are added to a general template searchpath. + This means that you need to add another subfolder with the blueprint's + name into that folder if you want :file:`blueprintname/template.html` as + the template name. + +If you continue to use the ``Module`` object which is deprecated, Flask will +restore the previous behavior as good as possible. However we strongly +recommend upgrading to the new blueprints as they provide a lot of useful +improvement such as the ability to attach a blueprint multiple times, +blueprint specific error handlers and a lot more. + + +Version 0.6 +----------- + +Flask 0.6 comes with a backwards incompatible change which affects the +order of after-request handlers. Previously they were called in the order +of the registration, now they are called in reverse order. This change +was made so that Flask behaves more like people expected it to work and +how other systems handle request pre- and post-processing. If you +depend on the order of execution of post-request functions, be sure to +change the order. + +Another change that breaks backwards compatibility is that context +processors will no longer override values passed directly to the template +rendering function. If for example ``request`` is as variable passed +directly to the template, the default context processor will not override +it with the current request object. This makes it easier to extend +context processors later to inject additional variables without breaking +existing template not expecting them. + +Version 0.5 +----------- + +Flask 0.5 is the first release that comes as a Python package instead of a +single module. There were a couple of internal refactoring so if you +depend on undocumented internal details you probably have to adapt the +imports. + +The following changes may be relevant to your application: + +- autoescaping no longer happens for all templates. Instead it is + configured to only happen on files ending with ``.html``, ``.htm``, + ``.xml`` and ``.xhtml``. If you have templates with different + extensions you should override the + :meth:`~flask.Flask.select_jinja_autoescape` method. +- Flask no longer supports zipped applications in this release. This + functionality might come back in future releases if there is demand + for this feature. Removing support for this makes the Flask internal + code easier to understand and fixes a couple of small issues that make + debugging harder than necessary. +- The ``create_jinja_loader`` function is gone. If you want to customize + the Jinja loader now, use the + :meth:`~flask.Flask.create_jinja_environment` method instead. + +Version 0.4 +----------- + +For application developers there are no changes that require changes in +your code. In case you are developing on a Flask extension however, and +that extension has a unittest-mode you might want to link the activation +of that mode to the new ``TESTING`` flag. + +Version 0.3 +----------- + +Flask 0.3 introduces configuration support and logging as well as +categories for flashing messages. All these are features that are 100% +backwards compatible but you might want to take advantage of them. + +Configuration Support +````````````````````` + +The configuration support makes it easier to write any kind of application +that requires some sort of configuration. (Which most likely is the case +for any application out there). + +If you previously had code like this:: + + app.debug = DEBUG + app.secret_key = SECRET_KEY + +You no longer have to do that, instead you can just load a configuration +into the config object. How this works is outlined in :ref:`config`. + +Logging Integration +``````````````````` + +Flask now configures a logger for you with some basic and useful defaults. +If you run your application in production and want to profit from +automatic error logging, you might be interested in attaching a proper log +handler. Also you can start logging warnings and errors into the logger +when appropriately. For more information on that, read +:ref:`application-errors`. + +Categories for Flash Messages +````````````````````````````` + +Flash messages can now have categories attached. This makes it possible +to render errors, warnings or regular messages differently for example. +This is an opt-in feature because it requires some rethinking in the code. + +Read all about that in the :ref:`message-flashing-pattern` pattern. diff --git a/docs/views.rst b/docs/views.rst index f2210270..68e88241 100644 --- a/docs/views.rst +++ b/docs/views.rst @@ -1,324 +1,237 @@ -Class-based Views -================= +.. _views: -.. currentmodule:: flask.views +Pluggable Views +=============== -This page introduces using the :class:`View` and :class:`MethodView` -classes to write class-based views. +.. versionadded:: 0.7 -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. +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. -An example of where this is useful is defining a class that creates an -API based on the database model it is initialized with. +Basic Principle +--------------- -For more complex API behavior and customization, look into the various -API extensions for Flask. +Consider you have a function that loads a list of objects from the +database and renders into a template:: - -Basic Reusable View -------------------- - -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. - -.. code-block:: python - - @app.route("/users/") - def user_list(): + @app.route('/users/') + def show_users(page): users = User.query.all() - return render_template("users.html", users=users) + return render_template('users.html', users=users) -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. +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:: -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. - -.. code-block:: python from flask.views import View - class UserList(View): + class ShowUsers(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=UserList.as_view("user_list")) + app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users')) -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`. +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:: -.. note:: - You can't decorate the class with ``@app.route()`` the way you'd - do with a basic view function. - -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. - -.. code-block:: python + from flask.views import View class ListView(View): - def __init__(self, model, template): - self.model = model - self.template = template + + def get_template_name(self): + raise NotImplementedError() + + def render_template(self, context): + return render_template(self.get_template_name(), **context) def dispatch_request(self): - items = self.model.query.all() - return render_template(self.template, items=items) + context = {'objects': self.get_objects()} + return self.render_template(context) -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. + class UserView(ListView): -.. code-block:: python + def get_template_name(self): + return 'users.html' - 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"), - ) + def get_objects(self): + return User.query.all() +This of course is not that helpful for such a small example, but it's good +enough to explain the basic principle. When you have a class-based view +the question comes up what ``self`` points to. The way this works is that +whenever the request is dispatched a new instance of the class is created +and the :meth:`~flask.views.View.dispatch_request` method is called with +the parameters from the URL rule. The class itself is instantiated with +the parameters passed to the :meth:`~flask.views.View.as_view` function. +For instance you can write a class like this:: -URL Variables -------------- - -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 - - 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): - items = self.model.query.all() - return render_template(self.template, items=items) + return render_template(self.template_name) -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(): - ... +And then you can register it like this:: + app.add_url_rule('/about', view_func=RenderTemplateView.as_view( + 'about_page', template_name='about.html')) Method Hints ------------ -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 +Pluggable views are attached to the application like a regular function by +either using :func:`~flask.Flask.route` or better +:meth:`~flask.Flask.add_url_rule`. That however also means that you would +have to provide the names of the HTTP methods the view supports when you +attach this. In order to move that information to the class you can +provide a :attr:`~flask.views.View.methods` attribute that has this +information:: class MyView(View): - methods = ["GET", "POST"] + methods = ['GET', 'POST'] def dispatch_request(self): - if request.method == "POST": + if request.method == 'POST': ... ... - app.add_url_rule('/my-view', view_func=MyView.as_view('my-view')) + app.add_url_rule('/myview', view_func=MyView.as_view('myview')) -This is equivalent to the following, except further subclasses can -inherit or change the methods. +Method Based Dispatching +------------------------ -.. code-block:: python - - app.add_url_rule( - "/my-view", - view_func=MyView.as_view("my-view"), - methods=["GET", "POST"], - ) - - -Method Dispatching and APIs ---------------------------- - -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. - -: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. - -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. - -.. code-block:: python +For RESTful APIs it's especially helpful to execute a different function +for each HTTP method. With the :class:`flask.views.MethodView` you can +easily do that. Each HTTP method maps to a function with the same name +(just in lowercase):: from flask.views import MethodView - class ItemAPI(MethodView): - init_every_request = False - - def __init__(self, model): - self.model = model - self.validator = generate_validator(model) - - def _get_item(self, id): - return self.model.query.get_or_404(id) - - def get(self, id): - item = self._get_item(id) - return jsonify(item.to_json()) - - def patch(self, id): - item = self._get_item(id) - errors = self.validator.validate(item, request.json) - - if errors: - return jsonify(errors), 400 - - item.update_from_json(request.json) - db.session.commit() - return jsonify(item.to_json()) - - def delete(self, id): - item = self._get_item(id) - db.session.delete(item) - db.session.commit() - return "", 204 - - class GroupAPI(MethodView): - init_every_request = False - - def __init__(self, model): - self.model = model - self.validator = generate_validator(model, create=True) + class UserAPI(MethodView): def get(self): - items = self.model.query.all() - return jsonify([item.to_json() for item in items]) + users = User.query.all() + ... def post(self): - errors = self.validator.validate(request.json) + user = User.from_form_data(request.form) + ... - if errors: - return jsonify(errors), 400 + app.add_url_rule('/users/', view_func=UserAPI.as_view('users')) - db.session.add(self.model.from_json(request.json)) - db.session.commit() - return jsonify(item.to_json()) +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. - 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) +Decorating Views +---------------- - register_api(app, User, "users") - register_api(app, Story, "stories") +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:: -This produces the following views, a standard REST API! + 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 -================= ========== =================== -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 -================= ========== =================== + view = user_required(UserAPI.as_view('users')) + app.add_url_rule('/users/', view_func=view) + +Starting with Flask 0.8 there is also an alternative way where you can +specify a list of decorators to apply in the class declaration:: + + class UserAPI(MethodView): + decorators = [user_required] + +Due to the implicit self from the caller's perspective you cannot use +regular view decorators on the individual methods of the view however, +keep this in mind. + +Method Views for APIs +--------------------- + +Web APIs are often working very closely with HTTP verbs so it makes a lot +of sense to implement such an API based on the +:class:`~flask.views.MethodView`. That said, you will notice that the API +will require different URL rules that go to the same method view most of +the time. For instance consider that you are exposing a user object on +the web: + +=============== =============== ====================================== +URL Method Description +--------------- --------------- -------------------------------------- +``/users/`` ``GET`` Gives a list of all users +``/users/`` ``POST`` Creates a new user +``/users/`` ``GET`` Shows a single user +``/users/`` ``PUT`` Updates a single user +``/users/`` ``DELETE`` Deletes a single user +=============== =============== ====================================== + +So how would you go about doing that with the +:class:`~flask.views.MethodView`? The trick is to take advantage of the +fact that you can provide multiple rules to the same view. + +Let's assume for the moment the view would look like this:: + + class UserAPI(MethodView): + + def get(self, user_id): + if user_id is None: + # return a list of users + pass + else: + # expose a single user + pass + + def post(self): + # create a new user + pass + + def delete(self, user_id): + # delete a single user + pass + + def put(self, user_id): + # update a single user + pass + +So how do we hook this up with the routing system? By adding two rules +and explicitly mentioning the methods for each:: + + user_view = UserAPI.as_view('user_api') + app.add_url_rule('/users/', defaults={'user_id': None}, + view_func=user_view, methods=['GET',]) + app.add_url_rule('/users/', view_func=user_view, methods=['POST',]) + app.add_url_rule('/users/', view_func=user_view, + methods=['GET', 'PUT', 'DELETE']) + +If you have a lot of APIs that look similar you can refactor that +registration code:: + + def register_api(view, endpoint, url, pk='id', pk_type='int'): + view_func = view.as_view(endpoint) + app.add_url_rule(url, defaults={pk: None}, + view_func=view_func, methods=['GET',]) + app.add_url_rule(url, view_func=view_func, methods=['POST',]) + app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func, + methods=['GET', 'PUT', 'DELETE']) + + register_api(UserAPI, 'user_api', '/users/', pk='user_id') diff --git a/examples/celery/README.md b/examples/celery/README.md deleted file mode 100644 index 038eb51e..00000000 --- a/examples/celery/README.md +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index f7d138e6..00000000 --- a/examples/celery/make_celery.py +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index cca36d8c..00000000 --- a/examples/celery/pyproject.toml +++ /dev/null @@ -1,17 +0,0 @@ -[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 deleted file mode 100644 index 29075ab5..00000000 --- a/examples/celery/requirements.txt +++ /dev/null @@ -1,58 +0,0 @@ -# -# 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 deleted file mode 100644 index dafff8aa..00000000 --- a/examples/celery/src/task_app/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index b6b3595d..00000000 --- a/examples/celery/src/task_app/tasks.py +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 4e1145cb..00000000 --- a/examples/celery/src/task_app/templates/index.html +++ /dev/null @@ -1,108 +0,0 @@ - - - - - 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 deleted file mode 100644 index 99cf92dc..00000000 --- a/examples/celery/src/task_app/views.py +++ /dev/null @@ -1,38 +0,0 @@ -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/javascript/.gitignore b/examples/javascript/.gitignore index a306afbc..85a35845 100644 --- a/examples/javascript/.gitignore +++ b/examples/javascript/.gitignore @@ -1,4 +1,4 @@ -.venv/ +venv/ *.pyc __pycache__/ instance/ diff --git a/examples/javascript/LICENSE b/examples/javascript/LICENSE new file mode 100644 index 00000000..8f9252f4 --- /dev/null +++ b/examples/javascript/LICENSE @@ -0,0 +1,31 @@ +Copyright © 2010 by the Pallets team. + +Some rights reserved. + +Redistribution and use in source and binary forms of the software as +well as documentation, with or without modification, are permitted +provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF +USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/examples/javascript/LICENSE.txt b/examples/javascript/LICENSE.txt deleted file mode 100644 index 9d227a0c..00000000 --- a/examples/javascript/LICENSE.txt +++ /dev/null @@ -1,28 +0,0 @@ -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/MANIFEST.in b/examples/javascript/MANIFEST.in new file mode 100644 index 00000000..0ba3d5b8 --- /dev/null +++ b/examples/javascript/MANIFEST.in @@ -0,0 +1,4 @@ +include LICENSE +graft js_example/templates +graft tests +global-exclude *.pyc diff --git a/examples/javascript/README.rst b/examples/javascript/README.rst index f5f66912..fc074284 100644 --- a/examples/javascript/README.rst +++ b/examples/javascript/README.rst @@ -3,37 +3,38 @@ 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 +page. Demonstrates using |XMLHttpRequest|_, |fetch|_, and +|jQuery.ajax|_. See the `Flask docs`_ about jQuery and Ajax. .. |XMLHttpRequest| replace:: ``XMLHttpRequest`` .. _XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest +.. |fetch| replace:: ``fetch`` +.. _fetch: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch + .. |jQuery.ajax| replace:: ``jQuery.ajax`` .. _jQuery.ajax: https://api.jquery.com/jQuery.ajax/ -.. _Flask docs: https://flask.palletsprojects.com/patterns/javascript/ +.. _Flask docs: http://flask.pocoo.org/docs/patterns/jquery/ Install ------- -.. code-block:: text +:: - $ python3 -m venv .venv - $ . .venv/bin/activate - $ pip install -e . + python3 -m venv venv + . venv/bin/activate + pip install -e . Run --- -.. code-block:: text +:: - $ flask --app js_example run + export FLASK_APP=js_example + flask run Open http://127.0.0.1:5000 in a browser. @@ -41,8 +42,8 @@ Open http://127.0.0.1:5000 in a browser. Test ---- -.. code-block:: text +:: - $ pip install -e '.[test]' - $ coverage run -m pytest - $ coverage report + 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 index 0ec3ca21..d90fc4d4 100644 --- a/examples/javascript/js_example/__init__.py +++ b/examples/javascript/js_example/__init__.py @@ -2,4 +2,4 @@ from flask import Flask app = Flask(__name__) -from js_example import views # noqa: E402, F401 +from js_example import views diff --git a/examples/javascript/js_example/templates/base.html b/examples/javascript/js_example/templates/base.html index a4d35bd7..50ce0e9c 100644 --- a/examples/javascript/js_example/templates/base.html +++ b/examples/javascript/js_example/templates/base.html @@ -1,7 +1,7 @@ JavaScript Example - - + + diff --git a/examples/javascript/js_example/templates/fetch.html b/examples/javascript/js_example/templates/fetch.html index e2944b85..780ecec5 100644 --- a/examples/javascript/js_example/templates/fetch.html +++ b/examples/javascript/js_example/templates/fetch.html @@ -2,11 +2,14 @@ {% block intro %} fetch - is the modern plain JavaScript way to make requests. It's - supported in all modern browsers. + is the new plain JavaScript way to make requests. It's + supported in all modern browsers except IE, which requires a + polyfill. {% endblock %} {% block script %} + + ') + 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('{{ "