diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml deleted file mode 100644 index 717b588e48..0000000000 --- a/.azure-pipelines.yml +++ /dev/null @@ -1,87 +0,0 @@ -trigger: - - 'master' - - '*.x' - -jobs: - - job: Flask - variables: - vmImage: ubuntu-latest - python.version: '3.7' - python.architecture: 'x64' - TOXENV: 'py,coverage-ci' - publish.test.results: 'true' - - strategy: - matrix: - Python37Linux: - python.version: '3.7' - Python37Windows: - python.version: '3.7' - vmImage: 'windows-latest' - Python37Mac: - python.version: '3.7' - vmImage: 'macos-latest' - Pypy3Linux: - python.version: 'pypy3' - Python36Linux: - python.version: '3.6' - Python35Linux: - python.version: '3.5' - Python27Linux: - python.version: '2.7' - Python27Windows: - python.version: '2.7' - vmImage: 'windows-latest' - DocsHtml: - TOXENV: 'docs-html' - publish.test.results: 'false' - Style: - TOXENV: stylecheck - publish.test.results: 'false' - VersionRange: - TOXENV: 'devel,lowest,coverage-ci' - - pool: - vmImage: $[ variables.vmImage ] - - steps: - - task: UsePythonVersion@0 - inputs: - versionSpec: $(python.version) - architecture: $(python.architecture) - displayName: Use Python $(python.version) - - - script: pip --disable-pip-version-check install -U tox - displayName: Install tox - - - script: tox -- --junitxml=test-results.xml tests examples - displayName: Run tox - - - task: PublishTestResults@2 - inputs: - testResultsFiles: test-results.xml - testRunTitle: $(Agent.JobName) - condition: eq(variables['publish.test.results'], 'true') - displayName: Publish test results - - - task: PublishCodeCoverageResults@1 - inputs: - codeCoverageTool: Cobertura - summaryFileLocation: coverage.xml - condition: eq(variables['publish.test.results'], 'true') - displayName: Publish coverage results - - # Test on the nightly version of Python. - # Use a container since Azure Pipelines may not have the latest build. - - job: FlaskOnNightly - pool: - vmImage: ubuntu-latest - container: python:rc-stretch - steps: - - script: | - echo "##vso[task.prependPath]$HOME/.local/bin" - pip --disable-pip-version-check install --user -U tox - displayName: Install tox - - - script: tox -e nightly - displayName: Run tox diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..45198266c6 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,17 @@ +{ + "name": "pallets/flask", + "image": "mcr.microsoft.com/devcontainers/python:3", + "customizations": { + "vscode": { + "settings": { + "python.defaultInterpreterPath": "${workspaceFolder}/.venv", + "python.terminal.activateEnvInCurrentTerminal": true, + "python.terminal.launchArgs": [ + "-X", + "dev" + ] + } + } + }, + "onCreateCommand": ".devcontainer/on-create-command.sh" +} diff --git a/.devcontainer/on-create-command.sh b/.devcontainer/on-create-command.sh new file mode 100755 index 0000000000..deffa37bfe --- /dev/null +++ b/.devcontainer/on-create-command.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -e + +python3 -m venv .venv +. .venv/bin/activate +pip install -U pip setuptools wheel +pip install -r requirements/dev.txt +pip install -e . +pre-commit install --install-hooks diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..e32c8029d1 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true +end_of_line = lf +charset = utf-8 +max_line_length = 88 + +[*.{yml,yaml,json,js,css,html}] +indent_size = 2 diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000000..8f3b4fd4bc --- /dev/null +++ b/.flake8 @@ -0,0 +1,25 @@ +[flake8] +extend-select = + # bugbear + B + # bugbear opinions + B9 + # implicit str concat + ISC +extend-ignore = + # slice notation whitespace, invalid + E203 + # line length, handled by bugbear B950 + E501 + # bare except, handled by bugbear B001 + E722 + # zip with strict=, requires python >= 3.10 + B905 + # string formatting opinion, B028 renamed to B907 + B028 + B907 +# up to 88 allowed by bugbear B950 +max-line-length = 80 +per-file-ignores = + # __init__ exports names + src/flask/__init__.py: F401 diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 8d41b16a4e..0000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,33 +0,0 @@ -**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 extra information that may be useful / related to your problem. -Ideally, create an [MCVE](https://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 new file mode 100644 index 0000000000..c2a15eeee8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,27 @@ +--- +name: Bug report +about: Report a bug in Flask (not other projects which depend on Flask) +--- + + + + + + + +Environment: + +- Python version: +- Flask version: diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000..abe3915622 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: Security issue + url: security@palletsprojects.com + about: Do not report security issues publicly. Email our security contact. + - name: Questions + url: https://stackoverflow.com/questions/tagged/flask?tab=Frequent + about: Search for and ask questions about your code on Stack Overflow. + - name: Questions and discussions + url: https://discord.gg/pallets + about: Discuss questions about your code on our Discord chat. diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md new file mode 100644 index 0000000000..52c2aed416 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.md @@ -0,0 +1,15 @@ +--- +name: Feature request +about: Suggest a new feature for Flask +--- + + + + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 9dda856ca1..0000000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,16 +0,0 @@ -Describe what this patch does to fix the issue. - -Link to any relevant issues or pull requests. - - diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000000..fcfac71bfc --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +If you believe you have identified a security issue with a Pallets +project, **do not open a public issue**. To responsibly report a +security issue, please email security@palletsprojects.com. A security +team member will contact you acknowledging the report and how to +continue. + +Be sure to include as much detail as necessary in your report. As with +reporting normal issues, a minimal reproducible example will help the +maintainers address the issue faster. If you are able, you may also +include a fix for the issue generated with `git format-patch`. + +The current and previous release will receive security patches, with +older versions evaluated based on usage information and severity. + +After fixing an issue, we will make a security release along with an +announcement on our blog. We may obtain a CVE id as well. You may +include a name and link if you would like to be credited for the report. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..90f94bc32b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,9 @@ +version: 2 +updates: +- package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + day: "monday" + time: "16:00" + timezone: "UTC" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..29fd35f855 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,30 @@ + + + + +- fixes # + + + +Checklist: + +- [ ] Add tests that demonstrate the correct behavior of the change. Tests should fail without the change. +- [ ] Add or update relevant docs, in the docs folder and in code. +- [ ] Add an entry in `CHANGES.rst` summarizing the change and linking to the issue. +- [ ] Add `.. versionchanged::` entries in any relevant code docs. +- [ ] Run `pre-commit` hooks and fix any issues. +- [ ] Run `pytest` and `tox`, no tests failed. diff --git a/.github/workflows/lock.yaml b/.github/workflows/lock.yaml new file mode 100644 index 0000000000..c790fae5cb --- /dev/null +++ b/.github/workflows/lock.yaml @@ -0,0 +1,25 @@ +name: 'Lock threads' +# Lock closed issues that have not received any further activity for +# two weeks. This does not close open issues, only humans may do that. +# We find that it is easier to respond to new issues with fresh examples +# rather than continuing discussions on old issues. + +on: + schedule: + - cron: '0 0 * * *' + +permissions: + issues: write + pull-requests: write + +concurrency: + group: lock + +jobs: + lock: + runs-on: ubuntu-latest + steps: + - uses: dessant/lock-threads@c1b35aecc5cdb1a34539d14196df55838bb2f836 + with: + issue-inactive-days: 14 + pr-inactive-days: 14 diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml new file mode 100644 index 0000000000..45a9c51b33 --- /dev/null +++ b/.github/workflows/publish.yaml @@ -0,0 +1,72 @@ +name: Publish +on: + push: + tags: + - '*' +jobs: + build: + runs-on: ubuntu-latest + outputs: + hash: ${{ steps.hash.outputs.hash }} + steps: + - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 + - uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 + with: + python-version: '3.x' + cache: 'pip' + cache-dependency-path: 'requirements/*.txt' + - run: pip install -r requirements/build.txt + # Use the commit date instead of the current date during the build. + - run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV + - run: python -m build + # Generate hashes used for provenance. + - name: generate hash + id: hash + run: cd dist && echo "hash=$(sha256sum * | base64 -w0)" >> $GITHUB_OUTPUT + - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce + with: + path: ./dist + provenance: + needs: ['build'] + permissions: + actions: read + id-token: write + contents: write + # Can't pin with hash due to how this workflow works. + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.5.0 + with: + base64-subjects: ${{ needs.build.outputs.hash }} + create-release: + # Upload the sdist, wheels, and provenance to a GitHub release. They remain + # available as build artifacts for a while as well. + needs: ['provenance'] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a + - name: create release + run: > + gh release create --draft --repo ${{ github.repository }} + ${{ github.ref_name }} + *.intoto.jsonl/* artifact/* + env: + GH_TOKEN: ${{ github.token }} + publish-pypi: + needs: ['provenance'] + # Wait for approval before attempting to upload to PyPI. This allows reviewing the + # files in the draft release. + environment: 'publish' + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a + # Try uploading to Test PyPI first, in case something fails. + - uses: pypa/gh-action-pypi-publish@29930c9cf57955dc1b98162d0d8bc3ec80d9e75c + with: + repository_url: https://test.pypi.org/legacy/ + packages_dir: artifact/ + - uses: pypa/gh-action-pypi-publish@29930c9cf57955dc1b98162d0d8bc3ec80d9e75c + with: + packages_dir: artifact/ diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 0000000000..79c382fec0 --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,57 @@ +name: Tests +on: + push: + branches: + - main + - '*.x' + paths-ignore: + - 'docs/**' + - '*.md' + - '*.rst' + pull_request: + branches: + - main + - '*.x' + paths-ignore: + - 'docs/**' + - '*.md' + - '*.rst' +jobs: + tests: + name: ${{ matrix.name }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - {name: Linux, python: '3.11', os: ubuntu-latest, tox: py311} + - {name: Windows, python: '3.11', os: windows-latest, tox: py311} + - {name: Mac, python: '3.11', os: macos-latest, tox: py311} + - {name: '3.12-dev', python: '3.12-dev', os: ubuntu-latest, tox: py312} + - {name: '3.10', python: '3.10', os: ubuntu-latest, tox: py310} + - {name: '3.9', python: '3.9', os: ubuntu-latest, tox: py39} + - {name: '3.8', python: '3.8', os: ubuntu-latest, tox: py38} + - {name: 'PyPy', python: 'pypy-3.9', os: ubuntu-latest, tox: pypy39} + - {name: 'Minimum Versions', python: '3.11', os: ubuntu-latest, tox: py311-min} + - {name: 'Development Versions', python: '3.8', os: ubuntu-latest, tox: py38-dev} + - {name: Typing, python: '3.11', os: ubuntu-latest, tox: typing} + steps: + - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 + - uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 + with: + python-version: ${{ matrix.python }} + cache: 'pip' + cache-dependency-path: 'requirements/*.txt' + - name: update pip + run: | + pip install -U wheel + pip install -U setuptools + python -m pip install -U pip + - name: cache mypy + uses: actions/cache@88522ab9f39a2ea568f7027eddc7d8d8bc9d59c8 + with: + path: ./.mypy_cache + key: mypy|${{ matrix.python }}|${{ hashFiles('pyproject.toml') }} + if: matrix.tox == 'typing' + - run: pip install tox + - run: tox run -e ${{ matrix.tox }} diff --git a/.gitignore b/.gitignore index 8a32355538..e6713351c1 100644 --- a/.gitignore +++ b/.gitignore @@ -4,17 +4,19 @@ *.pyc *.pyo env/ +venv/ +.venv/ env* dist/ build/ *.egg *.egg-info/ -_mailinglist .tox/ .cache/ .pytest_cache/ .idea/ docs/_build/ +.vscode # Coverage reports htmlcov/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6d2a2f1f24..79b632ae84 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,23 +1,37 @@ +ci: + autoupdate_branch: "2.2.x" + autoupdate_schedule: monthly repos: + - repo: https://github.com/asottile/pyupgrade + rev: v3.3.2 + hooks: + - id: pyupgrade + args: ["--py38-plus"] - repo: https://github.com/asottile/reorder_python_imports - rev: v1.5.0 + rev: v3.9.0 hooks: - id: reorder-python-imports name: Reorder Python imports (src, tests) files: "^(?!examples/)" - args: ["--application-directories", ".:src"] - - repo: https://github.com/python/black - rev: 19.3b0 + args: ["--application-directories", "src"] + - repo: https://github.com/psf/black + rev: 23.3.0 hooks: - id: black - - repo: https://gitlab.com/pycqa/flake8 - rev: 3.7.7 + - repo: https://github.com/PyCQA/flake8 + rev: 6.0.0 hooks: - id: flake8 - additional_dependencies: [flake8-bugbear] + additional_dependencies: + - flake8-bugbear + - flake8-implicit-str-concat + - repo: https://github.com/peterdemin/pip-compile-multi + rev: v2.6.2 + hooks: + - id: pip-compile-multi-verify - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.2.3 + rev: v4.4.0 hooks: - - id: check-byte-order-marker + - id: fix-byte-order-marker - id: trailing-whitespace - id: end-of-file-fixer diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000000..346900b200 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,13 @@ +version: 2 +build: + os: ubuntu-20.04 + tools: + python: "3.10" +python: + install: + - requirements: requirements/docs.txt + - method: pip + path: . +sphinx: + builder: dirhtml + fail_on_warning: true diff --git a/CHANGES.rst b/CHANGES.rst index dddddbdc0e..1ba0f341a7 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,4 +1,518 @@ -.. currentmodule:: flask +Version 2.3.2 +------------- + +Released 2022-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. + + +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.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 ``setuptools`` 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 ------------- @@ -25,31 +539,29 @@ Released 2019-07-04 base ``HTTPException``. This makes error handler behavior more consistent. :pr:`3266` - - :meth:`Flask.finalize_request` is called for all unhandled + - ``Flask.finalize_request`` is called for all unhandled exceptions even if there is no ``500`` error handler. -- :attr:`Flask.logger` takes the same name as - :attr:`Flask.name` (the value passed as - ``Flask(import_name)``. This reverts 1.0's behavior of always - logging to ``"flask.app"``, in order to support multiple apps in the - same process. A warning will be shown if old configuration is +- ``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` -- :meth:`flask.RequestContext.copy` includes the current session - object in the request context copy. This prevents ``session`` - pointing to an out-of-date object. :issue:`2935` +- ``RequestContext.copy`` includes the current session object in the + request context copy. This prevents ``session`` pointing to an + out-of-date object. :issue:`2935` - Using built-in RequestContext, unprintable Unicode characters in Host header will result in a HTTP 400 response and not HTTP 500 as previously. :pr:`2994` -- :func:`send_file` supports :class:`~os.PathLike` objects as - described in PEP 0519, to support :mod:`pathlib` in Python 3. - :pr:`3059` -- :func:`send_file` supports :class:`~io.BytesIO` partial content. +- ``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` -- :func:`open_resource` accepts the "rt" file mode. This still does - the same thing as "r". :issue:`3163` -- The :attr:`MethodView.methods` attribute set in a base class is used - by subclasses. :issue:`3138` -- :attr:`Flask.jinja_options` is a ``dict`` instead of an +- ``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 @@ -63,15 +575,14 @@ Released 2019-07-04 :issue:`3134` - Support empty ``static_folder`` without requiring setting an empty ``static_url_path`` as well. :pr:`3124` -- :meth:`jsonify` supports :class:`dataclasses.dataclass` objects. - :pr:`3195` -- Allow customizing the :attr:`Flask.url_map_class` used for routing. +- ``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 :meth:`cli.load_dotenv` is more consistent - with the documentation. It will return ``False`` if python-dotenv is - not installed, or if the given path isn't a file. :issue:`2937` +- 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 @@ -110,7 +621,7 @@ Released 2019-07-04 requires upgrading to Werkzeug 0.15.5. :issue:`3249` - ``send_file`` url quotes the ":" and "/" characters for more compatible UTF-8 filename support in some browsers. :issue:`3074` -- Fixes for PEP451 import loaders and pytest 5.x. :issue:`3275` +- Fixes for :pep:`451` import loaders and pytest 5.x. :issue:`3275` - Show message about dotenv on stderr instead of stdout. :issue:`3285` @@ -119,16 +630,16 @@ Version 1.0.3 Released 2019-05-17 -- :func:`send_file` encodes filenames as ASCII instead of Latin-1 +- ``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` + stricter about header encodings than :pep:`3333`. :issue:`2766` - Allow custom CLIs using ``FlaskGroup`` to set the debug flag without it always being overwritten based on environment variables. :pr:`2765` - ``flask --version`` outputs Werkzeug's version and simplifies the Python version. :pr:`2825` -- :func:`send_file` handles an ``attachment_filename`` that is a - native Python 2 string (bytes) with UTF-8 coded bytes. :issue:`2933` +- ``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 @@ -176,32 +687,30 @@ Released 2018-04-26 - Bump minimum dependency versions to the latest stable versions: Werkzeug >= 0.14, Jinja >= 2.10, itsdangerous >= 0.24, Click >= 5.1. :issue:`2586` -- Skip :meth:`app.run ` when a Flask application is run - from the command line. This avoids some behavior that was confusing - to debug. -- Change the default for :data:`JSONIFY_PRETTYPRINT_REGULAR` to - ``False``. :func:`~json.jsonify` returns a compact format by - default, and an indented format in debug mode. :pr:`2193` -- :meth:`Flask.__init__ ` accepts the ``host_matching`` - argument and sets it on :attr:`~Flask.url_map`. :issue:`1559` -- :meth:`Flask.__init__ ` accepts the ``static_host`` argument - and passes it as the ``host`` argument when defining the static - route. :issue:`1559` -- :func:`send_file` supports Unicode in ``attachment_filename``. +- 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 :func:`url_for` to - :meth:`~Flask.handle_url_build_error`. :pr:`2017` -- :meth:`~Flask.add_url_rule` accepts the - ``provide_automatic_options`` argument to disable adding the - ``OPTIONS`` method. :pr:`1489` -- :class:`~views.MethodView` subclasses inherit method handlers from - base classes. :pr:`1936` +- Pass ``_scheme`` argument from ``url_for`` to + ``Flask.handle_url_build_error``. :pr:`2017` +- ``Flask.add_url_rule`` accepts the ``provide_automatic_options`` + argument to disable adding the ``OPTIONS`` method. :pr:`1489` +- ``MethodView`` subclasses inherit method handlers from base classes. + :pr:`1936` - Errors caused while opening the session at the beginning of the request are handled by the app's error handlers. :pr:`2254` -- Blueprints gained :attr:`~Blueprint.json_encoder` and - :attr:`~Blueprint.json_decoder` attributes to override the app's +- Blueprints gained ``Blueprint.json_encoder`` and + ``Blueprint.json_decoder`` attributes to override the app's encoder and decoder. :pr:`1898` -- :meth:`Flask.make_response` raises ``TypeError`` instead of +- ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for bad response types. The error messages have been improved to describe why the type is invalid. :pr:`2256` - Add ``routes`` CLI command to output routes registered on the @@ -216,52 +725,49 @@ Released 2018-04-26 ``make_app`` from ``FLASK_APP``. :pr:`2297` - Factory functions are not required to take a ``script_info`` parameter to work with the ``flask`` command. If they take a single - parameter or a parameter named ``script_info``, the - :class:`~cli.ScriptInfo` object will be passed. :pr:`2319` + parameter or a parameter named ``script_info``, the ``ScriptInfo`` + object will be passed. :pr:`2319` - ``FLASK_APP`` can be set to an app factory, with arguments if needed, for example ``FLASK_APP=myproject.app:create_app('dev')``. :pr:`2326` - ``FLASK_APP`` can point to local packages that are not installed in editable mode, although ``pip install -e`` is still preferred. :pr:`2414` -- The :class:`~views.View` class attribute - :attr:`~views.View.provide_automatic_options` is set in - :meth:`~views.View.as_view`, to be detected by - :meth:`~Flask.add_url_rule`. :pr:`2316` +- The ``View`` class attribute + ``View.provide_automatic_options`` is set in ``View.as_view``, to be + detected by ``Flask.add_url_rule``. :pr:`2316` - Error handling will try handlers registered for ``blueprint, code``, ``app, code``, ``blueprint, exception``, ``app, exception``. :pr:`2314` - ``Cookie`` is added to the response's ``Vary`` header if the session is accessed at all during the request (and not deleted). :pr:`2288` -- :meth:`~Flask.test_request_context` accepts ``subdomain`` and +- ``Flask.test_request_context`` accepts ``subdomain`` and ``url_scheme`` arguments for use when building the base URL. :pr:`1621` -- Set :data:`APPLICATION_ROOT` to ``'/'`` by default. This was already - the implicit default when it was set to ``None``. -- :data:`TRAP_BAD_REQUEST_ERRORS` is enabled by default in debug mode. +- Set ``APPLICATION_ROOT`` to ``'/'`` by default. This was already the + implicit default when it was set to ``None``. +- ``TRAP_BAD_REQUEST_ERRORS`` is enabled by default in debug mode. ``BadRequestKeyError`` has a message with the bad key in debug mode instead of the generic bad request message. :pr:`2348` -- Allow registering new tags with - :class:`~json.tag.TaggedJSONSerializer` to support storing other - types in the session cookie. :pr:`2352` +- Allow registering new tags with ``TaggedJSONSerializer`` to support + storing other types in the session cookie. :pr:`2352` - Only open the session if the request has not been pushed onto the - context stack yet. This allows :func:`~stream_with_context` - generators to access the same session that the containing view uses. - :pr:`2354` + context stack yet. This allows ``stream_with_context`` generators to + access the same session that the containing view uses. :pr:`2354` - Add ``json`` keyword argument for the test client request methods. This will dump the given object as JSON and set the appropriate content type. :pr:`2358` -- Extract JSON handling to a mixin applied to both the - :class:`Request` and :class:`Response` classes. This adds the - :meth:`~Response.is_json` and :meth:`~Response.get_json` methods to - the response to make testing JSON response much easier. :pr:`2358` +- Extract JSON handling to a mixin applied to both the ``Request`` and + ``Response`` classes. This adds the ``Response.is_json`` and + ``Response.get_json`` methods to the response to make testing JSON + response much easier. :pr:`2358` - Removed error handler caching because it caused unexpected results for some exception inheritance hierarchies. Register handlers explicitly for each exception if you want to avoid traversing the MRO. :pr:`2362` - Fix incorrect JSON encoding of aware, non-UTC datetimes. :pr:`2374` - Template auto reloading will honor debug mode even even if - :attr:`~Flask.jinja_env` was already accessed. :pr:`2373` + ``Flask.jinja_env`` was already accessed. :pr:`2373` - The following old deprecated code was removed. :issue:`2385` - ``flask.ext`` - import extensions directly by their name instead @@ -269,57 +775,55 @@ Released 2018-04-26 ``import flask.ext.sqlalchemy`` becomes ``import flask_sqlalchemy``. - ``Flask.init_jinja_globals`` - extend - :meth:`Flask.create_jinja_environment` instead. + ``Flask.create_jinja_environment`` instead. - ``Flask.error_handlers`` - tracked by - :attr:`Flask.error_handler_spec`, use :meth:`Flask.errorhandler` + ``Flask.error_handler_spec``, use ``Flask.errorhandler`` to register handlers. - ``Flask.request_globals_class`` - use - :attr:`Flask.app_ctx_globals_class` instead. - - ``Flask.static_path`` - use :attr:`Flask.static_url_path` - instead. - - ``Request.module`` - use :attr:`Request.blueprint` instead. - -- The :attr:`Request.json` property is no longer deprecated. - :issue:`1421` -- Support passing a :class:`~werkzeug.test.EnvironBuilder` or ``dict`` - to :meth:`test_client.open `. :pr:`2412` -- The ``flask`` command and :meth:`Flask.run` will load environment + ``Flask.app_ctx_globals_class`` instead. + - ``Flask.static_path`` - use ``Flask.static_url_path`` instead. + - ``Request.module`` - use ``Request.blueprint`` instead. + +- The ``Request.json`` property is no longer deprecated. :issue:`1421` +- Support passing a ``EnvironBuilder`` or ``dict`` to + ``test_client.open``. :pr:`2412` +- The ``flask`` command and ``Flask.run`` will load environment variables from ``.env`` and ``.flaskenv`` files if python-dotenv is installed. :pr:`2416` - When passing a full URL to the test client, the scheme in the URL is - used instead of :data:`PREFERRED_URL_SCHEME`. :pr:`2430` -- :attr:`Flask.logger` has been simplified. ``LOGGER_NAME`` and + used instead of ``PREFERRED_URL_SCHEME``. :pr:`2430` +- ``Flask.logger`` has been simplified. ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` config was removed. The logger is always named ``flask.app``. The level is only set on first access, it - doesn't check :attr:`Flask.debug` each time. Only one format is - used, not different ones depending on :attr:`Flask.debug`. No - handlers are removed, and a handler is only added if no handlers are - already configured. :pr:`2436` + doesn't check ``Flask.debug`` each time. Only one format is used, + not different ones depending on ``Flask.debug``. No handlers are + removed, and a handler is only added if no handlers are already + configured. :pr:`2436` - Blueprint view function names may not contain dots. :pr:`2450` - Fix a ``ValueError`` caused by invalid ``Range`` requests in some cases. :issue:`2526` - The development server uses threads by default. :pr:`2529` -- Loading config files with ``silent=True`` will ignore - :data:`~errno.ENOTDIR` errors. :pr:`2581` +- Loading config files with ``silent=True`` will ignore ``ENOTDIR`` + errors. :pr:`2581` - Pass ``--cert`` and ``--key`` options to ``flask run`` to run the development server over HTTPS. :pr:`2606` -- Added :data:`SESSION_COOKIE_SAMESITE` to control the ``SameSite`` +- Added ``SESSION_COOKIE_SAMESITE`` to control the ``SameSite`` attribute on the session cookie. :pr:`2607` -- Added :meth:`~flask.Flask.test_cli_runner` to create a Click runner - that can invoke Flask CLI commands for testing. :pr:`2636` +- Added ``Flask.test_cli_runner`` to create a Click runner that can + invoke Flask CLI commands for testing. :pr:`2636` - Subdomain matching is disabled by default and setting - :data:`SERVER_NAME` does not implicitly enable it. It can be enabled - by passing ``subdomain_matching=True`` to the ``Flask`` constructor. + ``SERVER_NAME`` does not implicitly enable it. It can be enabled by + passing ``subdomain_matching=True`` to the ``Flask`` constructor. :pr:`2635` - A single trailing slash is stripped from the blueprint ``url_prefix`` when it is registered with the app. :pr:`2629` -- :meth:`Request.get_json` doesn't cache the result if parsing fails - when ``silent`` is true. :issue:`2651` -- :func:`Request.get_json` no longer accepts arbitrary encodings. - Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but - Flask will autodetect UTF-8, -16, or -32. :pr:`2691` -- Added :data:`MAX_COOKIE_SIZE` and :attr:`Response.max_cookie_size` - to control when Werkzeug warns about large cookies that browsers may +- ``Request.get_json`` doesn't cache the result if parsing fails when + ``silent`` is true. :issue:`2651` +- ``Request.get_json`` no longer accepts arbitrary encodings. Incoming + JSON should be encoded using UTF-8 per :rfc:`8259`, but Flask will + autodetect UTF-8, -16, or -32. :pr:`2691` +- Added ``MAX_COOKIE_SIZE`` and ``Response.max_cookie_size`` to + control when Werkzeug warns about large cookies that browsers may ignore. :pr:`2693` - Updated documentation theme to make docs look better in small windows. :pr:`2709` @@ -328,6 +832,14 @@ Released 2018-04-26 :pr:`2676` +Version 0.12.5 +-------------- + +Released 2020-02-10 + +- Pin Werkzeug to < 1.0.0. :issue:`3497` + + Version 0.12.4 -------------- @@ -341,7 +853,7 @@ Version 0.12.3 Released 2018-04-26 -- :func:`Request.get_json` no longer accepts arbitrary encodings. +- ``Request.get_json`` no longer accepts arbitrary encodings. Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but Flask will autodetect UTF-8, -16, or -32. :issue:`2692` - Fix a Python warning about imports when using ``python -m flask``. @@ -411,13 +923,12 @@ Version 0.11 Released 2016-05-29, codename Absinthe -- Added support to serializing top-level arrays to - :func:`flask.jsonify`. This introduces a security risk in ancient - browsers. See :ref:`json-security` for details. +- Added support to serializing top-level arrays to ``jsonify``. This + introduces a security risk in ancient browsers. - 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 ``**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 @@ -427,9 +938,9 @@ Released 2016-05-29, codename Absinthe - 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`. +- 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. @@ -437,7 +948,7 @@ Released 2016-05-29, codename Absinthe 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 +- 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 @@ -448,7 +959,7 @@ Released 2016-05-29, codename Absinthe 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`. +- 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. @@ -466,9 +977,7 @@ Released 2016-05-29, codename Absinthe space included by default after separators. - JSON responses are now terminated with a newline character, because it is a convention that UNIX text files end with a newline and some - clients don't deal well when this newline is missing. This came up - originally as a part of - https://github.com/postmanlabs/httpbin/issues/168. :pr:`1262` + 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` @@ -488,9 +997,9 @@ Released 2016-05-29, codename Absinthe - Exceptions during teardown handling will no longer leave bad application contexts lingering around. - Fixed broken ``test_appcontext_signals()`` test case. -- Raise an :exc:`AttributeError` in :func:`flask.helpers.find_package` - with a useful message explaining why it is raised when a PEP 302 - import hook is used without an ``is_package()`` method. +- 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 @@ -528,8 +1037,7 @@ Version 0.10 Released 2013-06-13, codename Limoncello - Changed default cookie serialization format from pickle to JSON to - limit the impact an attacker can do if the secret key leaks. See - :ref:`upgrading-to-010` for more information. + 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 @@ -537,7 +1045,7 @@ Released 2013-06-13, codename Limoncello - 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 +- ``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. @@ -558,8 +1066,7 @@ Released 2013-06-13, codename Limoncello - 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. + 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 @@ -608,12 +1115,12 @@ Version 0.9 Released 2012-07-01, codename Campari -- The :func:`flask.Request.on_json_loading_failed` now returns a JSON - formatted response by default. -- The :func:`flask.url_for` function now can generate anchors to the - generated links. -- The :func:`flask.url_for` function now can also explicitly generate - URL rules specific to a given HTTP method. +- 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 @@ -625,42 +1132,41 @@ Released 2012-07-01, codename Campari - 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. +- 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, :meth:`flask.Blueprint.app_template_filter`. + application wide, ``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. + ``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 :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. +- 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 :class:`flask.Response`. This allows for returning + an instance of ``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 +- ``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 @@ -672,14 +1178,13 @@ Released 2012-07-01, codename Campari - 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 ``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 :func:`flask.after_this_request`. -- Added :func:`flask.stream_with_context` and the ability to push - contexts multiple times without producing unexpected behavior. +- Added ``flask.after_this_request``. +- Added ``flask.stream_with_context`` and the ability to push contexts + multiple times without producing unexpected behavior. Version 0.8.1 @@ -712,8 +1217,8 @@ Released 2011-09-29, codename Rakija 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`) + 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 @@ -723,22 +1228,22 @@ Released 2011-09-29, codename Rakija 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`. + etc. - Added the ``APPLICATION_ROOT`` configuration variable. -- Implemented :meth:`~flask.testing.TestClient.session_transaction` to - easily modify sessions from the test environment. +- 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 :attr:`flask.views.View.decorators` to support simpler - decorating of pluggable (class-based) views. +- 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 :mod:`flask.ext` package to import - extensions from. +- 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 @@ -771,14 +1276,13 @@ Version 0.7 Released 2011-06-28, codename Grappa -- Added :meth:`~flask.Flask.make_default_options_response` which can - be used by subclasses to alter the default behavior for ``OPTIONS`` - responses. -- Unbound locals now raise a proper :exc:`RuntimeError` instead of an - :exc:`AttributeError`. +- 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 :func:`flask.send_file` because it was unreliable. - Pass filenames instead or attach your own etags and provide a proper + 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 @@ -803,17 +1307,16 @@ Released 2011-06-28, codename Grappa - 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` + longer executed when an exception is raised. +- Implemented ``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` + ``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 :func:`flask.get_flashed_messages` if - there are no messages in the session. +- 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 @@ -821,7 +1324,7 @@ Released 2011-06-28, codename Grappa 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). +- Implemented generic class-based views. Version 0.6.1 @@ -855,29 +1358,25 @@ Released 2010-07-27, codename Whisky - 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``. +- ``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 +- 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 :func:`flask.make_response` function that simplifies - creating response object instances in views. +- 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. + 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. + 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. -.. _blinker: https://pypi.org/project/blinker/ - Version 0.5.2 ------------- @@ -911,8 +1410,8 @@ Released 2010-07-06, codename Calvados 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. +- ``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. @@ -928,9 +1427,8 @@ Released 2010-06-18, codename Rakia - Added the ability to register application wide error handlers from modules. -- :meth:`~flask.Flask.after_request` handlers are now also invoked if - the request dies with an exception and an error handling page kicks - in. +- ``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. @@ -945,8 +1443,8 @@ Version 0.3.1 Released 2010-05-28 -- Fixed a error reporting bug with :meth:`flask.Config.from_envvar` -- Removed some unused code from flask +- 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) @@ -958,9 +1456,9 @@ Version 0.3 Released 2010-05-28, codename Schnaps - Added support for categories for flashed messages. -- The application now configures a :class:`logging.Handler` and will - log request handling exceptions to that logger when not in debug - mode. This makes it possible to receive mails on server errors for +- 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. @@ -976,14 +1474,13 @@ Released 2010-05-12, codename J?germeister - Various bugfixes - Integrated JSON support -- Added :func:`~flask.get_template_attribute` helper function. -- :meth:`~flask.Flask.add_url_rule` can now also register a view - function. +- 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 :func:`~flask.send_file` +- 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. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 80d7716467..24daa729d0 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -3,191 +3,236 @@ 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 ``#get-help`` channel on our Discord chat: https://discordapp.com/invite/t6rrQZH +Please don't use the issue tracker for this. The issue tracker is a tool +to address bugs and feature requests in Flask itself. Use one of the +following resources for questions about using Flask or issues with your +own code: - * The IRC channel ``#pocoo`` on FreeNode is linked to Discord, but - Discord is preferred. +- The ``#questions`` channel on our Discord chat: + https://discord.gg/pallets +- Ask on `Stack Overflow`_. Search with Google first using: + ``site:stackoverflow.com flask {search term, exception message, etc.}`` +- Ask on our `GitHub Discussions`_ for long term discussion or larger + 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?tab=Frequent +.. _GitHub Discussions: https://github.com/pallets/flask/discussions -.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?sort=linked Reporting issues ---------------- -- Describe what you expected to happen. -- If possible, include a `minimal reproducible example`_ to help us - identify the issue. This also helps check that the issue is not with - your own code. -- Describe what actually happened. Include the full traceback if there was an - exception. -- List your Python, Flask, and Werkzeug versions. If possible, check if this - issue is already fixed in the repository. +Include the following information in your post: + +- Describe what you expected to happen. +- If possible, include a `minimal reproducible example`_ to help us + identify the issue. This also helps check that the issue is not with + your own code. +- Describe what actually happened. Include the full traceback if there + was an exception. +- List your Python and Flask versions. If possible, check if this + issue is already fixed in the latest releases or the latest code in + the repository. .. _minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example + Submitting patches ------------------ -- Use `Black`_ to autoformat your code. This should be done for you as a - git `pre-commit`_ hook, which gets installed when you run ``pip install -e .[dev]``. - You may also wish to use Black's `Editor integration`_. -- Include tests if your patch is supposed to solve a bug, and explain - clearly under which circumstances the bug happens. Make sure the test fails - without your patch. -- Include a string like "Fixes #123" in your commit message - (where 123 is the issue you fixed). - See `Closing issues using keywords - `__. +If there is not an open issue for what you want to submit, prefer +opening one for discussion before working on a PR. You can work on any +issue that doesn't have an open PR linked to it or a maintainer assigned +to it. These show up in the sidebar. No need to ask if you can work on +an issue that interests you. + +Include the following in your patch: + +- Use `Black`_ to format your code. This and other tools will run + automatically if you install `pre-commit`_ using the instructions + below. +- Include tests if your patch adds or changes code. Make sure the test + fails without your patch. +- Update any relevant docs pages and docstrings. Docs pages and + docstrings should be wrapped at 72 characters. +- Add an entry in ``CHANGES.rst``. Use the same style as other + entries. Also include ``.. versionchanged::`` inline changelogs in + relevant docstrings. + +.. _Black: https://black.readthedocs.io +.. _pre-commit: https://pre-commit.com + + +First time setup using GitHub Codespaces +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +`GitHub Codespaces`_ creates a development environment that is already set up for the +project. By default it opens in Visual Studio Code for the Web, but this can +be changed in your GitHub profile settings to use Visual Studio Code or JetBrains +PyCharm on your local computer. -First time setup -~~~~~~~~~~~~~~~~ +- Make sure you have a `GitHub account`_. +- From the project's repository page, click the green "Code" button and then "Create + codespace on main". +- The codespace will be set up, then Visual Studio Code will open. However, you'll + need to wait a bit longer for the Python extension to be installed. You'll know it's + ready when the terminal at the bottom shows that the virtualenv was activated. +- Check out a branch and `start coding`_. -- Download and install the `latest version of git`_. -- Configure git with your `username`_ and `email`_:: +.. _GitHub Codespaces: https://docs.github.com/en/codespaces +.. _devcontainer: https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers - git config --global user.name 'your name' - git config --global user.email 'your email' +First time setup in your local environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Make sure you have a `GitHub account`_. -- Fork Flask to your GitHub account by clicking the `Fork`_ button. -- `Clone`_ your GitHub fork locally:: +- Make sure you have a `GitHub account`_. +- Download and install the `latest version of git`_. +- Configure git with your `username`_ and `email`_. - git clone https://github.com/{username}/flask - cd flask + .. code-block:: text -- Add the main repository as a remote to update later:: + $ git config --global user.name 'your name' + $ git config --global user.email 'your email' - git remote add pallets https://github.com/pallets/flask - git fetch pallets +- Fork Flask to your GitHub account by clicking the `Fork`_ button. +- `Clone`_ your fork locally, replacing ``your-username`` in the command below with + your actual username. -- Create a virtualenv:: + .. code-block:: text - python3 -m venv env - . env/bin/activate - # or "env\Scripts\activate" on Windows + $ git clone https://github.com/your-username/flask + $ cd flask -- Install Flask in editable mode with development dependencies:: +- Create a virtualenv. Use the latest version of Python. - pip install -e ".[dev]" + - Linux/macOS -- Install the pre-commit hooks: + .. code-block:: text - pre-commit install --install-hooks + $ python3 -m venv .venv + $ . .venv/bin/activate + + - Windows + + .. code-block:: text + + > py -3 -m venv .venv + > .venv\Scripts\activate + +- Install the development dependencies, then install Flask in editable mode. + + .. code-block:: text + + $ python -m pip install -U pip setuptools wheel + $ pip install -r requirements/dev.txt && pip install -e . + +- Install the pre-commit hooks. + + .. code-block:: text + + $ pre-commit install --install-hooks .. _GitHub account: https://github.com/join .. _latest version of git: https://git-scm.com/downloads -.. _username: https://help.github.com/en/articles/setting-your-username-in-git -.. _email: https://help.github.com/en/articles/setting-your-commit-email-address-in-git +.. _username: https://docs.github.com/en/github/using-git/setting-your-username-in-git +.. _email: https://docs.github.com/en/github/setting-up-and-managing-your-github-user-account/setting-your-commit-email-address .. _Fork: https://github.com/pallets/flask/fork -.. _Clone: https://help.github.com/en/articles/fork-a-repo#step-2-create-a-local-clone-of-your-fork +.. _Clone: https://docs.github.com/en/github/getting-started-with-github/fork-a-repo#step-2-create-a-local-clone-of-your-fork + +.. _start coding: Start coding ~~~~~~~~~~~~ -- Create a branch to identify the issue you would like to work on. If - you're submitting a bug or documentation fix, branch off of the - latest ".x" branch:: +- Create a branch to identify the issue you would like to work on. If you're + submitting a bug or documentation fix, branch off of the latest ".x" branch. - git checkout -b your-branch-name origin/1.0.x + .. code-block:: text - If you're submitting a feature addition or change, branch off of the - "master" branch:: + $ git fetch origin + $ git checkout -b your-branch-name origin/2.0.x - git checkout -b your-branch-name origin/master + If you're submitting a feature addition or change, branch off of the "main" branch. -- Using your favorite editor, make your changes, `committing as you go`_. -- Include tests that cover any code changes you make. Make sure the test fails - without your patch. `Run the tests. `_. -- Push your commits to GitHub and `create a pull request`_ by using:: + .. code-block:: text - git push --set-upstream origin your-branch-name + $ git fetch origin + $ git checkout -b your-branch-name origin/main -- Celebrate 🎉 +- Using your favorite editor, make your changes, `committing as you go`_. -.. _committing as you go: https://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes -.. _Black: https://black.readthedocs.io -.. _Editor integration: https://black.readthedocs.io/en/stable/editor_integration.html -.. _pre-commit: https://pre-commit.com -.. _create a pull request: https://help.github.com/en/articles/creating-a-pull-request + - If you are in a codespace, you will be prompted to `create a fork`_ the first + time you make a commit. Enter ``Y`` to continue. -.. _contributing-testsuite: +- Include tests that cover any code changes you make. Make sure the test fails without + your patch. Run the tests as described below. +- Push your commits to your fork on GitHub and `create a pull request`_. Link to the + issue being addressed with ``fixes #123`` in the pull request description. -Running the tests -~~~~~~~~~~~~~~~~~ + .. code-block:: text -Run the basic test suite with:: + $ git push --set-upstream origin your-branch-name - pytest +.. _committing as you go: https://afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes +.. _create a fork: https://docs.github.com/en/codespaces/developing-in-codespaces/using-source-control-in-your-codespace#about-automatic-forking +.. _create a pull request: https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request -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. +.. _Running the tests: -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:: +Running the tests +~~~~~~~~~~~~~~~~~ - tox +Run the basic test suite with pytest. -Running test coverage -~~~~~~~~~~~~~~~~~~~~~ +.. code-block:: text -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:: + $ pytest - coverage run -m pytest - coverage report - coverage html - # then open htmlcov/index.html +This runs the tests for the current environment, which is usually +sufficient. CI will run the full suite when you submit your pull +request. You can run the full test suite with tox if you don't want to +wait. -Read more about `coverage `_. +.. code-block:: text -Running the full test suite with ``tox`` will combine the coverage reports -from all runs. + $ tox -Building the docs -~~~~~~~~~~~~~~~~~ +Running test coverage +~~~~~~~~~~~~~~~~~~~~~ -Build the docs in the ``docs`` directory using Sphinx:: +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. - cd docs - make html +If you are using GitHub Codespaces, ``coverage`` is already installed +so you can skip the installation command. -Open ``_build/html/index.html`` in your browser to view the docs. +.. code-block:: text -Read more about `Sphinx `_. + $ pip install coverage + $ coverage run -m pytest + $ coverage html +Open ``htmlcov/index.html`` in your browser to explore the report. -Caution: zero-padded file modes -------------------------------- +Read more about `coverage `__. -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 :: +Building the docs +~~~~~~~~~~~~~~~~~ - [fetch] - fsckobjects = true +Build the docs in the ``docs`` directory using Sphinx. -or :: +.. code-block:: text - [receive] - fsckObjects = true + $ cd docs + $ make html + +Open ``_build/html/index.html`` in your browser to view the docs. -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. +Read more about `Sphinx `__. diff --git a/MANIFEST.in b/MANIFEST.in index 555022cb78..65a9774968 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,8 +1,11 @@ include CHANGES.rst include CONTRIBUTING.rst include tox.ini +include requirements/*.txt graft artwork graft docs prune docs/_build graft examples graft tests +include src/flask/py.typed +global-exclude *.pyc diff --git a/README.rst b/README.rst index ecfccedb66..4b7ff42ad1 100644 --- a/README.rst +++ b/README.rst @@ -12,6 +12,10 @@ 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/ + Installing ---------- @@ -20,7 +24,9 @@ Install and update using `pip`_: .. code-block:: text - pip install -U Flask + $ pip install -U Flask + +.. _pip: https://pip.pypa.io/en/stable/getting-started/ A Simple Example @@ -28,6 +34,7 @@ A Simple Example .. code-block:: python + # save this as app.py from flask import Flask app = Flask(__name__) @@ -38,9 +45,8 @@ A Simple Example .. code-block:: text - $ env FLASK_APP=hello.py flask run - * Serving Flask app "hello" - * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) + $ flask run + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Contributing @@ -49,7 +55,7 @@ Contributing For guidance on setting up a development environment and how to make a contribution to Flask, see the `contributing guidelines`_. -.. _contributing guidelines: https://github.com/pallets/flask/blob/master/CONTRIBUTING.rst +.. _contributing guidelines: https://github.com/pallets/flask/blob/main/CONTRIBUTING.rst Donate @@ -60,21 +66,15 @@ 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 +.. _please donate today: https://palletsprojects.com/donate Links ----- -* Website: https://palletsprojects.com/p/flask/ -* Documentation: https://flask.palletsprojects.com/ -* Releases: https://pypi.org/project/Flask/ -* Code: https://github.com/pallets/flask -* Issue tracker: https://github.com/pallets/flask/issues -* Test status: https://dev.azure.com/pallets/flask/_build -* Official chat: https://discord.gg/t6rrQZH - -.. _WSGI: https://wsgi.readthedocs.io -.. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/ -.. _Jinja: https://www.palletsprojects.com/p/jinja/ -.. _pip: https://pip.pypa.io/en/stable/quickstart/ +- Documentation: https://flask.palletsprojects.com/ +- Changes: https://flask.palletsprojects.com/changes/ +- PyPI Releases: https://pypi.org/project/Flask/ +- Source Code: https://github.com/pallets/flask/ +- Issue Tracker: https://github.com/pallets/flask/issues/ +- Chat: https://discord.gg/pallets diff --git a/artwork/LICENSE.rst b/artwork/LICENSE.rst deleted file mode 100644 index 605e41cb11..0000000000 --- a/artwork/LICENSE.rst +++ /dev/null @@ -1,19 +0,0 @@ -Copyright 2010 Pallets - -This logo or a modified version may be used by anyone to refer to the -Flask project, but does not indicate endorsement by the project. - -Redistribution and use in source (SVG) and binary (renders in PNG, etc.) -forms, with or without modification, are permitted provided that the -following conditions are met: - -1. Redistributions of source code must retain the above copyright - notice and this list of conditions. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -We would appreciate that you make the image a link to -https://palletsprojects.com/p/flask/ if you use it in a medium that -supports links. diff --git a/artwork/logo-full.svg b/artwork/logo-full.svg deleted file mode 100644 index 8c0748a286..0000000000 --- a/artwork/logo-full.svg +++ /dev/null @@ -1,290 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/artwork/logo-lineart.svg b/artwork/logo-lineart.svg deleted file mode 100644 index 615260dce6..0000000000 --- a/artwork/logo-lineart.svg +++ /dev/null @@ -1,165 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - diff --git a/docs/Makefile b/docs/Makefile index 51285967a7..d4bb2cbb9e 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -1,9 +1,10 @@ # Minimal makefile for Sphinx documentation # -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build SOURCEDIR = . BUILDDIR = _build diff --git a/docs/_static/flask-horizontal.png b/docs/_static/flask-horizontal.png new file mode 100644 index 0000000000..a0df2c6109 Binary files /dev/null and b/docs/_static/flask-horizontal.png differ diff --git a/docs/_static/flask-icon.png b/docs/_static/flask-icon.png deleted file mode 100644 index 55cb8478ef..0000000000 Binary files a/docs/_static/flask-icon.png and /dev/null differ diff --git a/docs/_static/flask-logo.png b/docs/_static/flask-logo.png deleted file mode 100644 index ce23606157..0000000000 Binary files a/docs/_static/flask-logo.png and /dev/null differ diff --git a/docs/_static/flask-vertical.png b/docs/_static/flask-vertical.png new file mode 100644 index 0000000000..d1fd149907 Binary files /dev/null and b/docs/_static/flask-vertical.png differ diff --git a/docs/_static/no.png b/docs/_static/no.png deleted file mode 100644 index 644c3f70f9..0000000000 Binary files a/docs/_static/no.png and /dev/null differ diff --git a/docs/_static/pycharm-run-config.png b/docs/_static/pycharm-run-config.png new file mode 100644 index 0000000000..ad025545a7 Binary files /dev/null and b/docs/_static/pycharm-run-config.png differ diff --git a/docs/_static/pycharm-runconfig.png b/docs/_static/pycharm-runconfig.png deleted file mode 100644 index dff21fa03b..0000000000 Binary files a/docs/_static/pycharm-runconfig.png and /dev/null differ diff --git a/docs/_static/shortcut-icon.png b/docs/_static/shortcut-icon.png new file mode 100644 index 0000000000..4d3e6c3774 Binary files /dev/null and b/docs/_static/shortcut-icon.png differ diff --git a/docs/_static/yes.png b/docs/_static/yes.png deleted file mode 100644 index 56917ab2c6..0000000000 Binary files a/docs/_static/yes.png and /dev/null differ diff --git a/docs/advanced_foreword.rst b/docs/advanced_foreword.rst deleted file mode 100644 index 4ac81905c4..0000000000 --- a/docs/advanced_foreword.rst +++ /dev/null @@ -1,48 +0,0 @@ -.. _advanced_foreword: - -Foreword for Experienced Programmers -==================================== - -Thread-Locals in Flask ----------------------- - -One of the design decisions in Flask was that simple tasks should be simple; -they should not take a lot of code and yet they should not limit you. Because -of that, Flask has a few design choices that some people might find -surprising or unorthodox. For example, Flask uses thread-local objects -internally so that you don’t have to pass objects around from -function to function within a request in order to stay threadsafe. -This approach is convenient, but requires a valid -request context for dependency injection or when attempting to reuse code which -uses a value pegged to the request. The Flask project is honest about -thread-locals, does not hide them, and calls out in the code and documentation -where they are used. - -Develop for the Web with Caution --------------------------------- - -Always keep security in mind when building web applications. - -If you write a web application, you are probably allowing users to register -and leave their data on your server. The users are entrusting you with data. -And even if you are the only user that might leave data in your application, -you still want that data to be stored securely. - -Unfortunately, there are many ways the security of a web application can be -compromised. Flask protects you against one of the most common security -problems of modern web applications: cross-site scripting (XSS). Unless you -deliberately mark insecure HTML as secure, Flask and the underlying Jinja2 -template engine have you covered. But there are many more ways to cause -security problems. - -The documentation will warn you about aspects of web development that require -attention to security. Some of these security concerns are far more complex -than one might think, and we all sometimes underestimate the likelihood that a -vulnerability will be exploited - until a clever attacker figures out a way to -exploit our applications. And don't think that your application is not -important enough to attract an attacker. Depending on the kind of attack, -chances are that automated bots are probing for ways to fill your database with -spam, links to malicious software, and the like. - -Flask is no different from any other framework in that you the developer must -build with caution, watching for exploits when building to your requirements. diff --git a/docs/api.rst b/docs/api.rst index 7e278fc61b..043beb0775 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,11 +1,9 @@ -.. _api: - API === .. module:: flask -This part of the documentation covers all the interfaces of Flask. For +This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation. @@ -29,76 +27,30 @@ Incoming Request Data --------------------- .. autoclass:: Request - :members: - :inherited-members: - - .. attribute:: environ - - The underlying WSGI environment. - - .. attribute:: path - .. attribute:: full_path - .. attribute:: script_root - .. attribute:: url - .. attribute:: base_url - .. attribute:: url_root - - Provides different ways to look at the current :rfc:`3987`. - Imagine your application is listening on the following application - root:: - - http://www.example.com/myapplication - - And a user requests the following URI:: - - http://www.example.com/myapplication/%CF%80/page.html?x=y - - In this case the values of the above mentioned attributes would be - the following: - - ============= ====================================================== - `path` ``u'/π/page.html'`` - `full_path` ``u'/π/page.html?x=y'`` - `script_root` ``u'/myapplication'`` - `base_url` ``u'http://www.example.com/myapplication/π/page.html'`` - `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'`` - `url_root` ``u'http://www.example.com/myapplication/'`` - ============= ====================================================== - + :members: + :inherited-members: + :exclude-members: json_module .. attribute:: request To access incoming request data, you can use the global `request` - object. Flask parses incoming request data for you and gives you - access to it through that global object. Internally Flask makes + object. Flask parses incoming request data for you and gives you + access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment. - This is a proxy. See :ref:`notes-on-proxies` for more information. + This is a proxy. See :ref:`notes-on-proxies` for more information. - The request object is an instance of a :class:`~werkzeug.wrappers.Request` - subclass and provides all of the attributes Werkzeug defines. This - just shows a quick overview of the most important ones. + The request object is an instance of a :class:`~flask.Request`. Response Objects ---------------- .. autoclass:: flask.Response - :members: set_cookie, 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. - + :members: + :inherited-members: + :exclude-members: json_module Sessions -------- @@ -117,7 +69,7 @@ To access the current session you can use the :class:`session` object: The session object works pretty much like an ordinary dict, with the difference that it keeps track of modifications. - This is a proxy. See :ref:`notes-on-proxies` for more information. + This is a proxy. See :ref:`notes-on-proxies` for more information. The following attributes are interesting: @@ -127,10 +79,10 @@ To access the current session you can use the :class:`session` object: .. attribute:: modified - ``True`` if the session object detected a modification. Be advised + ``True`` if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the - attribute to ``True`` yourself. Here an example:: + attribute to ``True`` yourself. Here an example:: # this change is not picked up because a mutable object (here # a list) is changed. @@ -141,8 +93,8 @@ To access the current session you can use the :class:`session` object: .. attribute:: permanent If set to ``True`` the session lives for - :attr:`~flask.Flask.permanent_session_lifetime` seconds. The - default is 31 days. If set to ``False`` (which is the default) the + :attr:`~flask.Flask.permanent_session_lifetime` seconds. The + default is 31 days. If set to ``False`` (which is the default) the session will be deleted when the user closes the browser. @@ -173,10 +125,9 @@ implementation that Flask is using. .. admonition:: Notice - The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer - starting with Flask 0.8. Either catch this down yourself or use - the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the - app which converts the result to an integer automatically. + The :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``. + The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a + ``timedelta``. Test Client @@ -204,9 +155,9 @@ Application Globals To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in -threaded environments. Flask provides you with a special object that +threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return -different values for each request. In a nutshell: it does the right +different values for each request. In a nutshell: it does the right thing, like it does for :class:`request` and :class:`session`. .. data:: g @@ -216,9 +167,9 @@ thing, like it does for :class:`request` and :class:`session`. :attr:`Flask.app_ctx_globals_class`, which defaults to :class:`ctx._AppCtxGlobals`. - This is a good place to store resources during a request. During - testing, you can use the :ref:`faking-resources` pattern to - pre-configure such resources. + This is a good place to store resources during a request. For + example, a ``before_request`` function could load a user object from + a session id, then set ``g.user`` to be used in the view function. This is a proxy. See :ref:`notes-on-proxies` for more information. @@ -266,12 +217,6 @@ Useful Functions and Classes .. autofunction:: send_from_directory -.. autofunction:: safe_join - -.. autofunction:: escape - -.. autoclass:: Markup - :members: escape, unescape, striptags Message Flashing ---------------- @@ -280,58 +225,29 @@ Message Flashing .. autofunction:: get_flashed_messages + JSON Support ------------ .. module:: flask.json -Flask uses ``simplejson`` for the JSON implementation. Since simplejson -is provided by both the standard library as well as extension, Flask will -try simplejson first and then fall back to the stdlib json module. On top -of that it will delegate access to the current application's JSON encoders -and decoders for easier customization. - -So for starters instead of doing:: - - try: - import simplejson as json - except ImportError: - import json - -You can instead just do this:: +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. - from flask import json - -For usage examples, read the :mod:`json` documentation in the standard -library. The following extensions are by default applied to the stdlib's -JSON module: - -1. ``datetime`` objects are serialized as :rfc:`822` strings. -2. Any object with an ``__html__`` method (like :class:`~flask.Markup`) - will have that method called and then the return value is serialized - as string. - -The :func:`~htmlsafe_dumps` function of this json module is also available -as a filter called ``|tojson`` in Jinja2. Note that in versions of Flask prior -to Flask 0.10, you must disable escaping with ``|safe`` if you intend to use -``|tojson`` output inside ``script`` tags. In Flask 0.10 and above, this -happens automatically (but it's harmless to include ``|safe`` anyway). +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 @@ -342,14 +258,17 @@ happens automatically (but it's harmless to include ``|safe`` anyway). .. autofunction:: load -.. autoclass:: JSONEncoder - :members: +.. autoclass:: flask.json.provider.JSONProvider + :members: + :member-order: bysource -.. autoclass:: JSONDecoder - :members: +.. autoclass:: flask.json.provider.DefaultJSONProvider + :members: + :member-order: bysource .. automodule:: flask.json.tag + Template Rendering ------------------ @@ -359,6 +278,10 @@ Template Rendering .. autofunction:: render_template_string +.. autofunction:: stream_template + +.. autofunction:: stream_template_string + .. autofunction:: get_template_attribute Configuration @@ -379,56 +302,28 @@ Useful Internals .. autoclass:: flask.ctx.RequestContext :members: -.. data:: _request_ctx_stack - - The internal :class:`~werkzeug.local.LocalStack` that holds - :class:`~flask.ctx.RequestContext` instances. Typically, the - :data:`request` and :data:`session` proxies should be accessed - instead of the stack. It may be useful to access the stack in - extension code. - - The following attributes are always present on each layer of the - stack: - - `app` - the active Flask application. - - `url_adapter` - the URL adapter that was used to match the request. - - `request` - the current request object. - - `session` - the active session object. - - `g` - an object with all the attributes of the :data:`flask.g` object. +.. data:: flask.globals.request_ctx - `flashes` - an internal cache for the flashed messages. + The current :class:`~flask.ctx.RequestContext`. If a request context + is not active, accessing attributes on this proxy will raise a + ``RuntimeError``. - Example usage:: - - from flask import _request_ctx_stack - - def get_session(): - ctx = _request_ctx_stack.top - if ctx is not None: - return ctx.session + This is an internal object that is essential to how Flask handles + requests. Accessing this should not be needed in most cases. Most + likely you want :data:`request` and :data:`session` instead. .. autoclass:: flask.ctx.AppContext :members: -.. data:: _app_ctx_stack +.. data:: flask.globals.app_ctx - The internal :class:`~werkzeug.local.LocalStack` that holds - :class:`~flask.ctx.AppContext` instances. Typically, the - :data:`current_app` and :data:`g` proxies should be accessed instead - of the stack. Extensions can access the contexts on the stack as a - namespace to store data. + The current :class:`~flask.ctx.AppContext`. If an app context is not + active, accessing attributes on this proxy will raise a + ``RuntimeError``. - .. versionadded:: 0.9 + This is an internal object that is essential to how Flask handles + requests. Accessing this should not be needed in most cases. Most + likely you want :data:`current_app` and :data:`g` instead. .. autoclass:: flask.blueprints.BlueprintSetupState :members: @@ -438,18 +333,13 @@ Useful Internals Signals ------- -.. versionadded:: 0.6 - -.. data:: signals.signals_available - - ``True`` if the signaling system is available. This is the case - when `blinker`_ is installed. +Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction. -The following signals exist in Flask: +.. _blinker: https://blinker.readthedocs.io/ .. data:: template_rendered - This signal is sent when a template was successfully rendered. The + This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as `template` and the context as dictionary (named `context`). @@ -483,7 +373,7 @@ The following signals exist in Flask: .. data:: request_started This signal is sent when the request context is set up, before - any request processing happens. Because the request context is already + any request processing happens. Because the request context is already bound, the subscriber can access the request with the standard global proxies such as :class:`~flask.request`. @@ -503,7 +393,7 @@ The following signals exist in Flask: Example subscriber:: def log_response(sender, response, **extra): - sender.logger.debug('Request context is about to close down. ' + sender.logger.debug('Request context is about to close down. ' 'Response: %s', response) from flask import request_finished @@ -511,23 +401,37 @@ The following signals exist in Flask: .. data:: got_request_exception - This signal is sent when an exception happens during request processing. - It is sent *before* the standard exception handling kicks in and even - in debug mode, where no exception handling happens. The exception - itself is passed to the subscriber as `exception`. + This signal is sent when an unhandled exception happens during + request processing, including when debugging. The exception is + passed to the subscriber as ``exception``. - Example subscriber:: + This signal is not sent for + :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that + have error handlers registered, unless the exception was raised from + an error handler. - def log_exception(sender, exception, **extra): - sender.logger.debug('Got exception during processing: %s', exception) + This example shows how to do some extra logging if a theoretical + ``SecurityException`` was raised: + + .. code-block:: python from flask import got_request_exception - got_request_exception.connect(log_exception, app) + + def log_security_exception(sender, exception, **extra): + if not isinstance(exception, SecurityException): + return + + security_logger.exception( + f"SecurityException at {request.url!r}", + exc_info=exception, + ) + + got_request_exception.connect(log_security_exception, app) .. data:: request_tearing_down - This signal is sent when the request is tearing down. This is always - called, even if an exception is caused. Currently functions listening + This signal is sent when the request is tearing down. This is always + called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on. @@ -545,8 +449,8 @@ The following signals exist in Flask: .. data:: appcontext_tearing_down - This signal is sent when the app context is tearing down. This is always - called, even if an exception is caused. Currently functions listening + This signal is sent when the app context is tearing down. This is always + called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on. @@ -563,9 +467,9 @@ The following signals exist in Flask: .. data:: appcontext_pushed - This signal is sent when an application context is pushed. The sender - is the application. This is usually useful for unittests in order to - temporarily hook in information. For instance it can be used to + This signal is sent when an application context is pushed. The sender + is the application. This is usually useful for unittests in order to + temporarily hook in information. For instance it can be used to set a resource early onto the `g` object. Example usage:: @@ -592,16 +496,15 @@ The following signals exist in Flask: .. data:: appcontext_popped - This signal is sent when an application context is popped. The sender - is the application. This usually falls in line with the + This signal is sent when an application context is popped. The sender + is the application. This usually falls in line with the :data:`appcontext_tearing_down` signal. .. versionadded:: 0.10 - .. data:: message_flashed - This signal is sent when the application is flashing a message. The + This signal is sent when the application is flashing a message. The messages is sent as `message` keyword argument and the category as `category`. @@ -616,24 +519,11 @@ The following signals exist in Flask: .. versionadded:: 0.10 -.. class:: signals.Namespace - - An alias for :class:`blinker.base.Namespace` if blinker is available, - otherwise a dummy class that creates fake signals. This class is - available for Flask extensions that want to provide the same fallback - system as Flask itself. - - .. method:: signal(name, doc=None) - - Creates a new signal for this namespace if blinker is available, - otherwise returns a fake signal that has a send method that will - do nothing but will fail with a :exc:`RuntimeError` for all other - operations, including connecting. - +.. data:: signals.signals_available -.. _blinker: https://pypi.org/project/blinker/ + .. deprecated:: 2.3 + Will be removed in Flask 2.4. Signals are always available -.. _class-based-views: Class-Based Views ----------------- @@ -661,7 +551,7 @@ Generally there are three ways to define rules for the routing system: which is exposed as :attr:`flask.Flask.url_map`. Variable parts in the route can be specified with angular brackets -(``/user/``). By default a variable part in the URL accepts any +(``/user/``). By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using ````. @@ -695,7 +585,7 @@ Here are some examples:: pass An important detail to keep in mind is how Flask deals with trailing -slashes. The idea is to keep each URL unique so the following rules +slashes. The idea is to keep each URL unique so the following rules apply: 1. If a rule ends with a slash and is requested without a slash by the @@ -704,11 +594,11 @@ apply: 2. If a rule does not end with a trailing slash and the user requests the page with a trailing slash, a 404 not found is raised. -This is consistent with how web servers deal with static files. This +This is consistent with how web servers deal with static files. This also makes it possible to use relative link targets safely. -You can also define multiple rules for the same function. They have to be -unique however. Defaults can also be specified. Here for example is a +You can also define multiple rules for the same function. They have to be +unique however. Defaults can also be specified. Here for example is a definition for a URL that accepts an optional page:: @app.route('/users/', defaults={'page': 1}) @@ -731,36 +621,35 @@ can't preserve form data. :: pass Here are the parameters that :meth:`~flask.Flask.route` and -:meth:`~flask.Flask.add_url_rule` accept. The only difference is that +:meth:`~flask.Flask.add_url_rule` accept. The only difference is that with the route parameter the view function is defined with the decorator instead of the `view_func` parameter. =============== ========================================================== `rule` the URL rule as string -`endpoint` the endpoint for the registered URL rule. Flask itself +`endpoint` the endpoint for the registered URL rule. Flask itself assumes that the name of the view function is the name of the endpoint if not explicitly stated. `view_func` the function to call when serving a request to the - provided endpoint. If this is not provided one can + provided endpoint. If this is not provided one can specify the function later by storing it in the :attr:`~flask.Flask.view_functions` dictionary with the endpoint as key. -`defaults` A dictionary with defaults for this rule. See the +`defaults` A dictionary with defaults for this rule. See the example above for how defaults work. `subdomain` specifies the rule for the subdomain in case subdomain - matching is in use. If not specified the default + matching is in use. If not specified the default subdomain is assumed. `**options` the options to be forwarded to the underlying - :class:`~werkzeug.routing.Rule` object. A change to - Werkzeug is handling of method options. methods is a list + :class:`~werkzeug.routing.Rule` object. A change to + Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` - etc.). By default a rule just listens for ``GET`` (and - implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is + etc.). By default a rule just listens for ``GET`` (and + implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request - handling. They have to be specified as keyword arguments. + handling. They have to be specified as keyword arguments. =============== ========================================================== -.. _view-func-options: View Function Options --------------------- @@ -770,19 +659,19 @@ customize behavior the view function would normally not have control over. The following attributes can be provided optionally to either override some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior: -- `__name__`: The name of a function is by default used as endpoint. If - endpoint is provided explicitly this value is used. Additionally this +- `__name__`: The name of a function is by default used as endpoint. If + endpoint is provided explicitly this value is used. Additionally this will be prefixed with the name of the blueprint by default which cannot be customized from the function itself. - `methods`: If methods are not provided when the URL rule is added, Flask will look on the view function object itself if a `methods` - attribute exists. If it does, it will pull the information for the + attribute exists. If it does, it will pull the information for the methods from there. - `provide_automatic_options`: if this attribute is set Flask will either force enable or disable the automatic implementation of the - HTTP ``OPTIONS`` response. This can be useful when working with + HTTP ``OPTIONS`` response. This can be useful when working with decorators that want to customize the ``OPTIONS`` response on a per-view basis. diff --git a/docs/appcontext.rst b/docs/appcontext.rst index a0d3a2dddd..5509a9a781 100644 --- a/docs/appcontext.rst +++ b/docs/appcontext.rst @@ -1,7 +1,5 @@ .. currentmodule:: flask -.. _app-context: - The Application Context ======================= @@ -10,7 +8,7 @@ a request, CLI command, or other activity. Rather than passing the application around to each function, the :data:`current_app` and :data:`g` proxies are accessed instead. -This is similar to the :doc:`/reqcontext`, which keeps track of +This is similar to :doc:`/reqcontext`, which keeps track of request-level data during a request. A corresponding application context is pushed when a request context is pushed. @@ -119,7 +117,7 @@ For example, you can manage a database connection using this pattern:: return g.db @app.teardown_appcontext - def teardown_db(): + def teardown_db(exception): db = g.pop('db', None) if db is not None: @@ -138,22 +136,12 @@ local from ``get_db()``:: Accessing ``db`` will call ``get_db`` internally, in the same way that :data:`current_app` works. ----- - -If you're writing an extension, :data:`g` should be reserved for user -code. You may store internal data on the context itself, but be sure to -use a sufficiently unique name. The current context is accessed with -:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see -:doc:`extensiondev`. - Events and Signals ------------------ -The application will call functions registered with -:meth:`~Flask.teardown_appcontext` when the application context is -popped. +The application will call functions registered with :meth:`~Flask.teardown_appcontext` +when the application context is popped. -If :data:`~signals.signals_available` is true, the following signals are -sent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and -:data:`appcontext_popped`. +The following signals are sent: :data:`appcontext_pushed`, +:data:`appcontext_tearing_down`, and :data:`appcontext_popped`. diff --git a/docs/async-await.rst b/docs/async-await.rst new file mode 100644 index 0000000000..06a29fccc1 --- /dev/null +++ b/docs/async-await.rst @@ -0,0 +1,131 @@ +.. _async_await: + +Using ``async`` and ``await`` +============================= + +.. versionadded:: 2.0 + +Routes, error handlers, before request, after request, and teardown +functions can all be coroutine functions if Flask is installed with the +``async`` extra (``pip install flask[async]``). This allows views to be +defined with ``async def`` and use ``await``. + +.. code-block:: python + + @app.route("/get-data") + async def get_data(): + data = await async_db_query(...) + return jsonify(data) + +Pluggable class-based views also support handlers that are implemented as +coroutines. This applies to the :meth:`~flask.views.View.dispatch_request` +method in views that inherit from the :class:`flask.views.View` class, as +well as all the HTTP method handlers in views that inherit from the +:class:`flask.views.MethodView` class. + +.. admonition:: Using ``async`` on Windows on Python 3.8 + + Python 3.8 has a bug related to asyncio on Windows. If you encounter + something like ``ValueError: set_wakeup_fd only works in main thread``, + please upgrade to Python 3.9. + +.. admonition:: Using ``async`` with greenlet + + When using gevent or eventlet to serve an application or patch the + runtime, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is + required. + + +Performance +----------- + +Async functions require an event loop to run. Flask, as a WSGI +application, uses one worker to handle one request/response cycle. +When a request comes in to an async view, Flask will start an event loop +in a thread, run the view function there, then return the result. + +Each request still ties up one worker, even for async views. The upside +is that you can run async code within a view, for example to make +multiple concurrent database queries, HTTP requests to an external API, +etc. However, the number of requests your application can handle at one +time will remain the same. + +**Async is not inherently faster than sync code.** Async is beneficial +when performing concurrent IO-bound tasks, but will probably not improve +CPU-bound tasks. Traditional Flask views will still be appropriate for +most use cases, but Flask's async support enables writing and using +code that wasn't possible natively before. + + +Background tasks +---------------- + +Async functions will run in an event loop until they complete, at +which stage the event loop will stop. This means any additional +spawned tasks that haven't completed when the async function completes +will be cancelled. Therefore you cannot spawn background tasks, for +example via ``asyncio.create_task``. + +If you wish to use background tasks it is best to use a task queue to +trigger background work, rather than spawn tasks in a view +function. With that in mind you can spawn asyncio tasks by serving +Flask with an ASGI server and utilising the asgiref WsgiToAsgi adapter +as described in :doc:`deploying/asgi`. This works as the adapter creates +an event loop that runs continually. + + +When to use Quart instead +------------------------- + +Flask's async support is less performant than async-first frameworks due +to the way it is implemented. If you have a mainly async codebase it +would make sense to consider `Quart`_. Quart is a reimplementation of +Flask based on the `ASGI`_ standard instead of WSGI. This allows it to +handle many concurrent requests, long running requests, and websockets +without requiring multiple worker processes or threads. + +It has also already been possible to run Flask with Gevent or Eventlet +to get many of the benefits of async request handling. These libraries +patch low-level Python functions to accomplish this, whereas ``async``/ +``await`` and ASGI use standard, modern Python capabilities. Deciding +whether you should use Flask, Quart, or something else is ultimately up +to understanding the specific needs of your project. + +.. _Quart: https://github.com/pallets/quart +.. _ASGI: https://asgi.readthedocs.io/en/latest/ + + +Extensions +---------- + +Flask extensions predating Flask's async support do not expect async views. +If they provide decorators to add functionality to views, those will probably +not work with async views because they will not await the function or be +awaitable. Other functions they provide will not be awaitable either and +will probably be blocking if called within an async view. + +Extension authors can support async functions by utilising the +:meth:`flask.Flask.ensure_sync` method. For example, if the extension +provides a view function decorator add ``ensure_sync`` before calling +the decorated function, + +.. code-block:: python + + def extension(func): + @wraps(func) + def wrapper(*args, **kwargs): + ... # Extension logic + return current_app.ensure_sync(func)(*args, **kwargs) + + return wrapper + +Check the changelog of the extension you want to use to see if they've +implemented async support, or make a feature request or PR to them. + + +Other event loops +----------------- + +At the moment Flask only supports :mod:`asyncio`. It's possible to +override :meth:`flask.Flask.ensure_sync` to change how async functions +are wrapped to use a different library. diff --git a/docs/becomingbig.rst b/docs/becomingbig.rst deleted file mode 100644 index d23c3acb56..0000000000 --- a/docs/becomingbig.rst +++ /dev/null @@ -1,102 +0,0 @@ -.. _becomingbig: - -Becoming Big -============ - -Here are your options when growing your codebase or scaling your application. - -Read the Source. ----------------- - -Flask started in part to demonstrate how to build your own framework on top of -existing well-used tools Werkzeug (WSGI) and Jinja (templating), and as it -developed, it became useful to a wide audience. As you grow your codebase, -don't just use Flask -- understand it. Read the source. Flask's code is -written to be read; its documentation is published so you can use its internal -APIs. Flask sticks to documented APIs in upstream libraries, and documents its -internal utilities so that you can find the hook points needed for your -project. - -Hook. Extend. -------------- - -The :ref:`api` docs are full of available overrides, hook points, and -:ref:`signals`. You can provide custom classes for things like the request and -response objects. Dig deeper on the APIs you use, and look for the -customizations which are available out of the box in a Flask release. Look for -ways in which your project can be refactored into a collection of utilities and -Flask extensions. Explore the many `extensions -`_ in the community, and look for patterns to -build your own extensions if you do not find the tools you need. - -Subclass. ---------- - -The :class:`~flask.Flask` class has many methods designed for subclassing. You -can quickly add or customize behavior by subclassing :class:`~flask.Flask` (see -the linked method docs) and using that subclass wherever you instantiate an -application class. This works well with :ref:`app-factories`. -See :doc:`/patterns/subclassing` for an example. - -Wrap with middleware. ---------------------- - -The :ref:`app-dispatch` chapter shows in detail how to apply middleware. You -can introduce WSGI middleware to wrap your Flask instances and introduce fixes -and changes at the layer between your Flask application and your HTTP -server. Werkzeug includes several `middlewares -`_. - -Fork. ------ - -If none of the above options work, fork Flask. The majority of code of Flask -is within Werkzeug and Jinja2. These libraries do the majority of the work. -Flask is just the paste that glues those together. For every project there is -the point where the underlying framework gets in the way (due to assumptions -the original developers had). This is natural because if this would not be the -case, the framework would be a very complex system to begin with which causes a -steep learning curve and a lot of user frustration. - -This is not unique to Flask. Many people use patched and modified -versions of their framework to counter shortcomings. This idea is also -reflected in the license of Flask. You don't have to contribute any -changes back if you decide to modify the framework. - -The downside of forking is of course that Flask extensions will most -likely break because the new framework has a different import name. -Furthermore integrating upstream changes can be a complex process, -depending on the number of changes. Because of that, forking should be -the very last resort. - -Scale like a pro. ------------------ - -For many web applications the complexity of the code is less an issue than -the scaling for the number of users or data entries expected. Flask by -itself is only limited in terms of scaling by your application code, the -data store you want to use and the Python implementation and webserver you -are running on. - -Scaling well means for example that if you double the amount of servers -you get about twice the performance. Scaling bad means that if you add a -new server the application won't perform any better or would not even -support a second server. - -There is only one limiting factor regarding scaling in Flask which are -the context local proxies. They depend on context which in Flask is -defined as being either a thread, process or greenlet. If your server -uses some kind of concurrency that is not based on threads or greenlets, -Flask will no longer be able to support these global proxies. However the -majority of servers are using either threads, greenlets or separate -processes to achieve concurrency which are all methods well supported by -the underlying Werkzeug library. - -Discuss with the community. ---------------------------- - -The Flask developers keep the framework accessible to users with codebases big -and small. If you find an obstacle in your way, caused by Flask, don't hesitate -to contact the developers on the mailing list or IRC channel. The best way for -the Flask and Flask extension developers to improve the tools for larger -applications is getting feedback from users. diff --git a/docs/blueprints.rst b/docs/blueprints.rst index 2e940be1d0..d5cf3d8237 100644 --- a/docs/blueprints.rst +++ b/docs/blueprints.rst @@ -1,5 +1,3 @@ -.. _blueprints: - Modular Applications with Blueprints ==================================== @@ -37,8 +35,9 @@ Blueprints in Flask are intended for these cases: A blueprint in Flask is not a pluggable app because it is not actually an application -- it's a set of operations which can be registered on an application, even multiple times. Why not have multiple application -objects? You can do that (see :ref:`app-dispatch`), but your applications -will have separate configs and will be managed at the WSGI layer. +objects? You can do that (see :doc:`/patterns/appdispatch`), but your +applications will have separate configs and will be managed at the WSGI +layer. Blueprints instead provide separation at the Flask level, share application config, and can change an application object as necessary with @@ -70,7 +69,7 @@ implement a blueprint that does simple rendering of static templates:: @simple_page.route('/') def show(page): try: - return render_template('pages/%s.html' % page) + return render_template(f'pages/{page}.html') except TemplateNotFound: abort(404) @@ -121,6 +120,44 @@ On top of that you can register blueprints multiple times though not every blueprint might respond properly to that. In fact it depends on how the blueprint is implemented if it can be mounted more than once. +Nesting Blueprints +------------------ + +It is possible to register a blueprint on another blueprint. + +.. code-block:: python + + parent = Blueprint('parent', __name__, url_prefix='/parent') + child = Blueprint('child', __name__, url_prefix='/child') + parent.register_blueprint(child) + app.register_blueprint(parent) + +The child blueprint will gain the parent's name as a prefix to its +name, and child URLs will be prefixed with the parent's URL prefix. + +.. code-block:: python + + url_for('parent.child.create') + /parent/child/create + +In addition a child blueprint's will gain their parent's subdomain, +with their subdomain as prefix if present i.e. + +.. code-block:: python + + parent = Blueprint('parent', __name__, subdomain='parent') + child = Blueprint('child', __name__, subdomain='child') + parent.register_blueprint(child) + app.register_blueprint(parent) + + url_for('parent.child.create', _external=True) + "child.parent.domain.tld" + +Blueprint-specific before request functions, etc. registered with the +parent will trigger for the child. If a child does not have an error +handler that can handle a given exception, the parent's will be tried. + + Blueprint Resources ------------------- @@ -243,8 +280,9 @@ you can use relative redirects by prefixing the endpoint with a dot only:: This will link to ``admin.index`` for instance in case the current request was dispatched to any other admin blueprint endpoint. -Error Handlers --------------- + +Blueprint Error Handlers +------------------------ Blueprints support the ``errorhandler`` decorator just like the :class:`Flask` application object, so it is easy to make Blueprint-specific custom error @@ -270,8 +308,8 @@ at the application level using the ``request`` proxy object:: @app.errorhandler(405) def _handle_api_error(ex): if request.path.startswith('/api/'): - return jsonify_error(ex) + return jsonify(error=str(ex)), ex.code else: return ex -More information on error handling see :ref:`errorpages`. +See :doc:`/errorhandling`. diff --git a/docs/changelog.rst b/docs/changes.rst similarity index 59% rename from docs/changelog.rst rename to docs/changes.rst index 218fe3339b..955deaf27b 100644 --- a/docs/changelog.rst +++ b/docs/changes.rst @@ -1,4 +1,4 @@ -Changelog -========= +Changes +======= .. include:: ../CHANGES.rst diff --git a/docs/cli.rst b/docs/cli.rst index 96c5396f3e..a72e6d51cb 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -1,7 +1,5 @@ .. currentmodule:: flask -.. _cli: - Command Line Interface ====================== @@ -17,58 +15,43 @@ Application Discovery --------------------- The ``flask`` command is installed by Flask, not your application; it must be -told where to find your application in order to use it. The ``FLASK_APP`` -environment variable is used to specify how to load the application. - -Unix Bash (Linux, Mac, etc.):: - - $ export FLASK_APP=hello - $ flask run - -Windows CMD:: - - > set FLASK_APP=hello - > flask run +told where to find your application in order to use it. The ``--app`` +option is used to specify how to load the application. -Windows PowerShell:: - - > $env:FLASK_APP = "hello" - > flask run - -While ``FLASK_APP`` supports a variety of options for specifying your +While ``--app`` supports a variety of options for specifying your application, most use cases should be simple. Here are the typical values: (nothing) - The file :file:`wsgi.py` is imported, automatically detecting an app - (``app``). This provides an easy way to create an app from a factory with - extra arguments. + The name "app" or "wsgi" is imported (as a ".py" file, or package), + automatically detecting an app (``app`` or ``application``) or + factory (``create_app`` or ``make_app``). -``FLASK_APP=hello`` - The name is imported, automatically detecting an app (``app``) or factory - (``create_app``). +``--app hello`` + The given name is imported, automatically detecting an app (``app`` + or ``application``) or factory (``create_app`` or ``make_app``). ---- -``FLASK_APP`` has three parts: an optional path that sets the current working +``--app`` has three parts: an optional path that sets the current working directory, a Python file or dotted import path, and an optional variable name of the instance or factory. If the name is a factory, it can optionally be followed by arguments in parentheses. The following values demonstrate these parts: -``FLASK_APP=src/hello`` +``--app src/hello`` Sets the current working directory to ``src`` then imports ``hello``. -``FLASK_APP=hello.web`` +``--app hello.web`` Imports the path ``hello.web``. -``FLASK_APP=hello:app2`` +``--app hello:app2`` Uses the ``app2`` Flask instance in ``hello``. -``FLASK_APP="hello:create_app('dev')"`` +``--app 'hello:create_app("dev")'`` The ``create_app`` factory in ``hello`` is called with the string ``'dev'`` as the argument. -If ``FLASK_APP`` is not set, the command will try to import "app" or +If ``--app`` is not set, the command will try to import "app" or "wsgi" (as a ".py" file, or package) and try to detect an application instance or factory. @@ -77,12 +60,8 @@ Within the given import, the command looks for an application instance named found, the command looks for a factory function named ``create_app`` or ``make_app`` that returns an instance. -When calling an application factory, if the factory takes an argument named -``script_info``, then the :class:`~cli.ScriptInfo` instance is passed as a -keyword argument. If the application factory takes only one argument and no -parentheses follow the factory name, the :class:`~cli.ScriptInfo` instance -is passed as a positional argument. If parentheses follow the factory name, -their contents are parsed as Python literals and passes as arguments to the +If parentheses follow the factory name, their contents are parsed as +Python literals and passed as arguments and keyword arguments to the function. This means that strings must still be in quotes. @@ -92,85 +71,79 @@ Run the Development Server The :func:`run ` command will start the development server. It replaces the :meth:`Flask.run` method in most cases. :: - $ flask run + $ flask --app hello run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) .. warning:: Do not use this command to run your application in production. Only use the development server during development. The development server is provided for convenience, but is not designed to be particularly secure, - stable, or efficient. See :ref:`deployment` for how to run in production. + stable, or efficient. See :doc:`/deploying/index` for how to run in production. +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. -Open a Shell ------------- -To explore the data in your application, you can start an interactive Python -shell with the :func:`shell ` command. An application -context will be active, and the app instance will be imported. :: +Debug Mode +~~~~~~~~~~ - $ flask shell - Python 3.6.2 (default, Jul 20 2017, 03:52:27) - [GCC 7.1.1 20170630] on linux - App: example - Instance: /home/user/Projects/hello/instance - >>> +In debug mode, the ``flask run`` command will enable the interactive debugger and the +reloader by default, and make errors easier to see and debug. To enable debug mode, use +the ``--debug`` option. -Use :meth:`~Flask.shell_context_processor` to add other automatic imports. +.. code-block:: console + $ flask --app hello run --debug + * Serving Flask app "hello" + * Debug mode: on + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) + * Restarting with inotify reloader + * Debugger is active! + * Debugger PIN: 223-456-919 -Environments ------------- +The ``--debug`` option can also be passed to the top level ``flask`` command to enable +debug mode for any command. The following two ``run`` calls are equivalent. -.. versionadded:: 1.0 +.. code-block:: console -The environment in which the Flask app runs is set by the -:envvar:`FLASK_ENV` environment variable. If not set it defaults to -``production``. The other recognized environment is ``development``. -Flask and extensions may choose to enable behaviors based on the -environment. + $ flask --app hello --debug run + $ flask --app hello run --debug -If the env is set to ``development``, the ``flask`` command will enable -debug mode and ``flask run`` will enable the interactive debugger and -reloader. -:: +Watch and Ignore Files with the Reloader +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - $ FLASK_ENV=development flask run - * Serving Flask app "hello" - * Environment: development - * Debug mode: on - * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) - * Restarting with inotify reloader - * Debugger is active! - * Debugger PIN: 223-456-919 +When using debug mode, the reloader will trigger whenever your Python code or imported +modules change. The reloader can watch additional files with the ``--extra-files`` +option. Multiple paths are separated with ``:``, or ``;`` on Windows. - -Watch Extra Files with the Reloader -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When using development mode, the reloader will trigger whenever your -Python code or imported modules change. The reloader can watch -additional files with the ``--extra-files`` option, or the -``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are -separated with ``:``, or ``;`` on Windows. - -.. code-block:: none +.. code-block:: text $ flask run --extra-files file1:dirA/file2:dirB/ - # or - $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/ - $ flask run * Running on http://127.0.0.1:8000/ * Detected change in '/path/to/file1', reloading +The reloader can also ignore files using :mod:`fnmatch` patterns with the +``--exclude-patterns`` option. Multiple patterns are separated with ``:``, or ``;`` on +Windows. -Debug Mode ----------- -Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``, -as described above. If you want to control debug mode separately, use -:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it. +Open a Shell +------------ + +To explore the data in your application, you can start an interactive Python +shell with the :func:`shell ` command. An application +context will be active, and the app instance will be imported. :: + + $ flask shell + Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux + App: example [production] + Instance: /home/david/Projects/pallets/flask/instance + >>> + +Use :meth:`~Flask.shell_context_processor` to add other automatic imports. .. _dotenv: @@ -178,14 +151,21 @@ as described above. If you want to control debug mode separately, use Environment Variables From dotenv --------------------------------- -Rather than setting ``FLASK_APP`` each time you open a new terminal, you can -use Flask's dotenv support to set environment variables automatically. +The ``flask`` command supports setting any option for any command with +environment variables. The variables are named like ``FLASK_OPTION`` or +``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or +``FLASK_RUN_PORT``. + +Rather than passing options every time you run a command, or environment +variables every time you open a new terminal, you can use Flask's dotenv +support to set environment variables automatically. If `python-dotenv`_ is installed, running the ``flask`` command will set -environment variables defined in the files :file:`.env` and :file:`.flaskenv`. -This can be used to avoid having to set ``FLASK_APP`` manually every time you -open a new terminal, and to set configuration using environment variables -similar to how some deployment services work. +environment variables defined in the files ``.env`` and ``.flaskenv``. +You can also specify an extra file to load with the ``--env-file`` +option. Dotenv files can be used to avoid having to set ``--app`` or +``FLASK_APP`` manually, and to set configuration using environment +variables similar to how some deployment services work. Variables set on the command line are used over those set in :file:`.env`, which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be @@ -193,9 +173,7 @@ used for public variables, such as ``FLASK_APP``, while :file:`.env` should not be committed to your repository so that it can set private variables. Directories are scanned upwards from the directory you call ``flask`` -from to locate the files. The current working directory will be set to the -location of the file, with the assumption that that is the top level project -directory. +from to locate the files. The files are only loaded by the ``flask`` command or calling :meth:`~Flask.run`. If you would like to load these files when running in @@ -212,11 +190,39 @@ environment variables. The variables use the pattern ``FLASK_COMMAND_OPTION``. For example, to set the port for the run command, instead of ``flask run --port 8000``: -.. code-block:: bash +.. tabs:: - $ export FLASK_RUN_PORT=8000 - $ flask run - * Running on http://127.0.0.1:8000/ + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_RUN_PORT=8000 + $ flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x FLASK_RUN_PORT 8000 + $ flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_RUN_PORT=8000 + > flask run + * Running on http://127.0.0.1:8000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_RUN_PORT = 8000 + > flask run + * Running on http://127.0.0.1:8000/ These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to control default command options. @@ -240,10 +246,35 @@ a project runner that loads them already. Keep in mind that the environment variables must be set before the app loads or it won't configure as expected. -.. code-block:: bash +.. tabs:: - $ export FLASK_SKIP_DOTENV=1 - $ flask run + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_SKIP_DOTENV=1 + $ flask run + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x FLASK_SKIP_DOTENV 1 + $ flask run + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_SKIP_DOTENV=1 + > flask run + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_SKIP_DOTENV = 1 + > flask run Environment Variables From virtualenv @@ -253,13 +284,31 @@ If you do not want to install dotenv support, you can still set environment variables by adding them to the end of the virtualenv's :file:`activate` script. Activating the virtualenv will set the variables. -Unix Bash, :file:`venv/bin/activate`:: +.. tabs:: + + .. group-tab:: Bash + + Unix Bash, :file:`.venv/bin/activate`:: + + $ export FLASK_APP=hello + + .. group-tab:: Fish + + Fish, :file:`.venv/bin/activate.fish`:: + + $ set -x FLASK_APP hello + + .. group-tab:: CMD + + Windows CMD, :file:`.venv\\Scripts\\activate.bat`:: - $ export FLASK_APP=hello + > set FLASK_APP=hello -Windows CMD, :file:`venv\\Scripts\\activate.bat`:: + .. group-tab:: Powershell - > set FLASK_APP=hello + Windows Powershell, :file:`.venv\\Scripts\\activate.ps1`:: + + > $env:FLASK_APP = "hello" It is preferred to use dotenv support over this, since :file:`.flaskenv` can be committed to the repository so that it works automatically wherever the project @@ -372,12 +421,14 @@ commands directly to the application's level: Application Context ~~~~~~~~~~~~~~~~~~~ -Commands added using the Flask app's :attr:`~Flask.cli` -:meth:`~cli.AppGroup.command` decorator will be executed with an application -context pushed, so your command and extensions have access to the app and its -configuration. If you create a command using the Click :func:`~click.command` -decorator instead of the Flask decorator, you can use -:func:`~cli.with_appcontext` to get the same behavior. :: +Commands added using the Flask app's :attr:`~Flask.cli` or +:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator +will be executed with an application context pushed, so your custom +commands and parameters have access to the app and its configuration. The +:func:`~cli.with_appcontext` decorator can be used to get the same +behavior, but is not needed in most cases. + +.. code-block:: python import click from flask.cli import with_appcontext @@ -389,36 +440,22 @@ decorator instead of the Flask decorator, you can use app.cli.add_command(do_work) -If you're sure a command doesn't need the context, you can disable it:: - - @app.cli.command(with_appcontext=False) - def do_work(): - ... - Plugins ------- Flask will automatically load commands specified in the ``flask.commands`` `entry point`_. This is useful for extensions that want to add commands when -they are installed. Entry points are specified in :file:`setup.py` :: - - from setuptools import setup +they are installed. Entry points are specified in :file:`pyproject.toml`: - setup( - name='flask-my-extension', - ..., - entry_points={ - 'flask.commands': [ - 'my-command=flask_my_extension.commands:cli' - ], - }, - ) +.. code-block:: toml + [project.entry-points."flask.commands"] + my-command = "my_extension.commands:cli" .. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points -Inside :file:`flask_my_extension/commands.py` you can then export a Click +Inside :file:`my_extension/commands.py` you can then export a Click object:: import click @@ -437,7 +474,7 @@ Custom Scripts -------------- When you are using the app factory pattern, it may be more convenient to define -your own Click script. Instead of using ``FLASK_APP`` and letting Flask load +your own Click script. Instead of using ``--app`` and letting Flask load your application, you can create your own Click object and export it as a `console script`_ entry point. @@ -456,22 +493,15 @@ Create an instance of :class:`~cli.FlaskGroup` and pass it the factory:: def cli(): """Management script for the Wiki application.""" -Define the entry point in :file:`setup.py`:: +Define the entry point in :file:`pyproject.toml`: - from setuptools import setup +.. code-block:: toml - setup( - name='flask-my-extension', - ..., - entry_points={ - 'console_scripts': [ - 'wiki=wiki:cli' - ], - }, - ) + [project.scripts] + wiki = "wiki:cli" Install the application in the virtualenv in editable mode and the custom -script is available. Note that you don't need to set ``FLASK_APP``. :: +script is available. Note that you don't need to set ``--app``. :: $ pip install -e . $ wiki run @@ -491,52 +521,36 @@ script is available. Note that you don't need to set ``FLASK_APP``. :: PyCharm Integration ------------------- -Prior to PyCharm 2018.1, the Flask CLI features weren't yet fully -integrated into PyCharm. We have to do a few tweaks to get them working -smoothly. These instructions should be similar for any other IDE you -might want to use. +PyCharm Professional provides a special Flask run configuration to run the development +server. For the Community Edition, and for other commands besides ``run``, you need to +create a custom run configuration. These instructions should be similar for any other +IDE you use. -In PyCharm, with your project open, click on *Run* from the menu bar and -go to *Edit Configurations*. You'll be greeted by a screen similar to -this: +In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit +Configurations*. You'll see a screen similar to this: -.. image:: _static/pycharm-runconfig.png +.. image:: _static/pycharm-run-config.png :align: center :class: screenshot - :alt: screenshot of pycharm's run configuration settings - -There's quite a few options to change, but once we've done it for one -command, we can easily copy the entire configuration and make a single -tweak to give us access to other commands, including any custom ones you -may implement yourself. - -Click the + (*Add New Configuration*) button and select *Python*. Give -the configuration a good descriptive name such as "Run Flask Server". -For the ``flask run`` command, check "Single instance only" since you -can't run the server more than once at the same time. + :alt: Screenshot of PyCharm run configuration. -Select *Module name* from the dropdown (**A**) then input ``flask``. +Once you create a configuration for the ``flask run``, you can copy and change it to +call any other command. -The *Parameters* field (**B**) is set to the CLI command to execute -(with any arguments). In this example we use ``run``, which will run -the development server. +Click the *+ (Add New Configuration)* button and select *Python*. Give the configuration +a name such as "flask run". -You can skip this next step if you're using :ref:`dotenv`. We need to -add an environment variable (**C**) to identify our application. Click -on the browse button and add an entry with ``FLASK_APP`` on the left and -the Python import or file on the right (``hello`` for example). +Click the *Script path* dropdown and change it to *Module name*, then input ``flask``. -Next we need to set the working directory (**D**) to be the folder where -our application resides. +The *Parameters* field is set to the CLI command to execute along with any arguments. +This example uses ``--app hello run --debug``, which will run the development server in +debug mode. ``--app hello`` should be the import or file with your Flask app. -If you have installed your project as a package in your virtualenv, you -may untick the *PYTHONPATH* options (**E**). This will more accurately -match how you deploy the app later. +If you installed your project as a package in your virtualenv, you may uncheck the +*PYTHONPATH* options. This will more accurately match how you deploy later. -Click *Apply* to save the configuration, or *OK* to save and close the -window. Select the configuration in the main PyCharm window and click -the play button next to it to run the server. +Click *OK* to save and close the configuration. Select the configuration in the main +PyCharm window and click the play button next to it to run the server. -Now that we have a configuration which runs ``flask run`` from within -PyCharm, we can copy that configuration and alter the *Script* argument -to run a different CLI command, e.g. ``flask shell``. +Now that you have a configuration for ``flask run``, you can copy that configuration and +change the *Parameters* argument to run a different CLI command. diff --git a/docs/conf.py b/docs/conf.py index 9fe9d98538..771a7228d1 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,3 +1,4 @@ +import packaging.version from pallets_sphinx_themes import get_version from pallets_sphinx_themes import ProjectLink @@ -17,16 +18,18 @@ "sphinxcontrib.log_cabinet", "pallets_sphinx_themes", "sphinx_issues", + "sphinx_tabs.tabs", ] +autodoc_typehints = "description" intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "werkzeug": ("https://werkzeug.palletsprojects.com/", None), "click": ("https://click.palletsprojects.com/", None), - "jinja": ("http://jinja.pocoo.org/docs/", None), + "jinja": ("https://jinja.palletsprojects.com/", None), "itsdangerous": ("https://itsdangerous.palletsprojects.com/", None), "sqlalchemy": ("https://docs.sqlalchemy.org/", None), - "wtforms": ("https://wtforms.readthedocs.io/en/stable/", None), - "blinker": ("https://pythonhosted.org/blinker/", None), + "wtforms": ("https://wtforms.readthedocs.io/", None), + "blinker": ("https://blinker.readthedocs.io/", None), } issues_github_path = "pallets/flask" @@ -36,29 +39,27 @@ html_theme_options = {"index_sidebar_logo": False} html_context = { "project_links": [ - ProjectLink("Donate to Pallets", "https://palletsprojects.com/donate"), - ProjectLink("Flask Website", "https://palletsprojects.com/p/flask/"), - ProjectLink("PyPI releases", "https://pypi.org/project/Flask/"), + ProjectLink("Donate", "https://palletsprojects.com/donate"), + ProjectLink("PyPI Releases", "https://pypi.org/project/Flask/"), ProjectLink("Source Code", "https://github.com/pallets/flask/"), ProjectLink("Issue Tracker", "https://github.com/pallets/flask/issues/"), + ProjectLink("Chat", "https://discord.gg/pallets"), ] } html_sidebars = { - "index": ["project.html", "localtoc.html", "searchbox.html"], - "**": ["localtoc.html", "relations.html", "searchbox.html"], + "index": ["project.html", "localtoc.html", "searchbox.html", "ethicalads.html"], + "**": ["localtoc.html", "relations.html", "searchbox.html", "ethicalads.html"], } -singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]} +singlehtml_sidebars = {"index": ["project.html", "localtoc.html", "ethicalads.html"]} html_static_path = ["_static"] -html_favicon = "_static/flask-icon.png" -html_logo = "_static/flask-icon.png" -html_title = "Flask Documentation ({})".format(version) +html_favicon = "_static/shortcut-icon.png" +html_logo = "_static/flask-vertical.png" +html_title = f"Flask Documentation ({version})" html_show_sourcelink = False # LaTeX ---------------------------------------------------------------- -latex_documents = [ - (master_doc, "Flask-{}.tex".format(version), html_title, author, "manual") -] +latex_documents = [(master_doc, f"Flask-{version}.tex", html_title, author, "manual")] # Local Extensions ----------------------------------------------------- @@ -74,10 +75,10 @@ def github_link(name, rawtext, text, lineno, inliner, options=None, content=None else: words = None - if release.endswith("dev"): - url = "{0}master/{1}".format(base_url, text) + if packaging.version.parse(release).is_devrelease: + url = f"{base_url}main/{text}" else: - url = "{0}{1}/{2}".format(base_url, release, text) + url = f"{base_url}{release}/{text}" if words is None: words = url diff --git a/docs/config.rst b/docs/config.rst index d4036f52d4..3c06b29cee 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -1,5 +1,3 @@ -.. _config: - Configuration Handling ====================== @@ -40,45 +38,26 @@ method:: app.config.update( TESTING=True, - SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/' + SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' ) -Environment and Debug Features ------------------------------- - -The :data:`ENV` and :data:`DEBUG` config values are special because they -may behave inconsistently if changed after the app has begun setting up. -In order to set the environment and debug mode reliably, Flask uses -environment variables. - -The environment is used to indicate to Flask, extensions, and other -programs, like Sentry, what context Flask is running in. It is -controlled with the :envvar:`FLASK_ENV` environment variable and -defaults to ``production``. - -Setting :envvar:`FLASK_ENV` to ``development`` will enable debug mode. -``flask run`` will use the interactive debugger and reloader by default -in debug mode. To control this separately from the environment, use the -:envvar:`FLASK_DEBUG` flag. - -.. versionchanged:: 1.0 - Added :envvar:`FLASK_ENV` to control the environment separately - from debug mode. The development environment enables debug mode. +Debug Mode +---------- -To switch Flask to the development environment and enable debug mode, -set :envvar:`FLASK_ENV`:: +The :data:`DEBUG` config value is special because it may behave inconsistently if +changed after the app has begun setting up. In order to set debug mode reliably, use the +``--debug`` option on the ``flask`` or ``flask run`` command. ``flask run`` will use the +interactive debugger and reloader by default in debug mode. - $ export FLASK_ENV=development - $ flask run +.. code-block:: text -(On Windows, use ``set`` instead of ``export``.) + $ flask --app hello run --debug -Using the environment variables as described above is recommended. While -it is possible to set :data:`ENV` and :data:`DEBUG` in your config or -code, this is strongly discouraged. They can't be read early by the -``flask`` command, and some systems or extensions may have already -configured themselves based on a previous value. +Using the option is recommended. While it is possible to set :data:`DEBUG` in your +config or code, this is strongly discouraged. It can't be read early by the +``flask run`` command, and some systems or extensions may have already configured +themselves based on a previous value. Builtin Configuration Values @@ -86,34 +65,17 @@ Builtin Configuration Values The following configuration values are used internally by Flask: -.. py:data:: ENV - - What environment the app is running in. Flask and extensions may - enable behaviors based on the environment, such as enabling debug - mode. The :attr:`~flask.Flask.env` attribute maps to this config - key. This is set by the :envvar:`FLASK_ENV` environment variable and - may not behave as expected if set in code. - - **Do not enable development when deploying in production.** - - Default: ``'production'`` - - .. versionadded:: 1.0 - .. py:data:: DEBUG - Whether debug mode is enabled. When using ``flask run`` to start the - development server, an interactive debugger will be shown for - unhandled exceptions, and the server will be reloaded when code - changes. The :attr:`~flask.Flask.debug` attribute maps to this - config key. This is enabled when :data:`ENV` is ``'development'`` - and is overridden by the ``FLASK_DEBUG`` environment variable. It - may not behave as expected if set in code. + Whether debug mode is enabled. When using ``flask run`` to start the development + server, an interactive debugger will be shown for unhandled exceptions, and the + server will be reloaded when code changes. The :attr:`~flask.Flask.debug` attribute + maps to this config key. This is set with the ``FLASK_DEBUG`` environment variable. + It may not behave as expected if set in code. **Do not enable debug mode when deploying in production.** - Default: ``True`` if :data:`ENV` is ``'development'``, or ``False`` - otherwise. + Default: ``False`` .. py:data:: TESTING @@ -131,14 +93,6 @@ The following configuration values are used internally by Flask: Default: ``None`` -.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION - - Don't pop the request context when an exception occurs. If not set, this - is true if ``DEBUG`` is true. This allows debuggers to introspect the - request data on errors, and should normally not need to be set directly. - - Default: ``None`` - .. py:data:: TRAP_HTTP_EXCEPTIONS If there is no handler for an ``HTTPException``-type exception, re-raise it @@ -161,11 +115,11 @@ The following configuration values are used internally by Flask: A secret key that will be used for securely signing the session cookie and can be used for any other security related needs by extensions or your - application. It should be a long random string of bytes, although unicode - is accepted too. For example, copy the output of this to your config:: + application. It should be a long random ``bytes`` or ``str``. For + example, copy the output of this to your config:: - $ python -c 'import os; print(os.urandom(16))' - b'_5#y2L"F4Q8z\n\xec]/' + $ python -c 'import secrets; print(secrets.token_hex())' + '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' **Do not reveal the secret key when posting questions or committing code.** @@ -180,12 +134,17 @@ The following configuration values are used internally by Flask: .. py:data:: SESSION_COOKIE_DOMAIN - The domain match rule that the session cookie will be valid for. If not - set, the cookie will be valid for all subdomains of :data:`SERVER_NAME`. - If ``False``, the cookie's domain will not be set. + The value of the ``Domain`` parameter on the session cookie. If not set, browsers + will only send the cookie to the exact domain it was set from. Otherwise, they + will send it to any subdomain of the given value as well. + + Not setting this value is more restricted and secure than setting it. Default: ``None`` + .. versionchanged:: 2.3 + Not set by default, does not fall back to ``SERVER_NAME``. + .. py:data:: SESSION_COOKIE_PATH The path that the session cookie will be valid for. If not set, the cookie @@ -249,36 +208,36 @@ The following configuration values are used internally by Flask: .. py:data:: SEND_FILE_MAX_AGE_DEFAULT When serving files, set the cache control max age to this number of - seconds. Can either be a :class:`datetime.timedelta` or an ``int``. + seconds. Can be a :class:`datetime.timedelta` or an ``int``. Override this value on a per-file basis using - :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint. + :meth:`~flask.Flask.get_send_file_max_age` on the application or + blueprint. + + If ``None``, ``send_file`` tells the browser to use conditional + requests will be used instead of a timed cache, which is usually + preferable. - Default: ``timedelta(hours=12)`` (``43200`` seconds) + Default: ``None`` .. py:data:: SERVER_NAME Inform the application what host and port it is bound to. Required for subdomain route matching support. - If set, will be used for the session cookie domain if - :data:`SESSION_COOKIE_DOMAIN` is not set. Modern web browsers will - not allow setting cookies for domains without a dot. To use a domain - locally, add any names that should route to the app to your - ``hosts`` file. :: - - 127.0.0.1 localhost.dev - If set, ``url_for`` can generate external URLs with only an application context instead of a request context. Default: ``None`` + .. versionchanged:: 2.3 + Does not affect ``SESSION_COOKIE_DOMAIN``. + .. py:data:: APPLICATION_ROOT Inform the application what path it is mounted under by the application / web server. This is used for generating URLs outside the context of a request (inside a request, the dispatcher is responsible for setting - ``SCRIPT_NAME`` instead; see :ref:`Application Dispatching ` + ``SCRIPT_NAME`` instead; see :doc:`/patterns/appdispatch` for examples of dispatch configuration). Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not @@ -300,37 +259,6 @@ The following configuration values are used internally by Flask: Default: ``None`` -.. py:data:: JSON_AS_ASCII - - Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON - will be returned as a Unicode string, or encoded as ``UTF-8`` by - ``jsonify``. This has security implications when rendering the JSON into - JavaScript in templates, and should typically remain enabled. - - Default: ``True`` - -.. py:data:: JSON_SORT_KEYS - - Sort the keys of JSON objects alphabetically. This is useful for caching - because it ensures the data is serialized the same way no matter what - Python's hash seed is. While not recommended, you can disable this for a - possible performance improvement at the cost of caching. - - Default: ``True`` - -.. py:data:: JSONIFY_PRETTYPRINT_REGULAR - - ``jsonify`` responses will be output with newlines, spaces, and indentation - for easier reading by humans. Always enabled in debug mode. - - Default: ``False`` - -.. py:data:: JSONIFY_MIMETYPE - - The mimetype of ``jsonify`` responses. - - Default: ``'application/json'`` - .. py:data:: TEMPLATES_AUTO_RELOAD Reload templates when they are changed. If not set, it will be enabled in @@ -392,17 +320,26 @@ The following configuration values are used internally by Flask: Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug. +.. versionchanged:: 2.2 + Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``. + +.. versionchanged:: 2.3 + ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_MIMETYPE``, and + ``JSONIFY_PRETTYPRINT_REGULAR`` were removed. The default ``app.json`` provider has + equivalent attributes instead. -Configuring from Files ----------------------- +.. versionchanged:: 2.3 + ``ENV`` was removed. -Configuration becomes more useful if you can store it in a separate file, -ideally located outside the actual application package. This makes -packaging and distributing your application possible via various package -handling tools (:ref:`distribute-deployment`) and finally modifying the -configuration file afterwards. -So a common pattern is this:: +Configuring from Python Files +----------------------------- + +Configuration becomes more useful if you can store it in a separate file, ideally +located outside the actual application package. You can deploy your application, then +separately configure it for the specific deployment. + +A common pattern is this:: app = Flask(__name__) app.config.from_object('yourapplication.default_settings') @@ -411,18 +348,42 @@ So a common pattern is this:: This first loads the configuration from the `yourapplication.default_settings` module and then overrides the values with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS` -environment variable points to. This environment variable can be set on -Linux or OS X with the export command in the shell before starting the -server:: +environment variable points to. This environment variable can be set +in the shell before starting the server: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Fish + + .. code-block:: text + + $ set -x YOURAPPLICATION_SETTINGS /path/to/settings.cfg + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: CMD - $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg - $ python run-app.py - * Running on http://127.0.0.1:5000/ - * Restarting with reloader... + .. code-block:: text -On Windows systems use the `set` builtin instead:: + > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg + > flask run + * Running on http://127.0.0.1:5000/ - > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg + .. group-tab:: Powershell + + .. code-block:: text + + > $env:YOURAPPLICATION_SETTINGS = "\path\to\settings.cfg" + > flask run + * Running on http://127.0.0.1:5000/ The configuration files themselves are actual Python files. Only values in uppercase are actually stored in the config object later on. So make @@ -431,8 +392,7 @@ sure to use uppercase letters for your config keys. Here is an example of a configuration file:: # Example configuration - DEBUG = False - SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/' + SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' Make sure to load the configuration very early on, so that extensions have the ability to access the configuration when starting up. There are other @@ -441,50 +401,116 @@ complete reference, read the :class:`~flask.Config` object's documentation. +Configuring from Data Files +--------------------------- + +It is also possible to load configuration from a file in a format of +your choice using :meth:`~flask.Config.from_file`. For example to load +from a TOML file: + +.. code-block:: python + + import toml + app.config.from_file("config.toml", load=toml.load) + +Or from a JSON file: + +.. code-block:: python + + import json + app.config.from_file("config.json", load=json.load) + + Configuring from Environment Variables -------------------------------------- -In addition to pointing to configuration files using environment variables, you -may find it useful (or necessary) to control your configuration values directly -from the environment. +In addition to pointing to configuration files using environment +variables, you may find it useful (or necessary) to control your +configuration values directly from the environment. Flask can be +instructed to load all environment variables starting with a specific +prefix into the config using :meth:`~flask.Config.from_prefixed_env`. -Environment variables can be set on Linux or OS X with the export command in -the shell before starting the server:: +Environment variables can be set in the shell before starting the +server: - $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f' - $ export MAIL_ENABLED=false - $ python run-app.py - * Running on http://127.0.0.1:5000/ +.. tabs:: -On Windows systems use the ``set`` builtin instead:: + .. group-tab:: Bash - > set SECRET_KEY='5f352379324c22463451387a0aec5d2f' + .. code-block:: text -While this approach is straightforward to use, it is important to remember that -environment variables are strings -- they are not automatically deserialized -into Python types. + $ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f" + $ export FLASK_MAIL_ENABLED=false + $ flask run + * Running on http://127.0.0.1:5000/ -Here is an example of a configuration file that uses environment variables:: + .. group-tab:: Fish - import os + .. code-block:: text - _mail_enabled = os.environ.get("MAIL_ENABLED", default="true") - MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"} + $ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f" + $ set -x FLASK_MAIL_ENABLED false + $ flask run + * Running on http://127.0.0.1:5000/ - SECRET_KEY = os.environ.get("SECRET_KEY") + .. group-tab:: CMD - if not SECRET_KEY: - raise ValueError("No SECRET_KEY set for Flask application") + .. code-block:: text + > set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f" + > set FLASK_MAIL_ENABLED=false + > flask run + * Running on http://127.0.0.1:5000/ -Notice that any value besides an empty string will be interpreted as a boolean -``True`` value in Python, which requires care if an environment explicitly sets -values intended to be ``False``. + .. group-tab:: Powershell -Make sure to load the configuration very early on, so that extensions have the -ability to access the configuration when starting up. There are other methods -on the config object as well to load from individual files. For a complete -reference, read the :class:`~flask.Config` class documentation. + .. code-block:: text + + > $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f" + > $env:FLASK_MAIL_ENABLED = "false" + > flask run + * Running on http://127.0.0.1:5000/ + +The variables can then be loaded and accessed via the config with a key +equal to the environment variable name without the prefix i.e. + +.. code-block:: python + + app.config.from_prefixed_env() + app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f" + +The prefix is ``FLASK_`` by default. This is configurable via the +``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`. + +Values will be parsed to attempt to convert them to a more specific type +than strings. By default :func:`json.loads` is used, so any valid JSON +value is possible, including lists and dicts. This is configurable via +the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`. + +When adding a boolean value with the default JSON parsing, only "true" +and "false", lowercase, are valid values. Keep in mind that any +non-empty string is considered ``True`` by Python. + +It is possible to set keys in nested dictionaries by separating the +keys with double underscore (``__``). Any intermediate keys that don't +exist on the parent dict will be initialized to an empty dict. + +.. code-block:: text + + $ export FLASK_MYAPI__credentials__username=user123 + +.. code-block:: python + + app.config["MYAPI"]["credentials"]["username"] # Is "user123" + +On Windows, environment variable keys are always uppercase, therefore +the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``. + +For even more config loading features, including merging and +case-insensitive Windows support, try a dedicated library such as +Dynaconf_, which includes integration with Flask. + +.. _Dynaconf: https://www.dynaconf.com/ Configuration Best Practices @@ -504,6 +530,10 @@ that experience: limit yourself to request-only accesses to the configuration you can reconfigure the object later on as needed. +3. Make sure to load the configuration very early on, so that + extensions can access the configuration when calling ``init_app``. + + .. _config-dev-prod: Development / Production @@ -536,17 +566,16 @@ An interesting pattern is also to use classes and inheritance for configuration:: class Config(object): - DEBUG = False TESTING = False - DATABASE_URI = 'sqlite:///:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): - DEBUG = True + DATABASE_URI = "sqlite:////tmp/foo.db" class TestingConfig(Config): + DATABASE_URI = 'sqlite:///:memory:' TESTING = True To enable such a config you just have to call into @@ -571,13 +600,12 @@ your configuration classes:: class Config(object): """Base config, uses staging database server.""" - DEBUG = False TESTING = False DB_SERVER = '192.168.1.56' @property - def DATABASE_URI(self): # Note: all caps - return 'mysql://user@{}/foo'.format(self.DB_SERVER) + def DATABASE_URI(self): # Note: all caps + return f"mysql://user@{self.DB_SERVER}/foo" class ProductionConfig(Config): """Uses production database server.""" @@ -585,11 +613,9 @@ your configuration classes:: class DevelopmentConfig(Config): DB_SERVER = 'localhost' - DEBUG = True class TestingConfig(Config): DB_SERVER = 'localhost' - DEBUG = True DATABASE_URI = 'sqlite:///:memory:' There are many different ways and it's up to you how you want to manage @@ -605,10 +631,8 @@ your configuration files. However here a list of good recommendations: code at all. If you are working often on different projects you can even create your own script for sourcing that activates a virtualenv and exports the development configuration for you. -- Use a tool like `fabric`_ in production to push code and - configurations separately to the production server(s). For some - details about how to do that, head over to the - :ref:`fabric-deployment` pattern. +- Use a tool like `fabric`_ to push code and configuration separately + to the production server(s). .. _fabric: https://www.fabfile.org/ @@ -658,7 +682,7 @@ locations are used: - Installed module or package:: - $PREFIX/lib/python2.X/site-packages/myapp + $PREFIX/lib/pythonX.Y/site-packages/myapp $PREFIX/var/myapp-instance ``$PREFIX`` is the prefix of your Python installation. This can be diff --git a/docs/debugging.rst b/docs/debugging.rst new file mode 100644 index 0000000000..f6b56cab2f --- /dev/null +++ b/docs/debugging.rst @@ -0,0 +1,99 @@ +Debugging Application Errors +============================ + + +In Production +------------- + +**Do not run the development server, or enable the built-in debugger, in +a production environment.** The debugger allows executing arbitrary +Python code from the browser. It's protected by a pin, but that should +not be relied on for security. + +Use an error logging tool, such as Sentry, as described in +:ref:`error-logging-tools`, or enable logging and notifications as +described in :doc:`/logging`. + +If you have access to the server, you could add some code to start an +external debugger if ``request.remote_addr`` matches your IP. Some IDE +debuggers also have a remote mode so breakpoints on the server can be +interacted with locally. Only enable a debugger temporarily. + + +The Built-In Debugger +--------------------- + +The built-in Werkzeug development server provides a debugger which shows +an interactive traceback in the browser when an unhandled error occurs +during a request. This debugger should only be used during development. + +.. image:: _static/debugger.png + :align: center + :class: screenshot + :alt: screenshot of debugger in action + +.. warning:: + + The debugger allows executing arbitrary Python code from the + browser. It is protected by a pin, but still represents a major + security risk. Do not run the development server or debugger in a + production environment. + +The debugger is enabled by default when the development server is run in debug mode. + +.. code-block:: text + + $ flask --app hello run --debug + +When running from Python code, passing ``debug=True`` enables debug mode, which is +mostly equivalent. + +.. code-block:: python + + app.run(debug=True) + +:doc:`/server` and :doc:`/cli` have more information about running the debugger and +debug mode. More information about the debugger can be found in the `Werkzeug +documentation `__. + + +External Debuggers +------------------ + +External debuggers, such as those provided by IDEs, can offer a more +powerful debugging experience than the built-in debugger. They can also +be used to step through code during a request before an error is raised, +or if no error is raised. Some even have a remote mode so you can debug +code running on another machine. + +When using an external debugger, the app should still be in debug mode, otherwise Flask +turns unhandled errors into generic 500 error pages. However, the built-in debugger and +reloader should be disabled so they don't interfere with the external debugger. + +.. code-block:: text + + $ flask --app hello run --debug --no-debugger --no-reload + +When running from Python: + +.. code-block:: python + + app.run(debug=True, use_debugger=False, use_reloader=False) + +Disabling these isn't required, an external debugger will continue to work with the +following caveats. + +- If the built-in debugger is not disabled, it will catch unhandled exceptions before + the external debugger can. +- If the reloader is not disabled, it could cause an unexpected reload if code changes + during a breakpoint. +- The development server will still catch unhandled exceptions if the built-in + debugger is disabled, otherwise it would crash on any error. If you want that (and + usually you don't) pass ``passthrough_errors=True`` to ``app.run``. + + .. code-block:: python + + app.run( + debug=True, passthrough_errors=True, + use_debugger=False, use_reloader=False + ) diff --git a/docs/deploying/apache-httpd.rst b/docs/deploying/apache-httpd.rst new file mode 100644 index 0000000000..bdeaf62657 --- /dev/null +++ b/docs/deploying/apache-httpd.rst @@ -0,0 +1,66 @@ +Apache httpd +============ + +`Apache httpd`_ is a fast, production level HTTP server. When serving +your application with one of the WSGI servers listed in :doc:`index`, it +is often good or necessary to put a dedicated HTTP server in front of +it. This "reverse proxy" can handle incoming requests, TLS, and other +security and performance concerns better than the WSGI server. + +httpd can be installed using your system package manager, or a pre-built +executable for Windows. Installing and running httpd itself is outside +the scope of this doc. This page outlines the basics of configuring +httpd to proxy your application. Be sure to read its documentation to +understand what features are available. + +.. _Apache httpd: https://httpd.apache.org/ + + +Domain Name +----------- + +Acquiring and configuring a domain name is outside the scope of this +doc. In general, you will buy a domain name from a registrar, pay for +server space with a hosting provider, and then point your registrar +at the hosting provider's name servers. + +To simulate this, you can also edit your ``hosts`` file, located at +``/etc/hosts`` on Linux. Add a line that associates a name with the +local IP. + +Modern Linux systems may be configured to treat any domain name that +ends with ``.localhost`` like this without adding it to the ``hosts`` +file. + +.. code-block:: python + :caption: ``/etc/hosts`` + + 127.0.0.1 hello.localhost + + +Configuration +------------- + +The httpd configuration is located at ``/etc/httpd/conf/httpd.conf`` on +Linux. It may be different depending on your operating system. Check the +docs and look for ``httpd.conf``. + +Remove or comment out any existing ``DocumentRoot`` directive. Add the +config lines below. We'll assume the WSGI server is listening locally at +``http://127.0.0.1:8000``. + +.. code-block:: apache + :caption: ``/etc/httpd/conf/httpd.conf`` + + LoadModule proxy_module modules/mod_proxy.so + LoadModule proxy_http_module modules/mod_proxy_http.so + ProxyPass / http://127.0.0.1:8000/ + RequestHeader set X-Forwarded-Proto http + RequestHeader set X-Forwarded-Prefix / + +The ``LoadModule`` lines might already exist. If so, make sure they are +uncommented instead of adding them manually. + +Then :doc:`proxy_fix` so that your application uses the ``X-Forwarded`` +headers. ``X-Forwarded-For`` and ``X-Forwarded-Host`` are automatically +set by ``ProxyPass``. diff --git a/docs/deploying/asgi.rst b/docs/deploying/asgi.rst new file mode 100644 index 0000000000..36acff8ac5 --- /dev/null +++ b/docs/deploying/asgi.rst @@ -0,0 +1,27 @@ +ASGI +==== + +If you'd like to use an ASGI server you will need to utilise WSGI to +ASGI middleware. The asgiref +`WsgiToAsgi `_ +adapter is recommended as it integrates with the event loop used for +Flask's :ref:`async_await` support. You can use the adapter by +wrapping the Flask app, + +.. code-block:: python + + from asgiref.wsgi import WsgiToAsgi + from flask import Flask + + app = Flask(__name__) + + ... + + asgi_app = WsgiToAsgi(app) + +and then serving the ``asgi_app`` with the ASGI server, e.g. using +`Hypercorn `_, + +.. sourcecode:: text + + $ hypercorn module:asgi_app diff --git a/docs/deploying/cgi.rst b/docs/deploying/cgi.rst deleted file mode 100644 index 4c1cdfbf0f..0000000000 --- a/docs/deploying/cgi.rst +++ /dev/null @@ -1,61 +0,0 @@ -CGI -=== - -If all other deployment methods do not work, CGI will work for sure. -CGI is supported by all major servers but usually has a sub-optimal -performance. - -This is also the way you can use a Flask application on Google's `App -Engine`_, where execution happens in a CGI-like environment. - -.. admonition:: Watch Out - - Please make sure in advance that any ``app.run()`` calls you might - have in your application file are inside an ``if __name__ == - '__main__':`` block or moved to a separate file. Just make sure it's - not called because this will always start a local WSGI server which - we do not want if we deploy that application to CGI / app engine. - - With CGI, you will also have to make sure that your code does not contain - any ``print`` statements, or that ``sys.stdout`` is overridden by something - that doesn't write into the HTTP response. - -Creating a `.cgi` file ----------------------- - -First you need to create the CGI application file. Let's call it -:file:`yourapplication.cgi`:: - - #!/usr/bin/python - from wsgiref.handlers import CGIHandler - from yourapplication import app - - CGIHandler().run(app) - -Server Setup ------------- - -Usually there are two ways to configure the server. Either just copy the -``.cgi`` into a :file:`cgi-bin` (and use `mod_rewrite` or something similar to -rewrite the URL) or let the server point to the file directly. - -In Apache for example you can put something like this into the config: - -.. sourcecode:: apache - - ScriptAlias /app /path/to/the/application.cgi - -On shared webhosting, though, you might not have access to your Apache config. -In this case, a file called ``.htaccess``, sitting in the public directory -you want your app to be available, works too but the ``ScriptAlias`` directive -won't work in that case: - -.. sourcecode:: apache - - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files - RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L] - -For more information consult the documentation of your webserver. - -.. _App Engine: https://cloud.google.com/appengine/docs/ diff --git a/docs/deploying/eventlet.rst b/docs/deploying/eventlet.rst new file mode 100644 index 0000000000..8a718b22f7 --- /dev/null +++ b/docs/deploying/eventlet.rst @@ -0,0 +1,80 @@ +eventlet +======== + +Prefer using :doc:`gunicorn` with eventlet workers rather than using +`eventlet`_ directly. Gunicorn provides a much more configurable and +production-tested server. + +`eventlet`_ allows writing asynchronous, coroutine-based code that looks +like standard synchronous Python. It uses `greenlet`_ to enable task +switching without writing ``async/await`` or using ``asyncio``. + +:doc:`gevent` is another library that does the same thing. Certain +dependencies you have, or other considerations, may affect which of the +two you choose to use. + +eventlet provides a WSGI server that can handle many connections at once +instead of one per worker process. You must actually use eventlet in +your own code to see any benefit to using the server. + +.. _eventlet: https://eventlet.net/ +.. _greenlet: https://greenlet.readthedocs.io/en/latest/ + + +Installing +---------- + +When using eventlet, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +Create a virtualenv, install your application, then install +``eventlet``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install eventlet + + +Running +------- + +To use eventlet to serve your application, write a script that imports +its ``wsgi.server``, as well as your app or app factory. + +.. code-block:: python + :caption: ``wsgi.py`` + + import eventlet + from eventlet import wsgi + from hello import create_app + + app = create_app() + wsgi.server(eventlet.listen(("127.0.0.1", 8000)), app) + +.. code-block:: text + + $ python wsgi.py + (x) wsgi starting up on http://127.0.0.1:8000 + + +Binding Externally +------------------ + +eventlet should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of eventlet. + +You can bind to all external IPs on a non-privileged port by using +``0.0.0.0`` in the server arguments shown in the previous section. +Don't do this when using a reverse proxy setup, otherwise it will be +possible to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/docs/deploying/fastcgi.rst b/docs/deploying/fastcgi.rst deleted file mode 100644 index 337040626b..0000000000 --- a/docs/deploying/fastcgi.rst +++ /dev/null @@ -1,240 +0,0 @@ -.. _deploying-fastcgi: - -FastCGI -======= - -FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and -`cherokee`_; see :doc:`uwsgi` and :doc:`wsgi-standalone` for other options. -To use your WSGI application with any of them you will need a FastCGI -server first. The most popular one is `flup`_ which we will use for -this guide. Make sure to have it installed to follow along. - -.. admonition:: Watch Out - - Please make sure in advance that any ``app.run()`` calls you might - have in your application file are inside an ``if __name__ == - '__main__':`` block or moved to a separate file. Just make sure it's - not called because this will always start a local WSGI server which - we do not want if we deploy that application to FastCGI. - -Creating a `.fcgi` file ------------------------ - -First you need to create the FastCGI server file. Let's call it -`yourapplication.fcgi`:: - - #!/usr/bin/python - from flup.server.fcgi import WSGIServer - from yourapplication import app - - if __name__ == '__main__': - WSGIServer(app).run() - -This is enough for Apache to work, however nginx and older versions of -lighttpd need a socket to be explicitly passed to communicate with the -FastCGI server. For that to work you need to pass the path to the -socket to the :class:`~flup.server.fcgi.WSGIServer`:: - - WSGIServer(application, bindAddress='/path/to/fcgi.sock').run() - -The path has to be the exact same path you define in the server -config. - -Save the :file:`yourapplication.fcgi` file somewhere you will find it again. -It makes sense to have that in :file:`/var/www/yourapplication` or something -similar. - -Make sure to set the executable bit on that file so that the servers -can execute it: - -.. sourcecode:: text - - $ chmod +x /var/www/yourapplication/yourapplication.fcgi - -Configuring Apache ------------------- - -The example above is good enough for a basic Apache deployment but your -`.fcgi` file will appear in your application URL e.g. -``example.com/yourapplication.fcgi/news/``. There are few ways to configure -your application so that yourapplication.fcgi does not appear in the URL. -A preferable way is to use the ScriptAlias and SetHandler configuration -directives to route requests to the FastCGI server. The following example -uses FastCgiServer to start 5 instances of the application which will -handle all incoming requests:: - - LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so - - FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 5 - - - ServerName webapp1.mydomain.com - DocumentRoot /var/www/html/yourapplication - - AddHandler fastcgi-script fcgi - ScriptAlias / /var/www/html/yourapplication/app.fcgi/ - - - SetHandler fastcgi-script - - - -These processes will be managed by Apache. If you're using a standalone -FastCGI server, you can use the FastCgiExternalServer directive instead. -Note that in the following the path is not real, it's simply used as an -identifier to other -directives such as AliasMatch:: - - FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:3000 - -If you cannot set ScriptAlias, for example on a shared web host, you can use -WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess:: - - - AddHandler fcgid-script .fcgi - - SetHandler fcgid-script - Options +FollowSymLinks +ExecCGI - - - - - Options +FollowSymlinks - RewriteEngine On - RewriteBase / - RewriteCond %{REQUEST_FILENAME} !-f - RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L] - - -Set yourapplication.fcgi:: - - #!/usr/bin/python - #: optional path to your local python site-packages folder - import sys - sys.path.insert(0, '/lib/python/site-packages') - - from flup.server.fcgi import WSGIServer - from yourapplication import app - - class ScriptNameStripper(object): - def __init__(self, app): - self.app = app - - def __call__(self, environ, start_response): - environ['SCRIPT_NAME'] = '' - return self.app(environ, start_response) - - app = ScriptNameStripper(app) - - if __name__ == '__main__': - WSGIServer(app).run() - -Configuring lighttpd --------------------- - -A basic FastCGI configuration for lighttpd looks like that:: - - fastcgi.server = ("/yourapplication.fcgi" => - (( - "socket" => "/tmp/yourapplication-fcgi.sock", - "bin-path" => "/var/www/yourapplication/yourapplication.fcgi", - "check-local" => "disable", - "max-procs" => 1 - )) - ) - - alias.url = ( - "/static/" => "/path/to/your/static/" - ) - - url.rewrite-once = ( - "^(/static($|/.*))$" => "$1", - "^(/.*)$" => "/yourapplication.fcgi$1" - ) - -Remember to enable the FastCGI, alias and rewrite modules. This configuration -binds the application to ``/yourapplication``. If you want the application to -work in the URL root you have to work around a lighttpd bug with the -:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware. - -Make sure to apply it only if you are mounting the application the URL -root. Also, see the Lighty docs for more information on `FastCGI and Python -`_ (note that -explicitly passing a socket to run() is no longer necessary). - -Configuring nginx ------------------ - -Installing FastCGI applications on nginx is a bit different because by -default no FastCGI parameters are forwarded. - -A basic Flask FastCGI configuration for nginx looks like this:: - - location = /yourapplication { rewrite ^ /yourapplication/ last; } - location /yourapplication { try_files $uri @yourapplication; } - location @yourapplication { - include fastcgi_params; - fastcgi_split_path_info ^(/yourapplication)(.*)$; - fastcgi_param PATH_INFO $fastcgi_path_info; - fastcgi_param SCRIPT_NAME $fastcgi_script_name; - fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; - } - -This configuration binds the application to ``/yourapplication``. If you -want to have it in the URL root it's a bit simpler because you don't -have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``:: - - location / { try_files $uri @yourapplication; } - location @yourapplication { - include fastcgi_params; - fastcgi_param PATH_INFO $fastcgi_script_name; - fastcgi_param SCRIPT_NAME ""; - fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; - } - -Running FastCGI Processes -------------------------- - -Since nginx and others do not load FastCGI apps, you have to do it by -yourself. `Supervisor can manage FastCGI processes. -`_ -You can look around for other FastCGI process managers or write a script -to run your `.fcgi` file at boot, e.g. using a SysV ``init.d`` script. -For a temporary solution, you can always run the ``.fcgi`` script inside -GNU screen. See ``man screen`` for details, and note that this is a -manual solution which does not persist across system restart:: - - $ screen - $ /var/www/yourapplication/yourapplication.fcgi - -Debugging ---------- - -FastCGI deployments tend to be hard to debug on most web servers. Very -often the only thing the server log tells you is something along the -lines of "premature end of headers". In order to debug the application -the only thing that can really give you ideas why it breaks is switching -to the correct user and executing the application by hand. - -This example assumes your application is called `application.fcgi` and -that your web server user is `www-data`:: - - $ su www-data - $ cd /var/www/yourapplication - $ python application.fcgi - Traceback (most recent call last): - File "yourapplication.fcgi", line 4, in - ImportError: No module named yourapplication - -In this case the error seems to be "yourapplication" not being on the -python path. Common problems are: - -- Relative paths being used. Don't rely on the current working directory. -- The code depending on environment variables that are not set by the - web server. -- Different python interpreters being used. - -.. _nginx: https://nginx.org/ -.. _lighttpd: https://www.lighttpd.net/ -.. _cherokee: http://cherokee-project.com/ -.. _flup: https://pypi.org/project/flup/ diff --git a/docs/deploying/gevent.rst b/docs/deploying/gevent.rst new file mode 100644 index 0000000000..448b93e78c --- /dev/null +++ b/docs/deploying/gevent.rst @@ -0,0 +1,80 @@ +gevent +====== + +Prefer using :doc:`gunicorn` or :doc:`uwsgi` with gevent workers rather +than using `gevent`_ directly. Gunicorn and uWSGI provide much more +configurable and production-tested servers. + +`gevent`_ allows writing asynchronous, coroutine-based code that looks +like standard synchronous Python. It uses `greenlet`_ to enable task +switching without writing ``async/await`` or using ``asyncio``. + +:doc:`eventlet` is another library that does the same thing. Certain +dependencies you have, or other considerations, may affect which of the +two you choose to use. + +gevent provides a WSGI server that can handle many connections at once +instead of one per worker process. You must actually use gevent in your +own code to see any benefit to using the server. + +.. _gevent: https://www.gevent.org/ +.. _greenlet: https://greenlet.readthedocs.io/en/latest/ + + +Installing +---------- + +When using gevent, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +Create a virtualenv, install your application, then install ``gevent``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install gevent + + +Running +------- + +To use gevent to serve your application, write a script that imports its +``WSGIServer``, as well as your app or app factory. + +.. code-block:: python + :caption: ``wsgi.py`` + + from gevent.pywsgi import WSGIServer + from hello import create_app + + app = create_app() + http_server = WSGIServer(("127.0.0.1", 8000), app) + http_server.serve_forever() + +.. code-block:: text + + $ python wsgi.py + +No output is shown when the server starts. + + +Binding Externally +------------------ + +gevent should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of gevent. + +You can bind to all external IPs on a non-privileged port by using +``0.0.0.0`` in the server arguments shown in the previous section. Don't +do this when using a reverse proxy setup, otherwise it will be possible +to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/docs/deploying/gunicorn.rst b/docs/deploying/gunicorn.rst new file mode 100644 index 0000000000..c50edc2326 --- /dev/null +++ b/docs/deploying/gunicorn.rst @@ -0,0 +1,130 @@ +Gunicorn +======== + +`Gunicorn`_ is a pure Python WSGI server with simple configuration and +multiple worker implementations for performance tuning. + +* It tends to integrate easily with hosting platforms. +* It does not support Windows (but does run on WSL). +* It is easy to install as it does not require additional dependencies + or compilation. +* It has built-in async worker support using gevent or eventlet. + +This page outlines the basics of running Gunicorn. Be sure to read its +`documentation`_ and use ``gunicorn --help`` to understand what features +are available. + +.. _Gunicorn: https://gunicorn.org/ +.. _documentation: https://docs.gunicorn.org/ + + +Installing +---------- + +Gunicorn is easy to install, as it does not require external +dependencies or compilation. It runs on Windows only under WSL. + +Create a virtualenv, install your application, then install +``gunicorn``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install gunicorn + + +Running +------- + +The only required argument to Gunicorn tells it how to load your Flask +application. The syntax is ``{module_import}:{app_variable}``. +``module_import`` is the dotted import name to the module with your +application. ``app_variable`` is the variable with the application. It +can also be a function call (with any arguments) if you're using the +app factory pattern. + +.. code-block:: text + + # equivalent to 'from hello import app' + $ gunicorn -w 4 'hello:app' + + # equivalent to 'from hello import create_app; create_app()' + $ gunicorn -w 4 'hello:create_app()' + + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: sync + Booting worker with pid: x + Booting worker with pid: x + Booting worker with pid: x + Booting worker with pid: x + +The ``-w`` option specifies the number of processes to run; a starting +value could be ``CPU * 2``. The default is only 1 worker, which is +probably not what you want for the default worker type. + +Logs for each request aren't shown by default, only worker info and +errors are shown. To show access logs on stdout, use the +``--access-logfile=-`` option. + + +Binding Externally +------------------ + +Gunicorn should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of Gunicorn. + +You can bind to all external IPs on a non-privileged port using the +``-b 0.0.0.0`` option. Don't do this when using a reverse proxy setup, +otherwise it will be possible to bypass the proxy. + +.. code-block:: text + + $ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()' + Listening at: http://0.0.0.0:8000 (x) + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. + + +Async with gevent or eventlet +----------------------------- + +The default sync worker is appropriate for many use cases. If you need +asynchronous support, Gunicorn provides workers using either `gevent`_ +or `eventlet`_. This is not the same as Python's ``async/await``, or the +ASGI server spec. You must actually use gevent/eventlet in your own code +to see any benefit to using the workers. + +When using either gevent or eventlet, greenlet>=1.0 is required, +otherwise context locals such as ``request`` will not work as expected. +When using PyPy, PyPy>=7.3.7 is required. + +To use gevent: + +.. code-block:: text + + $ gunicorn -k gevent 'hello:create_app()' + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: gevent + Booting worker with pid: x + +To use eventlet: + +.. code-block:: text + + $ gunicorn -k eventlet 'hello:create_app()' + Starting gunicorn 20.1.0 + Listening at: http://127.0.0.1:8000 (x) + Using worker: eventlet + Booting worker with pid: x + +.. _gevent: https://www.gevent.org/ +.. _eventlet: https://eventlet.net/ diff --git a/docs/deploying/index.rst b/docs/deploying/index.rst index 5e98f98c52..4135596a4f 100644 --- a/docs/deploying/index.rst +++ b/docs/deploying/index.rst @@ -1,35 +1,79 @@ -.. _deployment: +Deploying to Production +======================= -Deployment Options -================== +After developing your application, you'll want to make it available +publicly to other users. When you're developing locally, you're probably +using the built-in development server, debugger, and reloader. These +should not be used in production. Instead, you should use a dedicated +WSGI server or hosting platform, some of which will be described here. -While lightweight and easy to use, **Flask's built-in server is not suitable -for production** as it doesn't scale well. Some of the options available for -properly running Flask in production are documented here. +"Production" means "not development", which applies whether you're +serving your application publicly to millions of users or privately / +locally to a single user. **Do not use the development server when +deploying to production. It is intended for use only during local +development. It is not designed to be particularly secure, stable, or +efficient.** -If you want to deploy your Flask application to a WSGI server not listed here, -look up the server documentation about how to use a WSGI app with it. Just -remember that your :class:`Flask` application object is the actual WSGI -application. +Self-Hosted Options +------------------- +Flask is a WSGI *application*. A WSGI *server* is used to run the +application, converting incoming HTTP requests to the standard WSGI +environ, and converting outgoing WSGI responses to HTTP responses. -Hosted options --------------- +The primary goal of these docs is to familiarize you with the concepts +involved in running a WSGI application using a production WSGI server +and HTTP server. There are many WSGI servers and HTTP servers, with many +configuration possibilities. The pages below discuss the most common +servers, and show the basics of running each one. The next section +discusses platforms that can manage this for you. -- `Deploying Flask on Heroku `_ -- `Deploying Flask on Google App Engine `_ -- `Deploying Flask on AWS Elastic Beanstalk `_ -- `Deploying on Azure (IIS) `_ -- `Deploying on PythonAnywhere `_ +.. toctree:: + :maxdepth: 1 -Self-hosted options -------------------- + gunicorn + waitress + mod_wsgi + uwsgi + gevent + eventlet + asgi + +WSGI servers have HTTP servers built-in. However, a dedicated HTTP +server may be safer, more efficient, or more capable. Putting an HTTP +server in front of the WSGI server is called a "reverse proxy." .. toctree:: - :maxdepth: 2 + :maxdepth: 1 + + proxy_fix + nginx + apache-httpd + +This list is not exhaustive, and you should evaluate these and other +servers based on your application's needs. Different servers will have +different capabilities, configuration, and support. + + +Hosting Platforms +----------------- + +There are many services available for hosting web applications without +needing to maintain your own server, networking, domain, etc. Some +services may have a free tier up to a certain time or bandwidth. Many of +these services use one of the WSGI servers described above, or a similar +interface. The links below are for some of the most common platforms, +which have instructions for Flask, WSGI, or Python. + +- `PythonAnywhere `_ +- `Google App Engine `_ +- `Google Cloud Run `_ +- `AWS Elastic Beanstalk `_ +- `Microsoft Azure `_ + +This list is not exhaustive, and you should evaluate these and other +services based on your application's needs. Different services will have +different capabilities, configuration, pricing, and support. - wsgi-standalone - uwsgi - mod_wsgi - fastcgi - cgi +You'll probably need to :doc:`proxy_fix` when using most hosting +platforms. diff --git a/docs/deploying/mod_wsgi.rst b/docs/deploying/mod_wsgi.rst index 76d986b7ae..23e8227989 100644 --- a/docs/deploying/mod_wsgi.rst +++ b/docs/deploying/mod_wsgi.rst @@ -1,223 +1,94 @@ -.. _mod_wsgi-deployment: +mod_wsgi +======== -mod_wsgi (Apache) -================= +`mod_wsgi`_ is a WSGI server integrated with the `Apache httpd`_ server. +The modern `mod_wsgi-express`_ command makes it easy to configure and +start the server without needing to write Apache httpd configuration. -If you are using the `Apache`_ webserver, consider using `mod_wsgi`_. +* Tightly integrated with Apache httpd. +* Supports Windows directly. +* Requires a compiler and the Apache development headers to install. +* Does not require a reverse proxy setup. -.. admonition:: Watch Out +This page outlines the basics of running mod_wsgi-express, not the more +complex installation and configuration with httpd. Be sure to read the +`mod_wsgi-express`_, `mod_wsgi`_, and `Apache httpd`_ documentation to +understand what features are available. - Please make sure in advance that any ``app.run()`` calls you might - have in your application file are inside an ``if __name__ == - '__main__':`` block or moved to a separate file. Just make sure it's - not called because this will always start a local WSGI server which - we do not want if we deploy that application to mod_wsgi. +.. _mod_wsgi-express: https://pypi.org/project/mod-wsgi/ +.. _mod_wsgi: https://modwsgi.readthedocs.io/ +.. _Apache httpd: https://httpd.apache.org/ -.. _Apache: https://httpd.apache.org/ -Installing `mod_wsgi` ---------------------- +Installing +---------- -If you don't have `mod_wsgi` installed yet you have to either install it -using a package manager or compile it yourself. The mod_wsgi -`installation instructions`_ cover source installations on UNIX systems. +Installing mod_wsgi requires a compiler and the Apache server and +development headers installed. You will get an error if they are not. +How to install them depends on the OS and package manager that you use. -If you are using Ubuntu/Debian you can apt-get it and activate it as -follows: +Create a virtualenv, install your application, then install +``mod_wsgi``. -.. sourcecode:: text +.. code-block:: text - $ apt-get install libapache2-mod-wsgi + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install mod_wsgi -If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you -can install it as follows: -.. sourcecode:: text +Running +------- - $ yum install mod_wsgi +The only argument to ``mod_wsgi-express`` specifies a script containing +your Flask application, which must be called ``application``. You can +write a small script to import your app with this name, or to create it +if using the app factory pattern. -On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by -using pkg_add: +.. code-block:: python + :caption: ``wsgi.py`` -.. sourcecode:: text + from hello import app - $ pkg install ap22-mod_wsgi2 + application = app -If you are using pkgsrc you can install `mod_wsgi` by compiling the -`www/ap2-wsgi` package. +.. code-block:: python + :caption: ``wsgi.py`` -If you encounter segfaulting child processes after the first apache -reload you can safely ignore them. Just restart the server. + from hello import create_app -Creating a `.wsgi` file ------------------------ - -To run your application you need a :file:`yourapplication.wsgi` file. -This file contains the code `mod_wsgi` is executing on startup -to get the application object. The object called `application` -in that file is then used as application. - -For most applications the following file should be sufficient:: - - from yourapplication import app as application - -If a factory function is used in a :file:`__init__.py` file, then the function should be imported:: - - from yourapplication import create_app application = create_app() -If you don't have a factory function for application creation but a singleton -instance you can directly import that one as `application`. - -Store that file somewhere that you will find it again (e.g.: -:file:`/var/www/yourapplication`) and make sure that `yourapplication` and all -the libraries that are in use are on the python load path. If you don't -want to install it system wide consider using a `virtual python`_ -instance. Keep in mind that you will have to actually install your -application into the virtualenv as well. Alternatively there is the -option to just patch the path in the ``.wsgi`` file before the import:: - - import sys - sys.path.insert(0, '/path/to/the/application') - -Configuring Apache ------------------- - -The last thing you have to do is to create an Apache configuration file -for your application. In this example we are telling `mod_wsgi` to -execute the application under a different user for security reasons: - -.. sourcecode:: apache - - - ServerName example.com - - WSGIDaemonProcess yourapplication user=user1 group=group1 threads=5 - WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi - - - WSGIProcessGroup yourapplication - WSGIApplicationGroup %{GLOBAL} - Order deny,allow - Allow from all - - - -Note: WSGIDaemonProcess isn't implemented in Windows and Apache will -refuse to run with the above configuration. On a Windows system, eliminate those lines: - -.. sourcecode:: apache - - - ServerName example.com - WSGIScriptAlias / C:\yourdir\yourapp.wsgi - - Order deny,allow - Allow from all - - - -Note: There have been some changes in access control configuration -for `Apache 2.4`_. - -.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html - -Most notably, the syntax for directory permissions has changed from httpd 2.2 - -.. sourcecode:: apache +Now run the ``mod_wsgi-express start-server`` command. - Order allow,deny - Allow from all +.. code-block:: text -to httpd 2.4 syntax + $ mod_wsgi-express start-server wsgi.py --processes 4 -.. sourcecode:: apache +The ``--processes`` option specifies the number of worker processes to +run; a starting value could be ``CPU * 2``. - Require all granted +Logs for each request aren't show in the terminal. If an error occurs, +its information is written to the error log file shown when starting the +server. -For more information consult the `mod_wsgi documentation`_. - -.. _mod_wsgi: https://github.com/GrahamDumpleton/mod_wsgi -.. _installation instructions: https://modwsgi.readthedocs.io/en/develop/installation.html -.. _virtual python: https://pypi.org/project/virtualenv/ -.. _mod_wsgi documentation: https://modwsgi.readthedocs.io/en/develop/index.html - -Troubleshooting ---------------- - -If your application does not run, follow this guide to troubleshoot: - -**Problem:** application does not run, errorlog shows SystemExit ignored - You have an ``app.run()`` call in your application file that is not - guarded by an ``if __name__ == '__main__':`` condition. Either - remove that :meth:`~flask.Flask.run` call from the file and move it - into a separate :file:`run.py` file or put it into such an if block. - -**Problem:** application gives permission errors - Probably caused by your application running as the wrong user. Make - sure the folders the application needs access to have the proper - privileges set and the application runs as the correct user - (``user`` and ``group`` parameter to the `WSGIDaemonProcess` - directive) - -**Problem:** application dies with an error on print - Keep in mind that mod_wsgi disallows doing anything with - :data:`sys.stdout` and :data:`sys.stderr`. You can disable this - protection from the config by setting the `WSGIRestrictStdout` to - ``off``: - - .. sourcecode:: apache - - WSGIRestrictStdout Off - - Alternatively you can also replace the standard out in the .wsgi file - with a different stream:: - - import sys - sys.stdout = sys.stderr - -**Problem:** accessing resources gives IO errors - Your application probably is a single .py file you symlinked into - the site-packages folder. Please be aware that this does not work, - instead you either have to put the folder into the pythonpath the - file is stored in, or convert your application into a package. - - The reason for this is that for non-installed packages, the module - filename is used to locate the resources and for symlinks the wrong - filename is picked up. - -Support for Automatic Reloading -------------------------------- - -To help deployment tools you can activate support for automatic -reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will -reload all the daemon processes for us. - -For that, just add the following directive to your `Directory` section: - -.. sourcecode:: apache - - WSGIScriptReloading On - -Working with Virtual Environments ---------------------------------- - -Virtual environments have the advantage that they never install the -required dependencies system wide so you have a better control over what -is used where. If you want to use a virtual environment with mod_wsgi -you have to modify your ``.wsgi`` file slightly. - -Add the following lines to the top of your ``.wsgi`` file:: +Binding Externally +------------------ - activate_this = '/path/to/env/bin/activate_this.py' - execfile(activate_this, dict(__file__=activate_this)) +Unlike the other WSGI servers in these docs, mod_wsgi can be run as +root to bind to privileged ports like 80 and 443. However, it must be +configured to drop permissions to a different user and group for the +worker processes. -For Python 3 add the following lines to the top of your ``.wsgi`` file:: +For example, if you created a ``hello`` user and group, you should +install your virtualenv and application as that user, then tell +mod_wsgi to drop to that user after starting. - activate_this = '/path/to/env/bin/activate_this.py' - with open(activate_this) as file_: - exec(file_.read(), dict(__file__=activate_this)) +.. code-block:: text -This sets up the load paths according to the settings of the virtual -environment. Keep in mind that the path has to be absolute. + $ sudo /home/hello/.venv/bin/mod_wsgi-express start-server \ + /home/hello/wsgi.py \ + --user hello --group hello --port 80 --processes 4 diff --git a/docs/deploying/nginx.rst b/docs/deploying/nginx.rst new file mode 100644 index 0000000000..6b25c073e8 --- /dev/null +++ b/docs/deploying/nginx.rst @@ -0,0 +1,69 @@ +nginx +===== + +`nginx`_ is a fast, production level HTTP server. When serving your +application with one of the WSGI servers listed in :doc:`index`, it is +often good or necessary to put a dedicated HTTP server in front of it. +This "reverse proxy" can handle incoming requests, TLS, and other +security and performance concerns better than the WSGI server. + +Nginx can be installed using your system package manager, or a pre-built +executable for Windows. Installing and running Nginx itself is outside +the scope of this doc. This page outlines the basics of configuring +Nginx to proxy your application. Be sure to read its documentation to +understand what features are available. + +.. _nginx: https://nginx.org/ + + +Domain Name +----------- + +Acquiring and configuring a domain name is outside the scope of this +doc. In general, you will buy a domain name from a registrar, pay for +server space with a hosting provider, and then point your registrar +at the hosting provider's name servers. + +To simulate this, you can also edit your ``hosts`` file, located at +``/etc/hosts`` on Linux. Add a line that associates a name with the +local IP. + +Modern Linux systems may be configured to treat any domain name that +ends with ``.localhost`` like this without adding it to the ``hosts`` +file. + +.. code-block:: python + :caption: ``/etc/hosts`` + + 127.0.0.1 hello.localhost + + +Configuration +------------- + +The nginx configuration is located at ``/etc/nginx/nginx.conf`` on +Linux. It may be different depending on your operating system. Check the +docs and look for ``nginx.conf``. + +Remove or comment out any existing ``server`` section. Add a ``server`` +section and use the ``proxy_pass`` directive to point to the address the +WSGI server is listening on. We'll assume the WSGI server is listening +locally at ``http://127.0.0.1:8000``. + +.. code-block:: nginx + :caption: ``/etc/nginx.conf`` + + server { + listen 80; + server_name _; + + location / { + proxy_pass http://127.0.0.1:8000/; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_set_header X-Forwarded-Prefix /; + } + } + +Then :doc:`proxy_fix` so that your application uses these headers. diff --git a/docs/deploying/proxy_fix.rst b/docs/deploying/proxy_fix.rst new file mode 100644 index 0000000000..e2c42e8257 --- /dev/null +++ b/docs/deploying/proxy_fix.rst @@ -0,0 +1,33 @@ +Tell Flask it is Behind a Proxy +=============================== + +When using a reverse proxy, or many Python hosting platforms, the proxy +will intercept and forward all external requests to the local WSGI +server. + +From the WSGI server and Flask application's perspectives, requests are +now coming from the HTTP server to the local address, rather than from +the remote address to the external server address. + +HTTP servers should set ``X-Forwarded-`` headers to pass on the real +values to the application. The application can then be told to trust and +use those values by wrapping it with the +:doc:`werkzeug:middleware/proxy_fix` middleware provided by Werkzeug. + +This middleware should only be used if the application is actually +behind a proxy, and should be configured with the number of proxies that +are chained in front of it. Not all proxies set all the headers. Since +incoming headers can be faked, you must set how many proxies are setting +each header so the middleware knows what to trust. + +.. code-block:: python + + from werkzeug.middleware.proxy_fix import ProxyFix + + app.wsgi_app = ProxyFix( + app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 + ) + +Remember, only apply this middleware if you are behind a proxy, and set +the correct number of proxies that set each header. It can be a security +issue if you get this configuration wrong. diff --git a/docs/deploying/uwsgi.rst b/docs/deploying/uwsgi.rst index cbbf00aa62..1f9d5eca00 100644 --- a/docs/deploying/uwsgi.rst +++ b/docs/deploying/uwsgi.rst @@ -1,73 +1,145 @@ -.. _deploying-uwsgi: - uWSGI ===== -uWSGI is a deployment option on servers like `nginx`_, `lighttpd`_, and -`cherokee`_; see :doc:`fastcgi` and :doc:`wsgi-standalone` for other options. -To use your WSGI application with uWSGI protocol you will need a uWSGI server -first. uWSGI is both a protocol and an application server; the application -server can serve uWSGI, FastCGI, and HTTP protocols. +`uWSGI`_ is a fast, compiled server suite with extensive configuration +and capabilities beyond a basic server. + +* It can be very performant due to being a compiled program. +* It is complex to configure beyond the basic application, and has so + many options that it can be difficult for beginners to understand. +* It does not support Windows (but does run on WSL). +* It requires a compiler to install in some cases. + +This page outlines the basics of running uWSGI. Be sure to read its +documentation to understand what features are available. + +.. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/ + + +Installing +---------- + +uWSGI has multiple ways to install it. The most straightforward is to +install the ``pyuwsgi`` package, which provides precompiled wheels for +common platforms. However, it does not provide SSL support, which can be +provided with a reverse proxy instead. + +Create a virtualenv, install your application, then install ``pyuwsgi``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install pyuwsgi + +If you have a compiler available, you can install the ``uwsgi`` package +instead. Or install the ``pyuwsgi`` package from sdist instead of wheel. +Either method will include SSL support. + +.. code-block:: text + + $ pip install uwsgi + + # or + $ pip install --no-binary pyuwsgi pyuwsgi + -The most popular uWSGI server is `uwsgi`_, which we will use for this -guide. Make sure to have it installed to follow along. +Running +------- -.. admonition:: Watch Out +The most basic way to run uWSGI is to tell it to start an HTTP server +and import your application. - Please make sure in advance that any ``app.run()`` calls you might - have in your application file are inside an ``if __name__ == - '__main__':`` block or moved to a separate file. Just make sure it's - not called because this will always start a local WSGI server which - we do not want if we deploy that application to uWSGI. +.. code-block:: text -Starting your app with uwsgi ----------------------------- + $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app -`uwsgi` is designed to operate on WSGI callables found in python modules. + *** Starting uWSGI 2.0.20 (64bit) on [x] *** + *** Operational MODE: preforking *** + mounting hello:app on / + spawned uWSGI master process (pid: x) + spawned uWSGI worker 1 (pid: x, cores: 1) + spawned uWSGI worker 2 (pid: x, cores: 1) + spawned uWSGI worker 3 (pid: x, cores: 1) + spawned uWSGI worker 4 (pid: x, cores: 1) + spawned uWSGI http 1 (pid: x) -Given a flask application in myapp.py, use the following command: +If you're using the app factory pattern, you'll need to create a small +Python file to create the app, then point uWSGI at that. -.. sourcecode:: text +.. code-block:: python + :caption: ``wsgi.py`` - $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app + from hello import create_app -The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` -to uwsgi, since it is smarter about that. -It is used together with the ``--mount`` directive which will make -requests to ``/yourapplication`` be directed to ``myapp:app``. -If your application is accessible at root level, you can use a -single ``/`` instead of ``/yourapplication``. ``myapp`` refers to the name of -the file of your flask application (without extension) or the module which -provides ``app``. ``app`` is the callable inside of your application (usually -the line reads ``app = Flask(__name__)``. + app = create_app() -If you want to deploy your flask application inside of a virtual environment, -you need to also add ``--virtualenv /path/to/virtual/environment``. You might -also need to add ``--plugin python`` or ``--plugin python3`` depending on which -python version you use for your project. +.. code-block:: text -Configuring nginx + $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app + +The ``--http`` option starts an HTTP server at 127.0.0.1 port 8000. The +``--master`` option specifies the standard worker manager. The ``-p`` +option starts 4 worker processes; a starting value could be ``CPU * 2``. +The ``-w`` option tells uWSGI how to import your application + + +Binding Externally +------------------ + +uWSGI should not be run as root with the configuration shown in this doc +because it would cause your application code to run as root, which is +not secure. However, this means it will not be possible to bind to port +80 or 443. Instead, a reverse proxy such as :doc:`nginx` or +:doc:`apache-httpd` should be used in front of uWSGI. It is possible to +run uWSGI as root securely, but that is beyond the scope of this doc. + +uWSGI has optimized integration with `Nginx uWSGI`_ and +`Apache mod_proxy_uwsgi`_, and possibly other servers, instead of using +a standard HTTP proxy. That configuration is beyond the scope of this +doc, see the links for more information. + +.. _Nginx uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/Nginx.html +.. _Apache mod_proxy_uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/Apache.html#mod-proxy-uwsgi + +You can bind to all external IPs on a non-privileged port using the +``--http 0.0.0.0:8000`` option. Don't do this when using a reverse proxy +setup, otherwise it will be possible to bypass the proxy. + +.. code-block:: text + + $ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. + + +Async with gevent ----------------- -A basic flask nginx configuration looks like this:: +The default sync worker is appropriate for many use cases. If you need +asynchronous support, uWSGI provides a `gevent`_ worker. This is not the +same as Python's ``async/await``, or the ASGI server spec. You must +actually use gevent in your own code to see any benefit to using the +worker. + +When using gevent, greenlet>=1.0 is required, otherwise context locals +such as ``request`` will not work as expected. When using PyPy, +PyPy>=7.3.7 is required. + +.. code-block:: text - location = /yourapplication { rewrite ^ /yourapplication/; } - location /yourapplication { try_files $uri @yourapplication; } - location @yourapplication { - include uwsgi_params; - uwsgi_pass unix:/tmp/yourapplication.sock; - } + $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app -This configuration binds the application to ``/yourapplication``. If you want -to have it in the URL root its a bit simpler:: + *** Starting uWSGI 2.0.20 (64bit) on [x] *** + *** Operational MODE: async *** + mounting hello:app on / + spawned uWSGI master process (pid: x) + spawned uWSGI worker 1 (pid: x, cores: 100) + spawned uWSGI http 1 (pid: x) + *** running gevent loop engine [addr:x] *** - location / { try_files $uri @yourapplication; } - location @yourapplication { - include uwsgi_params; - uwsgi_pass unix:/tmp/yourapplication.sock; - } -.. _nginx: https://nginx.org/ -.. _lighttpd: https://www.lighttpd.net/ -.. _cherokee: http://cherokee-project.com/ -.. _uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/ +.. _gevent: https://www.gevent.org/ diff --git a/docs/deploying/waitress.rst b/docs/deploying/waitress.rst new file mode 100644 index 0000000000..aeafb9f776 --- /dev/null +++ b/docs/deploying/waitress.rst @@ -0,0 +1,75 @@ +Waitress +======== + +`Waitress`_ is a pure Python WSGI server. + +* It is easy to configure. +* It supports Windows directly. +* It is easy to install as it does not require additional dependencies + or compilation. +* It does not support streaming requests, full request data is always + buffered. +* It uses a single process with multiple thread workers. + +This page outlines the basics of running Waitress. Be sure to read its +documentation and ``waitress-serve --help`` to understand what features +are available. + +.. _Waitress: https://docs.pylonsproject.org/projects/waitress/ + + +Installing +---------- + +Create a virtualenv, install your application, then install +``waitress``. + +.. code-block:: text + + $ cd hello-app + $ python -m venv .venv + $ . .venv/bin/activate + $ pip install . # install your application + $ pip install waitress + + +Running +------- + +The only required argument to ``waitress-serve`` tells it how to load +your Flask application. The syntax is ``{module}:{app}``. ``module`` is +the dotted import name to the module with your application. ``app`` is +the variable with the application. If you're using the app factory +pattern, use ``--call {module}:{factory}`` instead. + +.. code-block:: text + + # equivalent to 'from hello import app' + $ waitress-serve --host 127.0.0.1 hello:app + + # equivalent to 'from hello import create_app; create_app()' + $ waitress-serve --host 127.0.0.1 --call hello:create_app + + Serving on http://127.0.0.1:8080 + +The ``--host`` option binds the server to local ``127.0.0.1`` only. + +Logs for each request aren't shown, only errors are shown. Logging can +be configured through the Python interface instead of the command line. + + +Binding Externally +------------------ + +Waitress should not be run as root because it would cause your +application code to run as root, which is not secure. However, this +means it will not be possible to bind to port 80 or 443. Instead, a +reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used +in front of Waitress. + +You can bind to all external IPs on a non-privileged port by not +specifying the ``--host`` option. Don't do this when using a revers +proxy setup, otherwise it will be possible to bypass the proxy. + +``0.0.0.0`` is not a valid address to navigate to, you'd use a specific +IP address in your browser. diff --git a/docs/deploying/wsgi-standalone.rst b/docs/deploying/wsgi-standalone.rst deleted file mode 100644 index 6614928be8..0000000000 --- a/docs/deploying/wsgi-standalone.rst +++ /dev/null @@ -1,155 +0,0 @@ -.. _deploying-wsgi-standalone: - -Standalone WSGI Containers -========================== - -There are popular servers written in Python that contain WSGI applications and -serve HTTP. These servers stand alone when they run; you can proxy to them -from your web server. Note the section on :ref:`deploying-proxy-setups` if you -run into issues. - -Gunicorn --------- - -`Gunicorn`_ 'Green Unicorn' is a WSGI HTTP Server for UNIX. It's a pre-fork -worker model ported from Ruby's Unicorn project. It supports both `eventlet`_ -and `greenlet`_. Running a Flask application on this server is quite simple:: - - $ gunicorn myproject:app - -`Gunicorn`_ provides many command-line options -- see ``gunicorn -h``. -For example, to run a Flask application with 4 worker processes (``-w -4``) binding to localhost port 4000 (``-b 127.0.0.1:4000``):: - - $ gunicorn -w 4 -b 127.0.0.1:4000 myproject:app - -The ``gunicorn`` command expects the names of your application module or -package and the application instance within the module. If you use the -application factory pattern, you can pass a call to that:: - - $ gunicorn "myproject:create_app()" - -.. _Gunicorn: https://gunicorn.org/ -.. _eventlet: https://eventlet.net/ - - -uWSGI --------- - -`uWSGI`_ is a fast application server written in C. It is very configurable -which makes it more complicated to setup than gunicorn. - -Running `uWSGI HTTP Router`_:: - - $ uwsgi --http 127.0.0.1:5000 --module myproject:app - -For a more optimized setup, see :doc:`configuring uWSGI and NGINX `. - -.. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/ -.. _uWSGI HTTP Router: https://uwsgi-docs.readthedocs.io/en/latest/HTTP.html#the-uwsgi-http-https-router - -Gevent -------- - -`Gevent`_ is a coroutine-based Python networking library that uses -`greenlet`_ to provide a high-level synchronous API on top of `libev`_ -event loop:: - - from gevent.pywsgi import WSGIServer - from yourapplication import app - - http_server = WSGIServer(('', 5000), app) - http_server.serve_forever() - -.. _Gevent: http://www.gevent.org/ -.. _greenlet: https://greenlet.readthedocs.io/en/latest/ -.. _libev: http://software.schmorp.de/pkg/libev.html - -Twisted Web ------------ - -`Twisted Web`_ is the web server shipped with `Twisted`_, a mature, -non-blocking event-driven networking library. Twisted Web comes with a -standard WSGI container which can be controlled from the command line using -the ``twistd`` utility:: - - $ twistd web --wsgi myproject.app - -This example will run a Flask application called ``app`` from a module named -``myproject``. - -Twisted Web supports many flags and options, and the ``twistd`` utility does -as well; see ``twistd -h`` and ``twistd web -h`` for more information. For -example, to run a Twisted Web server in the foreground, on port 8080, with an -application from ``myproject``:: - - $ twistd -n web --port tcp:8080 --wsgi myproject.app - -.. _Twisted: https://twistedmatrix.com/trac/ -.. _Twisted Web: https://twistedmatrix.com/trac/wiki/TwistedWeb - -.. _deploying-proxy-setups: - -Proxy Setups ------------- - -If you deploy your application using one of these servers behind an HTTP proxy -you will need to rewrite a few headers in order for the application to work. -The two problematic values in the WSGI environment usually are ``REMOTE_ADDR`` -and ``HTTP_HOST``. You can configure your httpd to pass these headers, or you -can fix them in middleware. Werkzeug ships a fixer that will solve some common -setups, but you might want to write your own WSGI middleware for specific -setups. - -Here's a simple nginx configuration which proxies to an application served on -localhost at port 8000, setting appropriate headers: - -.. sourcecode:: nginx - - server { - listen 80; - - server_name _; - - access_log /var/log/nginx/access.log; - error_log /var/log/nginx/error.log; - - location / { - proxy_pass http://127.0.0.1:8000/; - proxy_redirect off; - - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - } - } - -If your httpd is not providing these headers, the most common setup invokes the -host being set from ``X-Forwarded-Host`` and the remote address from -``X-Forwarded-For``:: - - from werkzeug.middleware.proxy_fix import ProxyFix - app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1) - -.. admonition:: Trusting Headers - - Please keep in mind that it is a security issue to use such a middleware in - a non-proxy setup because it will blindly trust the incoming headers which - might be forged by malicious clients. - -If you want to rewrite the headers from another header, you might want to -use a fixer like this:: - - class CustomProxyFix(object): - - def __init__(self, app): - self.app = app - - def __call__(self, environ, start_response): - host = environ.get('HTTP_X_FHOST', '') - if host: - environ['HTTP_HOST'] = host - return self.app(environ, start_response) - - app.wsgi_app = CustomProxyFix(app.wsgi_app) diff --git a/docs/design.rst b/docs/design.rst index 3dd1a284bd..066cf107c1 100644 --- a/docs/design.rst +++ b/docs/design.rst @@ -1,5 +1,3 @@ -.. _design: - Design Decisions in Flask ========================= @@ -77,7 +75,7 @@ to the application object :meth:`~flask.Flask.wsgi_app`). Furthermore this design makes it possible to use a factory function to create the application which is very helpful for unit testing and similar -things (:ref:`app-factories`). +things (:doc:`/patterns/appfactories`). The Routing System ------------------ @@ -109,14 +107,14 @@ has a certain understanding about how things work. On the surface they all work the same: you tell the engine to evaluate a template with a set of variables and take the return value as string. -But that's about where similarities end. Jinja2 for example has an -extensive filter system, a certain way to do template inheritance, support -for reusable blocks (macros) that can be used from inside templates and -also from Python code, uses Unicode for all operations, supports -iterative template rendering, configurable syntax and more. On the other -hand an engine like Genshi is based on XML stream evaluation, template -inheritance by taking the availability of XPath into account and more. -Mako on the other hand treats templates similar to Python modules. +But that's about where similarities end. Jinja2 for example has an +extensive filter system, a certain way to do template inheritance, +support for reusable blocks (macros) that can be used from inside +templates and also from Python code, supports iterative template +rendering, configurable syntax and more. On the other hand an engine +like Genshi is based on XML stream evaluation, template inheritance by +taking the availability of XPath into account and more. Mako on the +other hand treats templates similar to Python modules. When it comes to connecting a template engine with an application or framework there is more than just rendering templates. For instance, @@ -132,9 +130,25 @@ being present. You can easily use your own templating language, but an extension could still depend on Jinja itself. -Micro with Dependencies +What does "micro" mean? ----------------------- +“Micro” does not mean that your whole web application has to fit into a single +Python file (although it certainly can), nor does it mean that Flask is lacking +in functionality. The "micro" in microframework means Flask aims to keep the +core simple but extensible. Flask won't make many decisions for you, such as +what database to use. Those decisions that it does make, such as what +templating engine to use, are easy to change. Everything else is up to you, so +that Flask can be everything you need and nothing you don't. + +By default, Flask does not include a database abstraction layer, form +validation or anything else where different libraries already exist that can +handle that. Instead, Flask supports extensions to add such functionality to +your application as if it was implemented in Flask itself. Numerous extensions +provide database integration, form validation, upload handling, various open +authentication technologies, and more. Flask may be "micro", but it's ready for +production use on a variety of needs. + Why does Flask call itself a microframework and yet it depends on two libraries (namely Werkzeug and Jinja2). Why shouldn't it? If we look over to the Ruby side of web development there we have a protocol very @@ -169,8 +183,24 @@ large applications harder to maintain. However Flask is just not designed for large applications or asynchronous servers. Flask wants to make it quick and easy to write a traditional web application. -Also see the :ref:`becomingbig` section of the documentation for some -inspiration for larger applications based on Flask. + +Async/await and ASGI support +---------------------------- + +Flask supports ``async`` coroutines for view functions by executing the +coroutine on a separate thread instead of using an event loop on the +main thread as an async-first (ASGI) framework would. This is necessary +for Flask to remain backwards compatible with extensions and code built +before ``async`` was introduced into Python. This compromise introduces +a performance cost compared with the ASGI frameworks, due to the +overhead of the threads. + +Due to how tied to WSGI Flask's code is, it's not clear if it's possible +to make the ``Flask`` class support ASGI and WSGI at the same time. Work +is currently being done in Werkzeug to work with ASGI, which may +eventually enable support in Flask as well. + +See :doc:`/async-await` for more discussion. What Flask is, What Flask is Not @@ -187,5 +217,12 @@ requirements and Flask could not meet those if it would force any of this into the core. The majority of web applications will need a template engine in some sort. However not every application needs a SQL database. +As your codebase grows, you are free to make the design decisions appropriate +for your project. Flask will continue to provide a very simple glue layer to +the best that Python has to offer. You can implement advanced patterns in +SQLAlchemy or another database tool, introduce non-relational data persistence +as appropriate, and take advantage of framework-agnostic tools built for WSGI, +the Python web interface. + The idea of Flask is to build a good foundation for all applications. Everything else is up to you or extensions. diff --git a/docs/errorhandling.rst b/docs/errorhandling.rst index 2f4b7335e5..c281055f85 100644 --- a/docs/errorhandling.rst +++ b/docs/errorhandling.rst @@ -1,14 +1,10 @@ -.. _application-errors: +Handling Application Errors +=========================== -Application Errors -================== - -.. versionadded:: 0.3 - -Applications fail, servers fail. Sooner or later you will see an exception -in production. Even if your code is 100% correct, you will still see -exceptions from time to time. Why? Because everything else involved will -fail. Here are some situations where perfectly fine code can lead to server +Applications fail, servers fail. Sooner or later you will see an exception +in production. Even if your code is 100% correct, you will still see +exceptions from time to time. Why? Because everything else involved will +fail. Here are some situations where perfectly fine code can lead to server errors: - the client terminated the request early and the application was still @@ -20,13 +16,16 @@ errors: - a programming error in a library you are using - network connection of the server to another system failed -And that's just a small sample of issues you could be facing. So how do we -deal with that sort of problem? By default if your application runs in -production mode, Flask will display a very simple page for you and log the -exception to the :attr:`~flask.Flask.logger`. +And that's just a small sample of issues you could be facing. So how do we +deal with that sort of problem? By default if your application runs in +production mode, and an exception is raised Flask will display a very simple +page for you and log the exception to the :attr:`~flask.Flask.logger`. But there is more you can do, and we will cover some better setups to deal -with errors. +with errors including custom exceptions and 3rd party tools. + + +.. _error-logging-tools: Error Logging Tools ------------------- @@ -34,51 +33,66 @@ Error Logging Tools Sending error mails, even if just for critical ones, can become overwhelming if enough users are hitting the error and log files are typically never looked at. This is why we recommend using `Sentry -`_ for dealing with application errors. It's -available as an Open Source project `on GitHub +`_ for dealing with application errors. It's +available as a source-available project `on GitHub `_ and is also available as a `hosted version `_ which you can try for free. Sentry aggregates duplicate errors, captures the full stack trace and local variables for debugging, and sends you mails based on new errors or frequency thresholds. -To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies:: +To use Sentry you need to install the ``sentry-sdk`` client with extra +``flask`` dependencies. + +.. code-block:: text $ pip install sentry-sdk[flask] -And then add this to your Flask app:: +And then add this to your Flask app: + +.. code-block:: python import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration - sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()]) + sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()]) -The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get -from your Sentry installation. +The ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you +get from your Sentry installation. After installation, failures leading to an Internal Server Error are automatically reported to Sentry and from there you can receive error notifications. -Follow-up reads: +See also: -* Sentry also supports catching errors from your worker queue (RQ, Celery) in a - similar fashion. See the `Python SDK docs - `_ for more information. -* `Getting started with Sentry `_ -* `Flask-specific documentation `_. +- Sentry also supports catching errors from a worker queue + (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs + `__ for more information. +- `Flask-specific documentation `__ -.. _error-handlers: -Error handlers +Error Handlers -------------- +When an error occurs in Flask, an appropriate `HTTP status code +`__ will be +returned. 400-499 indicate errors with the client's request data, or +about the data requested. 500-599 indicate errors with the server or +application itself. + You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers. -An error handler is a normal view function that returns a response, but instead -of being registered for a route, it is registered for an exception or HTTP -status code that would be raised while trying to handle a request. +An error handler is a function that returns a response when a type of error is +raised, similar to how a view is a function that returns a response when a +request URL is matched. It is passed the instance of the error being handled, +which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. + +The status code of the response will not be set to the handler's code. Make +sure to provide the appropriate HTTP status code when returning a response from +a handler. + Registering ``````````` @@ -86,7 +100,9 @@ Registering Register handlers by decorating a function with :meth:`~flask.Flask.errorhandler`. Or use :meth:`~flask.Flask.register_error_handler` to register the function later. -Remember to set the error code when returning the response. :: +Remember to set the error code when returning the response. + +.. code-block:: python @app.errorhandler(werkzeug.exceptions.BadRequest) def handle_bad_request(e): @@ -102,7 +118,9 @@ when registering handlers. (``BadRequest.code == 400``) Non-standard HTTP codes cannot be registered by code because they are not known by Werkzeug. Instead, define a subclass of :class:`~werkzeug.exceptions.HTTPException` with the appropriate code and -register and raise that exception class. :: +register and raise that exception class. + +.. code-block:: python class InsufficientStorage(werkzeug.exceptions.HTTPException): code = 507 @@ -117,21 +135,36 @@ Handlers can be registered for any exception class, not just codes. Handlers can be registered for a specific class, or for all subclasses of a parent class. + Handling ```````` -When an exception is caught by Flask while handling a request, it is first -looked up by code. If no handler is registered for the code, it is looked up -by its class hierarchy; the most specific handler is chosen. If no handler is -registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a +When building a Flask application you *will* run into exceptions. If some part +of your code breaks while handling a request (and you have no error handlers +registered), a "500 Internal Server Error" +(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default. +Similarly, "404 Not Found" +(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route. +If a route receives an unallowed request method, a "405 Method Not Allowed" +(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all +subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by +default in Flask. + +Flask gives you the ability to raise any HTTP exception registered by +Werkzeug. However, the default HTTP exceptions return simple exception +pages. You might want to show custom error pages to the user when an error occurs. +This can be done by registering error handlers. + +When Flask catches an exception while handling a request, it is first looked up by code. +If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen. +If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a generic message about their code, while other exceptions are converted to a -generic 500 Internal Server Error. +generic "500 Internal Server Error". For example, if an instance of :exc:`ConnectionRefusedError` is raised, and a handler is registered for :exc:`ConnectionError` and -:exc:`ConnectionRefusedError`, -the more specific :exc:`ConnectionRefusedError` handler is called with the -exception instance to generate the response. +:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError` +handler is called with the exception instance to generate the response. Handlers registered on the blueprint take precedence over those registered globally on the application, assuming a blueprint is handling the request that @@ -147,8 +180,8 @@ It is possible to register error handlers for very generic base classes such as ``HTTPException`` or even ``Exception``. However, be aware that these will catch more than you might expect. -An error handler for ``HTTPException`` might be useful for turning -the default HTML errors pages into JSON, for example. However, this +For example, an error handler for ``HTTPException`` might be useful for turning +the default HTML errors pages into JSON. However, this handler will trigger for things you don't cause directly, such as 404 and 405 errors during routing. Be sure to craft your handler carefully so you don't lose information about the HTTP error. @@ -172,12 +205,13 @@ so you don't lose information about the HTTP error. response.content_type = "application/json" return response - An error handler for ``Exception`` might seem useful for changing how all errors, even unhandled ones, are presented to the user. However, this is similar to doing ``except Exception:`` in Python, it will capture *all* otherwise unhandled errors, including all HTTP status -codes. In most cases it will be safer to register handlers for more +codes. + +In most cases it will be safer to register handlers for more specific exceptions. Since ``HTTPException`` instances are valid WSGI responses, you could also pass them through directly. @@ -199,6 +233,7 @@ register handlers for both ``HTTPException`` and ``Exception``, the ``Exception`` handler will not handle ``HTTPException`` subclasses because it the ``HTTPException`` handler is more specific. + Unhandled Exceptions ```````````````````` @@ -210,88 +245,279 @@ behavior. If there is an error handler registered for ``InternalServerError``, this will be invoked. As of Flask 1.1.0, this error handler will always be passed an instance of ``InternalServerError``, not the original -unhandled error. The original error is available as ``e.original_error``. -Until Werkzeug 1.0.0, this attribute will only exist during unhandled -errors, use ``getattr`` to get access it for compatibility. +unhandled error. + +The original error is available as ``e.original_exception``. + +An error handler for "500 Internal Server Error" will be passed uncaught +exceptions in addition to explicit 500 errors. In debug mode, a handler +for "500 Internal Server Error" will not be used. Instead, the +interactive debugger will be shown. + + +Custom Error Pages +------------------ + +Sometimes when building a Flask application, you might want to raise a +:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that +something is wrong with the request. Fortunately, Flask comes with a handy +:func:`~flask.abort` function that aborts a request with a HTTP error from +werkzeug as desired. It will also provide a plain black and white error page +for you with a basic description, but nothing fancy. + +Depending on the error code it is less or more likely for the user to +actually see such an error. + +Consider the code below, we might have a user profile route, and if the user +fails to pass a username we can raise a "400 Bad Request". If the user passes a +username and we can't find it, we raise a "404 Not Found". .. code-block:: python - @app.errorhandler(InternalServerError) - def handle_500(e): - original = getattr(e, "original_exception", None) + from flask import abort, render_template, request - if original is None: - # direct 500 error, such as abort(500) - return render_template("500.html"), 500 + # a username needs to be supplied in the query args + # a successful request would be like /profile?username=jack + @app.route("/profile") + def user_profile(): + username = request.arg.get("username") + # if a username isn't supplied in the request, return a 400 bad request + if username is None: + abort(400) - # wrapped unhandled error - return render_template("500_unhandled.html", e=original), 500 + user = get_user(username=username) + # if a user can't be found by their username, return 404 not found + if user is None: + abort(404) + return render_template("profile.html", user=user) -Logging -------- +Here is another example implementation for a "404 Page Not Found" exception: + +.. code-block:: python -See :doc:`/logging` for information on how to log exceptions, such as by -emailing them to admins. + from flask import render_template + @app.errorhandler(404) + def page_not_found(e): + # note that we set the 404 status explicitly + return render_template('404.html'), 404 -Debugging Application Errors -============================ +When using :doc:`/patterns/appfactories`: -For production applications, configure your application with logging and -notifications as described in :ref:`application-errors`. This section provides -pointers when debugging deployment configuration and digging deeper with a -full-featured Python debugger. +.. code-block:: python + + from flask import Flask, render_template + + def page_not_found(e): + return render_template('404.html'), 404 + + def create_app(config_filename): + app = Flask(__name__) + app.register_error_handler(404, page_not_found) + return app + +An example template might be this: +.. code-block:: html+jinja -When in Doubt, Run Manually ---------------------------- + {% extends "layout.html" %} + {% block title %}Page Not Found{% endblock %} + {% block body %} +

Page Not Found

+

What you were looking for is just not there. +

go somewhere nice + {% endblock %} -Having problems getting your application configured for production? If you -have shell access to your host, verify that you can run your application -manually from the shell in the deployment environment. Be sure to run under -the same user account as the configured deployment to troubleshoot permission -issues. You can use Flask's builtin development server with `debug=True` on -your production host, which is helpful in catching configuration issues, but -**be sure to do this temporarily in a controlled environment.** Do not run in -production with `debug=True`. +Further Examples +```````````````` -.. _working-with-debuggers: +The above examples wouldn't actually be an improvement on the default +exception pages. We can create a custom 500.html template like this: -Working with Debuggers ----------------------- +.. code-block:: html+jinja -To dig deeper, possibly to trace code execution, Flask provides a debugger out -of the box (see :ref:`debug-mode`). If you would like to use another Python -debugger, note that debuggers interfere with each other. You have to set some -options in order to use your favorite debugger: + {% extends "layout.html" %} + {% block title %}Internal Server Error{% endblock %} + {% block body %} +

Internal Server Error

+

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

+

Go somewhere nice instead + {% endblock %} -* ``debug`` - whether to enable debug mode and catch exceptions -* ``use_debugger`` - whether to use the internal Flask debugger -* ``use_reloader`` - whether to reload and fork the process if modules - were changed +It can be implemented by rendering the template on "500 Internal Server Error": -``debug`` must be True (i.e., exceptions must be caught) in order for the other -two options to have any value. +.. code-block:: python + + from flask import render_template + + @app.errorhandler(500) + def internal_server_error(e): + # note that we set the 500 status explicitly + return render_template('500.html'), 500 -If you're using Aptana/Eclipse for debugging you'll need to set both -``use_debugger`` and ``use_reloader`` to False. +When using :doc:`/patterns/appfactories`: + +.. code-block:: python -A possible useful pattern for configuration is to set the following in your -config.yaml (change the block as appropriate for your application, of course):: + from flask import Flask, render_template + + def internal_server_error(e): + return render_template('500.html'), 500 + + def create_app(): + app = Flask(__name__) + app.register_error_handler(500, internal_server_error) + return app + +When using :doc:`/blueprints`: + +.. code-block:: python + + from flask import Blueprint + + blog = Blueprint('blog', __name__) + + # as a decorator + @blog.errorhandler(500) + def internal_server_error(e): + return render_template('500.html'), 500 + + # or with register_error_handler + blog.register_error_handler(500, internal_server_error) + + +Blueprint Error Handlers +------------------------ + +In :doc:`/blueprints`, most error handlers will work as expected. +However, there is a caveat concerning handlers for 404 and 405 +exceptions. These error handlers are only invoked from an appropriate +``raise`` statement or a call to ``abort`` in another of the blueprint's +view functions; they are not invoked by, e.g., an invalid URL access. + +This is because the blueprint does not "own" a certain URL space, so +the application instance has no way of knowing which blueprint error +handler it should run if given an invalid URL. If you would like to +execute different handling strategies for these errors based on URL +prefixes, they may be defined at the application level using the +``request`` proxy object. + +.. code-block:: python + + from flask import jsonify, render_template + + # at the application level + # not the blueprint level + @app.errorhandler(404) + def page_not_found(e): + # if a request is in our blog URL space + if request.path.startswith('/blog/'): + # we return a custom blog 404 page + return render_template("blog/404.html"), 404 + else: + # otherwise we return our generic site-wide 404 page + return render_template("404.html"), 404 + + @app.errorhandler(405) + def method_not_allowed(e): + # if a request has the wrong method to our API + if request.path.startswith('/api/'): + # we return a json saying so + return jsonify(message="Method Not Allowed"), 405 + else: + # otherwise we return a generic site-wide 405 page + return render_template("405.html"), 405 + + +Returning API Errors as JSON +---------------------------- + +When building APIs in Flask, some developers realise that the built-in +exceptions are not expressive enough for APIs and that the content type of +:mimetype:`text/html` they are emitting is not very useful for API consumers. + +Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON +responses to API errors. :func:`~flask.abort` is called +with a ``description`` parameter. The error handler will +use that as the JSON error message, and set the status code to 404. + +.. code-block:: python + + from flask import abort, jsonify + + @app.errorhandler(404) + def resource_not_found(e): + return jsonify(error=str(e)), 404 + + @app.route("/cheese") + def get_one_cheese(): + resource = get_resource() + + if resource is None: + abort(404, description="Resource not found") + + return jsonify(resource) + +We can also create custom exception classes. For instance, we can +introduce a new custom exception for an API that can take a proper human readable message, +a status code for the error and some optional payload to give more context +for the error. + +This is a simple example: + +.. code-block:: python + + from flask import jsonify, request + + class InvalidAPIUsage(Exception): + status_code = 400 + + def __init__(self, message, status_code=None, payload=None): + super().__init__() + self.message = message + if status_code is not None: + self.status_code = status_code + self.payload = payload + + def to_dict(self): + rv = dict(self.payload or ()) + rv['message'] = self.message + return rv + + @app.errorhandler(InvalidAPIUsage) + def invalid_api_usage(e): + return jsonify(e.to_dict()), e.status_code + + # an API app route for getting user information + # a correct request might be /api/user?user_id=420 + @app.route("/api/user") + def user_api(user_id): + user_id = request.arg.get("user_id") + if not user_id: + raise InvalidAPIUsage("No user id provided!") + + user = get_user(user_id=user_id) + if not user: + raise InvalidAPIUsage("No such user!", status_code=404) + + return jsonify(user.to_dict()) + +A view can now raise that exception with an error message. Additionally +some extra payload can be provided as a dictionary through the `payload` +parameter. + + +Logging +------- - FLASK: - DEBUG: True - DEBUG_WITH_APTANA: True +See :doc:`/logging` for information about how to log exceptions, such as +by emailing them to admins. -Then in your application's entry-point (main.py), -you could have something like:: - if __name__ == "__main__": - # To allow aptana to receive errors, set use_debugger=False - app = create_app(config="config.yaml") +Debugging +--------- - use_debugger = app.debug and not(app.config.get('DEBUG_WITH_APTANA')) - app.run(use_debugger=use_debugger, debug=app.debug, - use_reloader=use_debugger, host='0.0.0.0') +See :doc:`/debugging` for information about how to debug errors in +development and production. diff --git a/docs/extensiondev.rst b/docs/extensiondev.rst index a7b160624c..c9dee5ff63 100644 --- a/docs/extensiondev.rst +++ b/docs/extensiondev.rst @@ -1,344 +1,303 @@ -.. _extension-dev: - Flask Extension Development =========================== -Flask, being a microframework, often requires some repetitive steps to get -a third party library working. Many such extensions are already available -on `PyPI `_. - -If you want to create your own Flask extension for something that does not -exist yet, this guide to extension development will help you get your -extension running in no time and to feel like users would expect your -extension to behave. - -.. _Flask Extension Registry: http://flask.pocoo.org/extensions/ - -Anatomy of an Extension ------------------------ - -Extensions are all located in a package called ``flask_something`` -where "something" is the name of the library you want to bridge. So for -example if you plan to add support for a library named `simplexml` to -Flask, you would name your extension's package ``flask_simplexml``. - -The name of the actual extension (the human readable name) however would -be something like "Flask-SimpleXML". Make sure to include the name -"Flask" somewhere in that name and that you check the capitalization. -This is how users can then register dependencies to your extension in -their :file:`setup.py` files. - -But what do extensions look like themselves? An extension has to ensure -that it works with multiple Flask application instances at once. This is -a requirement because many people will use patterns like the -:ref:`app-factories` pattern to create their application as needed to aid -unittests and to support multiple configurations. Because of that it is -crucial that your application supports that kind of behavior. - -Most importantly the extension must be shipped with a :file:`setup.py` file and -registered on PyPI. Also the development checkout link should work so -that people can easily install the development version into their -virtualenv without having to download the library by hand. - -Flask extensions must be licensed under a BSD, MIT or more liberal license -in order to be listed in the Flask Extension Registry. Keep in mind -that the Flask Extension Registry is a moderated place and libraries will -be reviewed upfront if they behave as required. - -"Hello Flaskext!" ------------------ - -So let's get started with creating such a Flask extension. The extension -we want to create here will provide very basic support for SQLite3. - -First we create the following folder structure:: - - flask-sqlite3/ - flask_sqlite3.py - LICENSE - README - -Here's the contents of the most important files: - -setup.py -```````` - -The next file that is absolutely required is the :file:`setup.py` file which is -used to install your Flask extension. The following contents are -something you can work with:: - - """ - Flask-SQLite3 - ------------- - - This is the description for that library - """ - from setuptools import setup - - - setup( - name='Flask-SQLite3', - version='1.0', - url='http://example.com/flask-sqlite3/', - license='BSD', - author='Your Name', - author_email='your-email@example.com', - description='Very short description', - long_description=__doc__, - py_modules=['flask_sqlite3'], - # if you would be using a package instead use packages instead - # of py_modules: - # packages=['flask_sqlite3'], - zip_safe=False, - include_package_data=True, - platforms='any', - install_requires=[ - 'Flask' - ], - classifiers=[ - 'Environment :: Web Environment', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: BSD License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', - 'Topic :: Software Development :: Libraries :: Python Modules' - ] - ) - -That's a lot of code but you can really just copy/paste that from existing -extensions and adapt. - -flask_sqlite3.py -```````````````` - -Now this is where your extension code goes. But how exactly should such -an extension look like? What are the best practices? Continue reading -for some insight. - -Initializing Extensions ------------------------ - -Many extensions will need some kind of initialization step. For example, -consider an application that's currently connecting to SQLite like the -documentation suggests (:ref:`sqlite3`). So how does the extension -know the name of the application object? - -Quite simple: you pass it to it. - -There are two recommended ways for an extension to initialize: - -initialization functions: - - If your extension is called `helloworld` you might have a function - called ``init_helloworld(app[, extra_args])`` that initializes the - extension for that application. It could attach before / after - handlers etc. - -classes: - - Classes work mostly like initialization functions but can later be - used to further change the behavior. For an example look at how the - `OAuth extension`_ works: there is an `OAuth` object that provides - some helper functions like `OAuth.remote_app` to create a reference to - a remote application that uses OAuth. - -What to use depends on what you have in mind. For the SQLite 3 extension -we will use the class-based approach because it will provide users with an -object that handles opening and closing database connections. - -When designing your classes, it's important to make them easily reusable -at the module level. This means the object itself must not under any -circumstances store any application specific state and must be shareable -between different applications. - -The Extension Code ------------------- - -Here's the contents of the `flask_sqlite3.py` for copy/paste:: - - import sqlite3 - from flask import current_app, _app_ctx_stack - - - class SQLite3(object): +.. currentmodule:: flask + +Extensions are extra packages that add functionality to a Flask +application. While `PyPI`_ contains many Flask extensions, you may not +find one that fits your need. If this is the case, you can create your +own, and publish it for others to use as well. + +This guide will show how to create a Flask extension, and some of the +common patterns and requirements involved. Since extensions can do +anything, this guide won't be able to cover every possibility. + +The best ways to learn about extensions are to look at how other +extensions you use are written, and discuss with others. Discuss your +design ideas with others on our `Discord Chat`_ or +`GitHub Discussions`_. + +The best extensions share common patterns, so that anyone familiar with +using one extension won't feel completely lost with another. This can +only work if collaboration happens early. + + +Naming +------ + +A Flask extension typically has ``flask`` in its name as a prefix or +suffix. If it wraps another library, it should include the library name +as well. This makes it easy to search for extensions, and makes their +purpose clearer. + +A general Python packaging recommendation is that the install name from +the package index and the name used in ``import`` statements should be +related. The import name is lowercase, with words separated by +underscores (``_``). The install name is either lower case or title +case, with words separated by dashes (``-``). If it wraps another +library, prefer using the same case as that library's name. + +Here are some example install and import names: + +- ``Flask-Name`` imported as ``flask_name`` +- ``flask-name-lower`` imported as ``flask_name_lower`` +- ``Flask-ComboName`` imported as ``flask_comboname`` +- ``Name-Flask`` imported as ``name_flask`` + + +The Extension Class and Initialization +-------------------------------------- + +All extensions will need some entry point that initializes the +extension with the application. The most common pattern is to create a +class that represents the extension's configuration and behavior, with +an ``init_app`` method to apply the extension instance to the given +application instance. + +.. code-block:: python + + class HelloExtension: def __init__(self, app=None): - self.app = app if app is not None: self.init_app(app) def init_app(self, app): - app.config.setdefault('SQLITE3_DATABASE', ':memory:') - app.teardown_appcontext(self.teardown) - - def connect(self): - return sqlite3.connect(current_app.config['SQLITE3_DATABASE']) - - def teardown(self, exception): - ctx = _app_ctx_stack.top - if hasattr(ctx, 'sqlite3_db'): - ctx.sqlite3_db.close() - - @property - def connection(self): - ctx = _app_ctx_stack.top - if ctx is not None: - if not hasattr(ctx, 'sqlite3_db'): - ctx.sqlite3_db = self.connect() - return ctx.sqlite3_db - - -So here's what these lines of code do: - -1. The ``__init__`` method takes an optional app object and, if supplied, will - call ``init_app``. -2. The ``init_app`` method exists so that the ``SQLite3`` object can be - instantiated without requiring an app object. This method supports the - factory pattern for creating applications. The ``init_app`` will set the - configuration for the database, defaulting to an in memory database if - no configuration is supplied. In addition, the ``init_app`` method - attaches the ``teardown`` handler. -3. Next, we define a ``connect`` method that opens a database connection. -4. Finally, we add a ``connection`` property that on first access opens - the database connection and stores it on the context. This is also - the recommended way to handling resources: fetch resources lazily the - first time they are used. - - Note here that we're attaching our database connection to the top - application context via ``_app_ctx_stack.top``. Extensions should use - the top context for storing their own information with a sufficiently - complex name. - -So why did we decide on a class-based approach here? Because using our -extension looks something like this:: - - from flask import Flask - from flask_sqlite3 import SQLite3 - - app = Flask(__name__) - app.config.from_pyfile('the-config.cfg') - db = SQLite3(app) - -You can then use the database from views like this:: - - @app.route('/') - def show_all(): - cur = db.connection.cursor() - cur.execute(...) - -Likewise if you are outside of a request you can use the database by -pushing an app context:: - - with app.app_context(): - cur = db.connection.cursor() - cur.execute(...) - -At the end of the ``with`` block the teardown handles will be executed -automatically. - -Additionally, the ``init_app`` method is used to support the factory pattern -for creating apps:: - - db = SQLite3() - # Then later on. - app = create_app('the-config.cfg') - db.init_app(app) + app.before_request(...) + +It is important that the app is not stored on the extension, don't do +``self.app = app``. The only time the extension should have direct +access to an app is during ``init_app``, otherwise it should use +:data:`current_app`. + +This allows the extension to support the application factory pattern, +avoids circular import issues when importing the extension instance +elsewhere in a user's code, and makes testing with different +configurations easier. + +.. code-block:: python + + hello = HelloExtension() + + def create_app(): + app = Flask(__name__) + hello.init_app(app) + return app + +Above, the ``hello`` extension instance exists independently of the +application. This means that other modules in a user's project can do +``from project import hello`` and use the extension in blueprints before +the app exists. + +The :attr:`Flask.extensions` dict can be used to store a reference to +the extension on the application, or some other state specific to the +application. Be aware that this is a single namespace, so use a name +unique to your extension, such as the extension's name without the +"flask" prefix. + + +Adding Behavior +--------------- + +There are many ways that an extension can add behavior. Any setup +methods that are available on the :class:`Flask` object can be used +during an extension's ``init_app`` method. + +A common pattern is to use :meth:`~Flask.before_request` to initialize +some data or a connection at the beginning of each request, then +:meth:`~Flask.teardown_request` to clean it up at the end. This can be +stored on :data:`g`, discussed more below. + +A more lazy approach is to provide a method that initializes and caches +the data or connection. For example, a ``ext.get_db`` method could +create a database connection the first time it's called, so that a view +that doesn't use the database doesn't create a connection. + +Besides doing something before and after every view, your extension +might want to add some specific views as well. In this case, you could +define a :class:`Blueprint`, then call :meth:`~Flask.register_blueprint` +during ``init_app`` to add the blueprint to the app. + + +Configuration Techniques +------------------------ + +There can be multiple levels and sources of configuration for an +extension. You should consider what parts of your extension fall into +each one. + +- Configuration per application instance, through ``app.config`` + values. This is configuration that could reasonably change for each + deployment of an application. A common example is a URL to an + external resource, such as a database. Configuration keys should + start with the extension's name so that they don't interfere with + other extensions. +- Configuration per extension instance, through ``__init__`` + arguments. This configuration usually affects how the extension + is used, such that it wouldn't make sense to change it per + deployment. +- Configuration per extension instance, through instance attributes + and decorator methods. It might be more ergonomic to assign to + ``ext.value``, or use a ``@ext.register`` decorator to register a + function, after the extension instance has been created. +- Global configuration through class attributes. Changing a class + attribute like ``Ext.connection_class`` can customize default + behavior without making a subclass. This could be combined + per-extension configuration to override defaults. +- Subclassing and overriding methods and attributes. Making the API of + the extension itself something that can be overridden provides a + very powerful tool for advanced customization. + +The :class:`~flask.Flask` object itself uses all of these techniques. + +It's up to you to decide what configuration is appropriate for your +extension, based on what you need and what you want to support. + +Configuration should not be changed after the application setup phase is +complete and the server begins handling requests. Configuration is +global, any changes to it are not guaranteed to be visible to other +workers. + + +Data During a Request +--------------------- + +When writing a Flask application, the :data:`~flask.g` object is used to +store information during a request. For example the +:doc:`tutorial ` stores a connection to a SQLite +database as ``g.db``. Extensions can also use this, with some care. +Since ``g`` is a single global namespace, extensions must use unique +names that won't collide with user data. For example, use the extension +name as a prefix, or as a namespace. + +.. code-block:: python + + # an internal prefix with the extension name + g._hello_user_id = 2 + + # or an internal prefix as a namespace + from types import SimpleNamespace + g._hello = SimpleNamespace() + g._hello.user_id = 2 + +The data in ``g`` lasts for an application context. An application +context is active when a request context is, or when a CLI command is +run. If you're storing something that should be closed, use +:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed +when the application context ends. If it should only be valid during a +request, or would not be used in the CLI outside a request, use +:meth:`~flask.Flask.teardown_request`. + + +Views and Models +---------------- + +Your extension views might want to interact with specific models in your +database, or some other extension or data connected to your application. +For example, let's consider a ``Flask-SimpleBlog`` extension that works +with Flask-SQLAlchemy to provide a ``Post`` model and views to write +and read posts. + +The ``Post`` model needs to subclass the Flask-SQLAlchemy ``db.Model`` +object, but that's only available once you've created an instance of +that extension, not when your extension is defining its views. So how +can the view code, defined before the model exists, access the model? + +One method could be to use :doc:`views`. During ``__init__``, create +the model, then create the views by passing the model to the view +class's :meth:`~views.View.as_view` method. + +.. code-block:: python + + class PostAPI(MethodView): + def __init__(self, model): + self.model = model + + def get(self, id): + post = self.model.query.get(id) + return jsonify(post.to_json()) + + class BlogExtension: + def __init__(self, db): + class Post(db.Model): + id = db.Column(primary_key=True) + title = db.Column(db.String, nullable=False) + + self.post_model = Post -Keep in mind that supporting this factory pattern for creating apps is required -for approved flask extensions (described below). - -.. admonition:: Note on ``init_app`` - - As you noticed, ``init_app`` does not assign ``app`` to ``self``. This - is intentional! Class based Flask extensions must only store the - application on the object when the application was passed to the - constructor. This tells the extension: I am not interested in using - multiple applications. - - When the extension needs to find the current application and it does - not have a reference to it, it must either use the - :data:`~flask.current_app` context local or change the API in a way - that you can pass the application explicitly. - - -Using _app_ctx_stack --------------------- - -In the example above, before every request, a ``sqlite3_db`` variable is -assigned to ``_app_ctx_stack.top``. In a view function, this variable is -accessible using the ``connection`` property of ``SQLite3``. During the -teardown of a request, the ``sqlite3_db`` connection is closed. By using -this pattern, the *same* connection to the sqlite3 database is accessible -to anything that needs it for the duration of the request. - - -Learn from Others ------------------ - -This documentation only touches the bare minimum for extension -development. If you want to learn more, it's a very good idea to check -out existing extensions on the `Flask Extension Registry`_. If you feel -lost there is still the `mailinglist`_ and the `IRC channel`_ to get some -ideas for nice looking APIs. Especially if you do something nobody before -you did, it might be a very good idea to get some more input. This not only -generates useful feedback on what people might want from an extension, but -also avoids having multiple developers working in isolation on pretty much the -same problem. - -Remember: good API design is hard, so introduce your project on the -mailing list, and let other developers give you a helping hand with -designing the API. - -The best Flask extensions are extensions that share common idioms for the -API. And this can only work if collaboration happens early. - -Approved Extensions -------------------- - -Flask also has the concept of approved extensions. Approved extensions -are tested as part of Flask itself to ensure extensions do not break on -new releases. These approved extensions are listed on the `Flask -Extension Registry`_ and marked appropriately. If you want your own -extension to be approved you have to follow these guidelines: - -0. An approved Flask extension requires a maintainer. In the event an - extension author would like to move beyond the project, the project should - find a new maintainer including full source hosting transition and PyPI - access. If no maintainer is available, give access to the Flask core team. -1. An approved Flask extension must provide exactly one package or module - named ``flask_extensionname``. -2. It must ship a testing suite that can either be invoked with ``make test`` - or ``python setup.py test``. For test suites invoked with ``make - test`` the extension has to ensure that all dependencies for the test - are installed automatically. If tests are invoked with ``python setup.py - test``, test dependencies can be specified in the :file:`setup.py` file. - The test suite also has to be part of the distribution. -3. APIs of approved extensions will be checked for the following - characteristics: - - - an approved extension has to support multiple applications - running in the same Python process. - - it must be possible to use the factory pattern for creating - applications. - -4. The license must be BSD/MIT/WTFPL licensed. -5. The naming scheme for official extensions is *Flask-ExtensionName* or - *ExtensionName-Flask*. -6. Approved extensions must define all their dependencies in the - :file:`setup.py` file unless a dependency cannot be met because it is not - available on PyPI. -7. The documentation must use the ``flask`` theme from the - `Official Pallets Themes`_. -8. The setup.py description (and thus the PyPI description) has to - link to the documentation, website (if there is one) and there - must be a link to automatically install the development version - (``PackageName==dev``). -9. The ``zip_safe`` flag in the setup script must be set to ``False``, - even if the extension would be safe for zipping. -10. An extension currently has to support Python 3.4 and newer and 2.7. - - -.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/ -.. _mailinglist: http://flask.pocoo.org/mailinglist/ -.. _IRC channel: http://flask.pocoo.org/community/irc/ + def init_app(self, app): + api_view = PostAPI.as_view(model=self.post_model) + + db = SQLAlchemy() + blog = BlogExtension(db) + db.init_app(app) + blog.init_app(app) + +Another technique could be to use an attribute on the extension, such as +``self.post_model`` from above. Add the extension to ``app.extensions`` +in ``init_app``, then access +``current_app.extensions["simple_blog"].post_model`` from views. + +You may also want to provide base classes so that users can provide +their own ``Post`` model that conforms to the API your extension +expects. So they could implement ``class Post(blog.BasePost)``, then +set it as ``blog.post_model``. + +As you can see, this can get a bit complex. Unfortunately, there's no +perfect solution here, only different strategies and tradeoffs depending +on your needs and how much customization you want to offer. Luckily, +this sort of resource dependency is not a common need for most +extensions. Remember, if you need help with design, ask on our +`Discord Chat`_ or `GitHub Discussions`_. + + +Recommended Extension Guidelines +-------------------------------- + +Flask previously had the concept of "approved extensions", where the +Flask maintainers evaluated the quality, support, and compatibility of +the extensions before listing them. While the list became too difficult +to maintain over time, the guidelines are still relevant to all +extensions maintained and developed today, as they help the Flask +ecosystem remain consistent and compatible. + +1. An extension requires a maintainer. In the event an extension author + would like to move beyond the project, the project should find a new + maintainer and transfer access to the repository, documentation, + PyPI, and any other services. The `Pallets-Eco`_ organization on + GitHub allows for community maintenance with oversight from the + Pallets maintainers. +2. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*. + It must provide exactly one package or module named + ``flask_extension_name``. +3. The extension must use an open source license. The Python web + ecosystem tends to prefer BSD or MIT. It must be open source and + publicly available. +4. The extension's API must have the following characteristics: + + - It must support multiple applications running in the same Python + process. Use ``current_app`` instead of ``self.app``, store + configuration and state per application instance. + - It must be possible to use the factory pattern for creating + applications. Use the ``ext.init_app()`` pattern. + +5. From a clone of the repository, an extension with its dependencies + must be installable in editable mode with ``pip install -e .``. +6. It must ship tests that can be invoked with a common tool like + ``tox -e py``, ``nox -s test`` or ``pytest``. If not using ``tox``, + the test dependencies should be specified in a requirements file. + The tests must be part of the sdist distribution. +7. A link to the documentation or project website must be in the PyPI + metadata or the readme. The documentation should use the Flask theme + from the `Official Pallets Themes`_. +8. The extension's dependencies should not use upper bounds or assume + any particular version scheme, but should use lower bounds to + indicate minimum compatibility support. For example, + ``sqlalchemy>=1.4``. +9. Indicate the versions of Python supported using ``python_requires=">=version"``. + Flask itself supports Python >=3.8 as of April 2023, but this will update over time. + +.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask +.. _Discord Chat: https://discord.gg/pallets +.. _GitHub Discussions: https://github.com/pallets/flask/discussions .. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/ +.. _Pallets-Eco: https://github.com/pallets-eco diff --git a/docs/extensions.rst b/docs/extensions.rst index bd4565ec5f..4713ec8e2d 100644 --- a/docs/extensions.rst +++ b/docs/extensions.rst @@ -1,5 +1,3 @@ -.. _extensions: - Extensions ========== @@ -12,10 +10,8 @@ frameworks to help build certain types of applications, like a REST API. Finding Extensions ------------------ -Flask extensions are usually named "Flask-Foo" or "Foo-Flask". Many -extensions are listed in the `Extension Registry`_, which can be updated -by extension developers. You can also search PyPI for packages tagged -with `Framework :: Flask `_. +Flask extensions are usually named "Flask-Foo" or "Foo-Flask". You can +search PyPI for packages tagged with `Framework :: Flask `_. Using Extensions @@ -43,11 +39,10 @@ an extension called "Flask-Foo" might be used like this:: Building Extensions ------------------- -While the `Extension Registry`_ contains many Flask extensions, you may -not find an extension that fits your need. If this is the case, you can -create your own. Read :ref:`extension-dev` to develop your own Flask -extension. +While `PyPI `_ contains many Flask extensions, you may not find +an extension that fits your need. If this is the case, you can create +your own, and publish it for others to use as well. Read +:doc:`extensiondev` to develop your own Flask extension. -.. _Extension Registry: http://flask.pocoo.org/extensions/ .. _pypi: https://pypi.org/search/?c=Framework+%3A%3A+Flask diff --git a/docs/foreword.rst b/docs/foreword.rst deleted file mode 100644 index f0dfaee253..0000000000 --- a/docs/foreword.rst +++ /dev/null @@ -1,58 +0,0 @@ -Foreword -======== - -Read this before you get started with Flask. This hopefully answers some -questions about the purpose and goals of the project, and when you -should or should not be using it. - -What does "micro" mean? ------------------------ - -“Micro” does not mean that your whole web application has to fit into a single -Python file (although it certainly can), nor does it mean that Flask is lacking -in functionality. The "micro" in microframework means Flask aims to keep the -core simple but extensible. Flask won't make many decisions for you, such as -what database to use. Those decisions that it does make, such as what -templating engine to use, are easy to change. Everything else is up to you, so -that Flask can be everything you need and nothing you don't. - -By default, Flask does not include a database abstraction layer, form -validation or anything else where different libraries already exist that can -handle that. Instead, Flask supports extensions to add such functionality to -your application as if it was implemented in Flask itself. Numerous extensions -provide database integration, form validation, upload handling, various open -authentication technologies, and more. Flask may be "micro", but it's ready for -production use on a variety of needs. - -Configuration and Conventions ------------------------------ - -Flask has many configuration values, with sensible defaults, and a few -conventions when getting started. By convention, templates and static -files are stored in subdirectories within the application's Python -source tree, with the names :file:`templates` and :file:`static` -respectively. While this can be changed, you usually don't have to, -especially when getting started. - -Growing with Flask ------------------- - -Once you have Flask up and running, you'll find a variety of extensions -available in the community to integrate your project for production. The Flask -core team reviews extensions and ensures approved extensions do not break with -future releases. - -As your codebase grows, you are free to make the design decisions appropriate -for your project. Flask will continue to provide a very simple glue layer to -the best that Python has to offer. You can implement advanced patterns in -SQLAlchemy or another database tool, introduce non-relational data persistence -as appropriate, and take advantage of framework-agnostic tools built for WSGI, -the Python web interface. - -Flask includes many hooks to customize its behavior. Should you need more -customization, the Flask class is built for subclassing. If you are interested -in that, check out the :ref:`becomingbig` chapter. If you are curious about -the Flask design principles, head over to the section about :ref:`design`. - -Continue to :ref:`installation`, the :ref:`quickstart`, or the -:ref:`advanced_foreword`. diff --git a/docs/htmlfaq.rst b/docs/htmlfaq.rst deleted file mode 100644 index 056ecc7d52..0000000000 --- a/docs/htmlfaq.rst +++ /dev/null @@ -1,207 +0,0 @@ -HTML/XHTML FAQ -============== - -The Flask documentation and example applications are using HTML5. You -may notice that in many situations, when end tags are optional they are -not used, so that the HTML is cleaner and faster to load. Because there -is much confusion about HTML and XHTML among developers, this document tries -to answer some of the major questions. - - -History of XHTML ----------------- - -For a while, it appeared that HTML was about to be replaced by XHTML. -However, barely any websites on the Internet are actual XHTML (which is -HTML processed using XML rules). There are a couple of major reasons -why this is the case. One of them is Internet Explorer's lack of proper -XHTML support. The XHTML spec states that XHTML must be served with the MIME -type :mimetype:`application/xhtml+xml`, but Internet Explorer refuses -to read files with that MIME type. -While it is relatively easy to configure Web servers to serve XHTML properly, -few people do. This is likely because properly using XHTML can be quite -painful. - -One of the most important causes of pain is XML's draconian (strict and -ruthless) error handling. When an XML parsing error is encountered, -the browser is supposed to show the user an ugly error message, instead -of attempting to recover from the error and display what it can. Most of -the (X)HTML generation on the web is based on non-XML template engines -(such as Jinja, the one used in Flask) which do not protect you from -accidentally creating invalid XHTML. There are XML based template engines, -such as Kid and the popular Genshi, but they often come with a larger -runtime overhead and are not as straightforward to use because they have -to obey XML rules. - -The majority of users, however, assumed they were properly using XHTML. -They wrote an XHTML doctype at the top of the document and self-closed all -the necessary tags (``
`` becomes ``
`` or ``

`` in XHTML). -However, even if the document properly validates as XHTML, what really -determines XHTML/HTML processing in browsers is the MIME type, which as -said before is often not set properly. So the valid XHTML was being treated -as invalid HTML. - -XHTML also changed the way JavaScript is used. To properly work with XHTML, -programmers have to use the namespaced DOM interface with the XHTML -namespace to query for HTML elements. - -History of HTML5 ----------------- - -Development of the HTML5 specification was started in 2004 under the name -"Web Applications 1.0" by the Web Hypertext Application Technology Working -Group, or WHATWG (which was formed by the major browser vendors Apple, -Mozilla, and Opera) with the goal of writing a new and improved HTML -specification, based on existing browser behavior instead of unrealistic -and backwards-incompatible specifications. - -For example, in HTML4 ``Hello``. However, since people were using -XHTML-like tags along the lines of ````, browser vendors implemented -the XHTML syntax over the syntax defined by the specification. - -In 2007, the specification was adopted as the basis of a new HTML -specification under the umbrella of the W3C, known as HTML5. Currently, -it appears that XHTML is losing traction, as the XHTML 2 working group has -been disbanded and HTML5 is being implemented by all major browser vendors. - -HTML versus XHTML ------------------ - -The following table gives you a quick overview of features available in -HTML 4.01, XHTML 1.1 and HTML5. (XHTML 1.0 is not included, as it was -superseded by XHTML 1.1 and the barely-used XHTML5.) - -.. tabularcolumns:: |p{9cm}|p{2cm}|p{2cm}|p{2cm}| - -+-----------------------------------------+----------+----------+----------+ -| | HTML4.01 | XHTML1.1 | HTML5 | -+=========================================+==========+==========+==========+ -| ``value`` | |Y| [1]_ | |N| | |N| | -+-----------------------------------------+----------+----------+----------+ -| ``
`` supported | |N| | |Y| | |Y| [2]_ | -+-----------------------------------------+----------+----------+----------+ -| `` + +A less common pattern is to add the data to a ``data-`` attribute on an +HTML tag. In this case, you must use single quotes around the value, not +double quotes, otherwise you will produce invalid or unsafe HTML. + +.. code-block:: jinja + +

+ + +Generating URLs +--------------- + +The other way to get data from the server to JavaScript is to make a +request for it. First, you need to know the URL to request. + +The simplest way to generate URLs is to continue to use +:func:`~flask.url_for` when rendering the template. For example: + +.. code-block:: javascript + + const user_url = {{ url_for("user", id=current_user.id)|tojson }} + fetch(user_url).then(...) + +However, you might need to generate a URL based on information you only +know in JavaScript. As discussed above, JavaScript runs in the user's +browser, not as part of the template rendering, so you can't use +``url_for`` at that point. + +In this case, you need to know the "root URL" under which your +application is served. In simple setups, this is ``/``, but it might +also be something else, like ``https://example.com/myapp/``. + +A simple way to tell your JavaScript code about this root is to set it +as a global variable when rendering the template. Then you can use it +when generating URLs from JavaScript. + +.. code-block:: javascript + + const SCRIPT_ROOT = {{ request.script_root|tojson }} + let user_id = ... // do something to get a user id from the page + let user_url = `${SCRIPT_ROOT}/user/${user_id}` + fetch(user_url).then(...) + + +Making a Request with ``fetch`` +------------------------------- + +|fetch|_ takes two arguments, a URL and an object with other options, +and returns a |Promise|_. We won't cover all the available options, and +will only use ``then()`` on the promise, not other callbacks or +``await`` syntax. Read the linked MDN docs for more information about +those features. + +By default, the GET method is used. If the response contains JSON, it +can be used with a ``then()`` callback chain. + +.. code-block:: javascript + + const room_url = {{ url_for("room_detail", id=room.id)|tojson }} + fetch(room_url) + .then(response => response.json()) + .then(data => { + // data is a parsed JSON object + }) + +To send data, use a data method such as POST, and pass the ``body`` +option. The most common types for data are form data or JSON data. + +To send form data, pass a populated |FormData|_ object. This uses the +same format as an HTML form, and would be accessed with ``request.form`` +in a Flask view. + +.. code-block:: javascript + + let data = new FormData() + data.append("name": "Flask Room") + data.append("description": "Talk about Flask here.") + fetch(room_url, { + "method": "POST", + "body": data, + }).then(...) + +In general, prefer sending request data as form data, as would be used +when submitting an HTML form. JSON can represent more complex data, but +unless you need that it's better to stick with the simpler format. When +sending JSON data, the ``Content-Type: application/json`` header must be +sent as well, otherwise Flask will return a 400 error. + +.. code-block:: javascript + + let data = { + "name": "Flask Room", + "description": "Talk about Flask here.", + } + fetch(room_url, { + "method": "POST", + "headers": {"Content-Type": "application/json"}, + "body": JSON.stringify(data), + }).then(...) + +.. |Promise| replace:: ``Promise`` +.. _Promise: https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/Promise +.. |FormData| replace:: ``FormData`` +.. _FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData + + +Following Redirects +------------------- + +A response might be a redirect, for example if you logged in with +JavaScript instead of a traditional HTML form, and your view returned +a redirect instead of JSON. JavaScript requests do follow redirects, but +they don't change the page. If you want to make the page change you can +inspect the response and apply the redirect manually. + +.. code-block:: javascript + + fetch("/login", {"body": ...}).then( + response => { + if (response.redirected) { + window.location = response.url + } else { + showLoginError() + } + } + ) + + +Replacing Content +----------------- + +A response might be new HTML, either a new section of the page to add or +replace, or an entirely new page. In general, if you're returning the +entire page, it would be better to handle that with a redirect as shown +in the previous section. The following example shows how to replace a +``
`` with the HTML returned by a request. + +.. code-block:: html + +
+ {{ include "geology_fact.html" }} +
+ + + +Return JSON from Views +---------------------- + +To return a JSON object from your API view, you can directly return a +dict from the view. It will be serialized to JSON automatically. + +.. code-block:: python + + @app.route("/user/") + def user_detail(id): + user = User.query.get_or_404(id) + return { + "username": User.username, + "email": User.email, + "picture": url_for("static", filename=f"users/{id}/profile.png"), + } + +If you want to return another JSON type, use the +:func:`~flask.json.jsonify` function, which creates a response object +with the given data serialized to JSON. + +.. code-block:: python + + from flask import jsonify + + @app.route("/users") + def user_list(): + users = User.query.order_by(User.name).all() + return jsonify([u.to_json() for u in users]) + +It is usually not a good idea to return file data in a JSON response. +JSON cannot represent binary data directly, so it must be base64 +encoded, which can be slow, takes more bandwidth to send, and is not as +easy to cache. Instead, serve files using one view, and generate a URL +to the desired file to include in the JSON. Then the client can make a +separate request to get the linked resource after getting the JSON. + + +Receiving JSON in Views +----------------------- + +Use the :attr:`~flask.Request.json` property of the +:data:`~flask.request` object to decode the request's body as JSON. If +the body is not valid JSON, or the ``Content-Type`` header is not set to +``application/json``, a 400 Bad Request error will be raised. + +.. code-block:: python + + from flask import request + + @app.post("/user/") + def user_update(id): + user = User.query.get_or_404(id) + user.update_from_json(request.json) + db.session.commit() + return user.to_json() diff --git a/docs/patterns/jquery.rst b/docs/patterns/jquery.rst index b0c0287f81..7ac6856eac 100644 --- a/docs/patterns/jquery.rst +++ b/docs/patterns/jquery.rst @@ -1,167 +1,6 @@ +:orphan: + AJAX with jQuery ================ -`jQuery`_ is a small JavaScript library commonly used to simplify working -with the DOM and JavaScript in general. It is the perfect tool to make -web applications more dynamic by exchanging JSON between server and -client. - -JSON itself is a very lightweight transport format, very similar to how -Python primitives (numbers, strings, dicts and lists) look like which is -widely supported and very easy to parse. It became popular a few years -ago and quickly replaced XML as transport format in web applications. - -.. _jQuery: https://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 where -we can add two numbers and a link to trigger the function on the server -side. - -Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here -which will never fail. If the key is missing a default value (here ``0``) -is returned. Furthermore it can convert values to a specific type (like -in our case `int`). This is especially handy for code that is -triggered by a script (APIs, JavaScript etc.) because you don't need -special error reporting in that case. - -The HTML --------- - -Your index.html template either has to extend a :file:`layout.html` template with -jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top. -Here's the HTML code needed for our little application (:file:`index.html`). -Notice that we also drop the script directly into the HTML here. It is -usually a better idea to have that in a separate script file: - -.. sourcecode:: html - - -

jQuery Example

-

+ - = - ? -

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``. +Obsolete, see :doc:`/patterns/javascript` instead. diff --git a/docs/patterns/lazyloading.rst b/docs/patterns/lazyloading.rst index acb77f943a..658a1cd43c 100644 --- a/docs/patterns/lazyloading.rst +++ b/docs/patterns/lazyloading.rst @@ -58,7 +58,7 @@ loaded upfront. The trick is to actually load the view function as needed. This can be accomplished with a helper class that behaves just like a function but internally imports the real function on first use:: - from werkzeug import import_string, cached_property + from werkzeug.utils import import_string, cached_property class LazyView(object): @@ -93,7 +93,7 @@ write this by having a function that calls into name and a dot, and by wrapping `view_func` in a `LazyView` as needed. :: def url(import_name, url_rules=[], **options): - view = LazyView('yourapplication.' + import_name) + view = LazyView(f"yourapplication.{import_name}") for url_rule in url_rules: app.add_url_rule(url_rule, view_func=view, **options) diff --git a/docs/patterns/mongokit.rst b/docs/patterns/mongokit.rst deleted file mode 100644 index cf072d5da8..0000000000 --- a/docs/patterns/mongokit.rst +++ /dev/null @@ -1,7 +0,0 @@ -:orphan: - -MongoDB with MongoKit -===================== - -MongoKit is no longer maintained. See :doc:`/patterns/mongoengine` -instead. diff --git a/docs/patterns/packages.rst b/docs/patterns/packages.rst index e9d14ca59f..239a3fa2aa 100644 --- a/docs/patterns/packages.rst +++ b/docs/patterns/packages.rst @@ -1,7 +1,5 @@ -.. _larger-applications: - -Larger Applications -=================== +Large Applications as Packages +============================== Imagine a simple flask application structure that looks like this:: @@ -17,7 +15,7 @@ Imagine a simple flask application structure that looks like this:: While this is fine for small applications, for larger applications it's a good idea to use a package instead of a module. -The :ref:`tutorial ` is structured to use the package pattern, +The :doc:`/tutorial/index` is structured to use the package pattern, see the :gh:`example code `. Simple Packages @@ -44,36 +42,34 @@ You should then end up with something like that:: But how do you run your application now? The naive ``python yourapplication/__init__.py`` will not work. Let's just say that Python does not want modules in packages to be the startup file. But that is not -a big problem, just add a new file called :file:`setup.py` next to the inner -:file:`yourapplication` folder with the following contents:: +a big problem, just add a new file called :file:`pyproject.toml` next to the inner +:file:`yourapplication` folder with the following contents: - from setuptools import setup +.. code-block:: toml - setup( - name='yourapplication', - packages=['yourapplication'], - include_package_data=True, - install_requires=[ - 'flask', - ], - ) + [project] + name = "yourapplication" + dependencies = [ + "flask", + ] -In order to run the application you need to export an environment variable -that tells Flask where to find the application instance:: + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" - $ export FLASK_APP=yourapplication +Install your application so it is importable: -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:: +.. code-block:: text - $ export FLASK_ENV=development + $ pip install -e . -In order to install and run the application you need to issue the following -commands:: +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: - $ pip install -e . - $ flask run +.. code-block:: text + + $ flask --app yourapplication run What did we gain from this? Now we can restructure the application a bit into multiple modules. The only thing you have to remember is the @@ -105,7 +101,7 @@ And this is what :file:`views.py` would look like:: You should then end up with something like that:: /yourapplication - setup.py + pyproject.toml /yourapplication __init__.py views.py @@ -127,12 +123,6 @@ You should then end up with something like that:: ensuring the module is imported and we are doing that at the bottom of the file. - There are still some problems with that approach but if you want to use - decorators there is no way around that. Check out the - :ref:`becomingbig` section for some inspiration how to deal with that. - - -.. _working-with-modules: Working with Blueprints ----------------------- @@ -140,4 +130,4 @@ Working with Blueprints If you have larger applications it's recommended to divide them into smaller groups where each group is implemented with the help of a blueprint. For a gentle introduction into this topic refer to the -:ref:`blueprints` chapter of the documentation. +:doc:`/blueprints` chapter of the documentation. diff --git a/docs/patterns/requestchecksum.rst b/docs/patterns/requestchecksum.rst index 902be64ab8..25bc38b2a4 100644 --- a/docs/patterns/requestchecksum.rst +++ b/docs/patterns/requestchecksum.rst @@ -52,4 +52,4 @@ Example usage:: files = request.files # At this point the hash is fully constructed. checksum = hash.hexdigest() - return 'Hash was: %s' % checksum + return f"Hash was: {checksum}" diff --git a/docs/patterns/singlepageapplications.rst b/docs/patterns/singlepageapplications.rst index 71c048774d..1cb779b33b 100644 --- a/docs/patterns/singlepageapplications.rst +++ b/docs/patterns/singlepageapplications.rst @@ -10,7 +10,7 @@ The following example demonstrates how to serve an SPA along with an API:: from flask import Flask, jsonify - app = Flask(__name__, static_folder='app') + app = Flask(__name__, static_folder='app', static_url_path="/app") @app.route("/heartbeat") diff --git a/docs/patterns/sqlalchemy.rst b/docs/patterns/sqlalchemy.rst index e2dfcc5d09..734d550c2b 100644 --- a/docs/patterns/sqlalchemy.rst +++ b/docs/patterns/sqlalchemy.rst @@ -1,12 +1,10 @@ -.. _sqlalchemy-pattern: - SQLAlchemy in Flask =================== Many people prefer `SQLAlchemy`_ for database access. In this case it's encouraged to use a package instead of a module for your flask application -and drop the models into a separate module (:ref:`larger-applications`). -While that is not necessary, it makes a lot of sense. +and drop the models into a separate module (:doc:`packages`). While that +is not necessary, it makes a lot of sense. There are four very common ways to use SQLAlchemy. I will outline each of them here: @@ -39,7 +37,7 @@ Here's the example :file:`database.py` module for your application:: from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base - engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) + engine = create_engine('sqlite:////tmp/test.db') db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) @@ -86,7 +84,7 @@ Here is an example model (put this into :file:`models.py`, e.g.):: self.email = email def __repr__(self): - return '' % (self.name) + return f'' To create the database you can use the `init_db` function: @@ -104,13 +102,12 @@ You can insert entries into the database like this: Querying is simple as well: >>> User.query.all() -[] +[] >>> User.query.filter(User.name == 'admin').first() - + .. _SQLAlchemy: 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 -------------------------------- @@ -127,7 +124,7 @@ Here is an example :file:`database.py` module for your application:: from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import scoped_session, sessionmaker - engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) + engine = create_engine('sqlite:////tmp/test.db') metadata = MetaData() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, @@ -159,7 +156,7 @@ Here is an example table and model (put this into :file:`models.py`):: self.email = email def __repr__(self): - return '' % (self.name) + return f'' users = Table('users', metadata, Column('id', Integer, primary_key=True), @@ -179,7 +176,7 @@ you basically only need the engine:: from sqlalchemy import create_engine, MetaData, Table - engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) + engine = create_engine('sqlite:////tmp/test.db') metadata = MetaData(bind=engine) Then you can either declare the tables in your code like in the examples @@ -200,19 +197,19 @@ SQLAlchemy will automatically commit for us. To query your database, you use the engine directly or use a connection: >>> users.select(users.c.id == 1).execute().first() -(1, u'admin', u'admin@localhost') +(1, 'admin', 'admin@localhost') These results are also dict-like tuples: >>> r = users.select(users.c.id == 1).execute().first() >>> r['name'] -u'admin' +'admin' You can also pass strings of SQL statements to the :meth:`~sqlalchemy.engine.base.Connection.execute` method: >>> engine.execute('select * from users where id = :1', [1]).first() -(1, u'admin', u'admin@localhost') +(1, 'admin', 'admin@localhost') For more information about SQLAlchemy, head over to the `website `_. diff --git a/docs/patterns/sqlite3.rst b/docs/patterns/sqlite3.rst index eecaaae879..5932589ffa 100644 --- a/docs/patterns/sqlite3.rst +++ b/docs/patterns/sqlite3.rst @@ -1,5 +1,3 @@ -.. _sqlite3: - Using SQLite 3 with Flask ========================= @@ -32,10 +30,6 @@ or create an application context itself. At that point the ``get_db`` function can be used to get the current database connection. Whenever the context is destroyed the database connection will be terminated. -Note: if you use Flask 0.9 or older you need to use -``flask._app_ctx_stack.top`` instead of ``g`` as the :data:`flask.g` -object was bound to the request and not application context. - Example:: @app.route('/') @@ -62,7 +56,6 @@ the application context by hand:: with app.app_context(): # now you can use get_db() -.. _easy-querying: Easy Querying ------------- @@ -116,16 +109,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 f5bff3ca01..c9e6ef22be 100644 --- a/docs/patterns/streaming.rst +++ b/docs/patterns/streaming.rst @@ -15,14 +15,12 @@ This is a basic view function that generates a lot of CSV data on the fly. The trick is to have an inner function that uses a generator to generate data and to then invoke that function and pass it to a response object:: - from flask import Response - @app.route('/large.csv') def generate_large_csv(): def generate(): for row in iter_all_rows(): - yield ','.join(row) + '\n' - return Response(generate(), mimetype='text/csv') + yield f"{','.join(row)}\n" + return generate(), {"Content-Type": "text/csv"} Each ``yield`` expression is directly sent to the browser. Note though that some WSGI middlewares might break streaming, so be careful there in @@ -31,54 +29,57 @@ debug environments with profilers and other things you might have enabled. Streaming from Templates ------------------------ -The Jinja2 template engine also supports rendering templates piece by -piece. This functionality is not directly exposed by Flask because it is -quite uncommon, but you can easily do it yourself:: - - from flask import Response - - def stream_template(template_name, **context): - app.update_template_context(context) - t = app.jinja_env.get_template(template_name) - rv = t.stream(context) - rv.enable_buffering(5) - return rv - - @app.route('/my-large-page.html') - def render_large_template(): - rows = iter_all_rows() - return Response(stream_template('the_template.html', rows=rows)) - -The trick here is to get the template object from the Jinja2 environment -on the application and to call :meth:`~jinja2.Template.stream` instead of -:meth:`~jinja2.Template.render` which returns a stream object instead of a -string. Since we're bypassing the Flask template render functions and -using the template object itself we have to make sure to update the render -context ourselves by calling :meth:`~flask.Flask.update_template_context`. -The template is then evaluated as the stream is iterated over. Since each -time you do a yield the server will flush the content to the client you -might want to buffer up a few items in the template which you can do with -``rv.enable_buffering(size)``. ``5`` is a sane default. +The Jinja2 template engine supports rendering a template piece by +piece, returning an iterator of strings. Flask provides the +:func:`~flask.stream_template` and :func:`~flask.stream_template_string` +functions to make this easier to use. + +.. code-block:: python + + from flask import stream_template + + @app.get("/timeline") + def timeline(): + return stream_template("timeline.html") + +The parts yielded by the render stream tend to match statement blocks in +the template. + Streaming with Context ---------------------- -.. versionadded:: 0.9 +The :data:`~flask.request` will not be active while the generator is +running, because the view has already returned at that point. If you try +to access ``request``, you'll get a ``RuntimeError``. -Note that when you stream data, the request context is already gone the -moment the function executes. Flask 0.9 provides you with a helper that -can keep the request context around during the execution of the -generator:: +If your generator function relies on data in ``request``, use the +:func:`~flask.stream_with_context` wrapper. This will keep the request +context active during the generator. - from flask import stream_with_context, request, Response +.. code-block:: python + + from flask import stream_with_context, request + from markupsafe import escape @app.route('/stream') def streamed_response(): def generate(): - yield 'Hello ' - yield request.args['name'] - yield '!' - return Response(stream_with_context(generate())) + yield '

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

' + return stream_with_context(generate()) + +It can also be used as a decorator. + +.. code-block:: python + + @stream_with_context + def generate(): + ... + + return generate() -Without the :func:`~flask.stream_with_context` function you would get a -:class:`RuntimeError` at that point. +The :func:`~flask.stream_template` and +:func:`~flask.stream_template_string` functions automatically +use :func:`~flask.stream_with_context` if a request is active. diff --git a/docs/patterns/templateinheritance.rst b/docs/patterns/templateinheritance.rst index dbcb4163c7..bb5cba2706 100644 --- a/docs/patterns/templateinheritance.rst +++ b/docs/patterns/templateinheritance.rst @@ -1,5 +1,3 @@ -.. _template-inheritance: - Template Inheritance ==================== diff --git a/docs/patterns/urlprocessors.rst b/docs/patterns/urlprocessors.rst index 3f65d75876..0d743205fd 100644 --- a/docs/patterns/urlprocessors.rst +++ b/docs/patterns/urlprocessors.rst @@ -39,8 +39,8 @@ generate URLs from one function to another you would have to still provide the language code explicitly which can be annoying. For the latter, this is where :func:`~flask.Flask.url_defaults` functions -come in. They can automatically inject values into a call for -:func:`~flask.url_for` automatically. The code below checks if the +come in. They can automatically inject values into a call to +:func:`~flask.url_for`. The code below checks if the language code is not yet in the dictionary of URL values and if the endpoint wants a value named ``'lang_code'``:: diff --git a/docs/patterns/viewdecorators.rst b/docs/patterns/viewdecorators.rst index 7fd97dca4f..0b0479ef81 100644 --- a/docs/patterns/viewdecorators.rst +++ b/docs/patterns/viewdecorators.rst @@ -59,7 +59,7 @@ Caching Decorator Imagine you have a view function that does an expensive calculation and because of that you would like to cache the generated results for a certain amount of time. A decorator would be nice for that. We're -assuming you have set up a cache like mentioned in :ref:`caching-pattern`. +assuming you have set up a cache like mentioned in :doc:`caching`. Here is an example cache function. It generates the cache key from a specific prefix (actually a format string) and the current path of the @@ -70,7 +70,7 @@ straightforward to read. The decorated function will then work as follows -1. get the unique cache key for the current request base on the current +1. get the unique cache key for the current request based on the current path. 2. get the value for that key from the cache. If the cache returned something we will return that value. @@ -82,11 +82,11 @@ Here the code:: from functools import wraps from flask import request - def cached(timeout=5 * 60, key='view/%s'): + def cached(timeout=5 * 60, key='view/{}'): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): - cache_key = key % request.path + cache_key = key.format(request.path) rv = cache.get(cache_key) if rv is not None: return rv @@ -96,8 +96,8 @@ Here the code:: return decorated_function return decorator -Notice that this assumes an instantiated `cache` object is available, see -:ref:`caching-pattern` for more information. +Notice that this assumes an instantiated ``cache`` object is available, see +:doc:`caching`. Templating Decorator @@ -142,8 +142,7 @@ Here is the code for that decorator:: def decorated_function(*args, **kwargs): template_name = template if template_name is None: - template_name = request.endpoint \ - .replace('.', '/') + '.html' + template_name = f"{request.endpoint.replace('.', '/')}.html" ctx = f(*args, **kwargs) if ctx is None: ctx = {} diff --git a/docs/patterns/wtforms.rst b/docs/patterns/wtforms.rst index e3fe5723ee..3d626f5084 100644 --- a/docs/patterns/wtforms.rst +++ b/docs/patterns/wtforms.rst @@ -9,7 +9,7 @@ forms, you might want to give it a try. When you are working with WTForms you have to define your forms as classes first. I recommend breaking up the application into multiple modules -(:ref:`larger-applications`) for that and adding a separate module for the +(:doc:`packages`) for that and adding a separate module for the forms. .. admonition:: Getting the most out of WTForms with an Extension @@ -19,7 +19,7 @@ forms. fun. You can get it from `PyPI `_. -.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/ +.. _Flask-WTF: https://flask-wtf.readthedocs.io/ The Forms --------- @@ -55,7 +55,7 @@ In the view function, the usage of this form looks like this:: return render_template('register.html', form=form) Notice we're implying that the view is using SQLAlchemy here -(:ref:`sqlalchemy-pattern`), but that's not a requirement, of course. Adapt +(:doc:`sqlalchemy`), but that's not a requirement, of course. Adapt the code as necessary. Things to remember: @@ -98,9 +98,9 @@ This macro accepts a couple of keyword arguments that are forwarded to WTForm's field function, which renders the field for us. The keyword arguments will be inserted as HTML attributes. So, for example, you can call ``render_field(form.username, class='username')`` to add a class to -the input element. Note that WTForms returns standard Python unicode -strings, so we have to tell Jinja2 that this data is already HTML-escaped -with the ``|safe`` filter. +the input element. Note that WTForms returns standard Python strings, +so we have to tell Jinja2 that this data is already HTML-escaped with +the ``|safe`` filter. Here is the :file:`register.html` template for the function we used above, which takes advantage of the :file:`_formhelpers.html` template: diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 1a8e17c615..0d7ad3f695 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -1,77 +1,71 @@ -.. _quickstart: - Quickstart ========== -Eager to get started? This page gives a good introduction to Flask. It -assumes you already have Flask installed. If you do not, head over to the -:ref:`installation` section. +Eager to get started? This page gives a good introduction to Flask. +Follow :doc:`installation` to set up a project and install Flask first. A Minimal Application --------------------- -A minimal Flask application looks something like this:: +A minimal Flask application looks something like this: + +.. code-block:: python from flask import Flask + app = Flask(__name__) - @app.route('/') + @app.route("/") def hello_world(): - return 'Hello, World!' + return "

Hello, World!

" So what did that code do? -1. First we imported the :class:`~flask.Flask` class. An instance of this - class will be our WSGI application. -2. Next we create an instance of this class. The first argument is the name of - the application's module or package. If you are using a single module (as - in this example), you should use ``__name__`` because depending on if it's - started as application or imported as module the name will be different - (``'__main__'`` versus the actual import name). This is needed so that - Flask knows where to look for templates, static files, and so on. For more - information have a look at the :class:`~flask.Flask` documentation. -3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL - should trigger our function. -4. The function is given a name which is also used to generate URLs for that - particular function, and returns the message we want to display in the - user's browser. - -Just save it as :file:`hello.py` or something similar. Make sure to not call +1. First we imported the :class:`~flask.Flask` class. An instance of + this class will be our WSGI application. +2. Next we create an instance of this class. The first argument is the + name of the application's module or package. ``__name__`` is a + convenient shortcut for this that is appropriate for most cases. + This is needed so that Flask knows where to look for resources such + as templates and static files. +3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask + what URL should trigger our function. +4. The function returns the message we want to display in the user's + browser. The default content type is HTML, so HTML in the string + will be rendered by the browser. + +Save it as :file:`hello.py` or something similar. Make sure to not call your application :file:`flask.py` because this would conflict with Flask itself. -To run the application you can either use the :command:`flask` command or -python's ``-m`` switch with Flask. Before you can do that you need -to tell your terminal the application to work with by exporting the -``FLASK_APP`` environment variable:: - - $ export FLASK_APP=hello.py - $ flask run - * Running on http://127.0.0.1:5000/ - -If you are on Windows, the environment variable syntax depends on command line -interpreter. On Command Prompt:: - - C:\path\to\app>set FLASK_APP=hello.py +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. -And on PowerShell:: +.. code-block:: text - PS C:\path\to\app> $env:FLASK_APP = "hello.py" + $ flask --app hello run + * Serving Flask app 'hello' + * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) -Alternatively you can use :command:`python -m flask`:: +.. admonition:: Application Discovery Behavior - $ export FLASK_APP=hello.py - $ python -m flask run - * Running on http://127.0.0.1:5000/ + 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. -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`. +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`. Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting. +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. + .. _public-server: .. admonition:: Externally Visible Server @@ -90,86 +84,73 @@ world greeting. This tells your operating system to listen on all public IPs. -What to do if the Server does not Start ---------------------------------------- - -In case the :command:`python -m flask` fails or :command:`flask` -does not exist, there are multiple reasons this might be the case. -First of all you need to look at the error message. - -Old Version of Flask -```````````````````` - -Versions of Flask older than 0.11 use to have different ways to start the -application. In short, the :command:`flask` command did not exist, and -neither did :command:`python -m flask`. In that case you have two options: -either upgrade to newer Flask versions or have a look at the :ref:`server` -docs to see the alternative method for running a server. - -Invalid Import Name -``````````````````` - -The ``FLASK_APP`` environment variable is the name of the module to import at -:command:`flask run`. In case that module is incorrectly named you will get an -import error upon start (or if debug is enabled when you navigate to the -application). It will tell you what it tried to import and why it failed. - -The most common reason is a typo or because you did not actually create an -``app`` object. - -.. _debug-mode: - Debug Mode ---------- -(Want to just log errors and stack traces? See :ref:`application-errors`) +The ``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. + +.. image:: _static/debugger.png + :align: center + :class: screenshot + :alt: The interactive debugger in action. -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. +.. warning:: -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:: + 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. - $ export FLASK_ENV=development - $ flask run +To enable debug mode, use the ``--debug`` option. -(On Windows you need to use ``set`` instead of ``export``.) +.. code-block:: text -This does the following things: + $ 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 -1. it activates the debugger -2. it activates the automatic reloader -3. it enables the debug mode on the Flask application. +See also: -You can also control debug mode separately from the environment by -exporting ``FLASK_DEBUG=1``. +- :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. -There are more parameters that are explained in the :ref:`server` docs. -.. admonition:: Attention +HTML Escaping +------------- - 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**. +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. -Screenshot of the debugger in action: +: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. -.. image:: _static/debugger.png - :align: center - :class: screenshot - :alt: screenshot of debugger in action +.. code-block:: python -More information on using the debugger can be found in the `Werkzeug -documentation`_. + from markupsafe import escape -.. _Werkzeug documentation: https://werkzeug.palletsprojects.com/debug/#using-the-debugger + @app.route("/") + def hello(name): + return f"Hello, {escape(name)}!" -Have another debugger in mind? See :ref:`working-with-debuggers`. +If a user managed to submit the name ````, +escaping causes it to be rendered as text, rather than running the +script in the user's browser. + +```` in the route captures a value from the URL and passes it to +the view function. These variable rules are explained below. Routing @@ -200,20 +181,22 @@ 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 'User %s' % escape(username) + return f'User {escape(username)}' @app.route('/post/') def show_post(post_id): # show the post with the given id, the id is an integer - return 'Post %d' % post_id + return f'Post {post_id}' @app.route('/path/') def show_subpath(subpath): # show the subpath after /path/ - return 'Subpath %s' % escape(subpath) + return f'Subpath {escape(subpath)}' Converter types: @@ -225,6 +208,7 @@ Converter types: ``uuid`` accepts UUID strings ========== ========================================== + Unique URLs / Redirection Behavior `````````````````````````````````` @@ -240,14 +224,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, Flask redirects you to the canonical URL with the -trailing slash. +a trailing slash (``/projects``), Flask redirects you to the canonical URL +with the trailing slash (``/projects/``). The canonical URL for the ``about`` endpoint does not have a trailing slash. It's similar to the pathname of a file. Accessing the URL with a -trailing slash produces a 404 "Not Found" error. This helps keep URLs -unique for these resources, which helps search engines avoid indexing -the same page twice. +trailing slash (``/about/``) produces a 404 "Not Found" error. This helps +keep URLs unique for these resources, which helps search engines avoid +indexing the same page twice. .. _url-building: @@ -266,8 +250,7 @@ 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 and Unicode data - transparently. +3. URL building handles escaping of special characters transparently. 4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers. 5. If your application is placed outside the URL root, for example, in @@ -281,9 +264,7 @@ Python shell. See :ref:`context-locals`. .. code-block:: python - from flask import Flask, escape, url_for - - app = Flask(__name__) + from flask import url_for @app.route('/') def index(): @@ -295,7 +276,7 @@ Python shell. See :ref:`context-locals`. @app.route('/user/') def profile(username): - return '{}\'s profile'.format(escape(username)) + return f'{username}\'s profile' with app.test_request_context(): print(url_for('index')) @@ -329,6 +310,24 @@ 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. @@ -356,7 +355,15 @@ Rendering Templates Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the `Jinja2 -`_ template engine for you automatically. +`_ template engine for you automatically. + +Templates can be used to generate any type of text file. For web applications, you'll +primarily be generating HTML pages, but you can also generate markdown, plain text for +emails, and anything else. + +For a reference to HTML, CSS, and other web APIs, use the `MDN Web Docs`_. + +.. _MDN Web Docs: https://developer.mozilla.org/ To render a template you can use the :func:`~flask.render_template` method. All you have to do is provide the name of the template and the @@ -389,7 +396,7 @@ package it's actually inside your package: For templates you can use the full power of Jinja2 templates. Head over to the official `Jinja2 Template Documentation -`_ for more information. +`_ for more information. Here is an example template: @@ -403,31 +410,31 @@ Here is an example template:

Hello, World!

{% endif %} -Inside templates you also have access to the :class:`~flask.request`, -:class:`~flask.session` and :class:`~flask.g` [#]_ objects -as well as the :func:`~flask.get_flashed_messages` function. +Inside templates you also have access to the :data:`~flask.Flask.config`, +:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects +as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions. Templates are especially useful if inheritance is used. If you want to -know how that works, head over to the :ref:`template-inheritance` pattern -documentation. Basically template inheritance makes it possible to keep -certain elements on each page (like header, navigation and footer). +know how that works, see :doc:`patterns/templateinheritance`. Basically +template inheritance makes it possible to keep certain elements on each +page (like header, navigation and footer). Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the -:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the +:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the template. Head over to the Jinja 2 documentation for more examples. -Here is a basic introduction to how the :class:`~jinja2.Markup` class works:: +Here is a basic introduction to how the :class:`~markupsafe.Markup` class works:: - >>> from flask import Markup + >>> from markupsafe import Markup >>> Markup('Hello %s!') % 'hacker' - Markup(u'Hello <blink>hacker</blink>!') + Markup('Hello <blink>hacker</blink>!') >>> Markup.escape('hacker') - Markup(u'<blink>hacker</blink>') + Markup('<blink>hacker</blink>') >>> Markup('Marked up » HTML').striptags() - u'Marked up \xbb HTML' + 'Marked up » HTML' .. versionchanged:: 0.5 @@ -437,9 +444,8 @@ Here is a basic introduction to how the :class:`~jinja2.Markup` class works:: autoescaping disabled. .. [#] Unsure what that :class:`~flask.g` object is? It's something in which - you can store information for your own needs, check the documentation of - that object (:class:`~flask.g`) and the :ref:`sqlite3` for more - information. + you can store information for your own needs. See the documentation + for :class:`flask.g` and :doc:`patterns/sqlite3`. Accessing Request Data @@ -495,8 +501,6 @@ test request so that you can interact with it. Here is an example:: The other possibility is passing a whole WSGI environment to the :meth:`~flask.Flask.request_context` method:: - from flask import request - with app.request_context(environ): assert request.method == 'POST' @@ -582,17 +586,16 @@ of the client to store the file on the server, pass it through the :func:`~werkzeug.utils.secure_filename` function that Werkzeug provides for you:: - from flask import request from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': - f = request.files['the_file'] - f.save('/var/www/uploads/' + secure_filename(f.filename)) + file = request.files['the_file'] + file.save(f"/var/www/uploads/{secure_filename(file.filename)}") ... -For some better examples, checkout the :ref:`uploading-files` pattern. +For some better examples, see :doc:`patterns/fileuploads`. Cookies ``````` @@ -632,7 +635,7 @@ the :meth:`~flask.make_response` function and then modify it. Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the -:ref:`deferred-callbacks` pattern. +:doc:`patterns/deferredcallbacks` pattern. For this also see :ref:`about-responses`. @@ -672,7 +675,7 @@ Note the ``404`` after the :func:`~flask.render_template` call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well. -See :ref:`error-handlers` for more details. +See :doc:`errorhandling` for more details. .. _about-responses: @@ -683,22 +686,25 @@ The return value from a view function is automatically converted into a response object for you. If the return value is a string it's converted into a response object with the string as response body, a ``200 OK`` status code and a :mimetype:`text/html` mimetype. If the -return value is a dict, :func:`jsonify` is called to produce a response. -The logic that Flask applies to converting return values into response -objects is as follows: +return value is a dict or list, :func:`jsonify` is called to produce a +response. The logic that Flask applies to converting return values into +response objects is as follows: 1. If a response object of the correct type is returned it's directly returned from the view. 2. If it's a string, a response object is created with that data and the default parameters. -3. If it's a dict, a response object is created using ``jsonify``. -4. If a tuple is returned the items in the tuple can provide extra +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. -5. If none of that works, Flask will assume the return value is a +6. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object. If you want to get hold of the resulting response object inside the view @@ -706,6 +712,8 @@ you can use the :func:`~flask.make_response` function. Imagine you have a view like this:: + from flask import render_template + @app.errorhandler(404) def not_found(error): return render_template('error.html'), 404 @@ -714,6 +722,8 @@ 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) @@ -725,8 +735,8 @@ APIs with JSON `````````````` A common response format when writing an API is JSON. It's easy to get -started writing such an API with Flask. If you return a ``dict`` from a -view, it will be converted to a JSON response. +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 @@ -739,18 +749,20 @@ view, it will be converted to a JSON response. "image": url_for("user_image", filename=user.image), } -Depending on your API design, you may want to create JSON responses for -types other than ``dict``. In that case, use the -:func:`~flask.json.jsonify` function, which will serialize any supported -JSON data type. Or look into Flask community extensions that support -more complex applications. - -.. code-block:: python - @app.route("/users") def users_api(): users = get_all_users() - return jsonify([user.to_json() for user in users]) + 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: @@ -768,9 +780,7 @@ unless they know the secret key used for signing. In order to use sessions you have to set a secret key. Here is how sessions work:: - from flask import Flask, session, redirect, url_for, escape, request - - app = Flask(__name__) + from flask import session # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @@ -778,7 +788,7 @@ sessions work:: @app.route('/') def index(): if 'username' in session: - return 'Logged in as %s' % escape(session['username']) + return f'Logged in as {session["username"]}' return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) @@ -799,9 +809,6 @@ 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 @@ -809,8 +816,8 @@ not using the template engine (as in this example). generator. Use the following command to quickly generate a value for :attr:`Flask.secret_key` (or :data:`SECRET_KEY`):: - $ python -c 'import os; print(os.urandom(16))' - b'_5#y2L"F4Q8z\n\xec]/' + $ python -c 'import secrets; print(secrets.token_hex())' + '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' 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 @@ -835,8 +842,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. Check out the :ref:`message-flashing-pattern` -for a full example. +available in the templates. See :doc:`patterns/flashing` for a full +example. Logging ------- @@ -865,18 +872,25 @@ The attached :attr:`~flask.Flask.logger` is a standard logging :class:`~logging.Logger`, so head over to the official :mod:`logging` docs for more information. -Read more on :ref:`application-errors`. +See :doc:`errorhandling`. + -Hooking in WSGI Middlewares ---------------------------- +Hooking in WSGI Middleware +-------------------------- + +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 -If you want to add a WSGI middleware to your application you can wrap the -internal WSGI application. For example if you want to use one of the -middlewares from the Werkzeug package to work around bugs in lighttpd, you -can do it like this:: + from werkzeug.middleware.proxy_fix import ProxyFix + app.wsgi_app = ProxyFix(app.wsgi_app) - from werkzeug.contrib.fixers import LighttpdCGIRootFix - app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app) +Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still +points at your Flask application, not at the middleware, so you can +continue to use and configure ``app`` directly. Using Flask Extensions ---------------------- @@ -885,9 +899,9 @@ Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask. -For more on Flask extensions, have a look at :ref:`extensions`. +For more on Flask extensions, see :doc:`extensions`. Deploying to a Web Server ------------------------- -Ready to deploy your new Flask app? Go to :ref:`deployment`. +Ready to deploy your new Flask app? See :doc:`deploying/index`. diff --git a/docs/reqcontext.rst b/docs/reqcontext.rst index 5dad6fbf9b..4f1846a346 100644 --- a/docs/reqcontext.rst +++ b/docs/reqcontext.rst @@ -1,7 +1,5 @@ .. currentmodule:: flask -.. _request-context: - The Request Context =================== @@ -10,7 +8,7 @@ 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 +This is similar to :doc:`/appcontext`, which keeps track of the application-level data independent of a request. A corresponding application context is pushed when a request context is pushed. @@ -35,16 +33,18 @@ 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. +context, which also pushes an :doc:`app context `. 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. +:data:`request` cannot be passed to another thread, the other thread has +a different context space and will not know about the request the parent +thread was pointing to. -Context locals are implemented in Werkzeug. See :doc:`werkzeug:local` -for more information on how this works internally. +Context locals are implemented using Python's :mod:`contextvars` and +Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the +lifetime of context vars automatically, and local proxy wraps that +low-level interface to make the data easier to work with. Manually Push a Context @@ -69,11 +69,12 @@ 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') + format = request.args.get("format") ... with app.test_request_context( - '/make_report/2017', data={'format': 'short'}): + "/make_report/2017", query_string={"format": "short"} + ): generate_report() If you see that error somewhere else in your code not related to @@ -89,10 +90,9 @@ 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 +application contexts work like stacks. When contexts are pushed, the proxies that depend on them are available and point at information from -the top context on the stack. +the top item. When the request starts, a :class:`~ctx.RequestContext` is created and pushed, which creates and pushes an :class:`~ctx.AppContext` first if @@ -101,15 +101,15 @@ 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. +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 +and :meth:`~Flask.teardown_appcontext` functions are executed. These execute even if an unhandled exception occurred during dispatch. @@ -170,8 +170,8 @@ 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. +Use the :meth:`~Flask.test_client` as a ``with`` block to preserve the +contexts until the ``with`` block exits. .. code-block:: python @@ -199,45 +199,21 @@ contexts until the with block exits. print(request.path) # the contexts are popped and teardown functions are called after - # the client with block exists + # the client with block exits 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. +The following signals are sent: -Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it -will cause your application to leak memory on exceptions. +#. :data:`request_started` is sent before the :meth:`~Flask.before_request` functions + are called. +#. :data:`request_finished` is sent after the :meth:`~Flask.after_request` functions + are called. +#. :data:`got_request_exception` is sent when an exception begins to be handled, but + before an :meth:`~Flask.errorhandler` is looked up or called. +#. :data:`request_tearing_down` is sent after the :meth:`~Flask.teardown_request` + functions are called. .. _notes-on-proxies: @@ -251,13 +227,14 @@ point to the unique object bound to each worker behind the scenes as described on this page. Most of the time you don't have to care about that, but there are some -exceptions where it is good to know that this object is an actual proxy: +exceptions where it is good to know that this object is actually a proxy: - The proxy objects 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. +- The reference to the proxied object is needed in some situations, + such as sending :doc:`signals` or passing data to a background + thread. If you need to access the underlying object that is proxied, use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method:: diff --git a/docs/requirements.txt b/docs/requirements.txt deleted file mode 100644 index 543ec917fd..0000000000 --- a/docs/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -Sphinx~=2.1.2 -Pallets-Sphinx-Themes~=1.1.4 -sphinxcontrib-log-cabinet~=1.0.0 -sphinx-issues~=1.2.0 diff --git a/docs/security.rst b/docs/security.rst index 44c095acb7..3992e8da3b 100644 --- a/docs/security.rst +++ b/docs/security.rst @@ -5,7 +5,7 @@ Web applications usually face all kinds of security problems and it's very hard to get everything right. Flask tries to solve a few of these things for you, but there are a couple more you have to take care of yourself. -.. _xss: +.. _security-xss: Cross-Site Scripting (XSS) -------------------------- @@ -23,7 +23,7 @@ in templates, but there are still other places where you have to be careful: - generating HTML without the help of Jinja2 -- calling :class:`~flask.Markup` on data submitted by users +- calling :class:`~markupsafe.Markup` on data submitted by users - sending out HTML from uploaded files, never do that, use the ``Content-Disposition: attachment`` header to prevent that problem. - sending out textfiles from uploaded files. Some browsers are using @@ -101,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. -.. _json-security: +.. _security-json: JSON Security ------------- @@ -173,18 +173,6 @@ 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 @@ -258,3 +246,29 @@ certificate key to prevent MITM attacks. or upgrade your key incorrectly. - https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning + + +Copy/Paste to Terminal +---------------------- + +Hidden characters such as the backspace character (``\b``, ``^H``) can +cause text to render differently in HTML than how it is interpreted if +`pasted into a terminal `__. + +For example, ``import y\bose\bm\bi\bt\be\b`` renders as +``import yosemite`` in HTML, but the backspaces are applied when pasted +into a terminal, and it becomes ``import os``. + +If you expect users to copy and paste untrusted code from your site, +such as from comments posted by users on a technical blog, consider +applying extra filtering, such as replacing all ``\b`` characters. + +.. code-block:: python + + body = body.replace("\b", "") + +Most modern terminals will warn about and remove hidden characters when +pasting, so this isn't strictly necessary. It's also possible to craft +dangerous commands in other ways that aren't possible to filter. +Depending on your site's use case, it may be good to show a warning +about copying code in general. diff --git a/docs/server.rst b/docs/server.rst index db431a6c54..d38aa12089 100644 --- a/docs/server.rst +++ b/docs/server.rst @@ -1,62 +1,115 @@ -.. _server: +.. currentmodule:: flask Development Server ================== -.. currentmodule:: flask +Flask provides a ``run`` command to run the application with a development server. In +debug mode, this server provides an interactive debugger and will reload when code is +changed. + +.. warning:: + + Do not use the development server when deploying to production. It + is intended for use only during local development. It is not + designed to be particularly efficient, stable, or secure. -Starting with Flask 0.11 there are multiple built-in ways to run a -development server. The best one is the :command:`flask` command line utility -but you can also continue using the :meth:`Flask.run` method. + See :doc:`/deploying/index` for deployment options. Command Line ------------ -The :command:`flask` command line script (:ref:`cli`) is strongly -recommended for development because it provides a superior reload -experience due to how it loads the application. The basic usage is like -this:: +The ``flask run`` CLI command is the recommended way to run the development server. Use +the ``--app`` option to point to your application, and the ``--debug`` option to enable +debug mode. + +.. code-block:: text + + $ flask --app hello run --debug + +This enables debug mode, including the interactive debugger and reloader, and then +starts the server on http://localhost:5000/. Use ``flask run --help`` to see the +available options, and :doc:`/cli` for detailed instructions about configuring and using +the CLI. + + +.. _address-already-in-use: + +Address already in use +~~~~~~~~~~~~~~~~~~~~~~ + +If another program is already using port 5000, you'll see an ``OSError`` +when the server tries to start. It may have one of the following +messages: + +- ``OSError: [Errno 98] Address already in use`` +- ``OSError: [WinError 10013] An attempt was made to access a socket + in a way forbidden by its access permissions`` + +Either identify and stop the other program, or use +``flask run --port 5001`` to pick a different port. - $ export FLASK_APP=my_application - $ export FLASK_ENV=development - $ flask run +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. -This enables the development environment, including the interactive -debugger and reloader, and then starts the server on -*http://localhost:5000/*. +.. tabs:: -The individual features of the server can be controlled by passing more -arguments to the ``run`` option. For instance the reloader can be -disabled:: + .. tab:: ``netstat`` (Linux) - $ flask run --no-reload + .. code-block:: text -.. note:: + $ 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. To disable the service, go to System Preferences, Sharing, and +disable "AirPlay Receiver". + + +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. - Prior to Flask 1.0 the :envvar:`FLASK_ENV` environment variable was - not supported and you needed to enable debug mode by exporting - ``FLASK_DEBUG=1``. This can still be used to control debug mode, but - you should prefer setting the development environment as shown - above. In Code ------- -The alternative way to start the application is through the -:meth:`Flask.run` method. This will immediately launch a local server -exactly the same way the :command:`flask` script does. +The development server can also be started from Python with the :meth:`Flask.run` +method. This method takes arguments similar to the CLI options to control the server. +The main difference from the CLI command is that the server will crash if there are +errors when reloading. ``debug=True`` can be passed to enable debug mode. + +Place the call in a main block, otherwise it will interfere when trying to import and +run the application with a production server later. -Example:: +.. code-block:: python - if __name__ == '__main__': - app.run() + if __name__ == "__main__": + app.run(debug=True) -This works well for the common case but it does not work well for -development which is why from Flask 0.11 onwards the :command:`flask` -method is recommended. The reason for this is that due to how the reload -mechanism works there are some bizarre side-effects (like executing -certain code twice, sometimes crashing without message or dying when a -syntax or import error happens). +.. code-block:: text -It is however still a perfectly valid method for invoking a non automatic -reloading application. + $ python hello.py diff --git a/docs/shell.rst b/docs/shell.rst index c863a77d9c..7e42e28515 100644 --- a/docs/shell.rst +++ b/docs/shell.rst @@ -1,5 +1,3 @@ -.. _shell: - Working with the Shell ====================== @@ -23,8 +21,7 @@ that these functions are not only there for interactive shell usage, but also for unit testing and other situations that require a faked request context. -Generally it's recommended that you read the :ref:`request-context` -chapter of the documentation first. +Generally it's recommended that you read :doc:`reqcontext` first. Command Line Interface ---------------------- @@ -34,7 +31,7 @@ Starting with Flask 0.11 the recommended way to work with the shell is the For instance the shell is automatically initialized with a loaded application context. -For more information see :ref:`cli`. +For more information see :doc:`/cli`. Creating a Request Context -------------------------- diff --git a/docs/signals.rst b/docs/signals.rst index 2cf3ce60e1..739bb0b548 100644 --- a/docs/signals.rst +++ b/docs/signals.rst @@ -1,35 +1,28 @@ -.. _signals: - Signals ======= -.. versionadded:: 0.6 - -Starting with Flask 0.6, there is integrated support for signalling in -Flask. This support is provided by the excellent `blinker`_ library and -will gracefully fall back if it is not available. - -What are signals? Signals help you decouple applications by sending -notifications when actions occur elsewhere in the core framework or -another Flask extensions. In short, signals allow certain senders to -notify subscribers that something happened. - -Flask comes with a couple of signals and other extensions might provide -more. Also keep in mind that signals are intended to notify subscribers -and should not encourage subscribers to modify data. You will notice that -there are signals that appear to do the same thing like some of the -builtin decorators do (eg: :data:`~flask.request_started` is very similar -to :meth:`~flask.Flask.before_request`). However, there are differences in -how they work. The core :meth:`~flask.Flask.before_request` handler, for -example, is executed in a specific order and is able to abort the request -early by returning a response. In contrast all signal handlers are -executed in undefined order and do not modify any data. - -The big advantage of signals over handlers is that you can safely -subscribe to them for just a split second. These temporary -subscriptions are helpful for 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. +Signals are a lightweight way to notify subscribers of certain events during the +lifecycle of the application and each request. When an event occurs, it emits the +signal, which calls each subscriber. + +Signals are implemented by the `Blinker`_ library. See its documentation for detailed +information. Flask provides some built-in signals. Extensions may provide their own. + +Many signals mirror Flask's decorator-based callbacks with similar names. For example, +the :data:`.request_started` signal is similar to the :meth:`~.Flask.before_request` +decorator. The advantage of signals over handlers is that they can be subscribed to +temporarily, and can't directly affect the application. This is useful for testing, +metrics, auditing, and more. For example, if you want to know what templates were +rendered at what parts of what requests, there is a signal that will notify you of that +information. + + +Core Signals +------------ + +See :ref:`core-signals-list` for a list of all built-in signals. The :doc:`lifecycle` +page also describes the order that signals and decorators execute. + Subscribing to Signals ---------------------- @@ -101,17 +94,12 @@ The example above would then look like this:: ... template, context = templates[0] -.. admonition:: Blinker API Changes - - The :meth:`~blinker.base.Signal.connected_to` method arrived in Blinker - with version 1.1. - Creating Signals ---------------- If you want to use signals in your own application, you can use the blinker library directly. The most common use case are named signals in a -custom :class:`~blinker.base.Namespace`.. This is what is recommended +custom :class:`~blinker.base.Namespace`. This is what is recommended most of the time:: from blinker import Namespace @@ -125,12 +113,6 @@ The name for the signal here makes it unique and also simplifies debugging. You can access the name of the signal with the :attr:`~blinker.base.NamedSignal.name` attribute. -.. admonition:: For Extension Developers - - If you are writing a Flask extension and you want to gracefully degrade for - missing blinker installations, you can do so by using the - :class:`flask.signals.Namespace` class. - .. _signals-sending: Sending Signals @@ -162,7 +144,7 @@ function, you can pass ``current_app._get_current_object()`` as sender. Signals and Flask's Request Context ----------------------------------- -Signals fully support :ref:`request-context` when receiving signals. +Signals fully support :doc:`reqcontext` when receiving signals. Context-local variables are consistently available between :data:`~flask.request_started` and :data:`~flask.request_finished`, so you can rely on :class:`flask.g` and others as needed. Note the limitations described @@ -172,19 +154,14 @@ in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal. Decorator Based Signal Subscriptions ------------------------------------ -With Blinker 1.1 you can also easily subscribe to signals by using the new +You can also easily subscribe to signals by using the :meth:`~blinker.base.NamedSignal.connect_via` decorator:: from flask import template_rendered @template_rendered.connect_via(app) def when_template_rendered(sender, template, context, **extra): - print 'Template %s is rendered with %s' % (template.name, context) - -Core Signals ------------- - -Take a look at :ref:`core-signals-list` for a list of all builtin signals. + print(f'Template {template.name} is rendered with {context}') .. _blinker: https://pypi.org/project/blinker/ diff --git a/docs/styleguide.rst b/docs/styleguide.rst deleted file mode 100644 index 390d56684a..0000000000 --- a/docs/styleguide.rst +++ /dev/null @@ -1,200 +0,0 @@ -Pocoo Styleguide -================ - -The Pocoo styleguide is the styleguide for all Pocoo Projects, including -Flask. This styleguide is a requirement for Patches to Flask and a -recommendation for Flask extensions. - -In general the Pocoo Styleguide closely follows :pep:`8` with some small -differences and extensions. - -General Layout --------------- - -Indentation: - 4 real spaces. No tabs, no exceptions. - -Maximum line length: - 79 characters with a soft limit for 84 if absolutely necessary. Try - to avoid too nested code by cleverly placing `break`, `continue` and - `return` statements. - -Continuing long statements: - To continue a statement you can use backslashes in which case you should - align the next line with the last dot or equal sign, or indent four - spaces:: - - this_is_a_very_long(function_call, 'with many parameters') \ - .that_returns_an_object_with_an_attribute - - MyModel.query.filter(MyModel.scalar > 120) \ - .order_by(MyModel.name.desc()) \ - .limit(10) - - If you break in a statement with parentheses or braces, align to the - braces:: - - this_is_a_very_long(function_call, 'with many parameters', - 23, 42, 'and even more') - - For lists or tuples with many items, break immediately after the - opening brace:: - - items = [ - 'this is the first', 'set of items', 'with more items', - 'to come in this line', 'like this' - ] - -Blank lines: - Top level functions and classes are separated by two lines, everything - else by one. Do not use too many blank lines to separate logical - segments in code. Example:: - - def hello(name): - print 'Hello %s!' % name - - - def goodbye(name): - print 'See you %s.' % name - - - class MyClass(object): - """This is a simple docstring""" - - def __init__(self, name): - self.name = name - - def get_annoying_name(self): - return self.name.upper() + '!!!!111' - -Expressions and Statements --------------------------- - -General whitespace rules: - - No whitespace for unary operators that are not words - (e.g.: ``-``, ``~`` etc.) as well on the inner side of parentheses. - - Whitespace is placed between binary operators. - - Good:: - - exp = -1.05 - value = (item_value / item_count) * offset / exp - value = my_list[index] - value = my_dict['key'] - - Bad:: - - exp = - 1.05 - value = ( item_value / item_count ) * offset / exp - value = (item_value/item_count)*offset/exp - value=( item_value/item_count ) * offset/exp - value = my_list[ index ] - value = my_dict ['key'] - -Yoda statements are a no-go: - Never compare constant with variable, always variable with constant: - - Good:: - - if method == 'md5': - pass - - Bad:: - - if 'md5' == method: - pass - -Comparisons: - - against arbitrary types: ``==`` and ``!=`` - - against singletons with ``is`` and ``is not`` (eg: ``foo is not - None``) - - never compare something with ``True`` or ``False`` (for example never - do ``foo == False``, do ``not foo`` instead) - -Negated containment checks: - use ``foo not in bar`` instead of ``not foo in bar`` - -Instance checks: - ``isinstance(a, C)`` instead of ``type(A) is C``, but try to avoid - instance checks in general. Check for features. - - -Naming Conventions ------------------- - -- Class names: ``CamelCase``, with acronyms kept uppercase (``HTTPWriter`` - and not ``HttpWriter``) -- Variable names: ``lowercase_with_underscores`` -- Method and function names: ``lowercase_with_underscores`` -- Constants: ``UPPERCASE_WITH_UNDERSCORES`` -- precompiled regular expressions: ``name_re`` - -Protected members are prefixed with a single underscore. Double -underscores are reserved for mixin classes. - -On classes with keywords, trailing underscores are appended. Clashes with -builtins are allowed and **must not** be resolved by appending an -underline to the variable name. If the function needs to access a -shadowed builtin, rebind the builtin to a different name instead. - -Function and method arguments: - - class methods: ``cls`` as first parameter - - instance methods: ``self`` as first parameter - - lambdas for properties might have the first parameter replaced - with ``x`` like in ``display_name = property(lambda x: x.real_name - or x.username)`` - - -Docstrings ----------- - -Docstring conventions: - All docstrings are formatted with reStructuredText as understood by - Sphinx. Depending on the number of lines in the docstring, they are - laid out differently. If it's just one line, the closing triple - quote is on the same line as the opening, otherwise the text is on - the same line as the opening quote and the triple quote that closes - the string on its own line:: - - def foo(): - """This is a simple docstring""" - - - def bar(): - """This is a longer docstring with so much information in there - that it spans three lines. In this case the closing triple quote - is on its own line. - """ - -Module header: - The module header consists of 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 3fa7a0663f..23cfee4cb3 100644 --- a/docs/templating.rst +++ b/docs/templating.rst @@ -1,9 +1,7 @@ -.. _templates: - Templates ========= -Flask leverages Jinja2 as template engine. You are obviously free to use +Flask leverages Jinja2 as its template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present. @@ -11,7 +9,7 @@ An extension can depend on Jinja2 being present. This section only gives a very quick introduction into how Jinja2 is integrated into Flask. If you want information on the template engine's syntax itself, head over to the official `Jinja2 Template -Documentation `_ for +Documentation `_ for more information. Jinja Setup @@ -20,7 +18,7 @@ Jinja Setup Unless customized, Jinja2 is configured by Flask as follows: - autoescaping is enabled for all templates ending in ``.html``, - ``.htm``, ``.xml`` as well as ``.xhtml`` when using + ``.htm``, ``.xml``, ``.xhtml``, as well as ``.svg`` when using :func:`~flask.templating.render_template`. - autoescaping is enabled for all strings when using :func:`~flask.templating.render_template_string`. @@ -39,7 +37,7 @@ by default: .. data:: config :noindex: - The current configuration object (:data:`flask.config`) + The current configuration object (:data:`flask.Flask.config`) .. versionadded:: 0.6 @@ -97,37 +95,6 @@ by default: {% from '_helpers.html' import my_macro with context %} -Standard Filters ----------------- - -These filters are available in Jinja2 additionally to the filters provided -by Jinja2 itself: - -.. function:: tojson - :noindex: - - This function converts the given object into JSON representation. This - is for example very helpful if you try to generate JavaScript on the - fly. - - .. sourcecode:: html+jinja - - - - It is also safe to use the output of `|tojson` in a *single-quoted* HTML - attribute: - - .. sourcecode:: html+jinja - - - - Note that in versions of Flask prior to 0.10, if using the output of - ``|tojson`` inside ``script``, make sure to disable escaping with ``|safe``. - In Flask 0.10 and above, this happens automatically. Controlling Autoescaping ------------------------ @@ -139,7 +106,7 @@ carry specific meanings in documents on their own you have to replace them by so called "entities" if you want to use them for text. Not doing so would not only cause user frustration by the inability to use these characters in text, but can also lead to security problems. (see -:ref:`xss`) +:ref:`security-xss`) Sometimes however you will need to disable autoescaping in templates. This can be the case if you want to explicitly inject HTML into pages, for @@ -148,7 +115,7 @@ markdown to HTML converter. There are three ways to accomplish that: -- In the Python code, wrap the HTML string in a :class:`~flask.Markup` +- In the Python code, wrap the HTML string in a :class:`~markupsafe.Markup` object before passing it to the template. This is in general the recommended way. - Inside the template, use the ``|safe`` filter to explicitly mark a @@ -222,8 +189,8 @@ functions):: @app.context_processor def utility_processor(): - def format_price(amount, currency=u'€'): - return u'{0:.2f}{1}'.format(amount, currency) + def format_price(amount, currency="€"): + return f"{amount:.2f}{currency}" return dict(format_price=format_price) The context processor above makes the `format_price` function available to all @@ -234,3 +201,29 @@ templates:: You could also build `format_price` as a template filter (see :ref:`registering-filters`), but this demonstrates how to pass functions in a context processor. + +Streaming +--------- + +It can be useful to not render the whole template as one complete +string, instead render it as a stream, yielding smaller incremental +strings. This can be used for streaming HTML in chunks to speed up +initial page load, or to save memory when rendering a very large +template. + +The Jinja2 template engine supports rendering a template piece +by piece, returning an iterator of strings. Flask provides the +:func:`~flask.stream_template` and :func:`~flask.stream_template_string` +functions to make this easier to use. + +.. code-block:: python + + from flask import stream_template + + @app.get("/timeline") + def timeline(): + return stream_template("timeline.html") + +These functions automatically apply the +:func:`~flask.stream_with_context` wrapper if a request is active, so +that it remains available in the template. diff --git a/docs/testing.rst b/docs/testing.rst index 01eef000f4..8545bd3937 100644 --- a/docs/testing.rst +++ b/docs/testing.rst @@ -1,458 +1,319 @@ -.. _testing: - Testing Flask Applications ========================== - **Something that is untested is broken.** - -The origin of this quote is unknown and while it is not entirely correct, it -is also not far from the truth. Untested applications make it hard to -improve existing code and developers of untested applications tend to -become pretty paranoid. If an application has automated tests, you can -safely make changes and instantly know if anything breaks. +Flask provides utilities for testing an application. This documentation +goes over techniques for working with different parts of the application +in tests. -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. +We will use the `pytest`_ framework to set up and run our tests. -In this documentation we will use the `pytest`_ package as the base -framework for our tests. You can install it with ``pip``, like so:: +.. code-block:: text $ pip install pytest .. _pytest: https://docs.pytest.org/ -The Application ---------------- - -First, we need an application to test; we will use the application from -the :ref:`tutorial`. If you don't have that application yet, get the -source code from :gh:`the examples `. - -The Testing Skeleton --------------------- - -We begin by adding a tests directory under the application root. Then -create a Python file to store our tests (:file:`test_flaskr.py`). When we -format the filename like ``test_*.py``, it will be auto-discoverable by -pytest. - -Next, we create a `pytest fixture`_ called -:func:`client` that configures -the application for testing and initializes a new database:: - - import os - import tempfile - - import pytest - - from flaskr import flaskr - - - @pytest.fixture - def client(): - db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp() - flaskr.app.config['TESTING'] = True - - with flaskr.app.test_client() as client: - with flaskr.app.app_context(): - flaskr.init_db() - yield client - - os.close(db_fd) - os.unlink(flaskr.app.config['DATABASE']) - -This client fixture will be called by each individual test. It gives us a -simple interface to the application, where we can trigger test requests to the -application. The client will also keep track of cookies for us. - -During setup, the ``TESTING`` config flag is activated. What -this does is disable error catching during request handling, so that -you get better error reports when performing test requests against the -application. - -Because SQLite3 is filesystem-based, we can easily use the -:mod:`tempfile` module to create a temporary database and initialize it. -The :func:`~tempfile.mkstemp` function does two things for us: it returns a -low-level file handle and a random file name, the latter we use as -database name. We just have to keep the `db_fd` around so that we can use -the :func:`os.close` function to close the file. - -To delete the database after the test, the fixture closes the file and removes -it from the filesystem. - -If we now run the test suite, we should see the following output:: - - $ pytest - - ================ test session starts ================ - rootdir: ./flask/examples/flaskr, inifile: setup.cfg - collected 0 items - - =========== no tests ran in 0.07 seconds ============ - -Even though it did not run any actual tests, we already know that our -``flaskr`` application is syntactically valid, otherwise the import -would have died with an exception. - -.. _pytest fixture: - https://docs.pytest.org/en/latest/fixture.html - -The First Test --------------- - -Now it's time to start testing the functionality of the application. -Let's check that the application shows "No entries here so far" if we -access the root of the application (``/``). To do this, we add a new -test function to :file:`test_flaskr.py`, like this:: +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. - 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) +Identifying Tests +----------------- -Now we can easily test that logging in and out works and that it fails with -invalid credentials. Add this new test function:: +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``. - def test_login_logout(client): - """Make sure login and logout works.""" +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. - 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 +Fixtures +-------- - rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD']) - assert b'Invalid username' in rv.data +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``. - rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x') - assert b'Invalid password' in rv.data +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. -Test Adding Messages --------------------- +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. -We should also test that adding messages works. Add a new test function -like this:: +.. code-block:: python - def test_messages(client): - """Test that messages work.""" + import pytest + from my_project import create_app - 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 + @pytest.fixture() + def app(): + app = create_app() + app.config.update({ + "TESTING": True, + }) -Here we check that HTML is allowed in the text but not in the title, -which is the intended behavior. + # other setup can go here -Running that should now give us three passing tests:: + yield app - $ pytest -v + # clean up / reset resources here - ================ 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 + @pytest.fixture() + def client(app): + return app.test_client() - ============= 3 passed in 0.23 seconds ============== + @pytest.fixture() + def runner(app): + return app.test_cli_runner() -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:: +Sending Requests with the Test Client +------------------------------------- - import flask +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. - app = flask.Flask(__name__) +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``. - with app.test_request_context('/?name=Peter'): - assert flask.request.path == '/' - assert flask.request.args['name'] == 'Peter' +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)``. -All the other objects that are context bound can be used in the same -way. +.. code-block:: python -If you want to test your application with different configurations and -there does not seem to be a good way to do that, consider switching to -application factories (see :ref:`app-factories`). + def test_request_example(client): + response = client.get("/posts") + assert b"

Hello, World!

" in response.data -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__) +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. - with app.test_request_context('/?name=Peter'): - app.preprocess_request() - ... +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. -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:: +Form Data +~~~~~~~~~ - app = flask.Flask(__name__) +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. - with app.test_request_context('/?name=Peter'): - resp = Response('...') - resp = app.process_response(resp) - ... +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. -This in general is less useful because at that point you can directly -start using the test client. +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. -.. _faking-resources: +.. code-block:: python -Faking Resources and Context ----------------------------- + from pathlib import Path -.. versionadded:: 0.10 + # get the resources folder in the tests folder + resources = Path(__file__).parent / "resources" -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 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 - 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:: +JSON Data +~~~~~~~~~ - from contextlib import contextmanager - from flask import appcontext_pushed, g +To send JSON data, pass an object to ``json``. The ``Content-Type`` +header will be set to ``application/json`` automatically. - @contextmanager - def user_set(app, user): - def handler(sender, **kwargs): - g.user = user - with appcontext_pushed.connected_to(handler, app): - yield +Similarly, if the response contains JSON data, the ``response.json`` +attribute will contain the deserialized object. -And then to use it:: +.. code-block:: python - from flask import json, jsonify + 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" - @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) +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. -Keeping the Context Around --------------------------- +: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. -.. versionadded:: 0.4 +.. code-block:: python -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:: + def test_logout_redirect(client): + response = client.get("/logout") + # 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" - app = flask.Flask(__name__) - with app.test_client() as c: - rv = c.get('/?tequila=42') - assert request.args['tequila'] == '42' +Accessing and Modifying the Session +----------------------------------- -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). +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 -Accessing and Modifying Sessions --------------------------------- + from flask import session -.. versionadded:: 0.8 + def test_access_session(client): + with client: + client.post("/auth/login", data={"username": "flask"}) + # session is still accessible + assert session["user_id"] == 1 -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`:: + # session is no longer accessible - with app.test_client() as c: - rv = c.get('/') - assert flask.session['foo'] == 42 +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. -This however does not make it possible to also modify the session or to -access the session before a request was fired. Starting with Flask 0.8 we -provide a so called “session transaction” which simulates the appropriate -calls to open a session in the context of the test client and to modify -it. At the end of the transaction the session is stored and ready to be -used by the test client. This works independently of the session backend used:: +.. code-block:: python - with app.test_client() as c: - with c.session_transaction() as sess: - sess['a_key'] = 'a value' + from flask import session - # once this is reached the session was stored and ready to be used by the client - c.get(...) + 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 -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. + # session is saved now + response = client.get("/users/me") + assert response.json["username"] == "flask" -Testing JSON APIs ------------------ -.. versionadded:: 1.0 +.. _testing-cli: -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:: +Running Commands with the CLI Runner +------------------------------------ - from flask import request, jsonify +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. - @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)) +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. - with app.test_client() as c: - rv = c.post('/api/auth', json={ - 'email': 'flask@example.com', 'password': 'secret' - }) - json_data = rv.get_json() - assert verify_token(email, json_data['token']) +.. code-block:: python -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``. + import click + @app.cli.command("hello") + @click.option("--name", default="World") + def hello_command(name): + click.echo(f"Hello, {name}!") -.. _testing-cli: + def test_hello_command(runner): + result = runner.invoke(args="hello") + assert "World" in result.output -Testing CLI Commands --------------------- + result = runner.invoke(args=["hello", "--name", "Flask"]) + assert "Flask" in result.output -Click comes with `utilities for testing`_ your CLI commands. A -:class:`~click.testing.CliRunner` runs commands in isolation and -captures the output in a :class:`~click.testing.Result` object. -Flask provides :meth:`~flask.Flask.test_cli_runner` to create a -:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the -CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke` -method to call commands in the same way they would be called from the -command line. :: +Tests that depend on an Active Context +-------------------------------------- - import click +You may have functions that are called from views or commands, that +expect an active :doc:`application context ` or +:doc:`request context ` because they access ``request``, +``session``, or ``current_app``. Rather than testing them by making a +request or invoking the command, you can create and activate a context +directly. - @app.cli.command('hello') - @click.option('--name', default='World') - def hello_command(name) - click.echo(f'Hello, {name}!') +Use ``with app.app_context()`` to push an application context. For +example, database extensions usually require an active app context to +make queries. - def test_hello(): - runner = app.test_cli_runner() +.. code-block:: python - # invoke the command directly - result = runner.invoke(hello_command, ['--name', 'Flask']) - assert 'Hello, Flask' in result.output + def test_db_post_model(app): + with app.app_context(): + post = db.session.query(Post).get(1) - # or by name - result = runner.invoke(args=['hello']) - assert 'World' in result.output +Use ``with app.test_request_context()`` to push a request context. It +takes the same arguments as the test client's request methods. -In the example above, invoking the command by name is useful because it -verifies that the command was correctly registered with the app. +.. code-block:: python -If you want to test how your command parses parameters, without running -the command, use its :meth:`~click.BaseCommand.make_context` method. -This is useful for testing complex validation rules and custom types. :: + def 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() - def upper(ctx, param, value): - if value is not None: - return value.upper() + assert messages["name"][0] == "Name cannot be empty." - @app.cli.command('hello') - @click.option('--name', default='World', callback=upper) - def hello_command(name) - click.echo(f'Hello, {name}!') +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. - def test_hello_params(): - context = hello_command.make_context('hello', ['--name', 'flask']) - assert context.params['name'] == 'FLASK' +.. code-block:: python -.. _click: https://click.palletsprojects.com/ -.. _utilities for testing: https://click.palletsprojects.com/testing/ + def test_auth_token(app): + with app.test_request_context("/user/2/edit", headers={"X-Auth-Token": "1"}): + app.preprocess_request() + assert g.user.name == "Flask" diff --git a/docs/tutorial/blog.rst b/docs/tutorial/blog.rst index 18eac19389..b06329eaae 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: http://jinja.pocoo.org/docs/templates/#for +.. _Jinja for loops: https://jinja.palletsprojects.com/templates/#for Create @@ -207,7 +207,7 @@ it from each view. ).fetchone() if post is None: - abort(404, "Post id {0} doesn't exist.".format(id)) + abort(404, f"Post id {id} doesn't exist.") if check_author and post['author_id'] != g.user['id']: abort(403) diff --git a/docs/tutorial/database.rst b/docs/tutorial/database.rst index 942341dc37..934f6008ce 100644 --- a/docs/tutorial/database.rst +++ b/docs/tutorial/database.rst @@ -40,7 +40,6 @@ response is sent. import click from flask import current_app, g - from flask.cli import with_appcontext def get_db(): @@ -128,7 +127,6 @@ 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() @@ -142,7 +140,7 @@ read from the file. :func:`click.command` defines a command line command called ``init-db`` that calls the ``init_db`` function and shows a success message to the -user. You can read :ref:`cli` to learn more about writing commands. +user. You can read :doc:`/cli` to learn more about writing commands. Register with the Application @@ -196,15 +194,13 @@ 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 :ref:`install-activate-env`. - You'll also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on - the previous page. + and activate the env as described in :doc:`/installation`. Run the ``init-db`` command: .. code-block:: none - $ flask init-db + $ flask --app flaskr 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 8c1713beb8..eb3a53ac5e 100644 --- a/docs/tutorial/deploy.rst +++ b/docs/tutorial/deploy.rst @@ -14,26 +14,17 @@ application. Build and Install ----------------- -When you want to deploy your application elsewhere, you build a -distribution file. The current standard for Python distribution is the -*wheel* format, with the ``.whl`` extension. Make sure the wheel library -is installed first: +When you want to deploy your application elsewhere, you build a *wheel* +(``.whl``) file. Install and use the ``build`` tool to do this. .. code-block:: none - $ pip install 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 + $ pip install build + $ python -m build --wheel You can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The -file name is the name of the project, the version, and some tags about -the file can install. +file name is in the format of {project name}-{version}-{python tag} +-{abi tag}-{platform tag}. Copy this file to another machine, :ref:`set up a new virtualenv `, then install the @@ -48,14 +39,13 @@ Pip will install your project along with its dependencies. Since this is a different machine, you need to run ``init-db`` again to create the database in the instance folder. -.. code-block:: none + .. code-block:: text - $ export FLASK_APP=flaskr - $ flask init-db + $ flask --app flaskr init-db When Flask detects that it's installed (not in editable mode), it uses a different directory for the instance folder. You can find it at -``venv/var/flaskr-instance`` instead. +``.venv/var/flaskr-instance`` instead. Configure the Secret Key @@ -70,17 +60,17 @@ You can use the following command to output a random secret key: .. code-block:: none - $ python -c 'import os; print(os.urandom(16))' + $ python -c 'import secrets; print(secrets.token_hex())' - b'_5#y2L"F4Q8z\n\xec]/' + '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' Create the ``config.py`` file in the instance folder, which the factory will read from if it exists. Copy the generated value into it. .. code-block:: python - :caption: ``venv/var/flaskr-instance/config.py`` + :caption: ``.venv/var/flaskr-instance/config.py`` - SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/' + SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' You can also set any other necessary configuration here, although ``SECRET_KEY`` is the only one needed for Flaskr. @@ -102,7 +92,7 @@ first install it in the virtual environment: $ pip install waitress You need to tell Waitress about your application, but it doesn't use -``FLASK_APP`` like ``flask run`` does. You need to tell it to import and +``--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 diff --git a/docs/tutorial/factory.rst b/docs/tutorial/factory.rst index fbe1c8e23e..39febd135f 100644 --- a/docs/tutorial/factory.rst +++ b/docs/tutorial/factory.rst @@ -127,52 +127,36 @@ Run The Application Now you can run your application using the ``flask`` command. From the terminal, tell Flask where to find your application, then run it in -development mode. Remember, you should still be in the top-level +debug mode. Remember, you should still be in the top-level ``flask-tutorial`` directory, not the ``flaskr`` package. -Development mode shows an interactive debugger whenever a page raises an +Debug mode shows an interactive debugger whenever a page raises an exception, and restarts the server whenever you make changes to the code. You can leave it running and just reload the browser page as you follow the tutorial. -For Linux and Mac: +.. code-block:: text -.. 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 + $ flask --app flaskr run --debug You'll see output similar to this: -.. code-block:: none +.. code-block:: text * Serving Flask app "flaskr" - * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! - * Debugger PIN: 855-212-761 + * Debugger PIN: nnn-nnn-nnn Visit http://127.0.0.1:5000/hello in a browser and you should see the "Hello, World!" message. Congratulations, you're now running your Flask web application! +If another program is already using port 5000, you'll see +``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the +server tries to start. See :ref:`address-already-in-use` for how to +handle that. + Continue to :doc:`database`. diff --git a/docs/tutorial/index.rst b/docs/tutorial/index.rst index 9b43c510fa..d5dc5b3c39 100644 --- a/docs/tutorial/index.rst +++ b/docs/tutorial/index.rst @@ -1,5 +1,3 @@ -.. _tutorial: - Tutorial ======== @@ -35,11 +33,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 :ref:`quickstart` for an +cover all of Flask's features. Check out the :doc:`/quickstart` for an overview of what Flask can do, then dive into the docs to find out more. The tutorial only uses what's provided by Flask and Python. In another -project, you might decide to use :ref:`extensions` or other libraries to -make some tasks simpler. +project, you might decide to use :doc:`/extensions` or other libraries +to make some tasks simpler. .. image:: flaskr_login.png :align: center @@ -57,7 +55,7 @@ this structure and take full advantage of Flask's flexibility. .. image:: flaskr_edit.png :align: center :class: screenshot - :alt: screenshot of login page + :alt: screenshot of edit page :gh:`The tutorial project is available as an example in the Flask repository `, if you want to compare your project diff --git a/docs/tutorial/install.rst b/docs/tutorial/install.rst index 3d7d7c602b..9bb1234eda 100644 --- a/docs/tutorial/install.rst +++ b/docs/tutorial/install.rst @@ -1,11 +1,10 @@ Make the Project Installable ============================ -Making your project installable means that you can build a -*distribution* file and install that in another environment, just like -you installed Flask in your project's environment. This makes deploying -your project the same as installing any other library, so you're using -all the standard Python tools to manage everything. +Making your project installable means that you can build a *wheel* file and install that +in another environment, just like you installed Flask in your project's environment. +This makes deploying your project the same as installing any other library, so you're +using all the standard Python tools to manage everything. Installing also comes with other benefits that might not be obvious from the tutorial or as a new Python user, including: @@ -28,32 +27,25 @@ the tutorial or as a new Python user, including: Describe the Project -------------------- -The ``setup.py`` file describes your project and the files that belong -to it. +The ``pyproject.toml`` file describes your project and how to build it. -.. code-block:: python - :caption: ``setup.py`` +.. code-block:: toml + :caption: ``pyproject.toml`` - from setuptools import find_packages, setup + [project] + name = "flaskr" + version = "1.0.0" + dependencies = [ + "flask", + ] - setup( - name='flaskr', - version='1.0.0', - packages=find_packages(), - include_package_data=True, - zip_safe=False, - install_requires=[ - 'flask', - ], - ) + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" -``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. +The setuptools build backend needs another file named ``MANIFEST.in`` to tell it about +non-Python files to include. .. code-block:: none :caption: ``MANIFEST.in`` @@ -63,14 +55,15 @@ files, such as the static and templates directories, 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. +This tells the build 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 +See the official `Packaging tutorial `_ and +`detailed guide `_ for more explanation of the files and options used. -.. _official packaging guide: https://packaging.python.org/tutorials/packaging-projects/ +.. _packaging tutorial: https://packaging.python.org/tutorials/packaging-projects/ +.. _packaging guide: https://packaging.python.org/guides/distributing-packages-using-setuptools/ Install the Project @@ -82,10 +75,10 @@ Use ``pip`` to install your project in the virtual environment. $ pip install -e . -This tells pip to find ``setup.py`` in the current directory and install -it in *editable* or *development* mode. Editable mode means that as you -make changes to your local code, you'll only need to re-install if you -change the metadata about the project, such as its dependencies. +This tells pip to find ``pyproject.toml`` in the current directory and install the +project in *editable* or *development* mode. Editable mode means that as you make +changes to your local code, you'll only need to re-install if you change the metadata +about the project, such as its dependencies. You can observe that the project is now installed with ``pip list``. @@ -107,7 +100,7 @@ You can observe that the project is now installed with ``pip list``. wheel 0.30.0 Nothing changes from how you've been running your project so far. -``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs +``--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. diff --git a/docs/tutorial/layout.rst b/docs/tutorial/layout.rst index cb4d74b00d..6f8e59f44d 100644 --- a/docs/tutorial/layout.rst +++ b/docs/tutorial/layout.rst @@ -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,31 @@ 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/ - ├── setup.py + │ ├── conftest.py + │ ├── data.sql + │ ├── test_factory.py + │ ├── test_db.py + │ ├── test_auth.py + │ └── test_blog.py + ├── .venv/ + ├── pyproject.toml └── MANIFEST.in If you're using version control, the following files that are generated @@ -92,7 +92,7 @@ write. For example, with git: .. code-block:: none :caption: ``.gitignore`` - venv/ + .venv/ *.pyc __pycache__/ diff --git a/docs/tutorial/next.rst b/docs/tutorial/next.rst index 07bbc04886..d41e8ef21f 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 :ref:`quickstart` for an overview of what Flask can do, then +out the :doc:`/quickstart` for an overview of what Flask can do, then dive into the docs to keep learning. Flask uses `Jinja`_, `Click`_, `Werkzeug`_, and `ItsDangerous`_ behind the scenes, and they all have their own documentation too. You'll also be interested in -:ref:`extensions` which make tasks like working with the database or +:doc:`/extensions` which make tasks like working with the database or validating form data easier and more powerful. If you want to keep developing your Flaskr project, here are some ideas diff --git a/docs/tutorial/templates.rst b/docs/tutorial/templates.rst index 7baa8ebc79..1a5535cc4d 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: http://jinja.pocoo.org/docs/templates/ +.. _Jinja: https://jinja.palletsprojects.com/templates/ .. _HTML: https://developer.mozilla.org/docs/Web/HTML diff --git a/docs/tutorial/tests.rst b/docs/tutorial/tests.rst index e8b14e4c83..f4744cda27 100644 --- a/docs/tutorial/tests.rst +++ b/docs/tutorial/tests.rst @@ -107,7 +107,7 @@ local development configuration. return app.test_cli_runner() :func:`tempfile.mkstemp` creates and opens a temporary file, returning -the file object and the path to it. The ``DATABASE`` path is +the file descriptor and the path to it. The ``DATABASE`` path is overridden so it points to this temporary path instead of the instance folder. After setting the path, the database tables are created and the test data is inserted. After the test is over, the temporary file is @@ -266,11 +266,11 @@ messages. response = client.post( '/auth/register', data={'username': 'a', 'password': 'a'} ) - assert 'http://localhost/auth/login' == response.headers['Location'] + assert response.headers["Location"] == "/auth/login" 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 -Unicode text, use :meth:`get_data(as_text=True) ` +``data``. Bytes must be compared to bytes. If you want to compare text, +use :meth:`get_data(as_text=True) ` instead. ``pytest.mark.parametrize`` tells Pytest to run the same test function @@ -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'] == 'http://localhost/' + assert response.headers["Location"] == "/" with client: client.get('/') @@ -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'] == 'http://localhost/auth/login' + assert response.headers["Location"] == "/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'] == 'http://localhost/' + assert response.headers["Location"] == "/" with app.app_context(): db = get_db() @@ -490,20 +490,18 @@ 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 -``setup.cfg`` file. +Some extra configuration, which is not required but makes running tests with coverage +less verbose, can be added to the project's ``pyproject.toml`` file. -.. code-block:: none - :caption: ``setup.cfg`` +.. code-block:: toml + :caption: ``pyproject.toml`` - [tool:pytest] - testpaths = tests + [tool.pytest.ini_options] + testpaths = ["tests"] - [coverage:run] - branch = True - source = - flaskr + [tool.coverage.run] + branch = true + source = ["flaskr"] To run the tests, use the ``pytest`` command. It will find and run all the test functions you've written. @@ -514,7 +512,7 @@ the test functions you've written. ========================= test session starts ========================== platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0 - rootdir: /home/user/Projects/flask-tutorial, inifile: setup.cfg + rootdir: /home/user/Projects/flask-tutorial collected 23 items tests/test_auth.py ........ [ 34%] diff --git a/docs/tutorial/views.rst b/docs/tutorial/views.rst index 86689111b7..7092dbc28f 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: - db.execute( - 'INSERT INTO user (username, password) VALUES (?, ?)', - (username, generate_password_hash(password)) - ) - db.commit() - return redirect(url_for('auth.login')) + try: + db.execute( + "INSERT INTO user (username, password) VALUES (?, ?)", + (username, generate_password_hash(password)), + ) + db.commit() + except db.IntegrityError: + error = f"User {username} is already registered." + else: + return redirect(url_for("auth.login")) flash(error) @@ -125,26 +125,25 @@ 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*. +#. If validation succeeds, insert the new user data into the database. - :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. + - :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*. -#. If validation succeeds, insert the new user data into the database. - For security, passwords should never be stored in the database - directly. Instead, - :func:`~werkzeug.security.generate_password_hash` is used to - securely hash the password, and that hash is stored. Since this - query modifies data, :meth:`db.commit() ` - needs to be called afterwards to save the changes. + - For security, passwords should never be stored in the database + directly. Instead, + :func:`~werkzeug.security.generate_password_hash` is used to + securely hash the password, and that hash is stored. Since this + query modifies data, + :meth:`db.commit() ` needs to be + called afterwards to save the changes. + + - An :exc:`sqlite3.IntegrityError` will occur if the username + already exists, which should be shown to the user as another + validation error. #. After storing the user, they are redirected to the login page. :func:`url_for` generates the URL for the login view based on its @@ -200,6 +199,11 @@ 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. diff --git a/docs/unicode.rst b/docs/unicode.rst deleted file mode 100644 index 6e5612d241..0000000000 --- a/docs/unicode.rst +++ /dev/null @@ -1,107 +0,0 @@ -Unicode in Flask -================ - -Flask, like Jinja2 and Werkzeug, is totally Unicode based when it comes to -text. Not only these libraries, also the majority of web related Python -libraries that deal with text. If you don't know Unicode so far, you -should probably read `The Absolute Minimum Every Software Developer -Absolutely, Positively Must Know About Unicode and Character Sets -`_. -This part of the documentation just tries to cover the very basics so -that you have a pleasant experience with Unicode related things. - -Automatic Conversion --------------------- - -Flask has a few assumptions about your application (which you can change -of course) that give you basic and painless Unicode support: - -- the encoding for text on your website is UTF-8 -- internally you will always use Unicode exclusively for text except - for literal strings with only ASCII character points. -- encoding and decoding happens whenever you are talking over a protocol - that requires bytes to be transmitted. - -So what does this mean to you? - -HTTP is based on bytes. Not only the protocol, also the system used to -address documents on servers (so called URIs or URLs). However HTML which -is usually transmitted on top of HTTP supports a large variety of -character sets and which ones are used, are transmitted in an HTTP header. -To not make this too complex Flask just assumes that if you are sending -Unicode out you want it to be UTF-8 encoded. Flask will do the encoding -and setting of the appropriate headers for you. - -The same is true if you are talking to databases with the help of -SQLAlchemy or a similar ORM system. Some databases have a protocol that -already transmits Unicode and if they do not, SQLAlchemy or your other ORM -should take care of that. - -The Golden Rule ---------------- - -So the rule of thumb: if you are not dealing with binary data, work with -Unicode. What does working with Unicode in Python 2.x mean? - -- as long as you are using ASCII code points only (basically numbers, - some special characters of Latin letters without umlauts or anything - fancy) you can use regular string literals (``'Hello World'``). -- if you need anything else than ASCII in a string you have to mark - this string as Unicode string by prefixing it with a lowercase `u`. - (like ``u'Hänsel und Gretel'``) -- if you are using non-Unicode characters in your Python files you have - to tell Python which encoding your file uses. Again, I recommend - UTF-8 for this purpose. To tell the interpreter your encoding you can - put the ``# -*- coding: utf-8 -*-`` into the first or second line of - your Python source file. -- Jinja is configured to decode the template files from UTF-8. So make - sure to tell your editor to save the file as UTF-8 there as well. - -Encoding and Decoding Yourself ------------------------------- - -If you are talking with a filesystem or something that is not really based -on Unicode you will have to ensure that you decode properly when working -with Unicode interface. So for example if you want to load a file on the -filesystem and embed it into a Jinja2 template you will have to decode it -from the encoding of that file. Here the old problem that text files do -not specify their encoding comes into play. So do yourself a favour and -limit yourself to UTF-8 for text files as well. - -Anyways. To load such a file with Unicode you can use the built-in -:meth:`str.decode` method:: - - def read_file(filename, charset='utf-8'): - with open(filename, 'r') as f: - return f.read().decode(charset) - -To go from Unicode into a specific charset such as UTF-8 you can use the -:meth:`unicode.encode` method:: - - def write_file(filename, contents, charset='utf-8'): - with open(filename, 'w') as f: - f.write(contents.encode(charset)) - -Configuring Editors -------------------- - -Most editors save as UTF-8 by default nowadays but in case your editor is -not configured to do this you have to change it. Here some common ways to -set your editor to store as UTF-8: - -- Vim: put ``set enc=utf-8`` to your ``.vimrc`` file. - -- Emacs: either use an encoding cookie or put this into your ``.emacs`` - file:: - - (prefer-coding-system 'utf-8) - (setq default-buffer-file-coding-system 'utf-8) - -- Notepad++: - - 1. Go to *Settings -> Preferences ...* - 2. Select the "New Document/Default Directory" tab - 3. Select "UTF-8 without BOM" as encoding - - It is also recommended to use the Unix newline format, you can select - it in the same panel but this is not a requirement. diff --git a/docs/upgrading.rst b/docs/upgrading.rst deleted file mode 100644 index 805bf4ed45..0000000000 --- a/docs/upgrading.rst +++ /dev/null @@ -1,472 +0,0 @@ -Upgrading to Newer Releases -=========================== - -Flask itself is changing like any software is changing over time. Most of -the changes are the nice kind, the kind where you don't have to change -anything in your code to profit from a new release. - -However every once in a while there are changes that do require some -changes in your code or there are changes that make it possible for you to -improve your own code quality by taking advantage of new features in -Flask. - -This section of the documentation enumerates all the changes in Flask from -release to release and how you can change your code to have a painless -updating experience. - -Use the :command:`pip` command to upgrade your existing Flask installation by -providing the ``--upgrade`` parameter:: - - $ pip install --upgrade Flask - -.. _upgrading-to-012: - -Version 0.12 ------------- - -Changes to send_file -```````````````````` - -The ``filename`` is no longer automatically inferred from file-like objects. -This means that the following code will no longer automatically have -``X-Sendfile`` support, etag generation or MIME-type guessing:: - - response = send_file(open('/path/to/file.txt')) - -Any of the following is functionally equivalent:: - - fname = '/path/to/file.txt' - - # Just pass the filepath directly - response = send_file(fname) - - # Set the MIME-type and ETag explicitly - response = send_file(open(fname), mimetype='text/plain') - response.set_etag(...) - - # Set `attachment_filename` for MIME-type guessing - # ETag still needs to be manually set - response = send_file(open(fname), attachment_filename=fname) - response.set_etag(...) - -The reason for this is that some file-like objects have 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 68e8824154..f221027067 100644 --- a/docs/views.rst +++ b/docs/views.rst @@ -1,237 +1,324 @@ -.. _views: +Class-based Views +================= -Pluggable Views -=============== +.. currentmodule:: flask.views -.. versionadded:: 0.7 +This page introduces using the :class:`View` and :class:`MethodView` +classes to write class-based views. -Flask 0.7 introduces pluggable views inspired by the generic views from -Django which are based on classes instead of functions. The main -intention is that you can replace parts of the implementations and this -way have customizable pluggable views. +A class-based view is a class that acts as a view function. Because it +is a class, different instances of the class can be created with +different arguments, to change the behavior of the view. This is also +known as generic, reusable, or pluggable views. -Basic Principle ---------------- +An example of where this is useful is defining a class that creates an +API based on the database model it is initialized with. + +For more complex API behavior and customization, look into the various +API extensions for Flask. + + +Basic Reusable View +------------------- -Consider you have a function that loads a list of objects from the -database and renders into a template:: +Let's walk through an example converting a view function to a view +class. We start with a view function that queries a list of users then +renders a template to show the list. - @app.route('/users/') - def show_users(page): +.. code-block:: python + + @app.route("/users/") + def user_list(): users = User.query.all() - return render_template('users.html', users=users) + return render_template("users.html", users=users) -This is simple and flexible, but if you want to provide this view in a -generic fashion that can be adapted to other models and templates as well -you might want more flexibility. This is where pluggable class-based -views come into place. As the first step to convert this into a class -based view you would do this:: +This works for the user model, but let's say you also had more models +that needed list pages. You'd need to write another view function for +each model, even though the only thing that would change is the model +and template name. +Instead, you can write a :class:`View` subclass that will query a model +and render a template. As the first step, we'll convert the view to a +class without any customization. - from flask.views import View +.. code-block:: python - class ShowUsers(View): + from flask.views import View + class UserList(View): def dispatch_request(self): users = User.query.all() - return render_template('users.html', objects=users) + return render_template("users.html", objects=users) - app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users')) + app.add_url_rule("/users/", view_func=UserList.as_view("user_list")) -As you can see what you have to do is to create a subclass of -:class:`flask.views.View` and implement -:meth:`~flask.views.View.dispatch_request`. Then we have to convert that -class into an actual view function by using the -:meth:`~flask.views.View.as_view` class method. The string you pass to -that function is the name of the endpoint that view will then have. But -this by itself is not helpful, so let's refactor the code a bit:: +The :meth:`View.dispatch_request` method is the equivalent of the view +function. Calling :meth:`View.as_view` method will create a view +function that can be registered on the app with its +:meth:`~flask.Flask.add_url_rule` method. The first argument to +``as_view`` is the name to use to refer to the view with +:func:`~flask.url_for`. +.. note:: - from flask.views import View + You can't decorate the class with ``@app.route()`` the way you'd + do with a basic view function. - class ListView(View): +Next, we need to be able to register the same view class for different +models and templates, to make it more useful than the original function. +The class will take two arguments, the model and template, and store +them on ``self``. Then ``dispatch_request`` can reference these instead +of hard-coded values. - def get_template_name(self): - raise NotImplementedError() +.. code-block:: python - def render_template(self, context): - return render_template(self.get_template_name(), **context) + class ListView(View): + def __init__(self, model, template): + self.model = model + self.template = template def dispatch_request(self): - context = {'objects': self.get_objects()} - return self.render_template(context) + items = self.model.query.all() + return render_template(self.template, items=items) + +Remember, we create the view function with ``View.as_view()`` instead of +creating the class directly. Any extra arguments passed to ``as_view`` +are then passed when creating the class. Now we can register the same +view to handle multiple models. + +.. code-block:: python + + app.add_url_rule( + "/users/", + view_func=ListView.as_view("user_list", User, "users.html"), + ) + app.add_url_rule( + "/stories/", + view_func=ListView.as_view("story_list", Story, "stories.html"), + ) - class UserView(ListView): - def get_template_name(self): - return 'users.html' +URL Variables +------------- - def get_objects(self): - return User.query.all() +Any variables captured by the URL are passed as keyword arguments to the +``dispatch_request`` method, as they would be for a regular view +function. + +.. code-block:: python + + class DetailView(View): + def __init__(self, model): + self.model = model + self.template = f"{model.__name__.lower()}/detail.html" + + def dispatch_request(self, id) + item = self.model.query.get_or_404(id) + return render_template(self.template, item=item) + + app.add_url_rule( + "/users/", + view_func=DetailView.as_view("user_detail", User) + ) + + +View Lifetime and ``self`` +-------------------------- + +By default, a new instance of the view class is created every time a +request is handled. This means that it is safe to write other data to +``self`` during the request, since the next request will not see it, +unlike other forms of global state. + +However, if your view class needs to do a lot of complex initialization, +doing it for every request is unnecessary and can be inefficient. To +avoid this, set :attr:`View.init_every_request` to ``False``, which will +only create one instance of the class and use it for every request. In +this case, writing to ``self`` is not safe. If you need to store data +during the request, use :data:`~flask.g` instead. + +In the ``ListView`` example, nothing writes to ``self`` during the +request, so it is more efficient to create a single instance. + +.. code-block:: python + + class ListView(View): + init_every_request = False -This of course is not that helpful for such a small example, but it's good -enough to explain the basic principle. When you have a class-based view -the question comes up what ``self`` points to. The way this works is that -whenever the request is dispatched a new instance of the class is created -and the :meth:`~flask.views.View.dispatch_request` method is called with -the parameters from the URL rule. The class itself is instantiated with -the parameters passed to the :meth:`~flask.views.View.as_view` function. -For instance you can write a class like this:: + def __init__(self, model, template): + self.model = model + self.template = template - class RenderTemplateView(View): - def __init__(self, template_name): - self.template_name = template_name def dispatch_request(self): - return render_template(self.template_name) + items = self.model.query.all() + return render_template(self.template, items=items) -And then you can register it like this:: +Different instances will still be created each for each ``as_view`` +call, but not for each request to those views. + + +View Decorators +--------------- + +The view class itself is not the view function. View decorators need to +be applied to the view function returned by ``as_view``, not the class +itself. Set :attr:`View.decorators` to a list of decorators to apply. + +.. code-block:: python + + class UserList(View): + decorators = [cache(minutes=2), login_required] + + app.add_url_rule('/users/', view_func=UserList.as_view()) + +If you didn't set ``decorators``, you could apply them manually instead. +This is equivalent to: + +.. code-block:: python + + view = UserList.as_view("users_list") + view = cache(minutes=2)(view) + view = login_required(view) + app.add_url_rule('/users/', view_func=view) + +Keep in mind that order matters. If you're used to ``@decorator`` style, +this is equivalent to: + +.. code-block:: python + + @app.route("/users/") + @login_required + @cache(minutes=2) + def user_list(): + ... - app.add_url_rule('/about', view_func=RenderTemplateView.as_view( - 'about_page', template_name='about.html')) Method Hints ------------ -Pluggable views are attached to the application like a regular function by -either using :func:`~flask.Flask.route` or better -:meth:`~flask.Flask.add_url_rule`. That however also means that you would -have to provide the names of the HTTP methods the view supports when you -attach this. In order to move that information to the class you can -provide a :attr:`~flask.views.View.methods` attribute that has this -information:: +A common pattern is to register a view with ``methods=["GET", "POST"]``, +then check ``request.method == "POST"`` to decide what to do. Setting +:attr:`View.methods` is equivalent to passing the list of methods to +``add_url_rule`` or ``route``. + +.. code-block:: python class MyView(View): - methods = ['GET', 'POST'] + methods = ["GET", "POST"] def dispatch_request(self): - if request.method == 'POST': + if request.method == "POST": ... ... - app.add_url_rule('/myview', view_func=MyView.as_view('myview')) - -Method Based Dispatching ------------------------- + app.add_url_rule('/my-view', view_func=MyView.as_view('my-view')) -For RESTful APIs it's especially helpful to execute a different function -for each HTTP method. With the :class:`flask.views.MethodView` you can -easily do that. Each HTTP method maps to a function with the same name -(just in lowercase):: +This is equivalent to the following, except further subclasses can +inherit or change the methods. - from flask.views import MethodView +.. code-block:: python - class UserAPI(MethodView): + app.add_url_rule( + "/my-view", + view_func=MyView.as_view("my-view"), + methods=["GET", "POST"], + ) - def get(self): - users = User.query.all() - ... - def post(self): - user = User.from_form_data(request.form) - ... +Method Dispatching and APIs +--------------------------- - app.add_url_rule('/users/', view_func=UserAPI.as_view('users')) +For APIs it can be helpful to use a different function for each HTTP +method. :class:`MethodView` extends the basic :class:`View` to dispatch +to different methods of the class based on the request method. Each HTTP +method maps to a method of the class with the same (lowercase) name. -That way you also don't have to provide the -:attr:`~flask.views.View.methods` attribute. It's automatically set based -on the methods defined in the class. +:class:`MethodView` automatically sets :attr:`View.methods` based on the +methods defined by the class. It even knows how to handle subclasses +that override or define other methods. -Decorating Views ----------------- +We can make a generic ``ItemAPI`` class that provides get (detail), +patch (edit), and delete methods for a given model. A ``GroupAPI`` can +provide get (list) and post (create) methods. -Since the view class itself is not the view function that is added to the -routing system it does not make much sense to decorate the class itself. -Instead you either have to decorate the return value of -:meth:`~flask.views.View.as_view` by hand:: +.. code-block:: python - def user_required(f): - """Checks whether user is logged in or raises error 401.""" - def decorator(*args, **kwargs): - if not g.user: - abort(401) - return f(*args, **kwargs) - return decorator + from flask.views import MethodView - view = user_required(UserAPI.as_view('users')) - app.add_url_rule('/users/', view_func=view) + class ItemAPI(MethodView): + init_every_request = False -Starting with Flask 0.8 there is also an alternative way where you can -specify a list of decorators to apply in the class declaration:: + def __init__(self, model): + self.model = model + self.validator = generate_validator(model) - class UserAPI(MethodView): - decorators = [user_required] + def _get_item(self, id): + return self.model.query.get_or_404(id) -Due to the implicit self from the caller's perspective you cannot use -regular view decorators on the individual methods of the view however, -keep this in mind. + def get(self, id): + item = self._get_item(id) + return jsonify(item.to_json()) -Method Views for APIs ---------------------- + def patch(self, id): + item = self._get_item(id) + errors = self.validator.validate(item, request.json) -Web APIs are often working very closely with HTTP verbs so it makes a lot -of sense to implement such an API based on the -:class:`~flask.views.MethodView`. That said, you will notice that the API -will require different URL rules that go to the same method view most of -the time. For instance consider that you are exposing a user object on -the web: + if errors: + return jsonify(errors), 400 -=============== =============== ====================================== -URL Method Description ---------------- --------------- -------------------------------------- -``/users/`` ``GET`` Gives a list of all users -``/users/`` ``POST`` Creates a new user -``/users/`` ``GET`` Shows a single user -``/users/`` ``PUT`` Updates a single user -``/users/`` ``DELETE`` Deletes a single user -=============== =============== ====================================== + item.update_from_json(request.json) + db.session.commit() + return jsonify(item.to_json()) -So how would you go about doing that with the -:class:`~flask.views.MethodView`? The trick is to take advantage of the -fact that you can provide multiple rules to the same view. + def delete(self, id): + item = self._get_item(id) + db.session.delete(item) + db.session.commit() + return "", 204 -Let's assume for the moment the view would look like this:: + class GroupAPI(MethodView): + init_every_request = False - class UserAPI(MethodView): + def __init__(self, model): + self.model = model + self.validator = generate_validator(model, create=True) - def get(self, user_id): - if user_id is None: - # return a list of users - pass - else: - # expose a single user - pass + def get(self): + items = self.model.query.all() + return jsonify([item.to_json() for item in items]) def post(self): - # create a new user - pass - - def delete(self, user_id): - # delete a single user - pass - - def put(self, user_id): - # update a single user - pass - -So how do we hook this up with the routing system? By adding two rules -and explicitly mentioning the methods for each:: - - user_view = UserAPI.as_view('user_api') - app.add_url_rule('/users/', defaults={'user_id': None}, - view_func=user_view, methods=['GET',]) - app.add_url_rule('/users/', view_func=user_view, methods=['POST',]) - app.add_url_rule('/users/', view_func=user_view, - methods=['GET', 'PUT', 'DELETE']) - -If you have a lot of APIs that look similar you can refactor that -registration code:: - - def register_api(view, endpoint, url, pk='id', pk_type='int'): - view_func = view.as_view(endpoint) - app.add_url_rule(url, defaults={pk: None}, - view_func=view_func, methods=['GET',]) - app.add_url_rule(url, view_func=view_func, methods=['POST',]) - app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func, - methods=['GET', 'PUT', 'DELETE']) - - register_api(UserAPI, 'user_api', '/users/', pk='user_id') + errors = self.validator.validate(request.json) + + if errors: + return jsonify(errors), 400 + + db.session.add(self.model.from_json(request.json)) + db.session.commit() + return jsonify(item.to_json()) + + def register_api(app, model, name): + item = ItemAPI.as_view(f"{name}-item", model) + group = GroupAPI.as_view(f"{name}-group", model) + app.add_url_rule(f"/{name}/", view_func=item) + app.add_url_rule(f"/{name}/", view_func=group) + + register_api(app, User, "users") + register_api(app, Story, "stories") + +This produces the following views, a standard REST API! + +================= ========== =================== +URL Method Description +----------------- ---------- ------------------- +``/users/`` ``GET`` List all users +``/users/`` ``POST`` Create a new user +``/users/`` ``GET`` Show a single user +``/users/`` ``PATCH`` Update a user +``/users/`` ``DELETE`` Delete a user +``/stories/`` ``GET`` List all stories +``/stories/`` ``POST`` Create a new story +``/stories/`` ``GET`` Show a single story +``/stories/`` ``PATCH`` Update a story +``/stories/`` ``DELETE`` Delete a story +================= ========== =================== diff --git a/examples/celery/README.md b/examples/celery/README.md new file mode 100644 index 0000000000..038eb51eb6 --- /dev/null +++ b/examples/celery/README.md @@ -0,0 +1,27 @@ +Background Tasks with Celery +============================ + +This example shows how to configure Celery with Flask, how to set up an API for +submitting tasks and polling results, and how to use that API with JavaScript. See +[Flask's documentation about Celery](https://flask.palletsprojects.com/patterns/celery/). + +From this directory, create a virtualenv and install the application into it. Then run a +Celery worker. + +```shell +$ python3 -m venv .venv +$ . ./.venv/bin/activate +$ pip install -r requirements.txt && pip install -e . +$ celery -A make_celery worker --loglevel INFO +``` + +In a separate terminal, activate the virtualenv and run the Flask development server. + +```shell +$ . ./.venv/bin/activate +$ flask -A task_app run --debug +``` + +Go to http://localhost:5000/ and use the forms to submit tasks. You can see the polling +requests in the browser dev tools and the Flask logs. You can see the tasks submitting +and completing in the Celery logs. diff --git a/examples/celery/make_celery.py b/examples/celery/make_celery.py new file mode 100644 index 0000000000..f7d138e642 --- /dev/null +++ b/examples/celery/make_celery.py @@ -0,0 +1,4 @@ +from task_app import create_app + +flask_app = create_app() +celery_app = flask_app.extensions["celery"] diff --git a/examples/celery/pyproject.toml b/examples/celery/pyproject.toml new file mode 100644 index 0000000000..e480aebc27 --- /dev/null +++ b/examples/celery/pyproject.toml @@ -0,0 +1,11 @@ +[project] +name = "flask-example-celery" +version = "1.0.0" +description = "Example Flask application with Celery background tasks." +readme = "README.md" +requires-python = ">=3.8" +dependencies = ["flask>=2.2.2", "celery[redis]>=5.2.7"] + +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" diff --git a/examples/celery/requirements.txt b/examples/celery/requirements.txt new file mode 100644 index 0000000000..ce9ae72c9a --- /dev/null +++ b/examples/celery/requirements.txt @@ -0,0 +1,56 @@ +# +# This file is autogenerated by pip-compile with Python 3.10 +# 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 +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.2.3 + # 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.37 + # via click-repl +pytz==2022.7.1 + # via celery +redis==4.5.1 + # 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.2.3 + # via flask diff --git a/examples/celery/src/task_app/__init__.py b/examples/celery/src/task_app/__init__.py new file mode 100644 index 0000000000..dafff8aad8 --- /dev/null +++ b/examples/celery/src/task_app/__init__.py @@ -0,0 +1,39 @@ +from celery import Celery +from celery import Task +from flask import Flask +from flask import render_template + + +def create_app() -> Flask: + app = Flask(__name__) + app.config.from_mapping( + CELERY=dict( + broker_url="redis://localhost", + result_backend="redis://localhost", + task_ignore_result=True, + ), + ) + app.config.from_prefixed_env() + celery_init_app(app) + + @app.route("/") + def index() -> str: + return render_template("index.html") + + from . import views + + app.register_blueprint(views.bp) + return app + + +def celery_init_app(app: Flask) -> Celery: + class FlaskTask(Task): + def __call__(self, *args: object, **kwargs: object) -> object: + with app.app_context(): + return self.run(*args, **kwargs) + + celery_app = Celery(app.name, task_cls=FlaskTask) + celery_app.config_from_object(app.config["CELERY"]) + celery_app.set_default() + app.extensions["celery"] = celery_app + return celery_app diff --git a/examples/celery/src/task_app/tasks.py b/examples/celery/src/task_app/tasks.py new file mode 100644 index 0000000000..b6b3595d22 --- /dev/null +++ b/examples/celery/src/task_app/tasks.py @@ -0,0 +1,23 @@ +import time + +from celery import shared_task +from celery import Task + + +@shared_task(ignore_result=False) +def add(a: int, b: int) -> int: + return a + b + + +@shared_task() +def block() -> None: + time.sleep(5) + + +@shared_task(bind=True, ignore_result=False) +def process(self: Task, total: int) -> object: + for i in range(total): + self.update_state(state="PROGRESS", meta={"current": i + 1, "total": total}) + time.sleep(1) + + return {"current": total, "total": total} diff --git a/examples/celery/src/task_app/templates/index.html b/examples/celery/src/task_app/templates/index.html new file mode 100644 index 0000000000..4e1145cb8f --- /dev/null +++ b/examples/celery/src/task_app/templates/index.html @@ -0,0 +1,108 @@ + + + + + Celery Example + + +

Celery Example

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

Add

+

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

+
+
+ +
+

Result:

+ +
+

Block

+

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

+ +
+

+ +
+

Process

+

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

+
+ +
+

+ + + + diff --git a/examples/celery/src/task_app/views.py b/examples/celery/src/task_app/views.py new file mode 100644 index 0000000000..99cf92dc20 --- /dev/null +++ b/examples/celery/src/task_app/views.py @@ -0,0 +1,38 @@ +from celery.result import AsyncResult +from flask import Blueprint +from flask import request + +from . import tasks + +bp = Blueprint("tasks", __name__, url_prefix="/tasks") + + +@bp.get("/result/") +def result(id: str) -> dict[str, object]: + result = AsyncResult(id) + ready = result.ready() + return { + "ready": ready, + "successful": result.successful() if ready else None, + "value": result.get() if ready else result.result, + } + + +@bp.post("/add") +def add() -> dict[str, object]: + a = request.form.get("a", type=int) + b = request.form.get("b", type=int) + result = tasks.add.delay(a, b) + return {"result_id": result.id} + + +@bp.post("/block") +def block() -> dict[str, object]: + result = tasks.block.delay() + return {"result_id": result.id} + + +@bp.post("/process") +def process() -> dict[str, object]: + result = tasks.process.delay(total=request.form.get("total", type=int)) + return {"result_id": result.id} diff --git a/examples/javascript/.gitignore b/examples/javascript/.gitignore index 85a35845ad..a306afbc08 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 deleted file mode 100644 index 8f9252f452..0000000000 --- a/examples/javascript/LICENSE +++ /dev/null @@ -1,31 +0,0 @@ -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.rst b/examples/javascript/LICENSE.rst new file mode 100644 index 0000000000..9d227a0cc4 --- /dev/null +++ b/examples/javascript/LICENSE.rst @@ -0,0 +1,28 @@ +Copyright 2010 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/examples/javascript/MANIFEST.in b/examples/javascript/MANIFEST.in index 0ba3d5b8cf..c730a34e1a 100644 --- a/examples/javascript/MANIFEST.in +++ b/examples/javascript/MANIFEST.in @@ -1,4 +1,4 @@ -include LICENSE +include LICENSE.rst graft js_example/templates graft tests global-exclude *.pyc diff --git a/examples/javascript/README.rst b/examples/javascript/README.rst index b284d3c93e..697bb21760 100644 --- a/examples/javascript/README.rst +++ b/examples/javascript/README.rst @@ -3,38 +3,37 @@ 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 |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 +page. Demonstrates using |fetch|_, |XMLHttpRequest|_, and +|jQuery.ajax|_. See the `Flask docs`_ about JavaScript and Ajax. .. |fetch| replace:: ``fetch`` .. _fetch: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch +.. |XMLHttpRequest| replace:: ``XMLHttpRequest`` +.. _XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest + .. |jQuery.ajax| replace:: ``jQuery.ajax`` .. _jQuery.ajax: https://api.jquery.com/jQuery.ajax/ -.. _Flask docs: http://flask.pocoo.org/docs/patterns/jquery/ +.. _Flask docs: https://flask.palletsprojects.com/patterns/jquery/ Install ------- -:: +.. code-block:: text - $ python3 -m venv venv - $ . venv/bin/activate + $ python3 -m venv .venv + $ . .venv/bin/activate $ pip install -e . Run --- -:: +.. code-block:: text - $ export FLASK_APP=js_example - $ flask run + $ flask --app js_example run Open http://127.0.0.1:5000 in a browser. @@ -42,7 +41,7 @@ Open http://127.0.0.1:5000 in a browser. Test ---- -:: +.. code-block:: text $ pip install -e '.[test]' $ coverage run -m pytest diff --git a/examples/javascript/js_example/__init__.py b/examples/javascript/js_example/__init__.py index d90fc4d4c4..0ec3ca215a 100644 --- a/examples/javascript/js_example/__init__.py +++ b/examples/javascript/js_example/__init__.py @@ -2,4 +2,4 @@ app = Flask(__name__) -from js_example import views +from js_example import views # noqa: E402, F401 diff --git a/examples/javascript/js_example/templates/base.html b/examples/javascript/js_example/templates/base.html index 50ce0e9c4b..a4d35bd7d7 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 780ecec505..e2944b8575 100644 --- a/examples/javascript/js_example/templates/fetch.html +++ b/examples/javascript/js_example/templates/fetch.html @@ -2,14 +2,11 @@ {% block intro %} fetch - is the new plain JavaScript way to make requests. It's - supported in all modern browsers except IE, which requires a - polyfill. + is the modern plain JavaScript way to make requests. It's + supported in all modern browsers. {% 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('{{ "