diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 11bb6d4b0a..0000000000 --- a/.appveyor.yml +++ /dev/null @@ -1,26 +0,0 @@ -environment: - global: - TOXENV: py,codecov - - matrix: - - PYTHON: C:\Python36-x64 - - PYTHON: C:\Python27-x64 - -init: - - SET PATH=%PYTHON%;%PATH% - -install: - - python -m pip install -U tox - -build: false - -test_script: - - python -m tox - -branches: - only: - - master - - /^.*-maintenance$/ - -cache: - - '%LOCALAPPDATA%\pip\Cache' 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/.gitattributes b/.gitattributes deleted file mode 100644 index 6f9ff673b1..0000000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -CHANGES.rst merge=union diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 8b6910fb0e..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 any extra information that may be useful / related to your problem. -Ideally, create an [MCVE](http://stackoverflow.com/help/mcve), which helps us -understand the problem and helps check that it is not caused by something in -your code. - ---- - -### Expected Behavior - -Tell us what should happen. - -```python -Paste a minimal example that causes the problem. -``` - -### Actual Behavior - -Tell us what happens instead. - -```pytb -Paste the full traceback if there was an exception. -``` - -### Environment - -* Python version: -* Flask version: -* Werkzeug version: diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md 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..86e010dffa --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: +- package-ecosystem: pip + directory: "/" + schedule: + interval: monthly + time: "08:00" + open-pull-requests-limit: 99 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..7128f382b9 --- /dev/null +++ b/.github/workflows/lock.yaml @@ -0,0 +1,15 @@ +name: 'Lock threads' + +on: + schedule: + - cron: '0 0 * * *' + +jobs: + lock: + runs-on: ubuntu-latest + steps: + - uses: dessant/lock-threads@v2 + with: + github-token: ${{ github.token }} + issue-lock-inactive-days: 14 + pr-lock-inactive-days: 14 diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 0000000000..e656dcf840 --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,54 @@ +name: Tests +on: + push: + branches: + - master + - '*.x' + paths-ignore: + - 'docs/**' + - '*.md' + - '*.rst' + pull_request: + branches: + - master + - '*.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.9', os: ubuntu-latest, tox: py39} + - {name: Windows, python: '3.9', os: windows-latest, tox: py39} + - {name: Mac, python: '3.9', os: macos-latest, tox: py39} + - {name: '3.8', python: '3.8', os: ubuntu-latest, tox: py38} + - {name: '3.7', python: '3.7', os: ubuntu-latest, tox: py37} + - {name: '3.6', python: '3.6', os: ubuntu-latest, tox: py36} + - {name: 'PyPy', python: pypy3, os: ubuntu-latest, tox: pypy3} + - {name: Typing, python: '3.9', os: ubuntu-latest, tox: typing} + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + - name: update pip + run: | + pip install -U wheel + pip install -U setuptools + python -m pip install -U pip + - name: get pip cache dir + id: pip-cache + run: echo "::set-output name=dir::$(pip cache dir)" + - name: cache pip + uses: actions/cache@v2 + with: + path: ${{ steps.pip-cache.outputs.dir }} + key: pip|${{ runner.os }}|${{ matrix.python }}|${{ hashFiles('setup.py') }}|${{ hashFiles('requirements/*.txt') }} + - run: pip install tox + - run: tox -e ${{ matrix.tox }} diff --git a/.gitignore b/.gitignore index 8a32355538..71dafa39b6 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ _mailinglist .pytest_cache/ .idea/ docs/_build/ +.vscode # Coverage reports htmlcov/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000..d75f3c3102 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,32 @@ +ci: + autoupdate_schedule: monthly +repos: + - repo: https://github.com/asottile/pyupgrade + rev: v2.15.0 + hooks: + - id: pyupgrade + args: ["--py36-plus"] + - repo: https://github.com/asottile/reorder_python_imports + rev: v2.5.0 + hooks: + - id: reorder-python-imports + name: Reorder Python imports (src, tests) + files: "^(?!examples/)" + args: ["--application-directories", "src"] + - repo: https://github.com/psf/black + rev: 21.5b1 + hooks: + - id: black + - repo: https://github.com/PyCQA/flake8 + rev: 3.9.2 + hooks: + - id: flake8 + additional_dependencies: + - flake8-bugbear + - flake8-implicit-str-concat + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.4.0 + hooks: + - 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..0c363636f6 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,9 @@ +version: 2 +python: + install: + - requirements: requirements/docs.txt + - method: pip + path: . +sphinx: + builder: dirhtml + fail_on_warning: true diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b3ba1e1951..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,58 +0,0 @@ -os: linux -sudo: false -language: python - -matrix: - include: - - python: 3.6 - env: TOXENV=py,simplejson,devel,lowest,codecov - - python: 3.6 - env: TOXENV=docs-html - - python: 3.5 - env: TOXENV=py,codecov - - python: 3.4 - env: TOXENV=py,codecov - - python: 2.7 - env: TOXENV=py,simplejson,devel,lowest,codecov - - python: pypy3 - env: TOXENV=py,codecov - - python: nightly - env: TOXENV=py - - os: osx - language: generic - env: TOXENV=py3,py2,codecov - cache: - pip: false - directories: - - $HOME/Library/Caches/Homebrew - - $HOME/Library/Caches/pip - allow_failures: - - python: pypy3 - - python: nightly - - os: osx - fast_finish: true - -before_install: - - | - if [[ $TRAVIS_OS_NAME == 'osx' ]]; then - brew upgrade python - brew install python@2; - export PATH="/usr/local/opt/python/libexec/bin:${PATH}" - fi - -install: - - pip install tox - -script: - - tox - -cache: - - pip - -branches: - only: - - master - - /^.*-maintenance$/ - -notifications: - email: false diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 220046ed37..0000000000 --- a/AUTHORS +++ /dev/null @@ -1,12 +0,0 @@ -Flask is developed and maintained by the Pallets team and community -contributors. It was created by Armin Ronacher. The core maintainers -are: - -- David Lord (davidism) -- Adrian Mönnich (ThiefMaster) -- Armin Ronacher (mitsuhiko) -- Marcus Unterwaditzer (untitaker) - -A full list of contributors is available from git with:: - - git shortlog -sne diff --git a/CHANGES.rst b/CHANGES.rst index 1902cc85d0..0001bfe35b 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,166 +1,364 @@ .. currentmodule:: flask -Flask Changelog -=============== +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 :meth:`sessions.SessionInterface.get_cookie_name` to allow + setting the session cookie name dynamically. :pr:`3369` +- Add :meth:`Config.from_file` to load config using arbitrary file + loaders, such as ``toml.load`` or ``json.load``. + :meth:`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` +- :func:`send_file` raises a :exc:`ValueError` when passed an + :mod:`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.2 +------------- +Released 2020-04-03 -Version 1.1 ------------ +- Work around an issue when running the ``flask`` command with an + external debugger on Windows. :issue:`3297` +- The static route will not catch all URLs if the ``Flask`` + ``static_folder`` argument ends with a slash. :issue:`3452` + + +Version 1.1.1 +------------- + +Released 2019-07-08 + +- The ``flask.json_available`` flag was added back for compatibility + with some extensions. It will raise a deprecation warning when used, + and will be removed in version 2.0.0. :issue:`3288` + + +Version 1.1.0 +------------- + +Released 2019-07-04 + +- Bump minimum Werkzeug version to >= 0.15. +- Drop support for Python 3.4. +- Error handlers for ``InternalServerError`` or ``500`` will always be + passed an instance of ``InternalServerError``. If they are invoked + due to an unhandled exception, that original exception is now + available as ``e.original_exception`` rather than being passed + directly to the handler. The same is true if the handler is for the + base ``HTTPException``. This makes error handler behavior more + consistent. :pr:`3266` + + - :meth:`Flask.finalize_request` is called for all unhandled + exceptions even if there is no ``500`` error handler. + +- :attr:`Flask.logger` takes the same name as + :attr:`Flask.name` (the value passed as + ``Flask(import_name)``. This reverts 1.0's behavior of always + logging to ``"flask.app"``, in order to support multiple apps in the + same process. A warning will be shown if old configuration is + detected that needs to be moved. :issue:`2866` +- :meth:`flask.RequestContext.copy` includes the current session + object in the request context copy. This prevents ``session`` + pointing to an out-of-date object. :issue:`2935` +- Using built-in RequestContext, unprintable Unicode characters in + Host header will result in a HTTP 400 response and not HTTP 500 as + previously. :pr:`2994` +- :func:`send_file` supports :class:`~os.PathLike` objects as + described in PEP 0519, to support :mod:`pathlib` in Python 3. + :pr:`3059` +- :func:`send_file` supports :class:`~io.BytesIO` partial content. + :issue:`2957` +- :func:`open_resource` accepts the "rt" file mode. This still does + the same thing as "r". :issue:`3163` +- The :attr:`MethodView.methods` attribute set in a base class is used + by subclasses. :issue:`3138` +- :attr:`Flask.jinja_options` is a ``dict`` instead of an + ``ImmutableDict`` to allow easier configuration. Changes must still + be made before creating the environment. :pr:`3190` +- Flask's ``JSONMixin`` for the request and response wrappers was + moved into Werkzeug. Use Werkzeug's version with Flask-specific + support. This bumps the Werkzeug dependency to >= 0.15. + :issue:`3125` +- The ``flask`` command entry point is simplified to take advantage + of Werkzeug 0.15's better reloader support. This bumps the Werkzeug + dependency to >= 0.15. :issue:`3022` +- Support ``static_url_path`` that ends with a forward slash. + :issue:`3134` +- Support empty ``static_folder`` without requiring setting an empty + ``static_url_path`` as well. :pr:`3124` +- :meth:`jsonify` supports :class:`dataclasses.dataclass` objects. + :pr:`3195` +- Allow customizing the :attr:`Flask.url_map_class` used for routing. + :pr:`3069` +- The development server port can be set to 0, which tells the OS to + pick an available port. :issue:`2926` +- The return value from :meth:`cli.load_dotenv` is more consistent + with the documentation. It will return ``False`` if python-dotenv is + not installed, or if the given path isn't a file. :issue:`2937` +- Signaling support has a stub for the ``connect_via`` method when + the Blinker library is not installed. :pr:`3208` +- Add an ``--extra-files`` option to the ``flask run`` CLI command to + specify extra files that will trigger the reloader on change. + :issue:`2897` +- Allow returning a dictionary from a view function. Similar to how + returning a string will produce a ``text/html`` response, returning + a dict will call ``jsonify`` to produce a ``application/json`` + response. :pr:`3111` +- Blueprints have a ``cli`` Click group like ``app.cli``. CLI commands + registered with a blueprint will be available as a group under the + ``flask`` command. :issue:`1357`. +- When using the test client as a context manager (``with client:``), + all preserved request contexts are popped when the block exits, + ensuring nested contexts are cleaned up correctly. :pr:`3157` +- Show a better error message when the view return type is not + supported. :issue:`3214` +- ``flask.testing.make_test_environ_builder()`` has been deprecated in + favour of a new class ``flask.testing.EnvironBuilder``. :pr:`3232` +- The ``flask run`` command no longer fails if Python is not built + with SSL support. Using the ``--cert`` option will show an + appropriate error message. :issue:`3211` +- URL matching now occurs after the request context is pushed, rather + than when it's created. This allows custom URL converters to access + the app and request contexts, such as to query a database for an id. + :issue:`3088` + + +Version 1.0.4 +------------- + +Released 2019-07-04 -Unreleased +- The key information for ``BadRequestKeyError`` is no longer cleared + outside debug mode, so error handlers can still access it. This + requires upgrading to Werkzeug 0.15.5. :issue:`3249` +- ``send_file`` url quotes the ":" and "/" characters for more + compatible UTF-8 filename support in some browsers. :issue:`3074` +- Fixes for PEP451 import loaders and pytest 5.x. :issue:`3275` +- Show message about dotenv on stderr instead of stdout. :issue:`3285` Version 1.0.3 ------------- -Unreleased +Released 2019-05-17 - :func:`send_file` encodes filenames as ASCII instead of Latin-1 (ISO-8859-1). This fixes compatibility with Gunicorn, which is - stricter about header encodings than PEP 3333. (`#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. (`#2765`_) - -.. _#2766: https://github.com/pallets/flask/issues/2766 -.. _#2765: https://github.com/pallets/flask/pull/2765 + it always being overwritten based on environment variables. + :pr:`2765` +- ``flask --version`` outputs Werkzeug's version and simplifies the + Python version. :pr:`2825` +- :func:`send_file` handles an ``attachment_filename`` that is a + native Python 2 string (bytes) with UTF-8 coded bytes. :issue:`2933` +- A catch-all error handler registered for ``HTTPException`` will not + handle ``RoutingException``, which is used internally during + routing. This fixes the unexpected behavior that had been introduced + in 1.0. :pr:`2986` +- Passing the ``json`` argument to ``app.test_client`` does not + push/pop an extra app context. :issue:`2900` Version 1.0.2 ------------- -Released on May 2nd 2018 +Released 2018-05-02 - Fix more backwards compatibility issues with merging slashes between - a blueprint prefix and route. (`#2748`_) + a blueprint prefix and route. :pr:`2748` - Fix error with ``flask routes`` command when there are no routes. - (`#2751`_) - -.. _#2748: https://github.com/pallets/flask/pull/2748 -.. _#2751: https://github.com/pallets/flask/issues/2751 + :issue:`2751` Version 1.0.1 ------------- -Released on April 29th 2018 +Released 2018-04-29 - Fix registering partials (with no ``__name__``) as view functions. - (`#2730`_) + :pr:`2730` - Don't treat lists returned from view functions the same as tuples. - Only tuples are interpreted as response data. (`#2736`_) + Only tuples are interpreted as response data. :issue:`2736` - Extra slashes between a blueprint's ``url_prefix`` and a route URL are merged. This fixes some backwards compatibility issues with the - change in 1.0. (`#2731`_, `#2742`_) + change in 1.0. :issue:`2731`, :issue:`2742` - Only trap ``BadRequestKeyError`` errors in debug mode, not all ``BadRequest`` errors. This allows ``abort(400)`` to continue - working as expected. (`#2735`_) + working as expected. :issue:`2735` - The ``FLASK_SKIP_DOTENV`` environment variable can be set to ``1`` - to skip automatically loading dotenv files. (`#2722`_) - -.. _#2722: https://github.com/pallets/flask/issues/2722 -.. _#2730: https://github.com/pallets/flask/pull/2730 -.. _#2731: https://github.com/pallets/flask/issues/2731 -.. _#2735: https://github.com/pallets/flask/issues/2735 -.. _#2736: https://github.com/pallets/flask/issues/2736 -.. _#2742: https://github.com/pallets/flask/issues/2742 + to skip automatically loading dotenv files. :issue:`2722` Version 1.0 ----------- -Released on April 26th 2018 +Released 2018-04-26 -- **Python 2.6 and 3.3 are no longer supported.** (`pallets/meta#24`_) +- Python 2.6 and 3.3 are no longer supported. - Bump minimum dependency versions to the latest stable versions: Werkzeug >= 0.14, Jinja >= 2.10, itsdangerous >= 0.24, Click >= 5.1. - (`#2586`_) + :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. (`#2193`_) + 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`. (`#1559`_) + 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. (`#1559`_) + route. :issue:`1559` - :func:`send_file` supports Unicode in ``attachment_filename``. - (`#2223`_) + :pr:`2223` - Pass ``_scheme`` argument from :func:`url_for` to - :meth:`~Flask.handle_url_build_error`. (`#2017`_) + :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. (`#1489`_) + ``OPTIONS`` method. :pr:`1489` - :class:`~views.MethodView` subclasses inherit method handlers from - base classes. (`#1936`_) + base classes. :pr:`1936` - Errors caused while opening the session at the beginning of the - request are handled by the app's error handlers. (`#2254`_) + request are handled by the app's error handlers. :pr:`2254` - Blueprints gained :attr:`~Blueprint.json_encoder` and :attr:`~Blueprint.json_decoder` attributes to override the app's - encoder and decoder. (`#1898`_) + encoder and decoder. :pr:`1898` - :meth:`Flask.make_response` raises ``TypeError`` instead of ``ValueError`` for bad response types. The error messages have been - improved to describe why the type is invalid. (`#2256`_) + improved to describe why the type is invalid. :pr:`2256` - Add ``routes`` CLI command to output routes registered on the - application. (`#2259`_) + application. :pr:`2259` - Show warning when session cookie domain is a bare hostname or an IP address, as these may not behave properly in some browsers, such as - Chrome. (`#2282`_) -- Allow IP address as exact session cookie domain. (`#2282`_) + Chrome. :pr:`2282` +- Allow IP address as exact session cookie domain. :pr:`2282` - ``SESSION_COOKIE_DOMAIN`` is set if it is detected through - ``SERVER_NAME``. (`#2282`_) + ``SERVER_NAME``. :pr:`2282` - Auto-detect zero-argument app factory called ``create_app`` or - ``make_app`` from ``FLASK_APP``. (`#2297`_) + ``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. (`#2319`_) + :class:`~cli.ScriptInfo` object will be passed. :pr:`2319` - ``FLASK_APP`` can be set to an app factory, with arguments if needed, for example ``FLASK_APP=myproject.app:create_app('dev')``. - (`#2326`_) + :pr:`2326` - ``FLASK_APP`` can point to local packages that are not installed in editable mode, although ``pip install -e`` is still preferred. - (`#2414`_) + :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`. (`#2316`_) + :meth:`~Flask.add_url_rule`. :pr:`2316` - Error handling will try handlers registered for ``blueprint, code``, ``app, code``, ``blueprint, exception``, ``app, exception``. - (`#2314`_) + :pr:`2314` - ``Cookie`` is added to the response's ``Vary`` header if the session - is accessed at all during the request (and not deleted). (`#2288`_) + is accessed at all during the request (and not deleted). :pr:`2288` - :meth:`~Flask.test_request_context` accepts ``subdomain`` and ``url_scheme`` arguments for use when building the base URL. - (`#1621`_) + :pr:`1621` - Set :data:`APPLICATION_ROOT` to ``'/'`` by default. This was already the implicit default when it was set to ``None``. - :data:`TRAP_BAD_REQUEST_ERRORS` is enabled by default in debug mode. ``BadRequestKeyError`` has a message with the bad key in debug mode - instead of the generic bad request message. (`#2348`_) + 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. (`#2352`_) + 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. - (`#2354`_) + :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. (`#2358`_) + 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. (`#2358`_) + 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. (`#2362`_) -- Fix incorrect JSON encoding of aware, non-UTC datetimes. (`#2374`_) + 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. (`#2373`_) -- The following old deprecated code was removed. (`#2385`_) + :attr:`~Flask.jinja_env` was already accessed. :pr:`2373` +- The following old deprecated code was removed. :issue:`2385` - ``flask.ext`` - import extensions directly by their name instead of through the ``flask.ext`` namespace. For example, @@ -178,763 +376,725 @@ Released on April 26th 2018 - ``Request.module`` - use :attr:`Request.blueprint` instead. - The :attr:`Request.json` property is no longer deprecated. - (`#1421`_) -- Support passing a :class:`~werkzeug.test.EnvironBuilder` or - ``dict`` to :meth:`test_client.open `. - (`#2412`_) + :issue:`1421` +- Support passing a :class:`~werkzeug.test.EnvironBuilder` or ``dict`` + to :meth:`test_client.open `. :pr:`2412` - The ``flask`` command and :meth:`Flask.run` will load environment variables from ``.env`` and ``.flaskenv`` files if python-dotenv is - installed. (`#2416`_) + 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`. (`#2430`_) + used instead of :data:`PREFERRED_URL_SCHEME`. :pr:`2430` - :attr:`Flask.logger` has been simplified. ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` config was removed. The logger is always named ``flask.app``. The level is only set on first access, it doesn't check :attr:`Flask.debug` each time. Only one format is used, not different ones depending on :attr:`Flask.debug`. No handlers are removed, and a handler is only added if no handlers are - already configured. (`#2436`_) -- Blueprint view function names may not contain dots. (`#2450`_) + 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. (`#2526`_) -- The development server uses threads by default. (`#2529`_) + cases. :issue:`2526` +- The development server uses threads by default. :pr:`2529` - Loading config files with ``silent=True`` will ignore - :data:`~errno.ENOTDIR` errors. (`#2581`_) + :data:`~errno.ENOTDIR` errors. :pr:`2581` - Pass ``--cert`` and ``--key`` options to ``flask run`` to run the - development server over HTTPS. (`#2606`_) + development server over HTTPS. :pr:`2606` - Added :data:`SESSION_COOKIE_SAMESITE` to control the ``SameSite`` - attribute on the session cookie. (`#2607`_) + 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. (`#2636`_) + 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. - (`#2635`_) + :pr:`2635` - A single trailing slash is stripped from the blueprint - ``url_prefix`` when it is registered with the app. (`#2629`_) -- :meth:`Request.get_json` doesn't cache the - result if parsing fails when ``silent`` is true. (`#2651`_) + ``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. (`#2691`_) + Flask will autodetect UTF-8, -16, or -32. :pr:`2691` - Added :data:`MAX_COOKIE_SIZE` and :attr:`Response.max_cookie_size` to control when Werkzeug warns about large cookies that browsers may - ignore. (`#2693`_) + ignore. :pr:`2693` - Updated documentation theme to make docs look better in small - windows. (`#2709`_) + windows. :pr:`2709` - Rewrote the tutorial docs and example project to take a more structured approach to help new users avoid common pitfalls. - (`#2676`_) - -.. _pallets/meta#24: https://github.com/pallets/meta/issues/24 -.. _#1421: https://github.com/pallets/flask/issues/1421 -.. _#1489: https://github.com/pallets/flask/pull/1489 -.. _#1559: https://github.com/pallets/flask/issues/1559 -.. _#1621: https://github.com/pallets/flask/pull/1621 -.. _#1898: https://github.com/pallets/flask/pull/1898 -.. _#1936: https://github.com/pallets/flask/pull/1936 -.. _#2017: https://github.com/pallets/flask/pull/2017 -.. _#2193: https://github.com/pallets/flask/pull/2193 -.. _#2223: https://github.com/pallets/flask/pull/2223 -.. _#2254: https://github.com/pallets/flask/pull/2254 -.. _#2256: https://github.com/pallets/flask/pull/2256 -.. _#2259: https://github.com/pallets/flask/pull/2259 -.. _#2282: https://github.com/pallets/flask/pull/2282 -.. _#2288: https://github.com/pallets/flask/pull/2288 -.. _#2297: https://github.com/pallets/flask/pull/2297 -.. _#2314: https://github.com/pallets/flask/pull/2314 -.. _#2316: https://github.com/pallets/flask/pull/2316 -.. _#2319: https://github.com/pallets/flask/pull/2319 -.. _#2326: https://github.com/pallets/flask/pull/2326 -.. _#2348: https://github.com/pallets/flask/pull/2348 -.. _#2352: https://github.com/pallets/flask/pull/2352 -.. _#2354: https://github.com/pallets/flask/pull/2354 -.. _#2358: https://github.com/pallets/flask/pull/2358 -.. _#2362: https://github.com/pallets/flask/pull/2362 -.. _#2374: https://github.com/pallets/flask/pull/2374 -.. _#2373: https://github.com/pallets/flask/pull/2373 -.. _#2385: https://github.com/pallets/flask/issues/2385 -.. _#2412: https://github.com/pallets/flask/pull/2412 -.. _#2414: https://github.com/pallets/flask/pull/2414 -.. _#2416: https://github.com/pallets/flask/pull/2416 -.. _#2430: https://github.com/pallets/flask/pull/2430 -.. _#2436: https://github.com/pallets/flask/pull/2436 -.. _#2450: https://github.com/pallets/flask/pull/2450 -.. _#2526: https://github.com/pallets/flask/issues/2526 -.. _#2529: https://github.com/pallets/flask/pull/2529 -.. _#2586: https://github.com/pallets/flask/issues/2586 -.. _#2581: https://github.com/pallets/flask/pull/2581 -.. _#2606: https://github.com/pallets/flask/pull/2606 -.. _#2607: https://github.com/pallets/flask/pull/2607 -.. _#2636: https://github.com/pallets/flask/pull/2636 -.. _#2635: https://github.com/pallets/flask/pull/2635 -.. _#2629: https://github.com/pallets/flask/pull/2629 -.. _#2651: https://github.com/pallets/flask/issues/2651 -.. _#2676: https://github.com/pallets/flask/pull/2676 -.. _#2691: https://github.com/pallets/flask/pull/2691 -.. _#2693: https://github.com/pallets/flask/pull/2693 -.. _#2709: https://github.com/pallets/flask/pull/2709 + :pr:`2676` -Version 0.12.4 +Version 0.12.5 -------------- -Released on April 29 2018 +Released 2020-02-10 -- Repackage 0.12.3 to fix package layout issue. (`#2728`_) +- Pin Werkzeug to < 1.0.0. :issue:`3497` -.. _#2728: https://github.com/pallets/flask/issues/2728 + +Version 0.12.4 +-------------- + +Released 2018-04-29 + +- Repackage 0.12.3 to fix package layout issue. :issue:`2728` Version 0.12.3 -------------- -Released on April 26th 2018 +Released 2018-04-26 - :func:`Request.get_json` no longer accepts arbitrary encodings. Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but - Flask will autodetect UTF-8, -16, or -32. (`#2692`_) + Flask will autodetect UTF-8, -16, or -32. :issue:`2692` - Fix a Python warning about imports when using ``python -m flask``. - (`#2666`_) + :issue:`2666` - Fix a ``ValueError`` caused by invalid ``Range`` requests in some cases. -.. _#2666: https://github.com/pallets/flask/issues/2666 -.. _#2692: https://github.com/pallets/flask/issues/2692 - Version 0.12.2 -------------- -Released on May 16 2017 +Released 2017-05-16 + +- Fix a bug in ``safe_join`` on Windows. -- Fix a bug in `safe_join` on Windows. Version 0.12.1 -------------- -Bugfix release, released on March 31st 2017 +Released 2017-03-31 + +- Prevent ``flask run`` from showing a ``NoAppException`` when an + ``ImportError`` occurs within the imported application module. +- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. + :issue:`2118` +- Use the ``SERVER_NAME`` config if it is present as default values + for ``app.run``. :issue:`2109`, :pr:`2152` +- Call ``ctx.auto_pop`` with the exception object instead of ``None``, + in the event that a ``BaseException`` such as ``KeyboardInterrupt`` + is raised in a request handler. -- Prevent `flask run` from showing a NoAppException when an ImportError occurs - within the imported application module. -- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix - ``#2118``. -- Use the ``SERVER_NAME`` config if it is present as default values for - ``app.run``. ``#2109``, ``#2152`` -- Call `ctx.auto_pop` with the exception object instead of `None`, in the - event that a `BaseException` such as `KeyboardInterrupt` is raised in a - request handler. Version 0.12 ------------ -Released on December 21st 2016, codename Punsch. - -- the cli command now responds to `--version`. -- Mimetype guessing and ETag generation for file-like objects in ``send_file`` - has been removed, as per issue ``#104``. (`#1849`_) -- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to - ``application/octet-stream``. (`#1988`_) -- Make ``flask.safe_join`` able to join multiple paths like ``os.path.join`` - (`#1730`_). -- Revert a behavior change that made the dev server crash instead of returning - an Internal Server Error (`#2006`_). -- Correctly invoke response handlers for both regular request dispatching as - well as error handlers. -- Disable logger propagation by default for the app logger. -- Add support for range requests in ``send_file``. -- ``app.test_client`` includes preset default environment, which can now be - directly set, instead of per ``client.get``. - -.. _#1849: https://github.com/pallets/flask/pull/1849 -.. _#1988: https://github.com/pallets/flask/pull/1988 -.. _#1730: https://github.com/pallets/flask/pull/1730 -.. _#2006: https://github.com/pallets/flask/pull/2006 - -Version 0.11.2 --------------- - -Bugfix release, unreleased - -- Fix crash when running under PyPy3. (`#1814`_) +Released 2016-12-21, codename Punsch + +- The cli command now responds to ``--version``. +- Mimetype guessing and ETag generation for file-like objects in + ``send_file`` has been removed. :issue:`104`, :pr`1849` +- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall + back to ``application/octet-stream``. :pr:`1988` +- Make ``flask.safe_join`` able to join multiple paths like + ``os.path.join`` :pr:`1730` +- Revert a behavior change that made the dev server crash instead of + returning an Internal Server Error. :pr:`2006` +- Correctly invoke response handlers for both regular request + dispatching as well as error handlers. +- Disable logger propagation by default for the app logger. +- Add support for range requests in ``send_file``. +- ``app.test_client`` includes preset default environment, which can + now be directly set, instead of per ``client.get``. +- Fix crash when running under PyPy3. :pr:`1814` -.. _#1814: https://github.com/pallets/flask/pull/1814 Version 0.11.1 -------------- -Bugfix release, released on June 7th 2016. +Released 2016-06-07 + +- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from + working. :pr:`1872` -- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. (`#1872`_) - -.. _#1872: https://github.com/pallets/flask/pull/1872 Version 0.11 ------------ -Released on May 29th 2016, codename Absinthe. - -- Added support to serializing top-level arrays to :func:`flask.jsonify`. This - introduces a security risk in ancient browsers. See - :ref:`json-security` for details. -- Added before_render_template signal. -- Added `**kwargs` to :meth:`flask.Test.test_client` to support passing - additional keyword arguments to the constructor of - :attr:`flask.Flask.test_client_class`. -- Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the - set-cookie behavior. If set to ``True`` a permanent session will be - refreshed each request and get their lifetime extended, if set to - ``False`` it will only be modified if the session actually modifies. - Non permanent sessions are not affected by this and will always - expire if the browser window closes. -- Made Flask support custom JSON mimetypes for incoming data. -- Added support for returning tuples in the form ``(response, headers)`` - from a view function. -- Added :meth:`flask.Config.from_json`. -- Added :attr:`flask.Flask.config_class`. -- Added :meth:`flask.Config.get_namespace`. -- Templates are no longer automatically reloaded outside of debug mode. This - can be configured with the new ``TEMPLATES_AUTO_RELOAD`` config key. -- Added a workaround for a limitation in Python 3.3's namespace loader. -- Added support for explicit root paths when using Python 3.3's namespace - packages. -- Added :command:`flask` and the ``flask.cli`` module to start the local - debug server through the click CLI system. This is recommended over the old - ``flask.run()`` method as it works faster and more reliable due to a - different design and also replaces ``Flask-Script``. -- Error handlers that match specific classes are now checked first, - thereby allowing catching exceptions that are subclasses of HTTP - exceptions (in ``werkzeug.exceptions``). This makes it possible - for an extension author to create exceptions that will by default - result in the HTTP error of their choosing, but may be caught with - a custom error handler if desired. -- Added :meth:`flask.Config.from_mapping`. -- Flask will now log by default even if debug is disabled. The log format is - now hardcoded but the default log handling can be disabled through the - ``LOGGER_HANDLER_POLICY`` configuration key. -- Removed deprecated module functionality. -- Added the ``EXPLAIN_TEMPLATE_LOADING`` config flag which when enabled will - instruct Flask to explain how it locates templates. This should help - users debug when the wrong templates are loaded. -- Enforce blueprint handling in the order they were registered for template - loading. -- Ported test suite to py.test. -- Deprecated ``request.json`` in favour of ``request.get_json()``. -- Add "pretty" and "compressed" separators definitions in jsonify() method. - Reduces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing - unnecessary white space included by default after separators. -- JSON responses are now terminated with a newline character, because it is a - convention that UNIX text files end with a newline and some clients don't - deal well when this newline is missing. See - https://github.com/pallets/flask/pull/1262 -- this came up originally as a - part of https://github.com/kennethreitz/httpbin/issues/168 -- The automatically provided ``OPTIONS`` method is now correctly disabled if - the user registered an overriding rule with the lowercase-version - ``options`` (issue ``#1288``). -- ``flask.json.jsonify`` now supports the ``datetime.date`` type (`#1326`_). -- Don't leak exception info of already catched exceptions to context teardown - handlers (`#1393`_). -- Allow custom Jinja environment subclasses (`#1422`_). -- Updated extension dev guidelines. - -- ``flask.g`` now has ``pop()`` and ``setdefault`` methods. -- Turn on autoescape for ``flask.templating.render_template_string`` by default - (`#1515`_). -- ``flask.ext`` is now deprecated (`#1484`_). -- ``send_from_directory`` now raises BadRequest if the filename is invalid on - the server OS (`#1763`_). -- Added the ``JSONIFY_MIMETYPE`` configuration variable (`#1728`_). -- Exceptions during teardown handling will no longer leave bad application - contexts lingering around. - -.. _#1326: https://github.com/pallets/flask/pull/1326 -.. _#1393: https://github.com/pallets/flask/pull/1393 -.. _#1422: https://github.com/pallets/flask/pull/1422 -.. _#1515: https://github.com/pallets/flask/pull/1515 -.. _#1484: https://github.com/pallets/flask/pull/1484 -.. _#1763: https://github.com/pallets/flask/pull/1763 -.. _#1728: https://github.com/pallets/flask/pull/1728 - -Version 0.10.2 --------------- +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. +- Added before_render_template signal. +- Added ``**kwargs`` to :meth:`flask.Test.test_client` to support + passing additional keyword arguments to the constructor of + :attr:`flask.Flask.test_client_class`. +- Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the + set-cookie behavior. If set to ``True`` a permanent session will be + refreshed each request and get their lifetime extended, if set to + ``False`` it will only be modified if the session actually modifies. + Non permanent sessions are not affected by this and will always + expire if the browser window closes. +- Made Flask support custom JSON mimetypes for incoming data. +- Added support for returning tuples in the form ``(response, + headers)`` from a view function. +- Added :meth:`flask.Config.from_json`. +- Added :attr:`flask.Flask.config_class`. +- Added :meth:`flask.Config.get_namespace`. +- Templates are no longer automatically reloaded outside of debug + mode. This can be configured with the new ``TEMPLATES_AUTO_RELOAD`` + config key. +- Added a workaround for a limitation in Python 3.3's namespace + loader. +- Added support for explicit root paths when using Python 3.3's + namespace packages. +- Added :command:`flask` and the ``flask.cli`` module to start the + local debug server through the click CLI system. This is recommended + over the old ``flask.run()`` method as it works faster and more + reliable due to a different design and also replaces + ``Flask-Script``. +- Error handlers that match specific classes are now checked first, + thereby allowing catching exceptions that are subclasses of HTTP + exceptions (in ``werkzeug.exceptions``). This makes it possible for + an extension author to create exceptions that will by default result + in the HTTP error of their choosing, but may be caught with a custom + error handler if desired. +- Added :meth:`flask.Config.from_mapping`. +- Flask will now log by default even if debug is disabled. The log + format is now hardcoded but the default log handling can be disabled + through the ``LOGGER_HANDLER_POLICY`` configuration key. +- Removed deprecated module functionality. +- Added the ``EXPLAIN_TEMPLATE_LOADING`` config flag which when + enabled will instruct Flask to explain how it locates templates. + This should help users debug when the wrong templates are loaded. +- Enforce blueprint handling in the order they were registered for + template loading. +- Ported test suite to py.test. +- Deprecated ``request.json`` in favour of ``request.get_json()``. +- Add "pretty" and "compressed" separators definitions in jsonify() + method. Reduces JSON response size when + ``JSONIFY_PRETTYPRINT_REGULAR=False`` by removing unnecessary white + space included by default after separators. +- JSON responses are now terminated with a newline character, because + it is a convention that UNIX text files end with a newline and some + clients don't deal well when this newline is missing. This came up + originally as a part of + https://github.com/postmanlabs/httpbin/issues/168. :pr:`1262` +- The automatically provided ``OPTIONS`` method is now correctly + disabled if the user registered an overriding rule with the + lowercase-version ``options``. :issue:`1288` +- ``flask.json.jsonify`` now supports the ``datetime.date`` type. + :pr:`1326` +- Don't leak exception info of already caught exceptions to context + teardown handlers. :pr:`1393` +- Allow custom Jinja environment subclasses. :pr:`1422` +- Updated extension dev guidelines. +- ``flask.g`` now has ``pop()`` and ``setdefault`` methods. +- Turn on autoescape for ``flask.templating.render_template_string`` + by default. :pr:`1515` +- ``flask.ext`` is now deprecated. :pr:`1484` +- ``send_from_directory`` now raises BadRequest if the filename is + invalid on the server OS. :pr:`1763` +- Added the ``JSONIFY_MIMETYPE`` configuration variable. :pr:`1728` +- Exceptions during teardown handling will no longer leave bad + application contexts lingering around. +- Fixed broken ``test_appcontext_signals()`` test case. +- Raise an :exc:`AttributeError` in :func:`flask.helpers.find_package` + with a useful message explaining why it is raised when a PEP 302 + import hook is used without an ``is_package()`` method. +- Fixed an issue causing exceptions raised before entering a request + or app context to be passed to teardown handlers. +- Fixed an issue with query parameters getting removed from requests + in the test client when absolute URLs were requested. +- Made ``@before_first_request`` into a decorator as intended. +- Fixed an etags bug when sending a file streams with a name. +- Fixed ``send_from_directory`` not expanding to the application root + path correctly. +- Changed logic of before first request handlers to flip the flag + after invoking. This will allow some uses that are potentially + dangerous but should probably be permitted. +- Fixed Python 3 bug when a handler from + ``app.url_build_error_handlers`` reraises the ``BuildError``. -(bugfix release, release date to be announced) - -- Fixed broken `test_appcontext_signals()` test case. -- Raise an :exc:`AttributeError` in :func:`flask.helpers.find_package` with a - useful message explaining why it is raised when a PEP 302 import hook is used - without an `is_package()` method. -- Fixed an issue causing exceptions raised before entering a request or app - context to be passed to teardown handlers. -- Fixed an issue with query parameters getting removed from requests in - the test client when absolute URLs were requested. -- Made `@before_first_request` into a decorator as intended. -- Fixed an etags bug when sending a file streams with a name. -- Fixed `send_from_directory` not expanding to the application root path - correctly. -- Changed logic of before first request handlers to flip the flag after - invoking. This will allow some uses that are potentially dangerous but - should probably be permitted. -- Fixed Python 3 bug when a handler from `app.url_build_error_handlers` - reraises the `BuildError`. Version 0.10.1 -------------- -(bugfix release, released on June 14th 2013) +Released 2013-06-14 + +- Fixed an issue where ``|tojson`` was not quoting single quotes which + made the filter not work properly in HTML attributes. Now it's + possible to use that filter in single quoted attributes. This should + make using that filter with angular.js easier. +- Added support for byte strings back to the session system. This + broke compatibility with the common case of people putting binary + data for token verification into the session. +- Fixed an issue where registering the same method twice for the same + endpoint would trigger an exception incorrectly. -- Fixed an issue where ``|tojson`` was not quoting single quotes which - made the filter not work properly in HTML attributes. Now it's - possible to use that filter in single quoted attributes. This should - make using that filter with angular.js easier. -- Added support for byte strings back to the session system. This broke - compatibility with the common case of people putting binary data for - token verification into the session. -- Fixed an issue where registering the same method twice for the same endpoint - would trigger an exception incorrectly. Version 0.10 ------------ -Released on June 13th 2013, codename Limoncello. - -- Changed default cookie serialization format from pickle to JSON to - limit the impact an attacker can do if the secret key leaks. See - :ref:`upgrading-to-010` for more information. -- Added ``template_test`` methods in addition to the already existing - ``template_filter`` method family. -- Added ``template_global`` methods in addition to the already existing - ``template_filter`` method family. -- Set the content-length header for x-sendfile. -- ``tojson`` filter now does not escape script blocks in HTML5 parsers. -- ``tojson`` used in templates is now safe by default due. This was - allowed due to the different escaping behavior. -- Flask will now raise an error if you attempt to register a new function - on an already used endpoint. -- Added wrapper module around simplejson and added default serialization - of datetime objects. This allows much easier customization of how - JSON is handled by Flask or any Flask extension. -- Removed deprecated internal ``flask.session`` module alias. Use - ``flask.sessions`` instead to get the session module. This is not to - be confused with ``flask.session`` the session proxy. -- Templates can now be rendered without request context. The behavior is - slightly different as the ``request``, ``session`` and ``g`` objects - will not be available and blueprint's context processors are not - called. -- The config object is now available to the template as a real global and - not through a context processor which makes it available even in imported - templates by default. -- Added an option to generate non-ascii encoded JSON which should result - in less bytes being transmitted over the network. It's disabled by - default to not cause confusion with existing libraries that might expect - ``flask.json.dumps`` to return bytestrings by default. -- ``flask.g`` is now stored on the app context instead of the request - context. -- ``flask.g`` now gained a ``get()`` method for not erroring out on non - existing items. -- ``flask.g`` now can be used with the ``in`` operator to see what's defined - and it now is iterable and will yield all attributes stored. -- ``flask.Flask.request_globals_class`` got renamed to - ``flask.Flask.app_ctx_globals_class`` which is a better name to what it - does since 0.10. -- `request`, `session` and `g` are now also added as proxies to the template - context which makes them available in imported templates. One has to be - very careful with those though because usage outside of macros might - cause caching. -- Flask will no longer invoke the wrong error handlers if a proxy - exception is passed through. -- Added a workaround for chrome's cookies in localhost not working - as intended with domain names. -- Changed logic for picking defaults for cookie values from sessions - to work better with Google Chrome. -- Added `message_flashed` signal that simplifies flashing testing. -- Added support for copying of request contexts for better working with - greenlets. -- Removed custom JSON HTTP exception subclasses. If you were relying on them - you can reintroduce them again yourself trivially. Using them however is - strongly discouraged as the interface was flawed. -- Python requirements changed: requiring Python 2.6 or 2.7 now to prepare - for Python 3.3 port. -- Changed how the teardown system is informed about exceptions. This is now - more reliable in case something handles an exception halfway through - the error handling process. -- Request context preservation in debug mode now keeps the exception - information around which means that teardown handlers are able to - distinguish error from success cases. -- Added the ``JSONIFY_PRETTYPRINT_REGULAR`` configuration variable. -- Flask now orders JSON keys by default to not trash HTTP caches due to - different hash seeds between different workers. -- Added `appcontext_pushed` and `appcontext_popped` signals. -- The builtin run method now takes the ``SERVER_NAME`` into account when - picking the default port to run on. -- Added `flask.request.get_json()` as a replacement for the old - `flask.request.json` property. +Released 2013-06-13, codename Limoncello + +- Changed default cookie serialization format from pickle to JSON to + limit the impact an attacker can do if the secret key leaks. +- Added ``template_test`` methods in addition to the already existing + ``template_filter`` method family. +- Added ``template_global`` methods in addition to the already + existing ``template_filter`` method family. +- Set the content-length header for x-sendfile. +- ``tojson`` filter now does not escape script blocks in HTML5 + parsers. +- ``tojson`` used in templates is now safe by default due. This was + allowed due to the different escaping behavior. +- Flask will now raise an error if you attempt to register a new + function on an already used endpoint. +- Added wrapper module around simplejson and added default + serialization of datetime objects. This allows much easier + customization of how JSON is handled by Flask or any Flask + extension. +- Removed deprecated internal ``flask.session`` module alias. Use + ``flask.sessions`` instead to get the session module. This is not to + be confused with ``flask.session`` the session proxy. +- Templates can now be rendered without request context. The behavior + is slightly different as the ``request``, ``session`` and ``g`` + objects will not be available and blueprint's context processors are + not called. +- The config object is now available to the template as a real global + and not through a context processor which makes it available even in + imported templates by default. +- Added an option to generate non-ascii encoded JSON which should + result in less bytes being transmitted over the network. It's + disabled by default to not cause confusion with existing libraries + that might expect ``flask.json.dumps`` to return bytes by default. +- ``flask.g`` is now stored on the app context instead of the request + context. +- ``flask.g`` now gained a ``get()`` method for not erroring out on + non existing items. +- ``flask.g`` now can be used with the ``in`` operator to see what's + defined and it now is iterable and will yield all attributes stored. +- ``flask.Flask.request_globals_class`` got renamed to + ``flask.Flask.app_ctx_globals_class`` which is a better name to what + it does since 0.10. +- ``request``, ``session`` and ``g`` are now also added as proxies to + the template context which makes them available in imported + templates. One has to be very careful with those though because + usage outside of macros might cause caching. +- Flask will no longer invoke the wrong error handlers if a proxy + exception is passed through. +- Added a workaround for chrome's cookies in localhost not working as + intended with domain names. +- Changed logic for picking defaults for cookie values from sessions + to work better with Google Chrome. +- Added ``message_flashed`` signal that simplifies flashing testing. +- Added support for copying of request contexts for better working + with greenlets. +- Removed custom JSON HTTP exception subclasses. If you were relying + on them you can reintroduce them again yourself trivially. Using + them however is strongly discouraged as the interface was flawed. +- Python requirements changed: requiring Python 2.6 or 2.7 now to + prepare for Python 3.3 port. +- Changed how the teardown system is informed about exceptions. This + is now more reliable in case something handles an exception halfway + through the error handling process. +- Request context preservation in debug mode now keeps the exception + information around which means that teardown handlers are able to + distinguish error from success cases. +- Added the ``JSONIFY_PRETTYPRINT_REGULAR`` configuration variable. +- Flask now orders JSON keys by default to not trash HTTP caches due + to different hash seeds between different workers. +- Added ``appcontext_pushed`` and ``appcontext_popped`` signals. +- The builtin run method now takes the ``SERVER_NAME`` into account + when picking the default port to run on. +- Added ``flask.request.get_json()`` as a replacement for the old + ``flask.request.json`` property. + Version 0.9 ----------- -Released on July 1st 2012, codename Campari. - -- The :func:`flask.Request.on_json_loading_failed` now returns a JSON formatted - response by default. -- The :func:`flask.url_for` function now can generate anchors to the - generated links. -- The :func:`flask.url_for` function now can also explicitly generate - URL rules specific to a given HTTP method. -- Logger now only returns the debug log setting if it was not set - explicitly. -- Unregister a circular dependency between the WSGI environment and - the request object when shutting down the request. This means that - environ ``werkzeug.request`` will be ``None`` after the response was - returned to the WSGI server but has the advantage that the garbage - collector is not needed on CPython to tear down the request unless - the user created circular dependencies themselves. -- Session is now stored after callbacks so that if the session payload - is stored in the session you can still modify it in an after - request callback. -- The :class:`flask.Flask` class will avoid importing the provided import name - if it can (the required first parameter), to benefit tools which build Flask - instances programmatically. The Flask class will fall back to using import - on systems with custom module hooks, e.g. Google App Engine, or when the - import name is inside a zip archive (usually a .egg) prior to Python 2.7. -- Blueprints now have a decorator to add custom template filters application - wide, :meth:`flask.Blueprint.app_template_filter`. -- The Flask and Blueprint classes now have a non-decorator method for adding - custom template filters application wide, - :meth:`flask.Flask.add_template_filter` and - :meth:`flask.Blueprint.add_app_template_filter`. -- The :func:`flask.get_flashed_messages` function now allows rendering flashed - message categories in separate blocks, through a ``category_filter`` - argument. -- The :meth:`flask.Flask.run` method now accepts ``None`` for `host` and `port` - arguments, using default values when ``None``. This allows for calling run - using configuration values, e.g. ``app.run(app.config.get('MYHOST'), - app.config.get('MYPORT'))``, with proper behavior whether or not a config - file is provided. -- The :meth:`flask.render_template` method now accepts a either an iterable of - template names or a single template name. Previously, it only accepted a - single template name. On an iterable, the first template found is rendered. -- Added :meth:`flask.Flask.app_context` which works very similar to the - request context but only provides access to the current application. This - also adds support for URL generation without an active request context. -- View functions can now return a tuple with the first instance being an - instance of :class:`flask.Response`. This allows for returning - ``jsonify(error="error msg"), 400`` from a view function. -- :class:`~flask.Flask` and :class:`~flask.Blueprint` now provide a - :meth:`~flask.Flask.get_send_file_max_age` hook for subclasses to override - behavior of serving static files from Flask when using - :meth:`flask.Flask.send_static_file` (used for the default static file - handler) and :func:`~flask.helpers.send_file`. This hook is provided a - filename, which for example allows changing cache controls by file extension. - The default max-age for `send_file` and static files can be configured - through a new ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, which is - used in the default `get_send_file_max_age` implementation. -- Fixed an assumption in sessions implementation which could break message - flashing on sessions implementations which use external storage. -- Changed the behavior of tuple return values from functions. They are no - longer arguments to the response object, they now have a defined meaning. -- Added :attr:`flask.Flask.request_globals_class` to allow a specific class to - be used on creation of the :data:`~flask.g` instance of each request. -- Added `required_methods` attribute to view functions to force-add methods - on registration. -- Added :func:`flask.after_this_request`. -- Added :func:`flask.stream_with_context` and the ability to push contexts - multiple times without producing unexpected behavior. +Released 2012-07-01, codename Campari + +- The :func:`flask.Request.on_json_loading_failed` now returns a JSON + formatted response by default. +- The :func:`flask.url_for` function now can generate anchors to the + generated links. +- The :func:`flask.url_for` function now can also explicitly generate + URL rules specific to a given HTTP method. +- Logger now only returns the debug log setting if it was not set + explicitly. +- Unregister a circular dependency between the WSGI environment and + the request object when shutting down the request. This means that + environ ``werkzeug.request`` will be ``None`` after the response was + returned to the WSGI server but has the advantage that the garbage + collector is not needed on CPython to tear down the request unless + the user created circular dependencies themselves. +- Session is now stored after callbacks so that if the session payload + is stored in the session you can still modify it in an after request + callback. +- The :class:`flask.Flask` class will avoid importing the provided + import name if it can (the required first parameter), to benefit + tools which build Flask instances programmatically. The Flask class + will fall back to using import on systems with custom module hooks, + e.g. Google App Engine, or when the import name is inside a zip + archive (usually a .egg) prior to Python 2.7. +- Blueprints now have a decorator to add custom template filters + application wide, :meth:`flask.Blueprint.app_template_filter`. +- The Flask and Blueprint classes now have a non-decorator method for + adding custom template filters application wide, + :meth:`flask.Flask.add_template_filter` and + :meth:`flask.Blueprint.add_app_template_filter`. +- The :func:`flask.get_flashed_messages` function now allows rendering + flashed message categories in separate blocks, through a + ``category_filter`` argument. +- The :meth:`flask.Flask.run` method now accepts ``None`` for ``host`` + and ``port`` arguments, using default values when ``None``. This + allows for calling run using configuration values, e.g. + ``app.run(app.config.get('MYHOST'), app.config.get('MYPORT'))``, + with proper behavior whether or not a config file is provided. +- The :meth:`flask.render_template` method now accepts a either an + iterable of template names or a single template name. Previously, it + only accepted a single template name. On an iterable, the first + template found is rendered. +- Added :meth:`flask.Flask.app_context` which works very similar to + the request context but only provides access to the current + application. This also adds support for URL generation without an + active request context. +- View functions can now return a tuple with the first instance being + an instance of :class:`flask.Response`. This allows for returning + ``jsonify(error="error msg"), 400`` from a view function. +- :class:`~flask.Flask` and :class:`~flask.Blueprint` now provide a + :meth:`~flask.Flask.get_send_file_max_age` hook for subclasses to + override behavior of serving static files from Flask when using + :meth:`flask.Flask.send_static_file` (used for the default static + file handler) and :func:`~flask.helpers.send_file`. This hook is + provided a filename, which for example allows changing cache + controls by file extension. The default max-age for ``send_file`` + and static files can be configured through a new + ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, which is used + in the default ``get_send_file_max_age`` implementation. +- Fixed an assumption in sessions implementation which could break + message flashing on sessions implementations which use external + storage. +- Changed the behavior of tuple return values from functions. They are + no longer arguments to the response object, they now have a defined + meaning. +- Added :attr:`flask.Flask.request_globals_class` to allow a specific + class to be used on creation of the :data:`~flask.g` instance of + each request. +- Added ``required_methods`` attribute to view functions to force-add + methods on registration. +- Added :func:`flask.after_this_request`. +- Added :func:`flask.stream_with_context` and the ability to push + contexts multiple times without producing unexpected behavior. + Version 0.8.1 ------------- -Bugfix release, released on July 1st 2012 +Released 2012-07-01 + +- Fixed an issue with the undocumented ``flask.session`` module to not + work properly on Python 2.5. It should not be used but did cause + some problems for package managers. -- Fixed an issue with the undocumented `flask.session` module to not - work properly on Python 2.5. It should not be used but did cause - some problems for package managers. Version 0.8 ----------- -Released on September 29th 2011, codename Rakija - -- Refactored session support into a session interface so that - the implementation of the sessions can be changed without - having to override the Flask class. -- Empty session cookies are now deleted properly automatically. -- View functions can now opt out of getting the automatic - OPTIONS implementation. -- HTTP exceptions and Bad Request errors can now be trapped so that they - show up normally in the traceback. -- Flask in debug mode is now detecting some common problems and tries to - warn you about them. -- Flask in debug mode will now complain with an assertion error if a view - was attached after the first request was handled. This gives earlier - feedback when users forget to import view code ahead of time. -- Added the ability to register callbacks that are only triggered once at - the beginning of the first request. (:meth:`Flask.before_first_request`) -- Malformed JSON data will now trigger a bad request HTTP exception instead - of a value error which usually would result in a 500 internal server - error if not handled. This is a backwards incompatible change. -- Applications now not only have a root path where the resources and modules - are located but also an instance path which is the designated place to - drop files that are modified at runtime (uploads etc.). Also this is - conceptually only instance depending and outside version control so it's - the perfect place to put configuration files etc. For more information - see :ref:`instance-folders`. -- Added the ``APPLICATION_ROOT`` configuration variable. -- Implemented :meth:`~flask.testing.TestClient.session_transaction` to - easily modify sessions from the test environment. -- Refactored test client internally. The ``APPLICATION_ROOT`` configuration - variable as well as ``SERVER_NAME`` are now properly used by the test client - as defaults. -- Added :attr:`flask.views.View.decorators` to support simpler decorating of - pluggable (class-based) views. -- Fixed an issue where the test client if used with the "with" statement did not - trigger the execution of the teardown handlers. -- Added finer control over the session cookie parameters. -- HEAD requests to a method view now automatically dispatch to the `get` - method if no handler was implemented. -- Implemented the virtual :mod:`flask.ext` package to import extensions from. -- The context preservation on exceptions is now an integral component of - Flask itself and no longer of the test client. This cleaned up some - internal logic and lowers the odds of runaway request contexts in unittests. - -Version 0.7.3 -------------- - -Bugfix release, release date to be decided +Released 2011-09-29, codename Rakija + +- Refactored session support into a session interface so that the + implementation of the sessions can be changed without having to + override the Flask class. +- Empty session cookies are now deleted properly automatically. +- View functions can now opt out of getting the automatic OPTIONS + implementation. +- HTTP exceptions and Bad Request errors can now be trapped so that + they show up normally in the traceback. +- Flask in debug mode is now detecting some common problems and tries + to warn you about them. +- Flask in debug mode will now complain with an assertion error if a + view was attached after the first request was handled. This gives + earlier feedback when users forget to import view code ahead of + time. +- Added the ability to register callbacks that are only triggered once + at the beginning of the first request. + (:meth:`Flask.before_first_request`) +- Malformed JSON data will now trigger a bad request HTTP exception + instead of a value error which usually would result in a 500 + internal server error if not handled. This is a backwards + incompatible change. +- Applications now not only have a root path where the resources and + modules are located but also an instance path which is the + designated place to drop files that are modified at runtime (uploads + etc.). Also this is conceptually only instance depending and outside + version control so it's the perfect place to put configuration files + etc. +- Added the ``APPLICATION_ROOT`` configuration variable. +- Implemented :meth:`~flask.testing.TestClient.session_transaction` to + easily modify sessions from the test environment. +- Refactored test client internally. The ``APPLICATION_ROOT`` + configuration variable as well as ``SERVER_NAME`` are now properly + used by the test client as defaults. +- Added :attr:`flask.views.View.decorators` to support simpler + decorating of pluggable (class-based) views. +- Fixed an issue where the test client if used with the "with" + statement did not trigger the execution of the teardown handlers. +- Added finer control over the session cookie parameters. +- HEAD requests to a method view now automatically dispatch to the + ``get`` method if no handler was implemented. +- Implemented the virtual :mod:`flask.ext` package to import + extensions from. +- The context preservation on exceptions is now an integral component + of Flask itself and no longer of the test client. This cleaned up + some internal logic and lowers the odds of runaway request contexts + in unittests. +- Fixed the Jinja2 environment's ``list_templates`` method not + returning the correct names when blueprints or modules were + involved. -- Fixed the Jinja2 environment's list_templates method not returning the - correct names when blueprints or modules were involved. Version 0.7.2 ------------- -Bugfix release, released on July 6th 2011 +Released 2011-07-06 + +- Fixed an issue with URL processors not properly working on + blueprints. -- Fixed an issue with URL processors not properly working on - blueprints. Version 0.7.1 ------------- -Bugfix release, released on June 29th 2011 +Released 2011-06-29 + +- Added missing future import that broke 2.5 compatibility. +- Fixed an infinite redirect issue with blueprints. -- Added missing future import that broke 2.5 compatibility. -- Fixed an infinite redirect issue with blueprints. Version 0.7 ----------- -Released on June 28th 2011, codename Grappa - -- Added :meth:`~flask.Flask.make_default_options_response` - which can be used by subclasses to alter the default - behavior for ``OPTIONS`` responses. -- Unbound locals now raise a proper :exc:`RuntimeError` instead - of an :exc:`AttributeError`. -- Mimetype guessing and etag support based on file objects is now - deprecated for :func:`flask.send_file` because it was unreliable. - Pass filenames instead or attach your own etags and provide a - proper mimetype by hand. -- Static file handling for modules now requires the name of the - static folder to be supplied explicitly. The previous autodetection - was not reliable and caused issues on Google's App Engine. Until - 1.0 the old behavior will continue to work but issue dependency - warnings. -- fixed a problem for Flask to run on jython. -- added a ``PROPAGATE_EXCEPTIONS`` configuration variable that can be - used to flip the setting of exception propagation which previously - was linked to ``DEBUG`` alone and is now linked to either ``DEBUG`` or - ``TESTING``. -- Flask no longer internally depends on rules being added through the - `add_url_rule` function and can now also accept regular werkzeug - rules added to the url map. -- Added an `endpoint` method to the flask application object which - allows one to register a callback to an arbitrary endpoint with - a decorator. -- Use Last-Modified for static file sending instead of Date which - was incorrectly introduced in 0.6. -- Added `create_jinja_loader` to override the loader creation process. -- Implemented a silent flag for `config.from_pyfile`. -- Added `teardown_request` decorator, for functions that should run at the end - of a request regardless of whether an exception occurred. Also the behavior - for `after_request` was changed. It's now no longer executed when an exception - is raised. See :ref:`upgrading-to-new-teardown-handling` -- Implemented :func:`flask.has_request_context` -- Deprecated `init_jinja_globals`. Override the - :meth:`~flask.Flask.create_jinja_environment` method instead to - achieve the same functionality. -- Added :func:`flask.safe_join` -- The automatic JSON request data unpacking now looks at the charset - mimetype parameter. -- Don't modify the session on :func:`flask.get_flashed_messages` if there - are no messages in the session. -- `before_request` handlers are now able to abort requests with errors. -- it is not possible to define user exception handlers. That way you can - provide custom error messages from a central hub for certain errors that - might occur during request processing (for instance database connection - errors, timeouts from remote resources etc.). -- Blueprints can provide blueprint specific error handlers. -- Implemented generic :ref:`views` (class-based views). +Released 2011-06-28, codename Grappa + +- Added :meth:`~flask.Flask.make_default_options_response` which can + be used by subclasses to alter the default behavior for ``OPTIONS`` + responses. +- Unbound locals now raise a proper :exc:`RuntimeError` instead of an + :exc:`AttributeError`. +- Mimetype guessing and etag support based on file objects is now + deprecated for :func:`flask.send_file` because it was unreliable. + Pass filenames instead or attach your own etags and provide a proper + mimetype by hand. +- Static file handling for modules now requires the name of the static + folder to be supplied explicitly. The previous autodetection was not + reliable and caused issues on Google's App Engine. Until 1.0 the old + behavior will continue to work but issue dependency warnings. +- Fixed a problem for Flask to run on jython. +- Added a ``PROPAGATE_EXCEPTIONS`` configuration variable that can be + used to flip the setting of exception propagation which previously + was linked to ``DEBUG`` alone and is now linked to either ``DEBUG`` + or ``TESTING``. +- Flask no longer internally depends on rules being added through the + ``add_url_rule`` function and can now also accept regular werkzeug + rules added to the url map. +- Added an ``endpoint`` method to the flask application object which + allows one to register a callback to an arbitrary endpoint with a + decorator. +- Use Last-Modified for static file sending instead of Date which was + incorrectly introduced in 0.6. +- Added ``create_jinja_loader`` to override the loader creation + process. +- Implemented a silent flag for ``config.from_pyfile``. +- Added ``teardown_request`` decorator, for functions that should run + at the end of a request regardless of whether an exception occurred. + Also the behavior for ``after_request`` was changed. It's now no + longer executed when an exception is raised. +- Implemented :func:`flask.has_request_context` +- Deprecated ``init_jinja_globals``. Override the + :meth:`~flask.Flask.create_jinja_environment` method instead to + achieve the same functionality. +- Added :func:`flask.safe_join` +- The automatic JSON request data unpacking now looks at the charset + mimetype parameter. +- Don't modify the session on :func:`flask.get_flashed_messages` if + there are no messages in the session. +- ``before_request`` handlers are now able to abort requests with + errors. +- It is not possible to define user exception handlers. That way you + can provide custom error messages from a central hub for certain + errors that might occur during request processing (for instance + database connection errors, timeouts from remote resources etc.). +- Blueprints can provide blueprint specific error handlers. +- Implemented generic class-based views. + Version 0.6.1 ------------- -Bugfix release, released on December 31st 2010 +Released 2010-12-31 + +- Fixed an issue where the default ``OPTIONS`` response was not + exposing all valid methods in the ``Allow`` header. +- Jinja2 template loading syntax now allows "./" in front of a + template load path. Previously this caused issues with module + setups. +- Fixed an issue where the subdomain setting for modules was ignored + for the static folder. +- Fixed a security problem that allowed clients to download arbitrary + files if the host server was a windows based operating system and + the client uses backslashes to escape the directory the files where + exposed from. -- Fixed an issue where the default ``OPTIONS`` response was - not exposing all valid methods in the ``Allow`` header. -- Jinja2 template loading syntax now allows "./" in front of - a template load path. Previously this caused issues with - module setups. -- Fixed an issue where the subdomain setting for modules was - ignored for the static folder. -- Fixed a security problem that allowed clients to download arbitrary files - if the host server was a windows based operating system and the client - uses backslashes to escape the directory the files where exposed from. Version 0.6 ----------- -Released on July 27th 2010, codename Whisky - -- after request functions are now called in reverse order of - registration. -- OPTIONS is now automatically implemented by Flask unless the - application explicitly adds 'OPTIONS' as method to the URL rule. - In this case no automatic OPTIONS handling kicks in. -- static rules are now even in place if there is no static folder - for the module. This was implemented to aid GAE which will - remove the static folder if it's part of a mapping in the .yml - file. -- the :attr:`~flask.Flask.config` is now available in the templates - as `config`. -- context processors will no longer override values passed directly - to the render function. -- added the ability to limit the incoming request data with the - new ``MAX_CONTENT_LENGTH`` configuration value. -- the endpoint for the :meth:`flask.Module.add_url_rule` method - is now optional to be consistent with the function of the - same name on the application object. -- added a :func:`flask.make_response` function that simplifies - creating response object instances in views. -- added signalling support based on blinker. This feature is currently - optional and supposed to be used by extensions and applications. If - you want to use it, make sure to have `blinker`_ installed. -- refactored the way URL adapters are created. This process is now - fully customizable with the :meth:`~flask.Flask.create_url_adapter` - method. -- modules can now register for a subdomain instead of just an URL - prefix. This makes it possible to bind a whole module to a - configurable subdomain. +Released 2010-07-27, codename Whisky + +- After request functions are now called in reverse order of + registration. +- OPTIONS is now automatically implemented by Flask unless the + application explicitly adds 'OPTIONS' as method to the URL rule. In + this case no automatic OPTIONS handling kicks in. +- Static rules are now even in place if there is no static folder for + the module. This was implemented to aid GAE which will remove the + static folder if it's part of a mapping in the .yml file. +- The :attr:`~flask.Flask.config` is now available in the templates as + ``config``. +- Context processors will no longer override values passed directly to + the render function. +- Added the ability to limit the incoming request data with the new + ``MAX_CONTENT_LENGTH`` configuration value. +- The endpoint for the :meth:`flask.Module.add_url_rule` method is now + optional to be consistent with the function of the same name on the + application object. +- Added a :func:`flask.make_response` function that simplifies + creating response object instances in views. +- Added signalling support based on blinker. This feature is currently + optional and supposed to be used by extensions and applications. If + you want to use it, make sure to have `blinker`_ installed. +- Refactored the way URL adapters are created. This process is now + fully customizable with the :meth:`~flask.Flask.create_url_adapter` + method. +- Modules can now register for a subdomain instead of just an URL + prefix. This makes it possible to bind a whole module to a + configurable subdomain. .. _blinker: https://pypi.org/project/blinker/ + Version 0.5.2 ------------- -Bugfix Release, released on July 15th 2010 +Released 2010-07-15 + +- Fixed another issue with loading templates from directories when + modules were used. -- fixed another issue with loading templates from directories when - modules were used. Version 0.5.1 ------------- -Bugfix Release, released on July 6th 2010 +Released 2010-07-06 + +- Fixes an issue with template loading from directories when modules + where used. -- fixes an issue with template loading from directories when modules - where used. Version 0.5 ----------- -Released on July 6th 2010, codename Calvados - -- fixed a bug with subdomains that was caused by the inability to - specify the server name. The server name can now be set with - the ``SERVER_NAME`` config key. This key is now also used to set - the session cookie cross-subdomain wide. -- autoescaping is no longer active for all templates. Instead it - is only active for ``.html``, ``.htm``, ``.xml`` and ``.xhtml``. - Inside templates this behavior can be changed with the - ``autoescape`` tag. -- refactored Flask internally. It now consists of more than a - single file. -- :func:`flask.send_file` now emits etags and has the ability to - do conditional responses builtin. -- (temporarily) dropped support for zipped applications. This was a - rarely used feature and led to some confusing behavior. -- added support for per-package template and static-file directories. -- removed support for `create_jinja_loader` which is no longer used - in 0.5 due to the improved module support. -- added a helper function to expose files from any directory. +Released 2010-07-06, codename Calvados + +- Fixed a bug with subdomains that was caused by the inability to + specify the server name. The server name can now be set with the + ``SERVER_NAME`` config key. This key is now also used to set the + session cookie cross-subdomain wide. +- Autoescaping is no longer active for all templates. Instead it is + only active for ``.html``, ``.htm``, ``.xml`` and ``.xhtml``. Inside + templates this behavior can be changed with the ``autoescape`` tag. +- Refactored Flask internally. It now consists of more than a single + file. +- :func:`flask.send_file` now emits etags and has the ability to do + conditional responses builtin. +- (temporarily) dropped support for zipped applications. This was a + rarely used feature and led to some confusing behavior. +- Added support for per-package template and static-file directories. +- Removed support for ``create_jinja_loader`` which is no longer used + in 0.5 due to the improved module support. +- Added a helper function to expose files from any directory. + Version 0.4 ----------- -Released on June 18th 2010, codename Rakia - -- added the ability to register application wide error handlers - from modules. -- :meth:`~flask.Flask.after_request` handlers are now also invoked - if the request dies with an exception and an error handling page - kicks in. -- test client has the ability to preserve the request context - for a little longer. This can also be used to trigger custom - requests that do not pop the request stack for testing. -- because the Python standard library caches loggers, the name of - the logger is configurable now to better support unittests. -- added ``TESTING`` switch that can activate unittesting helpers. -- the logger switches to ``DEBUG`` mode now if debug is enabled. +Released 2010-06-18, codename Rakia + +- Added the ability to register application wide error handlers from + modules. +- :meth:`~flask.Flask.after_request` handlers are now also invoked if + the request dies with an exception and an error handling page kicks + in. +- Test client has not the ability to preserve the request context for + a little longer. This can also be used to trigger custom requests + that do not pop the request stack for testing. +- Because the Python standard library caches loggers, the name of the + logger is configurable now to better support unittests. +- Added ``TESTING`` switch that can activate unittesting helpers. +- The logger switches to ``DEBUG`` mode now if debug is enabled. + Version 0.3.1 ------------- -Bugfix release, released on May 28th 2010 +Released 2010-05-28 + +- Fixed a error reporting bug with :meth:`flask.Config.from_envvar` +- Removed some unused code from flask +- Release does no longer include development leftover files (.git + folder for themes, built documentation in zip and pdf file and some + .pyc files) -- fixed a error reporting bug with :meth:`flask.Config.from_envvar` -- removed some unused code from flask -- release does no longer include development leftover files (.git - folder for themes, built documentation in zip and pdf file and - some .pyc files) Version 0.3 ----------- -Released on May 28th 2010, codename Schnaps +Released 2010-05-28, codename Schnaps + +- Added support for categories for flashed messages. +- The application now configures a :class:`logging.Handler` and will + log request handling exceptions to that logger when not in debug + mode. This makes it possible to receive mails on server errors for + example. +- Added support for context binding that does not require the use of + the with statement for playing in the console. +- The request context is now available within the with statement + making it possible to further push the request context or pop it. +- Added support for configurations. -- added support for categories for flashed messages. -- the application now configures a :class:`logging.Handler` and will - log request handling exceptions to that logger when not in debug - mode. This makes it possible to receive mails on server errors - for example. -- added support for context binding that does not require the use of - the with statement for playing in the console. -- the request context is now available within the with statement making - it possible to further push the request context or pop it. -- added support for configurations. Version 0.2 ----------- -Released on May 12th 2010, codename Jägermeister - -- various bugfixes -- integrated JSON support -- added :func:`~flask.get_template_attribute` helper function. -- :meth:`~flask.Flask.add_url_rule` can now also register a - view function. -- refactored internal request dispatching. -- server listens on 127.0.0.1 by default now to fix issues with chrome. -- added external URL support. -- added support for :func:`~flask.send_file` -- module support and internal request handling refactoring - to better support pluggable applications. -- sessions can be set to be permanent now on a per-session basis. -- better error reporting on missing secret keys. -- added support for Google Appengine. +Released 2010-05-12, codename J?germeister + +- Various bugfixes +- Integrated JSON support +- Added :func:`~flask.get_template_attribute` helper function. +- :meth:`~flask.Flask.add_url_rule` can now also register a view + function. +- Refactored internal request dispatching. +- Server listens on 127.0.0.1 by default now to fix issues with + chrome. +- Added external URL support. +- Added support for :func:`~flask.send_file` +- Module support and internal request handling refactoring to better + support pluggable applications. +- Sessions can be set to be permanent now on a per-session basis. +- Better error reporting on missing secret keys. +- Added support for Google Appengine. + Version 0.1 ----------- -First public preview release. +Released 2010-04-16 + +- First public preview release. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..f4ba197dec --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at report@palletsprojects.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 36b7df3ab9..01a0117771 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -3,178 +3,219 @@ 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: +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 ``#get-help`` channel on our Discord chat: + https://discord.gg/pallets +- 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.}`` -* The IRC channel ``#pocoo`` on FreeNode. -* The IRC channel ``#python`` on FreeNode for more general questions. -* The mailing list flask@python.org for long term discussion or larger issues. -* Ask on `Stack Overflow`_. Search with Google first using: - ``site:stackoverflow.com flask {search term, exception message, etc.}`` +.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?tab=Frequent -.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?sort=linked Reporting issues ---------------- -- Describe what you expected to happen. -- If possible, include a `minimal, complete, and verifiable example`_ to help - us identify the issue. This also helps check that the issue is not with your - own code. -- Describe what actually happened. Include the full traceback if there was an - exception. -- List your Python, Flask, and Werkzeug versions. If possible, check if this - issue is already fixed in the repository. +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 -.. _minimal, complete, and verifiable example: https://stackoverflow.com/help/mcve Submitting patches ------------------ -- Include tests if your patch is supposed to solve a bug, and explain - clearly under which circumstances the bug happens. Make sure the test fails - without your patch. -- Try to follow `PEP8`_, but you may ignore the line length limit if following - it would make the code uglier. +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 ~~~~~~~~~~~~~~~~ -- Download and install the `latest version of git`_. -- Configure git with your `username`_ and `email`_:: +- Download and install the `latest version of git`_. +- Configure git with your `username`_ and `email`_. - git config --global user.name 'your name' - git config --global user.email 'your email' + .. code-block:: text -- Make sure you have a `GitHub account`_. -- Fork Flask to your GitHub account by clicking the `Fork`_ button. -- `Clone`_ your GitHub fork locally:: + $ git config --global user.name 'your name' + $ git config --global user.email 'your email' - git clone https://github.com/{username}/flask - cd flask +- Make sure you have a `GitHub account`_. +- Fork Flask to your GitHub account by clicking the `Fork`_ button. +- `Clone`_ the main repository locally. -- Add the main repository as a remote to update later:: + .. code-block:: text - git remote add pallets https://github.com/pallets/flask - git fetch pallets + $ git clone https://github.com/pallets/flask + $ cd flask -- Create a virtualenv:: +- Add your fork as a remote to push your work to. Replace + ``{username}`` with your username. This names the remote "fork", the + default Pallets remote is "origin". - python3 -m venv env - . env/bin/activate - # or "env\Scripts\activate" on Windows + .. code-block:: text -- Install Flask in editable mode with development dependencies:: + git remote add fork https://github.com/{username}/flask - pip install -e ".[dev]" +- Create a virtualenv. + + .. tabs:: + + .. group-tab:: Linux/macOS + + .. code-block:: text + + $ python3 -m venv env + $ . env/bin/activate + + .. group-tab:: Windows + + .. code-block:: text + + > py -3 -m venv env + > env\Scripts\activate + +- Install the development dependencies, then install Flask in editable + mode. + + .. code-block:: text + + $ pip install -r requirements/dev.txt && pip install -e . + +- Install the pre-commit hooks. + + .. code-block:: text + + $ pre-commit install -.. _GitHub account: https://github.com/join .. _latest version of git: https://git-scm.com/downloads -.. _username: https://help.github.com/articles/setting-your-username-in-git/ -.. _email: https://help.github.com/articles/setting-your-email-in-git/ -.. _Fork: https://github.com/pallets/flask/fork -.. _Clone: https://help.github.com/articles/fork-a-repo/#step-2-create-a-local-clone-of-your-fork +.. _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 +.. _GitHub account: https://github.com/join +.. _Fork: https://github.com/pallets/jinja/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 ~~~~~~~~~~~~ -- Create a branch to identify the issue you would like to work on (e.g. - ``2287-dry-test-suite``) -- Using your favorite editor, make your changes, `committing as you go`_. -- Try to follow `PEP8`_, but you may ignore the line length limit if following - it would make the code uglier. -- Include tests that cover any code changes you make. Make sure the test fails - without your patch. `Run the tests. `_. -- Push your commits to GitHub and `create a pull request`_. -- Celebrate 🎉 +- 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. -.. _committing as you go: http://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes -.. _PEP8: https://pep8.org/ -.. _create a pull request: https://help.github.com/articles/creating-a-pull-request/ + .. code-block:: text -.. _contributing-testsuite: + $ git fetch origin + $ git checkout -b your-branch-name origin/1.1.x -Running the tests -~~~~~~~~~~~~~~~~~ + If you're submitting a feature addition or change, branch off of the + "master" branch. -Run the basic test suite with:: + .. code-block:: text - pytest + $ git fetch origin + $ git checkout -b your-branch-name origin/master -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. +- 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 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. -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:: + .. code-block:: text - tox + $ git push --set-upstream fork your-branch-name -Running test coverage -~~~~~~~~~~~~~~~~~~~~~ +.. _committing as you go: https://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes +.. _create a pull request: https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request -Generating a report of lines that do not have test coverage can indicate -where to start contributing. Run ``pytest`` using ``coverage`` and generate a -report on the terminal and as an interactive HTML document:: - coverage run -m pytest - coverage report - coverage html - # then open htmlcov/index.html +Running the tests +~~~~~~~~~~~~~~~~~ -Read more about `coverage `_. +Run the basic test suite with pytest. -Running the full test suite with ``tox`` will combine the coverage reports -from all runs. +.. code-block:: text + $ pytest -Building the docs -~~~~~~~~~~~~~~~~~ +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. -Build the docs in the ``docs`` directory using Sphinx:: +.. code-block:: text - cd docs - make html + $ tox -Open ``_build/html/index.html`` in your browser to view the docs. -Read more about `Sphinx `_. +Running test coverage +~~~~~~~~~~~~~~~~~~~~~ + +Generating a report of lines that do not have test coverage can indicate +where to start contributing. Run ``pytest`` using ``coverage`` and +generate a report. +.. code-block:: text -make targets -~~~~~~~~~~~~ + $ pip install coverage + $ coverage run -m pytest + $ coverage html -Flask provides a ``Makefile`` with various shortcuts. They will ensure that -all dependencies are installed. +Open ``htmlcov/index.html`` in your browser to explore the report. -- ``make test`` runs the basic test suite with ``pytest`` -- ``make cov`` runs the basic test suite with ``coverage`` -- ``make test-all`` runs the full test suite with ``tox`` -- ``make docs`` builds the HTML documentation +Read more about `coverage `__. -Caution: zero-padded file modes -------------------------------- -This repository contains several zero-padded file modes that may cause issues -when pushing this repository to git hosts other than GitHub. Fixing this is -destructive to the commit history, so we suggest ignoring these warnings. If it -fails to push and you're using a self-hosted git service like GitLab, you can -turn off repository checks in the admin panel. +Building the docs +~~~~~~~~~~~~~~~~~ -These files can also cause issues while cloning. If you have :: +Build the docs in the ``docs`` directory using Sphinx. - [fetch] - fsckobjects = true +.. code-block:: text -or :: + $ cd docs + $ make html - [receive] - fsckObjects = true +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/LICENSE b/LICENSE deleted file mode 100644 index 8f9252f452..0000000000 --- a/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/LICENSE.rst b/LICENSE.rst new file mode 100644 index 0000000000..9d227a0cc4 --- /dev/null +++ b/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/MANIFEST.in b/MANIFEST.in index d8a725b583..65a9774968 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,11 +1,11 @@ -include Makefile CHANGES.rst LICENSE AUTHORS tox.ini - +include CHANGES.rst +include CONTRIBUTING.rst +include tox.ini +include requirements/*.txt graft artwork -graft tests -graft examples graft docs - -global-exclude *.py[co] - prune docs/_build -prune docs/_themes +graft examples +graft tests +include src/flask/py.typed +global-exclude *.pyc diff --git a/Makefile b/Makefile deleted file mode 100644 index 595b7c368f..0000000000 --- a/Makefile +++ /dev/null @@ -1,32 +0,0 @@ -.PHONY: all install-dev test coverage cov test-all tox docs release clean-pyc upload-docs ebook - -all: test - -install-dev: - pip install -q -e .[dev] - -test: clean-pyc install-dev - pytest - -coverage: clean-pyc install-dev - coverage run -m pytest - coverage report - coverage html - -cov: coverage - -test-all: install-dev - tox - -tox: test-all - -docs: clean-pyc install-dev - $(MAKE) -C docs html - -release: - python scripts/make-release.py - -clean-pyc: - find . -name '*.pyc' -exec rm -f {} + - find . -name '*.pyo' -exec rm -f {} + - find . -name '*~' -exec rm -f {} + diff --git a/README.rst b/README.rst index 4243793cd3..95f9bbaec0 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/quickstart/ A Simple Example @@ -28,19 +34,19 @@ A Simple Example .. code-block:: python + # save this as app.py from flask import Flask app = Flask(__name__) - @app.route('/') + @app.route("/") def hello(): - return 'Hello, World!' + return "Hello, World!" .. code-block:: text - $ env FLASK_APP=hello.py flask run - * Serving Flask app "hello" - * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) + $ flask run + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Contributing @@ -60,26 +66,17 @@ 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://www.palletsprojects.com/p/flask/ -* Documentation: http://flask.pocoo.org/docs/ -* License: `BSD `_ -* Releases: https://pypi.org/project/Flask/ -* Code: https://github.com/pallets/flask -* Issue tracker: https://github.com/pallets/flask/issues -* Test status: - - * Linux, Mac: https://travis-ci.org/pallets/flask - * Windows: https://ci.appveyor.com/project/pallets/flask - -* Test coverage: https://codecov.io/gh/pallets/flask - -.. _WSGI: https://wsgi.readthedocs.io -.. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/ -.. _Jinja: https://www.palletsprojects.com/p/jinja/ -.. _pip: https://pip.pypa.io/en/stable/quickstart/ +- 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/ +- Website: https://palletsprojects.com/p/flask/ +- Twitter: https://twitter.com/PalletsTeam +- Chat: https://discord.gg/pallets diff --git a/artwork/LICENSE b/artwork/LICENSE deleted file mode 100644 index c6df416cde..0000000000 --- a/artwork/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2010 by Armin Ronacher. - -Some rights reserved. - -This logo or a modified version may be used by anyone to refer to the -Flask project, but does not indicate endorsement by the project. - -Redistribution and use in source (the SVG file) and binary forms (rendered -PNG files etc.) of the image, with or without modification, are permitted -provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright - notice and this list of conditions. - -* The names of the contributors to the Flask software (see AUTHORS) may - not be used to endorse or promote products derived from this software - without specific prior written permission. - -Note: we would appreciate that you make the image a link to -http://flask.pocoo.org/ if you use it on a web page. diff --git a/artwork/LICENSE.rst b/artwork/LICENSE.rst new file mode 100644 index 0000000000..605e41cb11 --- /dev/null +++ b/artwork/LICENSE.rst @@ -0,0 +1,19 @@ +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/docs/Makefile b/docs/Makefile index fc19e49d9b..d4bb2cbb9e 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -1,10 +1,10 @@ # Minimal makefile for Sphinx documentation # -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -SPHINXPROJ = Flask +# 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 @@ -17,4 +17,4 @@ help: # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/_static/flask-favicon.ico b/docs/_static/flask-favicon.ico deleted file mode 100644 index bf0a961573..0000000000 Binary files a/docs/_static/flask-favicon.ico and /dev/null differ diff --git a/docs/_static/flask.png b/docs/_static/flask-icon.png similarity index 100% rename from docs/_static/flask.png rename to docs/_static/flask-icon.png diff --git a/docs/_static/logo-full.png b/docs/_static/flask-logo.png similarity index 100% rename from docs/_static/logo-full.png rename to docs/_static/flask-logo.png diff --git a/docs/_static/touch-icon.png b/docs/_static/touch-icon.png deleted file mode 100644 index ef151f15df..0000000000 Binary files a/docs/_static/touch-icon.png and /dev/null differ diff --git a/docs/advanced_foreword.rst b/docs/advanced_foreword.rst index bd56f53ced..9c36158a8d 100644 --- a/docs/advanced_foreword.rst +++ b/docs/advanced_foreword.rst @@ -1,5 +1,3 @@ -.. _advanced_foreword: - Foreword for Experienced Programmers ==================================== @@ -8,10 +6,11 @@ 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 +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 diff --git a/docs/api.rst b/docs/api.rst index ee7eb04185..e686287831 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,5 +1,3 @@ -.. _api: - API === @@ -29,42 +27,9 @@ 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 `IRI - `_. Imagine your application is - listening on the following application root:: - - http://www.example.com/myapplication - - And a user requests the following URI:: - - http://www.example.com/myapplication/%CF%80/page.html?x=y - - In this case the values of the above mentioned attributes would be - the following: - - ============= ====================================================== - `path` ``u'/π/page.html'`` - `full_path` ``u'/π/page.html?x=y'`` - `script_root` ``u'/myapplication'`` - `base_url` ``u'http://www.example.com/myapplication/π/page.html'`` - `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'`` - `url_root` ``u'http://www.example.com/myapplication/'`` - ============= ====================================================== - + :members: + :inherited-members: + :exclude-members: json_module .. attribute:: request @@ -76,29 +41,16 @@ Incoming Request Data 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 -------- @@ -280,58 +232,35 @@ Message Flashing .. autofunction:: get_flashed_messages + JSON Support ------------ .. module:: flask.json -Flask uses ``simplejson`` for the JSON implementation. Since simplejson -is provided by both the standard library as well as extension, Flask will -try simplejson first and then fall back to the stdlib json module. On top -of that it will delegate access to the current application's JSON encoders -and decoders for easier customization. - -So for starters instead of doing:: - - try: - import simplejson as json - except ImportError: - import json - -You can instead just do this:: - - from flask import json - -For usage examples, read the :mod:`json` documentation in the standard -library. The following extensions are by default applied to the stdlib's -JSON module: +Flask uses the built-in :mod:`json` module for handling JSON. It will +use the current blueprint's or application's JSON encoder and decoder +for easier customization. By default it handles some extra data types: -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. +- :class:`datetime.datetime` and :class:`datetime.date` are serialized + to :rfc:`822` strings. This is the same as the HTTP date format. +- :class:`uuid.UUID` is serialized to a string. +- :class:`dataclasses.dataclass` is passed to + :func:`dataclasses.asdict`. +- :class:`~markupsafe.Markup` (or any object with a ``__html__`` + method) will call the ``__html__`` method to get a string. -The :func:`~htmlsafe_dumps` function of this json module is also available -as filter called ``|tojson`` in Jinja2. Note that inside ``script`` -tags no escaping must take place, so make sure to disable escaping -with ``|safe`` if you intend to use it inside ``script`` tags unless -you are using Flask 0.10 which implies that: +Jinja's ``|tojson`` filter is configured to use Flask's :func:`dumps` +function. The filter marks the output with ``|safe`` automatically. Use +the filter to render data inside `` -.. 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 @@ -350,6 +279,7 @@ you are using Flask 0.10 which implies that: .. automodule:: flask.json.tag + Template Rendering ------------------ @@ -511,18 +441,32 @@ 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 @@ -633,7 +577,6 @@ The following signals exist in Flask: .. _blinker: https://pypi.org/project/blinker/ -.. _class-based-views: Class-Based Views ----------------- @@ -726,7 +669,7 @@ requests, make sure the default route only handles ``GET``, as redirects can't preserve form data. :: @app.route('/region/', defaults={'id': 1}) - @app.route('/region/', methods=['GET', 'POST']) + @app.route('/region/', methods=['GET', 'POST']) def region(id): pass @@ -760,7 +703,6 @@ instead of the `view_func` parameter. handling. They have to be specified as keyword arguments. =============== ========================================================== -.. _view-func-options: View Function Options --------------------- diff --git a/docs/appcontext.rst b/docs/appcontext.rst index cdc14d9452..681764941d 100644 --- a/docs/appcontext.rst +++ b/docs/appcontext.rst @@ -1,7 +1,5 @@ .. currentmodule:: flask -.. _app-context: - The Application Context ======================= @@ -49,7 +47,7 @@ Typically, an application context will have the same lifetime as a request. See :doc:`/reqcontext` for more information about how the contexts work -and the full lifecycle of a request. +and the full life cycle of a request. Manually Push a Context @@ -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: @@ -144,7 +142,7 @@ 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`. +:doc:`/extensiondev`. Events and Signals diff --git a/docs/async-await.rst b/docs/async-await.rst new file mode 100644 index 0000000000..34751d47b9 --- /dev/null +++ b/docs/async-await.rst @@ -0,0 +1,119 @@ +.. _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) + +.. 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. + + +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 :ref:`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://gitlab.com/pgjones/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 index 0facbfee90..5e7a88e030 100644 --- a/docs/becomingbig.rst +++ b/docs/becomingbig.rst @@ -1,5 +1,3 @@ -.. _becomingbig: - Becoming Big ============ @@ -20,14 +18,14 @@ 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. +The :doc:`/api` docs are full of available overrides, hook points, and +:doc:`/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 +:doc:`/extensions` in the community, and look for patterns to build your +own extensions if you do not find the tools you need. Subclass. --------- @@ -35,16 +33,17 @@ 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. +application class. This works well with :doc:`/patterns/appfactories`. +See :doc:`/patterns/subclassing` for an example. Wrap with middleware. --------------------- -The :ref:`app-dispatch` chapter shows in detail how to apply middleware. You +The :doc:`/patterns/appdispatch` pattern 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. ----- @@ -96,6 +95,6 @@ Discuss with the community. The Flask developers keep the framework accessible to users with codebases big and small. If you find an obstacle in your way, caused by Flask, don't hesitate -to contact the developers on the mailinglist or IRC channel. The best way for +to contact the developers on the mailing list or Discord server. 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 3d670b99e4..6e8217abc9 100644 --- a/docs/blueprints.rst +++ b/docs/blueprints.rst @@ -1,5 +1,3 @@ -.. _blueprints: - Modular Applications with Blueprints ==================================== @@ -37,8 +35,9 @@ Blueprints in Flask are intended for these cases: A blueprint in Flask is not a pluggable app because it is not actually an application -- it's a set of operations which can be registered on an application, even multiple times. Why not have multiple application -objects? You can do that (see :ref:`app-dispatch`), but your applications -will have separate configs and will be managed at the WSGI layer. +objects? You can do that (see :doc:`/patterns/appdispatch`), but your +applications will have separate configs and will be managed at the WSGI +layer. Blueprints instead provide separation at the Flask level, share application config, and can change an application object as necessary with @@ -70,16 +69,17 @@ implement a blueprint that does simple rendering of static templates:: @simple_page.route('/') def show(page): try: - return render_template('pages/%s.html' % page) + return render_template(f'pages/{page}.html') except TemplateNotFound: abort(404) When you bind a function with the help of the ``@simple_page.route`` -decorator the blueprint will record the intention of registering the -function `show` on the application when it's later registered. +decorator, the blueprint will record the intention of registering the +function ``show`` on the application when it's later registered. Additionally it will prefix the endpoint of the function with the name of the blueprint which was given to the :class:`Blueprint` -constructor (in this case also ``simple_page``). +constructor (in this case also ``simple_page``). The blueprint's name +does not modify the URL, only the endpoint. Registering Blueprints ---------------------- @@ -120,6 +120,31 @@ 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 + +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 ------------------- @@ -242,10 +267,11 @@ you can use relative redirects by prefixing the endpoint with a dot only:: This will link to ``admin.index`` for instance in case the current request was dispatched to any other admin blueprint endpoint. -Error Handlers --------------- -Blueprints support the errorhandler decorator just like the :class:`Flask` +Blueprint Error Handlers +------------------------ + +Blueprints support the ``errorhandler`` decorator just like the :class:`Flask` application object, so it is easy to make Blueprint-specific custom error pages. @@ -260,7 +286,7 @@ concerning handlers for 404 and 405 exceptions. These errorhandlers are only invoked from an appropriate ``raise`` statement or a call to ``abort`` in another of the blueprint's view functions; they are not invoked by, e.g., an invalid URL access. This is because the blueprint does not "own" a certain URL space, so -the application instance has no way of knowing which blueprint errorhandler it +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:: @@ -269,8 +295,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 62% rename from docs/changelog.rst rename to docs/changes.rst index d9e113ec68..955deaf27b 100644 --- a/docs/changelog.rst +++ b/docs/changes.rst @@ -1 +1,4 @@ +Changes +======= + .. include:: ../CHANGES.rst diff --git a/docs/cli.rst b/docs/cli.rst index d8bb39c186..6036cb2d84 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -1,7 +1,5 @@ .. currentmodule:: flask -.. _cli: - Command Line Interface ====================== @@ -10,7 +8,7 @@ interface, in your virtualenv. Executed from the terminal, this script gives access to built-in, extension, and application-defined commands. The ``--help`` option will give more information about any commands and options. -.. _Click: http://click.pocoo.org/ +.. _Click: https://click.palletsprojects.com/ Application Discovery @@ -20,32 +18,40 @@ 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.):: +.. tabs:: - $ export FLASK_APP=hello - $ flask run + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_APP=hello + $ flask run + + .. group-tab:: CMD -Windows CMD:: + .. code-block:: text - > set FLASK_APP=hello - > flask run + > set FLASK_APP=hello + > flask run -Windows PowerShell:: + .. group-tab:: Powershell - > $env:FLASK_APP = "hello" - > flask run + .. code-block:: text + + > $env:FLASK_APP = "hello" + > flask run While ``FLASK_APP`` supports a variety of options for specifying your application, most use cases should be simple. Here are the typical values: (nothing) - The file :file:`wsgi.py` is imported, automatically detecting an app - (``app``). This provides an easy way to create an app from a factory with - extra arguments. + 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``). + The given name is imported, automatically detecting an app (``app`` + or ``application``) or factory (``create_app`` or ``make_app``). ---- @@ -68,21 +74,17 @@ parts: The ``create_app`` factory in ``hello`` is called with the string ``'dev'`` as the argument. -If ``FLASK_APP`` is not set, the command will look for a file called -:file:`wsgi.py` or :file:`app.py` and try to detect an application instance or -factory. +If ``FLASK_APP`` is not set, the command will try to import "app" or +"wsgi" (as a ".py" file, or package) and try to detect an application +instance or factory. Within the given import, the command looks for an application instance named ``app`` or ``application``, then any application instance. If no instance is found, the command looks for a factory function named ``create_app`` or ``make_app`` that returns an instance. -When calling an application factory, if the factory takes an argument named -``script_info``, then the :class:`~cli.ScriptInfo` instance is passed as a -keyword argument. If the application factory takes only one argument and no -parentheses follow the factory name, the :class:`~cli.ScriptInfo` instance -is passed as a positional argument. If parentheses follow the factory name, -their contents are parsed as Python literals and passes as arguments to the +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. @@ -99,7 +101,7 @@ replaces the :meth:`Flask.run` method in most cases. :: .. 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. Open a Shell @@ -134,16 +136,94 @@ If the env is set to ``development``, the ``flask`` command will enable debug mode and ``flask run`` will enable the interactive debugger and reloader. -:: +.. tabs:: - $ 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 + .. group-tab:: Bash + + .. code-block:: text + + $ export 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 + + .. group-tab:: CMD + + .. code-block:: text + + > set 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 + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_ENV = "development" + > flask run + * Serving Flask app "hello" + * Environment: development + * Debug mode: on + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) + * Restarting with inotify reloader + * Debugger is active! + * Debugger PIN: 223-456-919 + + +Watch Extra Files with the Reloader +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When using development mode, the reloader will trigger whenever your +Python code or imported modules change. The reloader can watch +additional files with the ``--extra-files`` option, or the +``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are +separated with ``:``, or ``;`` on Windows. + +.. tabs:: + + .. group-tab:: Bash + + .. 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 + + .. group-tab:: CMD + + .. code-block:: text + + > flask run --extra-files file1:dirA/file2:dirB/ + # or + > set 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 + + .. group-tab:: Powershell + + .. code-block:: text + + > flask run --extra-files file1:dirA/file2:dirB/ + # or + > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/" + > flask run + * Running on http://127.0.0.1:8000/ + * Detected change in '/path/to/file1', reloading Debug Mode @@ -193,11 +273,31 @@ 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:: none +.. 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:: 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. @@ -209,9 +309,9 @@ Disable dotenv The ``flask`` command will show a message if it detects dotenv files but python-dotenv is not installed. -.. code-block:: none +.. code-block:: bash - flask run + $ flask run * Tip: There are .env files present. Do "pip install python-dotenv" to use them. You can tell Flask not to load dotenv files even when python-dotenv is @@ -221,10 +321,28 @@ 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:: none +.. tabs:: - export FLASK_SKIP_DOTENV=1 - flask run + .. group-tab:: Bash + + .. code-block:: text + + $ export 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 @@ -234,13 +352,25 @@ 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 + $ export FLASK_APP=hello -Windows CMD, :file:`venv\\Scripts\\activate.bat`:: + .. group-tab:: CMD - set FLASK_APP=hello + Windows CMD, :file:`venv\\Scripts\\activate.bat`:: + + > set FLASK_APP=hello + + .. group-tab:: Powershell + + Windows Powershell, :file:`venv\\Scripts\\activate.ps1`:: + + > $env:FLASK_APP = "hello" It is preferred to use dotenv support over this, since :file:`.flaskenv` can be committed to the repository so that it works automatically wherever the project @@ -253,7 +383,7 @@ Custom Commands The ``flask`` command is implemented using `Click`_. See that project's documentation for full information about writing commands. -This example adds the command ``create_user`` that takes the argument +This example adds the command ``create-user`` that takes the argument ``name``. :: import click @@ -261,14 +391,14 @@ This example adds the command ``create_user`` that takes the argument app = Flask(__name__) - @app.cli.command() - @click.argument('name') + @app.cli.command("create-user") + @click.argument("name") def create_user(name): ... :: - flask create_user admin + $ flask create-user admin This example adds the same command, but as ``user create``, a command in a group. This is useful if you want to organize multiple related commands. :: @@ -289,12 +419,67 @@ group. This is useful if you want to organize multiple related commands. :: :: - flask user create demo + $ flask user create demo See :ref:`testing-cli` for an overview of how to test your custom commands. +Registering Commands with Blueprints +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your application uses blueprints, you can optionally register CLI +commands directly onto them. When your blueprint is registered onto your +application, the associated commands will be available to the ``flask`` +command. By default, those commands will be nested in a group matching +the name of the blueprint. + +.. code-block:: python + + from flask import Blueprint + + bp = Blueprint('students', __name__) + + @bp.cli.command('create') + @click.argument('name') + def create(name): + ... + + app.register_blueprint(bp) + +.. code-block:: text + + $ flask students create alice + +You can alter the group name by specifying the ``cli_group`` parameter +when creating the :class:`Blueprint` object, or later with +:meth:`app.register_blueprint(bp, cli_group='...') `. +The following are equivalent: + +.. code-block:: python + + bp = Blueprint('students', __name__, cli_group='other') + # or + app.register_blueprint(bp, cli_group='other') + +.. code-block:: text + + $ flask other create alice + +Specifying ``cli_group=None`` will remove the nesting and merge the +commands directly to the application's level: + +.. code-block:: python + + bp = Blueprint('students', __name__, cli_group=None) + # or + app.register_blueprint(bp, cli_group=None) + +.. code-block:: text + + $ flask create alice + + Application Context ~~~~~~~~~~~~~~~~~~~ @@ -308,7 +493,7 @@ decorator instead of the Flask decorator, you can use import click from flask.cli import with_appcontext - @click.command + @click.command() @with_appcontext def do_work(): ... @@ -342,7 +527,7 @@ they are installed. Entry points are specified in :file:`setup.py` :: ) -.. _entry point: https://packaging.python.org/tutorials/distributing-packages/#entry-points +.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points Inside :file:`flask_my_extension/commands.py` you can then export a Click object:: @@ -411,16 +596,16 @@ script is available. Note that you don't need to set ``FLASK_APP``. :: The ``flask`` command, being separate from your code, does not have this issue and is recommended in most cases. -.. _console script: https://packaging.python.org/tutorials/distributing-packages/#console-scripts +.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts PyCharm Integration ------------------- -Prior to PyCharm 2018.1, the Flask CLI features weren't yet fully -integrated into PyCharm. We have to do a few tweaks to get them working -smoothly. These instructions should be similar for any other IDE you -might want to use. +PyCharm Professional provides a special Flask run configuration. For +the Community Edition, we need to configure it to call the ``flask run`` +CLI command with the correct environment variables. These instructions +should be similar for any other IDE you might want to use. In PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit Configurations*. You'll be greeted by a screen similar to @@ -429,7 +614,7 @@ this: .. image:: _static/pycharm-runconfig.png :align: center :class: screenshot - :alt: screenshot of pycharm's run configuration settings + :alt: Screenshot of PyCharms'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 @@ -437,9 +622,9 @@ 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. +the configuration a name such as "flask run". For the ``flask run`` +command, check "Single instance only" since you can't run the server +more than once at the same time. Select *Module name* from the dropdown (**A**) then input ``flask``. @@ -450,7 +635,8 @@ the development server. You can skip this next step if you're using :ref:`dotenv`. We need to add an environment variable (**C**) to identify our application. Click on the browse button and add an entry with ``FLASK_APP`` on the left and -the Python import or file on the right (``hello`` for example). +the Python import or file on the right (``hello`` for example). Add an +entry with ``FLASK_ENV`` and set it to ``development``. Next we need to set the working directory (**D**) to be the folder where our application resides. diff --git a/docs/conf.py b/docs/conf.py index 041724417a..b26ba8cb7c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,168 +1,93 @@ -# -*- coding: utf-8 -*- -from __future__ import print_function - -import inspect -import re - -from pallets_sphinx_themes import DocVersion, ProjectLink, get_version +import packaging.version +from pallets_sphinx_themes import get_version +from pallets_sphinx_themes import ProjectLink # Project -------------------------------------------------------------- -project = 'Flask' -copyright = '2010 Pallets Team' -author = 'Pallets Team' -release, version = get_version('Flask') +project = "Flask" +copyright = "2010 Pallets" +author = "Pallets" +release, version = get_version("Flask") # General -------------------------------------------------------------- -master_doc = 'index' - +master_doc = "index" extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinxcontrib.log_cabinet', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinxcontrib.log_cabinet", + "pallets_sphinx_themes", + "sphinx_issues", + "sphinx_tabs.tabs", ] - +autodoc_typehints = "description" intersphinx_mapping = { - 'python': ('https://docs.python.org/3/', None), - 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None), - 'click': ('http://click.pocoo.org/', None), - 'jinja': ('http://jinja.pocoo.org/docs/', None), - 'itsdangerous': ('https://pythonhosted.org/itsdangerous', None), - 'sqlalchemy': ('https://docs.sqlalchemy.org/en/latest/', None), - 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None), - 'blinker': ('https://pythonhosted.org/blinker/', None), + "python": ("https://docs.python.org/3/", None), + "werkzeug": ("https://werkzeug.palletsprojects.com/", None), + "click": ("https://click.palletsprojects.com/", None), + "jinja": ("https://jinja.palletsprojects.com/", None), + "itsdangerous": ("https://itsdangerous.palletsprojects.com/", None), + "sqlalchemy": ("https://docs.sqlalchemy.org/", None), + "wtforms": ("https://wtforms.readthedocs.io/", None), + "blinker": ("https://pythonhosted.org/blinker/", None), } +issues_github_path = "pallets/flask" # HTML ----------------------------------------------------------------- -html_theme = 'flask' +html_theme = "flask" +html_theme_options = {"index_sidebar_logo": False} html_context = { - 'project_links': [ - ProjectLink('Donate to Pallets', 'https://psfmember.org/civicrm/contribute/transact?reset=1&id=20'), - ProjectLink('Flask Website', 'https://palletsprojects.com/p/flask/'), - ProjectLink('PyPI releases', 'https://pypi.org/project/Flask/'), - ProjectLink('Source Code', 'https://github.com/pallets/flask/'), - ProjectLink( - 'Issue Tracker', 'https://github.com/pallets/flask/issues/'), - ], - 'versions': [ - DocVersion('dev', 'Development', 'unstable'), - DocVersion('1.0', 'Flask 1.0', 'stable'), - DocVersion('0.12', 'Flask 0.12'), - ], - 'canonical_url': 'http://flask.pocoo.org/docs/{}/'.format(version), - 'carbon_ads_args': 'zoneid=1673&serve=C6AILKT&placement=pocooorg', -} -html_sidebars = { - 'index': [ - 'project.html', - 'versions.html', - 'carbon_ads.html', - 'searchbox.html', - ], - '**': [ - 'localtoc.html', - 'relations.html', - 'versions.html', - 'carbon_ads.html', - 'searchbox.html', + "project_links": [ + ProjectLink("Donate", "https://palletsprojects.com/donate"), + ProjectLink("PyPI Releases", "https://pypi.org/project/Flask/"), + ProjectLink("Source Code", "https://github.com/pallets/flask/"), + ProjectLink("Issue Tracker", "https://github.com/pallets/flask/issues/"), + ProjectLink("Website", "https://palletsprojects.com/p/flask/"), + ProjectLink("Twitter", "https://twitter.com/PalletsTeam"), + ProjectLink("Chat", "https://discord.gg/pallets"), ] } -html_static_path = ['_static'] -html_favicon = '_static/flask-favicon.ico' -html_logo = '_static/flask.png' -html_additional_pages = { - '404': '404.html', +html_sidebars = { + "index": ["project.html", "localtoc.html", "searchbox.html"], + "**": ["localtoc.html", "relations.html", "searchbox.html"], } +singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]} +html_static_path = ["_static"] +html_favicon = "_static/flask-icon.png" +html_logo = "_static/flask-icon.png" +html_title = f"Flask Documentation ({version})" html_show_sourcelink = False # LaTeX ---------------------------------------------------------------- -latex_documents = [ - (master_doc, 'Flask.tex', 'Flask Documentation', 'Pallets Team', 'manual'), -] -latex_use_modindex = False -latex_elements = { - 'papersize': 'a4paper', - 'pointsize': '12pt', - 'fontpkg': r'\usepackage{mathpazo}', - 'preamble': r'\usepackage{flaskstyle}', -} -latex_use_parts = True -latex_additional_files = ['flaskstyle.sty', 'logo.pdf'] - -# linkcheck ------------------------------------------------------------ - -linkcheck_anchors = False +latex_documents = [(master_doc, f"Flask-{version}.tex", html_title, author, "manual")] # Local Extensions ----------------------------------------------------- -def unwrap_decorators(): - import sphinx.util.inspect as inspect - import functools - - old_getargspec = inspect.getargspec - def getargspec(x): - return old_getargspec(getattr(x, '_original_function', x)) - inspect.getargspec = getargspec - - old_update_wrapper = functools.update_wrapper - def update_wrapper(wrapper, wrapped, *a, **kw): - rv = old_update_wrapper(wrapper, wrapped, *a, **kw) - rv._original_function = wrapped - return rv - functools.update_wrapper = update_wrapper - -unwrap_decorators() -del unwrap_decorators - - -_internal_mark_re = re.compile(r'^\s*:internal:\s*$(?m)', re.M) - - -def skip_internal(app, what, name, obj, skip, options): - docstring = inspect.getdoc(obj) or '' - - if skip or _internal_mark_re.search(docstring) is not None: - return True - - -def cut_module_meta(app, what, name, obj, options, lines): - """Remove metadata from autodoc output.""" - if what != 'module': - return - - lines[:] = [ - line for line in lines - if not line.startswith((':copyright:', ':license:')) - ] - - -def github_link( - name, rawtext, text, lineno, inliner, options=None, content=None -): +def github_link(name, rawtext, text, lineno, inliner, options=None, content=None): app = inliner.document.settings.env.app release = app.config.release - base_url = 'https://github.com/pallets/flask/tree/' + base_url = "https://github.com/pallets/flask/tree/" - if text.endswith('>'): - words, text = text[:-1].rsplit('<', 1) + if text.endswith(">"): + words, text = text[:-1].rsplit("<", 1) words = words.strip() else: words = None - if release.endswith('dev'): - url = '{0}master/{1}'.format(base_url, text) + if packaging.version.parse(release).is_devrelease: + url = f"{base_url}master/{text}" else: - url = '{0}{1}/{2}'.format(base_url, release, text) + url = f"{base_url}{release}/{text}" if words is None: words = url from docutils.nodes import reference from docutils.parsers.rst.roles import set_classes + options = options or {} set_classes(options) node = reference(rawtext, words, refuri=url, **options) @@ -170,6 +95,4 @@ def github_link( def setup(app): - app.connect('autodoc-skip-member', skip_internal) - app.connect('autodoc-process-docstring', cut_module_meta) - app.add_role('gh', github_link) + app.add_role("gh", github_link) diff --git a/docs/config.rst b/docs/config.rst index c2958bf715..768cf60d88 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -1,5 +1,3 @@ -.. _config: - Configuration Handling ====================== @@ -9,7 +7,7 @@ toggling the debug mode, setting the secret key, and other such environment-specific things. The way Flask is designed usually requires the configuration to be -available when the application starts up. You can hardcode the +available when the application starts up. You can hard code the configuration in the code, which for many small applications is not actually that bad, but there are better ways. @@ -67,12 +65,30 @@ in debug mode. To control this separately from the environment, use the from debug mode. The development environment enables debug mode. To switch Flask to the development environment and enable debug mode, -set :envvar:`FLASK_ENV`:: +set :envvar:`FLASK_ENV`: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_ENV=development + $ flask run + + .. group-tab:: CMD + + .. code-block:: text - $ export FLASK_ENV=development - $ flask run + > set FLASK_ENV=development + > flask run -(On Windows, use ``set`` instead of ``export``.) + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_ENV = "development" + > flask run Using the environment variables as described above is recommended. While it is possible to set :data:`ENV` and :data:`DEBUG` in your config or @@ -161,10 +177,10 @@ 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))' + $ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/' **Do not reveal the secret key when posting questions or committing code.** @@ -249,11 +265,16 @@ 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. - Default: ``timedelta(hours=12)`` (``43200`` seconds) + If ``None``, ``send_file`` tells the browser to use conditional + requests will be used instead of a timed cache, which is usually + preferable. + + Default: ``None`` .. py:data:: SERVER_NAME @@ -276,7 +297,10 @@ The following configuration values are used internally by Flask: .. py:data:: APPLICATION_ROOT Inform the application what path it is mounted under by the application / - web server. + web server. This is used for generating URLs outside the context of a + request (inside a request, the dispatcher is responsible for setting + ``SCRIPT_NAME`` instead; see :doc:`/patterns/appdispatch` + for examples of dispatch configuration). Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not set. @@ -299,10 +323,10 @@ The following configuration values are used internally by Flask: .. 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 in - to JavaScript in templates, and should typically remain enabled. + Serialize objects to ASCII-encoded JSON. If this is disabled, the + JSON returned from ``jsonify`` will contain Unicode characters. This + has security implications when rendering the JSON into JavaScript in + templates, and should typically remain enabled. Default: ``True`` @@ -379,7 +403,7 @@ The following configuration values are used internally by Flask: .. versionchanged:: 1.0 ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See - :ref:`logging` for information about configuration. + :doc:`/logging` for information about configuration. Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment variable. @@ -390,13 +414,13 @@ The following configuration values are used internally by Flask: Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug. -Configuring from Files ----------------------- +Configuring from Python Files +----------------------------- Configuration becomes more useful if you can store it in a separate file, ideally located outside the actual application package. This makes packaging and distributing your application possible via various package -handling tools (:ref:`distribute-deployment`) and finally modifying the +handling tools (:doc:`/patterns/distribute`) and finally modifying the configuration file afterwards. So a common pattern is this:: @@ -408,18 +432,34 @@ 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 - $ python run-app.py - * Running on http://127.0.0.1:5000/ - * Restarting with reloader... + $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg + $ flask run + * Running on http://127.0.0.1:5000/ -On Windows systems use the `set` builtin instead:: + .. group-tab:: CMD - >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg + .. code-block:: text + + > set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg + > flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:YOURAPPLICATION_SETTINGS = "\path\to\settings.cfg" + > flask run + * Running on http://127.0.0.1:5000/ The configuration files themselves are actual Python files. Only values in uppercase are actually stored in the config object later on. So make @@ -428,7 +468,6 @@ sure to use uppercase letters for your config keys. Here is an example of a configuration file:: # Example configuration - DEBUG = False SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/' Make sure to load the configuration very early on, so that extensions have @@ -437,6 +476,27 @@ methods on the config object as well to load from individual files. For a complete reference, read the :class:`~flask.Config` object's documentation. + +Configuring from 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 -------------------------------------- @@ -444,19 +504,36 @@ In addition to pointing to configuration files using environment variables, you may find it useful (or necessary) to control your configuration values directly from the environment. -Environment variables can be set on Linux or OS X with the export command in -the shell before starting the server:: +Environment variables can be set in the shell before starting the server: - $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f' - $ export DEBUG=False - $ python run-app.py - * Running on http://127.0.0.1:5000/ - * Restarting with reloader... +.. tabs:: -On Windows systems use the `set` builtin instead:: + .. group-tab:: Bash - >set SECRET_KEY='5f352379324c22463451387a0aec5d2f' - >set DEBUG=False + .. code-block:: text + + $ export SECRET_KEY="5f352379324c22463451387a0aec5d2f" + $ export MAIL_ENABLED=false + $ flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: CMD + + .. code-block:: text + + > set SECRET_KEY="5f352379324c22463451387a0aec5d2f" + > set MAIL_ENABLED=false + > flask run + * Running on http://127.0.0.1:5000/ + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:SECRET_KEY = "5f352379324c22463451387a0aec5d2f" + > $env:MAIL_ENABLED = "false" + > flask run + * Running on http://127.0.0.1:5000/ While this approach is straightforward to use, it is important to remember that environment variables are strings -- they are not automatically deserialized @@ -464,17 +541,15 @@ into Python types. Here is an example of a configuration file that uses environment variables:: - # Example configuration import os - ENVIRONMENT_DEBUG = os.environ.get("DEBUG", default=False) - if ENVIRONMENT_DEBUG.lower() in ("f", "false"): - ENVIRONMENT_DEBUG = False + _mail_enabled = os.environ.get("MAIL_ENABLED", default="true") + MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"} + + SECRET_KEY = os.environ.get("SECRET_KEY") - DEBUG = ENVIRONMENT_DEBUG - SECRET_KEY = os.environ.get("SECRET_KEY", default=None) if not SECRET_KEY: - raise ValueError("No secret key set for Flask application") + raise ValueError("No SECRET_KEY set for Flask application") Notice that any value besides an empty string will be interpreted as a boolean @@ -486,6 +561,7 @@ ability to access the configuration when starting up. There are other methods on the config object as well to load from individual files. For a complete reference, read the :class:`~flask.Config` class documentation. + Configuration Best Practices ---------------------------- @@ -496,7 +572,7 @@ that experience: 1. Create your application in a function and register blueprints on it. That way you can create multiple instances of your application with - different configurations attached which makes unittesting a lot + different configurations attached which makes unit testing a lot easier. You can use this to pass in configuration as needed. 2. Do not write code that needs the configuration at import time. If you @@ -529,23 +605,22 @@ the config file by adding ``from yourapplication.default_settings import *`` to the top of the file and then overriding the changes by hand. You could also inspect an environment variable like ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc -and import different hardcoded files based on that. +and import different hard-coded files based on that. An interesting pattern is also to use classes and inheritance for configuration:: class Config(object): - DEBUG = False TESTING = False - DATABASE_URI = 'sqlite:///:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): - DEBUG = True + DATABASE_URI = "sqlite:////tmp/foo.db" class TestingConfig(Config): + DATABASE_URI = 'sqlite:///:memory:' TESTING = True To enable such a config you just have to call into @@ -553,6 +628,41 @@ To enable such a config you just have to call into app.config.from_object('configmodule.ProductionConfig') +Note that :meth:`~flask.Config.from_object` does not instantiate the class +object. If you need to instantiate the class, such as to access a property, +then you must do so before calling :meth:`~flask.Config.from_object`:: + + from configmodule import ProductionConfig + app.config.from_object(ProductionConfig()) + + # Alternatively, import via string: + from werkzeug.utils import import_string + cfg = import_string('configmodule.ProductionConfig')() + app.config.from_object(cfg) + +Instantiating the configuration object allows you to use ``@property`` in +your configuration classes:: + + class Config(object): + """Base config, uses staging database server.""" + TESTING = False + DB_SERVER = '192.168.1.56' + + @property + def DATABASE_URI(self): # Note: all caps + return f"mysql://user@{self.DB_SERVER}/foo" + + class ProductionConfig(Config): + """Uses production database server.""" + DB_SERVER = '192.168.19.32' + + class DevelopmentConfig(Config): + DB_SERVER = 'localhost' + + class TestingConfig(Config): + DB_SERVER = 'localhost' + DATABASE_URI = 'sqlite:///:memory:' + There are many different ways and it's up to you how you want to manage your configuration files. However here a list of good recommendations: @@ -569,9 +679,9 @@ your configuration files. However here a list of good recommendations: - 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. + :doc:`/patterns/fabric` pattern. -.. _fabric: http://www.fabfile.org/ +.. _fabric: https://www.fabfile.org/ .. _instance-folders: @@ -619,7 +729,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 @@ -636,7 +746,7 @@ root” (the default) to “relative to instance folder” via the app = Flask(__name__, instance_relative_config=True) Here is a full example of how to configure Flask to preload the config -from a module and then override the config from a file in the config +from a module and then override the config from a file in the instance folder if it exists:: app = Flask(__name__, instance_relative_config=True) diff --git a/docs/contents.rst.inc b/docs/contents.rst.inc deleted file mode 100644 index f76b1591cd..0000000000 --- a/docs/contents.rst.inc +++ /dev/null @@ -1,62 +0,0 @@ -User's Guide ------------- - -This part of the documentation, which is mostly prose, begins with some -background information about Flask, then focuses on step-by-step -instructions for web development with Flask. - -.. toctree:: - :maxdepth: 2 - - foreword - advanced_foreword - installation - quickstart - tutorial/index - templating - testing - errorhandling - logging - config - signals - views - appcontext - reqcontext - blueprints - extensions - cli - server - shell - patterns/index - deploying/index - becomingbig - -API Reference -------------- - -If you are looking for information on a specific function, class or -method, this part of the documentation is for you. - -.. toctree:: - :maxdepth: 2 - - api - -Additional Notes ----------------- - -Design notes, legal information and changelog are here for the interested. - -.. toctree:: - :maxdepth: 2 - - design - htmlfaq - security - unicode - extensiondev - styleguide - upgrading - changelog - license - contributing diff --git a/docs/debugging.rst b/docs/debugging.rst new file mode 100644 index 0000000000..a9f984b44f --- /dev/null +++ b/docs/debugging.rst @@ -0,0 +1,133 @@ +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. + +To enable the debugger, run the development server with the +``FLASK_ENV`` environment variable set to ``development``. This puts +Flask in debug mode, which changes how it handles some errors, and +enables the debugger and reloader. + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_ENV=development + $ flask run + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_ENV=development + > flask run + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_ENV = "development" + > flask run + +``FLASK_ENV`` can only be set as an environment variable. When running +from Python code, passing ``debug=True`` enables debug mode, which is +mostly equivalent. Debug mode can be controled separately from +``FLASK_ENV`` with the ``FLASK_DEBUG`` environment variable as well. + +.. code-block:: python + + app.run(debug=True) + +:doc:`/server` and :doc:`/cli` have more information about running the +debugger, debug mode, and development 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, +but it can be useful to disable the built-in debugger and reloader, +which can interfere. + +When running from the command line: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_ENV=development + $ flask run --no-debugger --no-reload + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_ENV=development + > flask run --no-debugger --no-reload + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_ENV = "development" + > flask run --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 debugging. diff --git a/docs/deploying/asgi.rst b/docs/deploying/asgi.rst new file mode 100644 index 0000000000..c7e04027ac --- /dev/null +++ b/docs/deploying/asgi.rst @@ -0,0 +1,29 @@ +.. _asgi: + +ASGI +==== + +If you'd like to use an ASGI server you will need to utilise WSGI to +ASGI middleware. The asgiref +[WsgiToAsgi](https://github.com/django/asgiref#wsgi-to-asgi-adapter) +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 index 503d942617..4c1cdfbf0f 100644 --- a/docs/deploying/cgi.rst +++ b/docs/deploying/cgi.rst @@ -46,9 +46,9 @@ In Apache for example you can put something like this into the config: 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: +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 @@ -58,4 +58,4 @@ work in that case: For more information consult the documentation of your webserver. -.. _App Engine: https://developers.google.com/appengine/ +.. _App Engine: https://cloud.google.com/appengine/docs/ diff --git a/docs/deploying/fastcgi.rst b/docs/deploying/fastcgi.rst index 26d181a50d..ef2201c86b 100644 --- a/docs/deploying/fastcgi.rst +++ b/docs/deploying/fastcgi.rst @@ -1,13 +1,11 @@ -.. _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. +`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 @@ -49,7 +47,7 @@ can execute it: .. sourcecode:: text - # chmod +x /var/www/yourapplication/yourapplication.fcgi + $ chmod +x /var/www/yourapplication/yourapplication.fcgi Configuring Apache ------------------ diff --git a/docs/deploying/index.rst b/docs/deploying/index.rst index edf5a256da..4511bf4538 100644 --- a/docs/deploying/index.rst +++ b/docs/deploying/index.rst @@ -1,5 +1,3 @@ -.. _deployment: - Deployment Options ================== @@ -17,12 +15,9 @@ Hosted options -------------- - `Deploying Flask on Heroku `_ -- `Deploying Flask on OpenShift `_ -- `Deploying Flask on Webfaction `_ -- `Deploying Flask on Google App Engine `_ +- `Deploying Flask on Google App Engine `_ - `Deploying Flask on AWS Elastic Beanstalk `_ -- `Sharing your Localhost Server with Localtunnel `_ -- `Deploying on Azure (IIS) `_ +- `Deploying on Azure (IIS) `_ - `Deploying on PythonAnywhere `_ Self-hosted options @@ -36,3 +31,4 @@ Self-hosted options mod_wsgi fastcgi cgi + asgi diff --git a/docs/deploying/mod_wsgi.rst b/docs/deploying/mod_wsgi.rst index c9da6a2d38..801dfa5c1f 100644 --- a/docs/deploying/mod_wsgi.rst +++ b/docs/deploying/mod_wsgi.rst @@ -1,5 +1,3 @@ -.. _mod_wsgi-deployment: - mod_wsgi (Apache) ================= @@ -27,21 +25,21 @@ follows: .. sourcecode:: text - # apt-get install libapache2-mod-wsgi + $ apt-get install libapache2-mod-wsgi-py3 If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you can install it as follows: .. sourcecode:: text - # yum install mod_wsgi + $ yum install mod_wsgi On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by using pkg_add: .. sourcecode:: text - # pkg install ap22-mod_wsgi2 + $ pkg install ap24-py37-mod_wsgi If you are using pkgsrc you can install `mod_wsgi` by compiling the `www/ap2-wsgi` package. @@ -52,15 +50,20 @@ reload you can safely ignore them. Just restart the server. Creating a `.wsgi` file ----------------------- -To run your application you need a :file:`yourapplication.wsgi` file. This file -contains the code `mod_wsgi` is executing on startup to get the application -object. The object called `application` in that file is then used as -application. +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`. @@ -103,16 +106,17 @@ refuse to run with the above configuration. On a Windows system, eliminate those .. sourcecode:: apache - - ServerName example.com - WSGIScriptAlias / C:\yourdir\yourapp.wsgi - - Order deny,allow - Allow from all - - + + 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`_. +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 @@ -204,11 +208,6 @@ you have to modify your ``.wsgi`` file slightly. Add the following lines to the top of your ``.wsgi`` file:: - activate_this = '/path/to/env/bin/activate_this.py' - execfile(activate_this, dict(__file__=activate_this)) - -For Python 3 add the following lines to the top of your ``.wsgi`` file:: - activate_this = '/path/to/env/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) diff --git a/docs/deploying/uwsgi.rst b/docs/deploying/uwsgi.rst index d0501a3588..22930d7bd4 100644 --- a/docs/deploying/uwsgi.rst +++ b/docs/deploying/uwsgi.rst @@ -1,5 +1,3 @@ -.. _deploying-uwsgi: - uWSGI ===== @@ -31,10 +29,11 @@ Given a flask application in myapp.py, use the following command: $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app -The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` to uwsgi, -since it is smarter about that. It is used together with the ``--mount`` -directive which will make requests to ``/yourapplication`` be directed to -``myapp:app``. If your application is accessible at root level, you can use a +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 @@ -69,4 +68,4 @@ to have it in the URL root its a bit simpler:: .. _nginx: https://nginx.org/ .. _lighttpd: https://www.lighttpd.net/ .. _cherokee: http://cherokee-project.com/ -.. _uwsgi: http://projects.unbit.it/uwsgi/ +.. _uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/ diff --git a/docs/deploying/wsgi-standalone.rst b/docs/deploying/wsgi-standalone.rst index aeff9f0fb5..1339a6257b 100644 --- a/docs/deploying/wsgi-standalone.rst +++ b/docs/deploying/wsgi-standalone.rst @@ -1,5 +1,3 @@ -.. _deploying-wsgi-standalone: - Standalone WSGI Containers ========================== @@ -15,17 +13,23 @@ Gunicorn 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 myproject:app `Gunicorn`_ provides many command-line options -- see ``gunicorn -h``. For example, to run a Flask application with 4 worker processes (``-w 4``) binding to localhost port 4000 (``-b 127.0.0.1:4000``):: - gunicorn -w 4 -b 127.0.0.1:4000 myproject:app + $ gunicorn -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/ -.. _Gunicorn: http://gunicorn.org/ -.. _eventlet: http://eventlet.net/ -.. _greenlet: https://greenlet.readthedocs.io/en/latest/ uWSGI -------- @@ -35,12 +39,12 @@ which makes it more complicated to setup than gunicorn. Running `uWSGI HTTP Router`_:: - uwsgi --http 127.0.0.1:5000 --module myproject:app + $ uwsgi --http 127.0.0.1:5000 --module myproject:app For a more optimized setup, see :doc:`configuring uWSGI and NGINX `. -.. _uWSGI: http://uwsgi-docs.readthedocs.io/en/latest/ -.. _uWSGI HTTP Router: http://uwsgi-docs.readthedocs.io/en/latest/HTTP.html#the-uwsgi-http-https-router +.. _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 ------- @@ -67,7 +71,7 @@ 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 + $ twistd web --wsgi myproject.app This example will run a Flask application called ``app`` from a module named ``myproject``. @@ -77,9 +81,9 @@ 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 + $ twistd -n web --port tcp:8080 --wsgi myproject.app -.. _Twisted: https://twistedmatrix.com/ +.. _Twisted: https://twistedmatrix.com/trac/ .. _Twisted Web: https://twistedmatrix.com/trac/wiki/TwistedWeb .. _deploying-proxy-setups: @@ -123,8 +127,8 @@ If your httpd is not providing these headers, the most common setup invokes the host being set from ``X-Forwarded-Host`` and the remote address from ``X-Forwarded-For``:: - from werkzeug.contrib.fixers import ProxyFix - app.wsgi_app = ProxyFix(app.wsgi_app) + from werkzeug.middleware.proxy_fix import ProxyFix + app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1) .. admonition:: Trusting Headers diff --git a/docs/design.rst b/docs/design.rst index f0f7126d09..5d57063e20 100644 --- a/docs/design.rst +++ b/docs/design.rst @@ -1,5 +1,3 @@ -.. _design: - Design Decisions in Flask ========================= @@ -41,7 +39,7 @@ the time. There are ways to fake multiple applications with a single application object, like maintaining a stack of applications, but this causes some problems I won't outline here in detail. Now the question is: when does a microframework need more than one application at the same -time? A good example for this is unittesting. When you want to test +time? A good example for this is unit testing. When you want to test something it can be very helpful to create a minimal application to test specific behavior. When the application object is deleted everything it allocated will be freed again. @@ -76,8 +74,8 @@ there are better ways to do that so that you do not lose the reference to the application object :meth:`~flask.Flask.wsgi_app`). Furthermore this design makes it possible to use a factory function to -create the application which is very helpful for unittesting and similar -things (:ref:`app-factories`). +create the application which is very helpful for unit testing and similar +things (:doc:`/patterns/appfactories`). The Routing System ------------------ @@ -109,14 +107,14 @@ has a certain understanding about how things work. On the surface they all work the same: you tell the engine to evaluate a template with a set of variables and take the return value as string. -But that's about where similarities end. Jinja2 for example has an -extensive filter system, a certain way to do template inheritance, support -for reusable blocks (macros) that can be used from inside templates and -also from Python code, uses Unicode for all operations, supports -iterative template rendering, configurable syntax and more. On the other -hand an engine like Genshi is based on XML stream evaluation, template -inheritance by taking the availability of XPath into account and more. -Mako on the other hand treats templates similar to Python modules. +But that's about where similarities end. Jinja2 for example has an +extensive filter system, a certain way to do template inheritance, +support for reusable blocks (macros) that can be used from inside +templates and also from Python code, supports iterative template +rendering, configurable syntax and more. On the other hand an engine +like Genshi is based on XML stream evaluation, template inheritance by +taking the availability of XPath into account and more. Mako on the +other hand treats templates similar to Python modules. When it comes to connecting a template engine with an application or framework there is more than just rendering templates. For instance, @@ -169,10 +167,29 @@ 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 +Also see the :doc:`/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 -------------------------------- diff --git a/docs/errorhandling.rst b/docs/errorhandling.rst index 4c260112b4..764dfd20db 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,67 @@ Error Logging Tools Sending error mails, even if just for critical ones, can become overwhelming if enough users are hitting the error and log files are typically never looked at. This is why we recommend using `Sentry -`_ for dealing with application errors. It's -available as an Open Source project `on GitHub -`__ and is also available as a `hosted version -`_ which you can try for free. Sentry +`_ for dealing with application errors. It's +available as a source-available project `on GitHub +`_ and is also available as a `hosted version +`_ which you can try for free. Sentry aggregates duplicate errors, captures the full stack trace and local variables for debugging, and sends you mails based on new errors or frequency thresholds. -To use Sentry you need to install the `raven` client with extra `flask` dependencies:: +To use Sentry you need to install the ``sentry-sdk`` client with extra +``flask`` dependencies. - $ pip install raven[flask] +.. code-block:: text -And then add this to your Flask app:: + $ pip install sentry-sdk[flask] - from raven.contrib.flask import Sentry - sentry = Sentry(app, dsn='YOUR_DSN_HERE') +And then add this to your Flask app: -Or if you are using factories you can also init it later:: +.. code-block:: python - from raven.contrib.flask import Sentry - sentry = Sentry(dsn='YOUR_DSN_HERE') + import sentry_sdk + from sentry_sdk.integrations.flask import FlaskIntegration - def create_app(): - app = Flask(__name__) - sentry.init_app(app) - ... - return app + sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()]) -The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get -from your Sentry installation. +The ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you +get from your Sentry installation. -Afterwards failures are automatically reported to Sentry and from there -you can receive error notifications. +After installation, failures leading to an Internal Server Error +are automatically reported to Sentry and from there you can +receive error notifications. -.. _error-handlers: +See also: -Error handlers +- Sentry also supports catching errors from a worker queue + (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs + `__ for more information. +- `Getting started with Sentry `__ +- `Flask-specific documentation `__ + + +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 return a response, but instead -of being registered for a route, it is registered for an exception or HTTP -status code that would is 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 +101,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,13 +119,15 @@ 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 description = 'Not enough storage space.' - app.register_error_handler(InsuffcientStorage, handle_507) + app.register_error_handler(InsufficientStorage, handle_507) raise InsufficientStorage() @@ -117,20 +136,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 to 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. +For example, if an instance of :exc:`ConnectionRefusedError` is raised, +and a handler is registered for :exc:`ConnectionError` and +:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError` +handler is called with the exception instance to generate the response. Handlers registered on the blueprint take precedence over those registered globally on the application, assuming a blueprint is handling the request that @@ -138,78 +173,352 @@ raises the exception. However, the blueprint cannot handle 404 routing errors because the 404 occurs at the routing level before the blueprint can be determined. -.. versionchanged:: 0.11 - Handlers are prioritized by specificity of the exception classes they are - registered for instead of the order they are registered in. +Generic Exception Handlers +`````````````````````````` -Logging -------- +It is possible to register error handlers for very generic base classes +such as ``HTTPException`` or even ``Exception``. However, be aware that +these will catch more than you might expect. + +For example, an error handler for ``HTTPException`` might be useful for turning +the default HTML errors pages into JSON. However, this +handler will trigger for things you don't cause directly, such as 404 +and 405 errors during routing. Be sure to craft your handler carefully +so you don't lose information about the HTTP error. + +.. code-block:: python + + from flask import json + from werkzeug.exceptions import HTTPException + + @app.errorhandler(HTTPException) + def handle_exception(e): + """Return JSON instead of HTML for HTTP errors.""" + # start with the correct headers and status code from the error + response = e.get_response() + # replace the body with JSON + response.data = json.dumps({ + "code": e.code, + "name": e.name, + "description": e.description, + }) + response.content_type = "application/json" + return response + +An error handler for ``Exception`` might seem useful for changing how +all errors, even unhandled ones, are presented to the user. However, +this is similar to doing ``except Exception:`` in Python, it will +capture *all* otherwise unhandled errors, including all HTTP status +codes. + +In most cases it will be safer to register handlers for more +specific exceptions. Since ``HTTPException`` instances are valid WSGI +responses, you could also pass them through directly. + +.. code-block:: python + + from werkzeug.exceptions import HTTPException + + @app.errorhandler(Exception) + def handle_exception(e): + # pass through HTTP errors + if isinstance(e, HTTPException): + return e + + # now you're handling non-HTTP exceptions only + return render_template("500_generic.html", e=e), 500 + +Error handlers still respect the exception class hierarchy. If you +register handlers for both ``HTTPException`` and ``Exception``, the +``Exception`` handler will not handle ``HTTPException`` subclasses +because it the ``HTTPException`` handler is more specific. + + +Unhandled Exceptions +```````````````````` + +When there is no error handler registered for an exception, a 500 +Internal Server Error will be returned instead. See +:meth:`flask.Flask.handle_exception` for information about this +behavior. + +If there is an error handler registered for ``InternalServerError``, +this will be invoked. As of Flask 1.1.0, this error handler will always +be passed an instance of ``InternalServerError``, not the original +unhandled error. + +The original error is available as ``e.original_exception``. + +An error handler for "500 Internal Server Error" will be passed uncaught +exceptions in addition to explicit 500 errors. In debug mode, a handler +for "500 Internal Server Error" will not be used. Instead, the +interactive debugger will be shown. + + +Custom Error Pages +------------------ + +Sometimes when building a Flask application, you might want to raise a +:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that +something is wrong with the request. Fortunately, Flask comes with a handy +:func:`~flask.abort` function that aborts a request with a HTTP error from +werkzeug as desired. It will also provide a plain black and white error page +for you with a basic description, but nothing fancy. + +Depending on the error code it is less or more likely for the user to +actually see such an error. + +Consider the code below, we might have a user profile route, and if the user +fails to pass a username we can raise a "400 Bad Request". If the user passes a +username and we can't find it, we raise a "404 Not Found". + +.. code-block:: python + + from flask import abort, render_template, request + + # a username needs to be supplied in the query args + # a successful request would be like /profile?username=jack + @app.route("/profile") + def user_profile(): + username = request.arg.get("username") + # if a username isn't supplied in the request, return a 400 bad request + if username is None: + abort(400) + + user = get_user(username=username) + # if a user can't be found by their username, return 404 not found + if user is None: + abort(404) + + return render_template("profile.html", user=user) + +Here is another example implementation for a "404 Page Not Found" exception: + +.. code-block:: python + + from flask import render_template + + @app.errorhandler(404) + def page_not_found(e): + # note that we set the 404 status explicitly + return render_template('404.html'), 404 + +When using :doc:`/patterns/appfactories`: -See :ref:`logging` for information on how to log exceptions, such as by -emailing them to admins. +.. code-block:: python + from flask import Flask, render_template -Debugging Application Errors -============================ + def page_not_found(e): + return render_template('404.html'), 404 -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. + def create_app(config_filename): + app = Flask(__name__) + app.register_error_handler(404, page_not_found) + return app + +An example template might be this: + +.. code-block:: html+jinja + + {% extends "layout.html" %} + {% block title %}Page Not Found{% endblock %} + {% block body %} +

Page Not Found

+

What you were looking for is just not there. +

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

Internal Server Error

+

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

+

Go somewhere nice instead + {% endblock %} + +It can be implemented by rendering the template on "500 Internal Server Error": + +.. code-block:: python + + from flask import render_template + + @app.errorhandler(500) + def internal_server_error(e): + # note that we set the 500 status explicitly + return render_template('500.html'), 500 + +When using :doc:`/patterns/appfactories`: + +.. code-block:: python + + from flask import Flask, render_template + + def internal_server_error(e): + return render_template('500.html'), 500 + + def create_app(): + app = Flask(__name__) + app.register_error_handler(500, internal_server_error) + return app + +When using :doc:`/blueprints`: + +.. code-block:: python + + from flask import Blueprint + + blog = Blueprint('blog', __name__) + # as a decorator + @blog.errorhandler(500) + def internal_server_error(e): + return render_template('500.html'), 500 -When in Doubt, Run Manually ---------------------------- + # or with register_error_handler + blog.register_error_handler(500, internal_server_error) -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`. +Blueprint Error Handlers +------------------------ -.. _working-with-debuggers: +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. -Working with Debuggers ----------------------- +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. -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: +.. code-block:: python -* ``debug`` - whether to enable debug mode and catch exceptions -* ``use_debugger`` - whether to use the internal Flask debugger -* ``use_reloader`` - whether to reload and fork the process on exception + from flask import jsonify, render_template -``debug`` must be True (i.e., exceptions must be caught) in order for the other -two options to have any value. + # 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 -If you're using Aptana/Eclipse for debugging you'll need to set both -``use_debugger`` and ``use_reloader`` to False. + @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 -A possible useful pattern for configuration is to set the following in your -config.yaml (change the block as appropriate for your application, of course):: - FLASK: - DEBUG: True - DEBUG_WITH_APTANA: True +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()) + + # an API app route for getting user information + # a correct request might be /api/user?user_id=420 + @app.route("/api/user") + def user_api(user_id): + user_id = request.arg.get("user_id") + if not user_id: + raise InvalidAPIUsage("No user id provided!") + + user = get_user(user_id=user_id) + if not user: + raise InvalidAPIUsage("No such user!", status_code=404) + + return jsonify(user.to_dict()) + +A view can now raise that exception with an error message. Additionally +some extra payload can be provided as a dictionary through the `payload` +parameter. + + +Logging +------- + +See :doc:`/logging` for information about how to log exceptions, such as +by emailing them to admins. -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 +--------- - if app.debug: use_debugger = True - try: - # Disable Flask's debugger if external debugger is requested - use_debugger = not(app.config.get('DEBUG_WITH_APTANA')) - except: - pass - app.run(use_debugger=use_debugger, debug=app.debug, - use_reloader=use_debugger, host='0.0.0.0') +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 f48fb46b76..18b4fa7d20 100644 --- a/docs/extensiondev.rst +++ b/docs/extensiondev.rst @@ -1,20 +1,15 @@ -.. _extension-dev: - Flask Extension Development =========================== Flask, being a microframework, often requires some repetitive steps to get -a third party library working. Because very often these steps could be -abstracted to support multiple projects the `Flask Extension Registry`_ -was created. +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 ----------------------- @@ -32,9 +27,10 @@ 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. +:doc:`/patterns/appfactories` 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 @@ -122,8 +118,8 @@ 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? +documentation suggests (:doc:`/patterns/sqlite3`). So how does the +extension know the name of the application object? Quite simple: you pass it to it. @@ -139,10 +135,7 @@ initialization functions: 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. + used to further change the behavior. 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 @@ -197,8 +190,8 @@ So here's what these lines of code do: 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. + 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 @@ -240,7 +233,7 @@ automatically. Additionally, the ``init_app`` method is used to support the factory pattern for creating apps:: - db = Sqlite3() + db = SQLite3() # Then later on. app = create_app('the-config.cfg') db.init_app(app) @@ -276,18 +269,17 @@ 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. +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 `PyPI`_. If you feel lost there is still the `mailinglist`_ and the +`Discord server`_ 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 -mailinglist, and let other developers give you a helping hand with +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 @@ -296,50 +288,45 @@ 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: +Flask previously had the concept of approved extensions. These came with +some vetting of support and compatibility. While this 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. 0. An approved Flask extension requires a maintainer. In the event an - extension author would like to move beyond the project, the project should - find a new maintainer including full source hosting transition and PyPI - access. If no maintainer is available, give access to the Flask core team. -1. An approved Flask extension must provide exactly one package or module - named ``flask_extensionname``. -2. It must ship a testing suite that can either be invoked with ``make test`` - or ``python setup.py test``. For test suites invoked with ``make - test`` the extension has to ensure that all dependencies for the test - are installed automatically. If tests are invoked with ``python setup.py - test``, test dependencies can be specified in the :file:`setup.py` file. The - test suite also has to be part of the distribution. -3. APIs of approved extensions will be checked for the following - characteristics: - - - an approved extension has to support multiple applications - running in the same Python process. - - it must be possible to use the factory pattern for creating - applications. - -4. The license must be BSD/MIT/WTFPL licensed. -5. The naming scheme for official extensions is *Flask-ExtensionName* or - *ExtensionName-Flask*. -6. Approved extensions must define all their dependencies in the - :file:`setup.py` file unless a dependency cannot be met because it is not - available on PyPI. -7. The documentation must use the ``flask`` theme from the `Official - Pallets Themes`_. -8. The setup.py description (and thus the PyPI description) has to - link to the documentation, website (if there is one) and there - must be a link to automatically install the development version - (``PackageName==dev``). -9. The ``zip_safe`` flag in the setup script must be set to ``False``, - even if the extension would be safe for zipping. -10. An extension currently has to support Python 3.4 and newer and 2.7. - - -.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/ -.. _mailinglist: http://flask.pocoo.org/mailinglist/ -.. _IRC channel: http://flask.pocoo.org/community/irc/ -.. _Official Pallets Themes: https://pypi.org/project/pallets-sphinx-themes/ + 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. If no maintainer + is available, give access to the Pallets core team. +1. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*. + It must provide exactly one package or module named + ``flask_extension_name``. +2. The extension must be BSD or MIT licensed. It must be open source + and publicly available. +3. 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. + +4. From a clone of the repository, an extension with its dependencies + must be installable with ``pip install -e .``. +5. It must ship a testing suite that can be invoked with ``tox -e py`` + or ``pytest``. If not using ``tox``, the test dependencies should be + specified in a ``requirements.txt`` file. The tests must be part of + the sdist distribution. +6. The documentation must use the ``flask`` theme from the + `Official Pallets Themes`_. A link to the documentation or project + website must be in the PyPI metadata or the readme. +7. For maximum compatibility, the extension should support the same + versions of Python that Flask supports. 3.6+ is recommended as of + 2020. Use ``python_requires=">= 3.6"`` in ``setup.py`` to indicate + supported versions. + +.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask +.. _mailinglist: https://mail.python.org/mailman/listinfo/flask +.. _Discord server: https://discord.gg/pallets +.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/ diff --git a/docs/extensions.rst b/docs/extensions.rst index 92e8a5b255..784fd807a7 100644 --- a/docs/extensions.rst +++ b/docs/extensions.rst @@ -1,21 +1,17 @@ -.. _extensions: - Extensions ========== Extensions are extra packages that add functionality to a Flask application. For example, an extension might add support for sending email or connecting to a database. Some extensions add entire new -frameworks to help build certain types of applications, like a ReST API. +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 @@ -25,7 +21,7 @@ Consult each extension's documentation for installation, configuration, and usage instructions. Generally, extensions pull their own configuration from :attr:`app.config ` and are passed an application instance during initialization. For example, -an extension caled "Flask-Foo" might be used like this:: +an extension called "Flask-Foo" might be used like this:: from flask_foo import Foo @@ -43,11 +39,10 @@ an extension caled "Flask-Foo" might be used like this:: Building Extensions ------------------- -While the `Extension Registry`_ contains many Flask extensions, you may +While the `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. Read :ref:`extension-dev` to develop your own Flask +create your own. 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/flaskstyle.sty b/docs/flaskstyle.sty deleted file mode 100644 index cd53c898cf..0000000000 --- a/docs/flaskstyle.sty +++ /dev/null @@ -1,124 +0,0 @@ -\definecolor{TitleColor}{rgb}{0,0,0} -\definecolor{InnerLinkColor}{rgb}{0,0,0} - -% Replace Unicode character 'PARTY POPPER' (U+1F389) with a non-breaking space. -% pdfLaTeX doesn't support Unicode. -\DeclareUnicodeCharacter{1F389}{\nobreakspace} - -\renewcommand{\maketitle}{% - \begin{titlepage}% - \let\footnotesize\small - \let\footnoterule\relax - % Apply following fix only on PDF output, i.e. pdfoutput macro is not - % undefined - \ifx\pdfoutput\undefined\else - \begingroup - % This \def is required to deal with multi-line authors; it - % changes \\ to ', ' (comma-space), making it pass muster for - % generating document info in the PDF file. - \def\\{, } - \pdfinfo{ - /Author (\@author) - /Title (\@title) - } - \endgroup - \fi - \begin{flushright}% - %\sphinxlogo% - {\center - \vspace*{3cm} - \includegraphics{logo.pdf} - \vspace{3cm} - \par - {\rm\Huge \@title \par}% - {\em\LARGE \py@release\releaseinfo \par} - {\large - \@date \par - \py@authoraddress \par - }}% - \end{flushright}%\par - \@thanks - \end{titlepage}% - \cleardoublepage% - \setcounter{footnote}{0}% - \let\thanks\relax\let\maketitle\relax - %\gdef\@thanks{}\gdef\@author{}\gdef\@title{} -} - -\fancypagestyle{normal}{ - \fancyhf{} - \fancyfoot[LE,RO]{{\thepage}} - \fancyfoot[LO]{{\nouppercase{\rightmark}}} - \fancyfoot[RE]{{\nouppercase{\leftmark}}} - \fancyhead[LE,RO]{{ \@title, \py@release}} - \renewcommand{\headrulewidth}{0.4pt} - \renewcommand{\footrulewidth}{0.4pt} -} - -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[LE,RO]{{\thepage}} - \renewcommand{\headrulewidth}{0pt} - \renewcommand{\footrulewidth}{0.4pt} -} - -\titleformat{\section}{\Large}% - {\py@TitleColor\thesection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\subsection}{\large}% - {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\subsubsection}{}% - {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\paragraph}{\large}% - {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor} - -\ChNameVar{\raggedleft\normalsize} -\ChNumVar{\raggedleft \bfseries\Large} -\ChTitleVar{\raggedleft \rm\Huge} - -\renewcommand\thepart{\@Roman\c@part} -\renewcommand\part{% - \pagestyle{plain} - \if@noskipsec \leavevmode \fi - \cleardoublepage - \vspace*{6cm}% - \@afterindentfalse - \secdef\@part\@spart} - -\def\@part[#1]#2{% - \ifnum \c@secnumdepth >\m@ne - \refstepcounter{part}% - \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}% - \else - \addcontentsline{toc}{part}{#1}% - \fi - {\parindent \z@ %\center - \interlinepenalty \@M - \normalfont - \ifnum \c@secnumdepth >\m@ne - \rm\Large \partname~\thepart - \par\nobreak - \fi - \MakeUppercase{\rm\Huge #2}% - \markboth{}{}\par}% - \nobreak - \vskip 8ex - \@afterheading} -\def\@spart#1{% - {\parindent \z@ %\center - \interlinepenalty \@M - \normalfont - \huge \bfseries #1\par}% - \nobreak - \vskip 3ex - \@afterheading} - -% use inconsolata font -\usepackage{inconsolata} - -% fix single quotes, for inconsolata. (does not work) -%%\usepackage{textcomp} -%%\begingroup -%% \catcode`'=\active -%% \g@addto@macro\@noligs{\let'\textsinglequote} -%% \endgroup -%%\endinput diff --git a/docs/foreword.rst b/docs/foreword.rst index 4142cb8337..6a6d17f974 100644 --- a/docs/foreword.rst +++ b/docs/foreword.rst @@ -28,18 +28,17 @@ 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. +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. +available in the community to integrate your project for production. 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 @@ -50,8 +49,5 @@ 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`. +in that, check out the :doc:`becomingbig` chapter. If you are curious about +the Flask design principles, head over to the section about :doc:`design`. diff --git a/docs/htmlfaq.rst b/docs/htmlfaq.rst index 0b6ff5048b..4807c2662d 100644 --- a/docs/htmlfaq.rst +++ b/docs/htmlfaq.rst @@ -16,8 +16,8 @@ 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. +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. @@ -183,10 +183,10 @@ and to use. geolocation, and offline applications. Many other features have been added, as well. A good guide to new features -in HTML5 is Mark Pilgrim's soon-to-be-published book, `Dive Into HTML5`_. +in HTML5 is Mark Pilgrim's book, `Dive Into HTML5`_. Not all of them are supported in browsers yet, however, so use caution. -.. _Dive Into HTML5: http://diveintohtml5.info/ +.. _Dive Into HTML5: https://diveintohtml5.info/ What should be used? -------------------- @@ -195,8 +195,7 @@ Currently, the answer is HTML5. There are very few reasons to use XHTML considering the latest developments in Web browsers. To summarize the reasons given above: -- Internet Explorer (which, sadly, currently leads in market share) - has poor support for XHTML. +- Internet Explorer has poor support for XHTML. - Many JavaScript libraries also do not support XHTML, due to the more complicated namespacing API it requires. - HTML5 adds several new features, including semantic tags and the diff --git a/docs/index.rst b/docs/index.rst index 64ed4e9213..6ff6252940 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,26 +1,91 @@ -:orphan: +.. rst-class:: hide-header Welcome to Flask ================ -.. image:: _static/logo-full.png +.. image:: _static/flask-logo.png :alt: Flask: web development, one drop at a time - :align: right + :align: center + :target: https://palletsprojects.com/p/flask/ -Welcome to Flask's documentation. Get started with :ref:`installation` -and then get an overview with the :ref:`quickstart`. There is also a -more detailed :ref:`tutorial` that shows how to create a small but +Welcome to Flask's documentation. Get started with :doc:`installation` +and then get an overview with the :doc:`quickstart`. There is also a +more detailed :doc:`tutorial/index` that shows how to create a small but complete application with Flask. Common patterns are described in the -:ref:`patterns` section. The rest of the docs describe each component of -Flask in detail, with a full reference in the :ref:`api` section. +:doc:`patterns/index` section. The rest of the docs describe each +component of Flask in detail, with a full reference in the :doc:`api` +section. Flask depends on the `Jinja`_ template engine and the `Werkzeug`_ WSGI toolkit. The documentation for these libraries can be found at: -- `Jinja documentation `_ -- `Werkzeug documentation `_ +- `Jinja documentation `_ +- `Werkzeug documentation `_ .. _Jinja: https://www.palletsprojects.com/p/jinja/ .. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/ -.. include:: contents.rst.inc + +User's Guide +------------ + +This part of the documentation, which is mostly prose, begins with some +background information about Flask, then focuses on step-by-step +instructions for web development with Flask. + +.. toctree:: + :maxdepth: 2 + + foreword + advanced_foreword + installation + quickstart + tutorial/index + templating + testing + errorhandling + debugging + logging + config + signals + views + appcontext + reqcontext + blueprints + extensions + cli + server + shell + patterns/index + deploying/index + becomingbig + async-await + + +API Reference +------------- + +If you are looking for information on a specific function, class or +method, this part of the documentation is for you. + +.. toctree:: + :maxdepth: 2 + + api + + +Additional Notes +---------------- + +Design notes, legal information and changelog are here for the interested. + +.. toctree:: + :maxdepth: 2 + + design + htmlfaq + security + extensiondev + contributing + license + changes diff --git a/docs/installation.rst b/docs/installation.rst index 0014f1368b..aef7df0c20 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -1,13 +1,13 @@ -.. _installation: - Installation ============ + Python Version -------------- -We recommend using the latest version of Python 3. Flask supports Python 3.4 -and newer, Python 2.7, and PyPy. +We recommend using the latest version of Python. Flask supports Python +3.6 and newer. + Dependencies ------------ @@ -25,11 +25,12 @@ These distributions will be installed automatically when installing Flask. * `Click`_ is a framework for writing command line applications. It provides the ``flask`` command and allows adding custom management commands. -.. _Werkzeug: http://werkzeug.pocoo.org/ -.. _Jinja: http://jinja.pocoo.org/ -.. _MarkupSafe: https://pypi.org/project/MarkupSafe/ -.. _ItsDangerous: https://pythonhosted.org/itsdangerous/ -.. _Click: http://click.pocoo.org/ +.. _Werkzeug: https://palletsprojects.com/p/werkzeug/ +.. _Jinja: https://palletsprojects.com/p/jinja/ +.. _MarkupSafe: https://palletsprojects.com/p/markupsafe/ +.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/ +.. _Click: https://palletsprojects.com/p/click/ + Optional dependencies ~~~~~~~~~~~~~~~~~~~~~ @@ -37,20 +38,17 @@ Optional dependencies These distributions will not be installed automatically. Flask will detect and use them if you install them. -* `Blinker`_ provides support for :ref:`signals`. -* `SimpleJSON`_ is a fast JSON implementation that is compatible with - Python's ``json`` module. It is preferred for JSON operations if it is - installed. +* `Blinker`_ provides support for :doc:`signals`. * `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask`` commands. * `Watchdog`_ provides a faster, more efficient reloader for the development server. .. _Blinker: https://pythonhosted.org/blinker/ -.. _SimpleJSON: https://simplejson.readthedocs.io/ .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme .. _watchdog: https://pythonhosted.org/watchdog/ + Virtual environments -------------------- @@ -66,11 +64,9 @@ Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system's packages. -Python 3 comes bundled with the :mod:`venv` module to create virtual -environments. If you're using a modern version of Python, you can continue on -to the next section. +Python comes bundled with the :mod:`venv` module to create virtual +environments. -If you're using Python 2, see :ref:`install-install-virtualenv` first. .. _install-create-env: @@ -79,30 +75,24 @@ Create an environment Create a project folder and a :file:`venv` folder within: -.. code-block:: sh - - mkdir myproject - cd myproject - python3 -m venv venv - -On Windows: +.. tabs:: -.. code-block:: bat + .. group-tab:: macOS/Linux - py -3 -m venv venv + .. code-block:: text -If you needed to install virtualenv because you are on an older version of -Python, use the following command instead: - -.. code-block:: sh + $ mkdir myproject + $ cd myproject + $ python3 -m venv venv - virtualenv venv + .. group-tab:: Windows -On Windows: + .. code-block:: text -.. code-block:: bat + > mkdir myproject + > cd myproject + > py -3 -m venv venv - \Python27\Scripts\virtualenv.exe venv .. _install-activate-env: @@ -111,76 +101,33 @@ Activate the environment Before you work on your project, activate the corresponding environment: -.. code-block:: sh +.. tabs:: + + .. group-tab:: macOS/Linux + + .. code-block:: text - . venv/bin/activate + $ . venv/bin/activate -On Windows: + .. group-tab:: Windows -.. code-block:: bat + .. code-block:: text - venv\Scripts\activate + > venv\Scripts\activate + +Your shell prompt will change to show the name of the activated +environment. -Your shell prompt will change to show the name of the activated environment. Install Flask ------------- -Within the activated environment, use the following command to install Flask: +Within the activated environment, use the following command to install +Flask: .. code-block:: sh - pip install Flask + $ pip install Flask Flask is now installed. Check out the :doc:`/quickstart` or go to the :doc:`Documentation Overview `. - -Living on the edge -~~~~~~~~~~~~~~~~~~ - -If you want to work with the latest Flask code before it's released, install or -update the code from the master branch: - -.. code-block:: sh - - pip install -U https://github.com/pallets/flask/archive/master.tar.gz - -.. _install-install-virtualenv: - -Install virtualenv ------------------- - -If you are using Python 2, the venv module is not available. Instead, -install `virtualenv`_. - -On Linux, virtualenv is provided by your package manager: - -.. code-block:: sh - - # Debian, Ubuntu - sudo apt-get install python-virtualenv - - # CentOS, Fedora - sudo yum install python-virtualenv - - # Arch - sudo pacman -S python-virtualenv - -If you are on Mac OS X or Windows, download `get-pip.py`_, then: - -.. code-block:: sh - - sudo python2 Downloads/get-pip.py - sudo python2 -m pip install virtualenv - -On Windows, as an administrator: - -.. code-block:: bat - - \Python27\python.exe Downloads\get-pip.py - \Python27\python.exe -m pip install virtualenv - -Now you can return above and :ref:`install-create-env`. - -.. _virtualenv: https://virtualenv.pypa.io/ -.. _get-pip.py: https://bootstrap.pypa.io/get-pip.py diff --git a/docs/latexindex.rst b/docs/latexindex.rst deleted file mode 100644 index 288197c37c..0000000000 --- a/docs/latexindex.rst +++ /dev/null @@ -1,6 +0,0 @@ -:orphan: - -Flask Documentation -=================== - -.. include:: contents.rst.inc diff --git a/docs/license.rst b/docs/license.rst index 696ee676a9..f3f64823b9 100644 --- a/docs/license.rst +++ b/docs/license.rst @@ -1,48 +1,19 @@ License ======= -Flask is licensed under a three clause BSD License. It basically means: -do whatever you want with it as long as the copyright in Flask sticks -around, the conditions are not modified and the disclaimer is present. -Furthermore you must not use the names of the authors to promote derivatives -of the software without written consent. - -The full license text can be found below (:ref:`flask-license`). For the -documentation and artwork different licenses apply. - -.. _authors: - -Authors -------- - -.. include:: ../AUTHORS - -General License Definitions +BSD-3-Clause Source License --------------------------- -The following section contains the full license texts for Flask and the -documentation. - -- "AUTHORS" hereby refers to all the authors listed in the - :ref:`authors` section. - -- The ":ref:`flask-license`" applies to all the source code shipped as - part of Flask (Flask itself as well as the examples and the unittests) - as well as documentation. - -- The ":ref:`artwork-license`" applies to the project's Horn-Logo. - -.. _flask-license: - -Flask License -------------- +The BSD-3-Clause license applies to all files in the Flask repository +and source distribution. This includes Flask's source code, the +examples, and tests, as well as the documentation. -.. include:: ../LICENSE +.. include:: ../LICENSE.rst -.. _artwork-license: +Artwork License +--------------- -Flask Artwork License ---------------------- +This license applies to Flask's logo. -.. include:: ../artwork/LICENSE +.. include:: ../artwork/LICENSE.rst diff --git a/docs/logging.rst b/docs/logging.rst index a96a8f2895..0912b7a1d5 100644 --- a/docs/logging.rst +++ b/docs/logging.rst @@ -1,12 +1,12 @@ -.. _logging: - Logging ======= -Flask uses standard Python :mod:`logging`. All Flask-related messages are -logged under the ``'flask'`` logger namespace. -:meth:`Flask.logger ` returns the logger named -``'flask.app'``, and can be used to log messages for your application. :: +Flask uses standard Python :mod:`logging`. Messages about your Flask +application are logged with :meth:`app.logger `, +which takes the same name as :attr:`app.name `. This +logger can also be used to log your own messages. + +.. code-block:: python @app.route('/login', methods=['POST']) def login(): @@ -20,6 +20,9 @@ logged under the ``'flask'`` logger namespace. app.logger.info('%s failed to log in', user.username) abort(401) +If you don't configure logging, Python's default log level is usually +'warning'. Nothing below the configured level will be visible. + Basic Configuration ------------------- @@ -117,14 +120,19 @@ your own fields that can be used in messages. You can change the formatter for Flask's default handler, the mail handler defined above, or any other handler. :: - from flask import request + from flask import has_request_context, request from flask.logging import default_handler class RequestFormatter(logging.Formatter): def format(self, record): - record.url = request.url - record.remote_addr = request.remote_addr - return super(RequestFormatter, self).format(record) + if has_request_context(): + record.url = request.url + record.remote_addr = request.remote_addr + else: + record.url = None + record.remote_addr = None + + return super().format(record) formatter = RequestFormatter( '[%(asctime)s] %(remote_addr)s requested %(url)s\n' diff --git a/docs/logo.pdf b/docs/logo.pdf deleted file mode 100644 index bd820c2472..0000000000 Binary files a/docs/logo.pdf and /dev/null differ diff --git a/docs/make.bat b/docs/make.bat index 5ca2df6d61..922152e96a 100644 --- a/docs/make.bat +++ b/docs/make.bat @@ -1,36 +1,35 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=. -set BUILDDIR=_build -set SPHINXPROJ=Flask - -if "%1" == "" goto help - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% - -:end -popd +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/patterns/apierrors.rst b/docs/patterns/apierrors.rst deleted file mode 100644 index 90e8c13d8b..0000000000 --- a/docs/patterns/apierrors.rst +++ /dev/null @@ -1,63 +0,0 @@ -Implementing API Exceptions -=========================== - -It's very common to implement RESTful APIs on top of Flask. One of the -first things that developers run into is the realization that the builtin -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. - -The better solution than using ``abort`` to signal errors for invalid API -usage is to implement your own exception type and install an error handler -for it that produces the errors in the format the user is expecting. - -Simple Exception Class ----------------------- - -The basic idea is to introduce a new exception 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:: - - from flask import jsonify - - class InvalidUsage(Exception): - status_code = 400 - - def __init__(self, message, status_code=None, payload=None): - Exception.__init__(self) - 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 - -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. - -Registering an Error Handler ----------------------------- - -At that point views can raise that error, but it would immediately result -in an internal server error. The reason for this is that there is no -handler registered for this error class. That however is easy to add:: - - @app.errorhandler(InvalidUsage) - def handle_invalid_usage(error): - response = jsonify(error.to_dict()) - response.status_code = error.status_code - return response - -Usage in Views --------------- - -Here is how a view can use that functionality:: - - @app.route('/foo') - def get_foo(): - raise InvalidUsage('This view is gone', status_code=410) diff --git a/docs/patterns/appdispatch.rst b/docs/patterns/appdispatch.rst index 726850e2b7..0c5e846efd 100644 --- a/docs/patterns/appdispatch.rst +++ b/docs/patterns/appdispatch.rst @@ -1,5 +1,3 @@ -.. _app-dispatch: - Application Dispatching ======================= @@ -10,25 +8,25 @@ Django and a Flask application in the same interpreter side by side if you want. The usefulness of this depends on how the applications work internally. -The fundamental difference from the :ref:`module approach -` is that in this case you are running the same or -different Flask applications that are entirely isolated from each other. -They run different configurations and are dispatched on the WSGI level. +The fundamental difference from :doc:`packages` is that in this case you +are running the same or different Flask applications that are entirely +isolated from each other. They run different configurations and are +dispatched on the WSGI level. Working with this Document -------------------------- -Each of the techniques and examples below results in an ``application`` object -that can be run with any WSGI server. For production, see :ref:`deployment`. -For development, Werkzeug provides a builtin server for development available -at :func:`werkzeug.serving.run_simple`:: +Each of the techniques and examples below results in an ``application`` +object that can be run with any WSGI server. For production, see +:doc:`/deploying/index`. For development, Werkzeug provides a server +through :func:`werkzeug.serving.run_simple`:: from werkzeug.serving import run_simple run_simple('localhost', 5000, application, use_reloader=True) Note that :func:`run_simple ` is not intended for -use in production. Use a :ref:`full-blown WSGI server `. +use in production. Use a production WSGI server. See :doc:`/deploying/index`. In order to use the interactive debugger, debugging must be enabled both on the application and the simple server. Here is the "hello world" example with @@ -62,12 +60,12 @@ dispatched based on prefix. For example you could have your main application run on ``/`` and your backend interface on ``/backend``:: - from werkzeug.wsgi import DispatcherMiddleware + from werkzeug.middleware.dispatcher import DispatcherMiddleware from frontend_app import application as frontend from backend_app import application as backend application = DispatcherMiddleware(frontend, { - '/backend': backend + '/backend': backend }) @@ -79,7 +77,7 @@ with different configurations. Assuming the application is created inside a function and you can call that function to instantiate it, that is really easy to implement. In order to develop your application to support creating new instances in functions have a look at the -:ref:`app-factories` pattern. +:doc:`appfactories` pattern. A very common example would be creating applications per subdomain. For instance you configure your webserver to dispatch all requests for all diff --git a/docs/patterns/appfactories.rst b/docs/patterns/appfactories.rst index 3e880205c1..79c78d6021 100644 --- a/docs/patterns/appfactories.rst +++ b/docs/patterns/appfactories.rst @@ -1,10 +1,8 @@ -.. _app-factories: - Application Factories ===================== If you are already using packages and blueprints for your application -(:ref:`blueprints`) there are a couple of really nice ways to further improve +(:doc:`/blueprints`) there are a couple of really nice ways to further improve the experience. A common pattern is creating the application object when the blueprint is imported. But if you move the creation of this object into a function, you can then create multiple instances of this app later. @@ -60,7 +58,7 @@ Factories & Extensions It's preferable to create your extensions and app factories so that the extension object does not initially get bound to the application. -Using `Flask-SQLAlchemy `_, +Using `Flask-SQLAlchemy `_, as an example, you should not do something along those lines:: def create_app(config_filename): @@ -89,17 +87,57 @@ For more information about the design of extensions refer to :doc:`/extensiondev Using Applications ------------------ -To run such an application, you can use the :command:`flask` command:: +To run such an application, you can use the :command:`flask` command: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_APP=myapp + $ flask run + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_APP=myapp + > flask run + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_APP = "myapp" + > flask run + +Flask will automatically detect the factory (``create_app`` or ``make_app``) +in ``myapp``. You can also pass arguments to the factory like this: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_APP="myapp:create_app('dev')" + $ flask run + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_APP="myapp:create_app('dev')" + > flask run + + .. group-tab:: Powershell + + .. code-block:: text - export FLASK_APP=myapp - flask run - -Flask will automatically detect the factory (``create_app`` or ``make_app``) -in ``myapp``. You can also pass arguments to the factory like this:: + > $env:FLASK_APP = "myapp:create_app('dev')" + > flask run - export FLASK_APP="myapp:create_app('dev')" - flask run - Then the ``create_app`` factory in ``myapp`` is called with the string ``'dev'`` as the argument. See :doc:`/cli` for more detail. diff --git a/docs/patterns/caching.rst b/docs/patterns/caching.rst index fb96a55918..9bf7b72a2c 100644 --- a/docs/patterns/caching.rst +++ b/docs/patterns/caching.rst @@ -1,5 +1,3 @@ -.. _caching-pattern: - Caching ======= @@ -10,60 +8,9 @@ still be good enough if they were 5 minutes old. So then the idea is that you actually put the result of that calculation into a cache for some time. -Flask itself does not provide caching for you, but Werkzeug, one of the -libraries it is based on, has some very basic cache support. It supports -multiple cache backends, normally you want to use a memcached server. - -Setting up a Cache ------------------- - -You create a cache object once and keep it around, similar to how -:class:`~flask.Flask` objects are created. If you are using the -development server you can create a -:class:`~werkzeug.contrib.cache.SimpleCache` object, that one is a simple -cache that keeps the item stored in the memory of the Python interpreter:: - - from werkzeug.contrib.cache import SimpleCache - cache = SimpleCache() - -If you want to use memcached, make sure to have one of the memcache modules -supported (you get them from `PyPI `_) and a -memcached server running somewhere. This is how you connect to such an -memcached server then:: - - from werkzeug.contrib.cache import MemcachedCache - cache = MemcachedCache(['127.0.0.1:11211']) - -If you are using App Engine, you can connect to the App Engine memcache -server easily:: - - from werkzeug.contrib.cache import GAEMemcachedCache - cache = GAEMemcachedCache() - -Using a Cache -------------- - -Now how can one use such a cache? There are two very important -operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and -:meth:`~werkzeug.contrib.cache.BaseCache.set`. This is how to use them: - -To get an item from the cache call -:meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name. -If something is in the cache, it is returned. Otherwise that function -will return ``None``:: - - rv = cache.get('my-item') - -To add items to the cache, use the :meth:`~werkzeug.contrib.cache.BaseCache.set` -method instead. The first argument is the key and the second the value -that should be set. Also a timeout can be provided after which the cache -will automatically remove item. +Flask itself does not provide caching for you, but `Flask-Caching`_, an +extension for Flask does. Flask-Caching supports various backends, and it is +even possible to develop your own caching backend. -Here a full example how this looks like normally:: - def get_my_item(): - rv = cache.get('my-item') - if rv is None: - rv = calculate_value() - cache.set('my-item', rv, timeout=5 * 60) - return rv +.. _Flask-Caching: https://flask-caching.readthedocs.io/en/latest/ diff --git a/docs/patterns/celery.rst b/docs/patterns/celery.rst index c3098a9ed3..e1f6847e11 100644 --- a/docs/patterns/celery.rst +++ b/docs/patterns/celery.rst @@ -10,7 +10,7 @@ immediately. Celery is a powerful task queue that can be used for simple background tasks as well as complex multi-stage programs and schedules. This guide will show you how to configure Celery using Flask, but assumes you've already read the -`First Steps with Celery `_ +`First Steps with Celery `_ guide in the Celery documentation. Install diff --git a/docs/patterns/deferredcallbacks.rst b/docs/patterns/deferredcallbacks.rst index bc20cdd6be..4ff8814b40 100644 --- a/docs/patterns/deferredcallbacks.rst +++ b/docs/patterns/deferredcallbacks.rst @@ -1,5 +1,3 @@ -.. _deferred-callbacks: - Deferred Request Callbacks ========================== @@ -16,7 +14,7 @@ response object. One way is to avoid the situation. Very often that is possible. For instance you can try to move that logic into a :meth:`~flask.Flask.after_request` -callback instead. However, sometimes moving code there makes it more +callback instead. However, sometimes moving code there makes it more complicated or awkward to reason about. As an alternative, you can use :func:`~flask.after_this_request` to register @@ -41,5 +39,6 @@ user in a cookie in a :meth:`~flask.Flask.before_request` callback:: @after_this_request def remember_language(response): response.set_cookie('user_lang', language) + return response g.language = language diff --git a/docs/patterns/distribute.rst b/docs/patterns/distribute.rst index 51a7352809..83885df73f 100644 --- a/docs/patterns/distribute.rst +++ b/docs/patterns/distribute.rst @@ -1,5 +1,3 @@ -.. _distribute-deployment: - Deploying with Setuptools ========================= @@ -19,22 +17,17 @@ complex constructs that make larger applications easier to distribute: other package. - **installation manager**: :command:`pip` can install other libraries for you. -If you have Python 2 (>=2.7.9) or Python 3 (>=3.4) installed from python.org, -you will already have pip and setuptools on your system. Otherwise, you -will need to install them yourself. - Flask itself, and all the libraries you can find on PyPI are distributed with either setuptools or distutils. In this case we assume your application is called -:file:`yourapplication.py` and you are not using a module, but a :ref:`package -`. If you have not yet converted your application into -a package, head over to the :ref:`larger-applications` pattern to see -how this can be done. +:file:`yourapplication.py` and you are not using a module, but a +package. If you have not yet converted your application into a package, +head over to :doc:`packages` to see how this can be done. A working deployment with setuptools is the first step into more complex and more automated deployment scenarios. If you want to fully automate -the process, also read the :ref:`fabric-deployment` chapter. +the process, also read the :doc:`fabric` chapter. Basic Setup Script ------------------ @@ -42,8 +35,8 @@ Basic Setup Script Because you have Flask installed, you have setuptools available on your system. Flask already depends upon setuptools. -Standard disclaimer applies: :ref:`you better use a virtualenv -`. +Standard disclaimer applies: :ref:`use a virtualenv +`. Your setup code always goes into a file named :file:`setup.py` next to your application. The name of the file is only convention, but because diff --git a/docs/patterns/errorpages.rst b/docs/patterns/errorpages.rst deleted file mode 100644 index 1df9c06148..0000000000 --- a/docs/patterns/errorpages.rst +++ /dev/null @@ -1,99 +0,0 @@ -.. _errorpages: - -Custom Error Pages -================== - -Flask comes with a handy :func:`~flask.abort` function that aborts a -request with an HTTP error code early. 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. - -Common Error Codes ------------------- - -The following error codes are some that are often displayed to the user, -even if the application behaves correctly: - -*404 Not Found* - The good old "chap, you made a mistake typing that URL" message. So - common that even novices to the internet know that 404 means: damn, - the thing I was looking for is not there. It's a very good idea to - make sure there is actually something useful on a 404 page, at least a - link back to the index. - -*403 Forbidden* - If you have some kind of access control on your website, you will have - to send a 403 code for disallowed resources. So make sure the user - is not lost when they try to access a forbidden resource. - -*410 Gone* - Did you know that there the "404 Not Found" has a brother named "410 - Gone"? Few people actually implement that, but the idea is that - resources that previously existed and got deleted answer with 410 - instead of 404. If you are not deleting documents permanently from - the database but just mark them as deleted, do the user a favour and - use the 410 code instead and display a message that what they were - looking for was deleted for all eternity. - -*500 Internal Server Error* - Usually happens on programming errors or if the server is overloaded. - A terribly good idea is to have a nice page there, because your - application *will* fail sooner or later (see also: - :ref:`application-errors`). - - -Error Handlers --------------- - -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`. An error -handler for "500 Internal Server Error" will be passed uncaught exceptions in -addition to explicit 500 errors. - -An error handler is registered with the :meth:`~flask.Flask.errorhandler` -decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler -can be registered for a status code, like 404, or for an exception class. - -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. - -A handler for "500 Internal Server Error" will not be used when running in -debug mode. Instead, the interactive debugger will be shown. - -Here is an example implementation for a "404 Page Not Found" exception:: - - from flask import render_template - - @app.errorhandler(404) - def page_not_found(e): - # note that we set the 404 status explicitly - return render_template('404.html'), 404 - -When using the :ref:`application factory pattern `:: - - 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: - -.. sourcecode:: html+jinja - - {% extends "layout.html" %} - {% block title %}Page Not Found{% endblock %} - {% block body %} -

Page Not Found

-

What you were looking for is just not there. -

go somewhere nice - {% endblock %} diff --git a/docs/patterns/fabric.rst b/docs/patterns/fabric.rst index 3dbf21463e..0cd39ddc70 100644 --- a/docs/patterns/fabric.rst +++ b/docs/patterns/fabric.rst @@ -1,12 +1,10 @@ -.. _fabric-deployment: - Deploying with Fabric ===================== `Fabric`_ is a tool for Python similar to Makefiles but with the ability to execute commands on a remote server. In combination with a properly -set up Python package (:ref:`larger-applications`) and a good concept for -configurations (:ref:`config`) it is very easy to deploy Flask +set up Python package (:doc:`packages`) and a good concept for +configurations (:doc:`/config`) it is very easy to deploy Flask applications to external servers. Before we get started, here a quick checklist of things we have to ensure @@ -15,7 +13,7 @@ upfront: - Fabric 1.0 has to be installed locally. This tutorial assumes the latest version of Fabric. - The application already has to be a package and requires a working - :file:`setup.py` file (:ref:`distribute-deployment`). + :file:`setup.py` file (:doc:`distribute`). - In the following example we are using `mod_wsgi` for the remote servers. You can of course use your own favourite server there, but for this example we chose Apache + `mod_wsgi` because it's very easy @@ -49,16 +47,16 @@ virtual environment:: def deploy(): # figure out the package name and version dist = local('python setup.py --fullname', capture=True).strip() - filename = '%s.tar.gz' % dist + filename = f'{dist}.tar.gz' # upload the package to the temporary folder on the server - put('dist/%s' % filename, '/tmp/%s' % filename) + put(f'dist/{filename}', f'/tmp/{filename}') # install the package in the application's virtualenv with pip - run('/var/www/yourapplication/env/bin/pip install /tmp/%s' % filename) + run(f'/var/www/yourapplication/env/bin/pip install /tmp/{filename}') # remove the uploaded package - run('rm -r /tmp/%s' % filename) + run(f'rm -r /tmp/{filename}') # touch the .wsgi file to trigger a reload in mod_wsgi run('touch /var/www/yourapplication.wsgi') @@ -101,7 +99,7 @@ To setup a new server you would roughly do these steps: 3. Create a new Apache config for ``yourapplication`` and activate it. Make sure to activate watching for changes of the ``.wsgi`` file so that we can automatically reload the application by touching it. - (See :ref:`mod_wsgi-deployment` for more information) + See :doc:`/deploying/mod_wsgi`. So now the question is, where do the :file:`application.wsgi` and :file:`application.cfg` files come from? @@ -124,7 +122,7 @@ the config at that environment variable:: app.config.from_object('yourapplication.default_config') app.config.from_envvar('YOURAPPLICATION_CONFIG') -This approach is explained in detail in the :ref:`config` section of the +This approach is explained in detail in the :doc:`/config` section of the documentation. The Configuration File @@ -183,4 +181,4 @@ type ``fab deploy`` and see your application being deployed automatically to one or more remote servers. -.. _Fabric: http://www.fabfile.org/ +.. _Fabric: https://www.fabfile.org/ diff --git a/docs/patterns/fileuploads.rst b/docs/patterns/fileuploads.rst index d3b1664333..f24a43caf2 100644 --- a/docs/patterns/fileuploads.rst +++ b/docs/patterns/fileuploads.rst @@ -1,5 +1,3 @@ -.. _uploading-files: - Uploading Files =============== @@ -39,7 +37,7 @@ Why do we limit the extensions that are allowed? You probably don't want your users to be able to upload everything there if the server is directly sending out the data to the client. That way you can make sure that users are not able to upload HTML files that would cause XSS problems (see -:ref:`xss`). Also make sure to disallow ``.php`` files if the server +:ref:`security-xss`). Also make sure to disallow ``.php`` files if the server executes them, but who has PHP installed on their server, right? :) Next the functions that check if an extension is valid and that uploads @@ -57,16 +55,15 @@ the file and redirects the user to the URL for the uploaded file:: flash('No file part') return redirect(request.url) file = request.files['file'] - # if user does not select file, browser also - # submit an empty part without filename + # If the user does not select a file, the browser submits an + # empty file without a filename. if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) - return redirect(url_for('uploaded_file', - filename=filename)) + return redirect(url_for('download_file', name=filename)) return ''' Upload new File @@ -104,31 +101,28 @@ before storing it directly on the filesystem. >>> secure_filename('../../../../home/username/.bashrc') 'home_username_.bashrc' -Now one last thing is missing: the serving of the uploaded files. In the -:func:`upload_file()` we redirect the user to -``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``. -So we write the :func:`uploaded_file` function to return the file of that name. As -of Flask 0.5 we can use a function that does that for us:: +We want to be able to serve the uploaded files so they can be downloaded +by users. We'll define a ``download_file`` view to serve files in the +upload folder by name. ``url_for("download_file", name=name)`` generates +download URLs. + +.. code-block:: python from flask import send_from_directory - @app.route('/uploads/') - def uploaded_file(filename): - return send_from_directory(app.config['UPLOAD_FOLDER'], - filename) + @app.route('/uploads/') + def download_file(name): + return send_from_directory(app.config["UPLOAD_FOLDER"], name) -Alternatively you can register `uploaded_file` as `build_only` rule and -use the :class:`~werkzeug.wsgi.SharedDataMiddleware`. This also works with -older versions of Flask:: +If you're using middleware or the HTTP server to serve files, you can +register the ``download_file`` endpoint as ``build_only`` so ``url_for`` +will work without a view function. - from werkzeug import SharedDataMiddleware - app.add_url_rule('/uploads/', 'uploaded_file', - build_only=True) - app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { - '/uploads': app.config['UPLOAD_FOLDER'] - }) +.. code-block:: python -If you now run the application everything should work as expected. + app.add_url_rule( + "/uploads/", endpoint="download_file", build_only=True + ) Improving Uploads @@ -137,17 +131,17 @@ Improving Uploads .. versionadded:: 0.6 So how exactly does Flask handle uploads? Well it will store them in the -webserver's memory if the files are reasonable small otherwise in a +webserver's memory if the files are reasonably small, otherwise in a temporary location (as returned by :func:`tempfile.gettempdir`). But how do you specify the maximum file size after which an upload is aborted? By -default Flask will happily accept file uploads to an unlimited amount of +default Flask will happily accept file uploads with an unlimited amount of memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH`` config key:: from flask import Flask, Request app = Flask(__name__) - app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 + app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000 The code above will limit the maximum allowed payload to 16 megabytes. If a larger file is transmitted, Flask will raise a @@ -169,10 +163,9 @@ Upload Progress Bars A while ago many developers had the idea to read the incoming file in small chunks and store the upload progress in the database to be able to -poll the progress with JavaScript from the client. Long story short: the -client asks the server every 5 seconds how much it has transmitted -already. Do you realize the irony? The client is asking for something it -should already know. +poll the progress with JavaScript from the client. The client asks the +server every 5 seconds how much it has transmitted, but this is +something it should already know. An Easier Solution ------------------ @@ -183,8 +176,8 @@ construction of progress bar. Because the common pattern for file uploads exists almost unchanged in all applications dealing with uploads, there is also a Flask extension called -`Flask-Uploads`_ that implements a full fledged upload mechanism with white and -blacklisting of extensions and more. +`Flask-Uploads`_ that implements a full fledged upload mechanism that +allows controlling which file extensions are allowed to be uploaded. .. _jQuery: https://jquery.com/ -.. _Flask-Uploads: https://pythonhosted.org/Flask-Uploads/ +.. _Flask-Uploads: https://flask-uploads.readthedocs.io/en/latest/ diff --git a/docs/patterns/flashing.rst b/docs/patterns/flashing.rst index a61c719fef..8eb6b3aca2 100644 --- a/docs/patterns/flashing.rst +++ b/docs/patterns/flashing.rst @@ -1,5 +1,3 @@ -.. _message-flashing-pattern: - Message Flashing ================ @@ -103,7 +101,7 @@ error messages could be displayed with a red background. To flash a message with a different category, just use the second argument to the :func:`~flask.flash` function:: - flash(u'Invalid password provided', 'error') + flash('Invalid password provided', 'error') Inside the template you then have to tell the :func:`~flask.get_flashed_messages` function to also return the diff --git a/docs/patterns/index.rst b/docs/patterns/index.rst index 78a66a1da9..f765cd8a45 100644 --- a/docs/patterns/index.rst +++ b/docs/patterns/index.rst @@ -1,17 +1,16 @@ -.. _patterns: - Patterns for Flask ================== -Certain things are common enough that the chances are high you will find -them in most web applications. For example quite a lot of applications -are using relational databases and user authentication. In that case, -chances are they will open a database connection at the beginning of the -request and get the information of the currently logged in user. At the -end of the request, the database connection is closed again. +Certain features and interactions are common enough that you will find +them in most web applications. For example, many applications use a +relational database and user authentication. They will open a database +connection at the beginning of the request and get the information for +the logged in user. At the end of the request, the database connection +is closed. -There are more user contributed snippets and patterns in the `Flask -Snippet Archives `_. +These types of patterns may be a bit outside the scope of Flask itself, +but Flask makes it easy to implement them. Some common patterns are +collected in the following pages. .. toctree:: :maxdepth: 2 @@ -19,7 +18,6 @@ Snippet Archives `_. packages appfactories appdispatch - apierrors urlprocessors distribute fabric @@ -32,9 +30,8 @@ Snippet Archives `_. templateinheritance flashing jquery - errorpages lazyloading - mongokit + mongoengine favicon streaming deferredcallbacks @@ -42,3 +39,4 @@ Snippet Archives `_. requestchecksum celery subclassing + singlepageapplications diff --git a/docs/patterns/jquery.rst b/docs/patterns/jquery.rst index d4e2c92d86..fafbdf1827 100644 --- a/docs/patterns/jquery.rst +++ b/docs/patterns/jquery.rst @@ -11,7 +11,7 @@ Python primitives (numbers, strings, dicts and lists) look like which is widely supported and very easy to parse. It became popular a few years ago and quickly replaced XML as transport format in web applications. -.. _jQuery: http://jquery.com/ +.. _jQuery: https://jquery.com/ Loading jQuery -------------- @@ -27,7 +27,7 @@ to add a script statement to the bottom of your ```` to load jQuery: url_for('static', filename='jquery.js') }}"> Another method is using Google's `AJAX Libraries API -`_ to load jQuery: +`_ to load jQuery: .. sourcecode:: html @@ -60,27 +60,9 @@ 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 ------------------- @@ -105,7 +87,7 @@ example that shows how you would use jQuery and Flask nonetheless:: 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 +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. 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/methodoverrides.rst b/docs/patterns/methodoverrides.rst index d5c187b67c..45dbb87e20 100644 --- a/docs/patterns/methodoverrides.rst +++ b/docs/patterns/methodoverrides.rst @@ -2,14 +2,14 @@ Adding HTTP Method Overrides ============================ Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP -methods (such as PATCH). In that case it's possible to “proxy” HTTP +methods (such as PATCH). In that case it's possible to "proxy" HTTP methods through another HTTP method in total violation of the protocol. The way this works is by letting the client do an HTTP POST request and -set the ``X-HTTP-Method-Override`` header and set the value to the -intended HTTP method (such as ``PATCH``). +set the ``X-HTTP-Method-Override`` header. Then the method is replaced +with the header value before being passed to Flask. -This can easily be accomplished with an HTTP middleware:: +This can be accomplished with an HTTP middleware:: class HTTPMethodOverrideMiddleware(object): allowed_methods = frozenset([ @@ -29,13 +29,12 @@ This can easily be accomplished with an HTTP middleware:: def __call__(self, environ, start_response): method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper() if method in self.allowed_methods: - method = method.encode('ascii', 'replace') environ['REQUEST_METHOD'] = method if method in self.bodyless_methods: environ['CONTENT_LENGTH'] = '0' return self.app(environ, start_response) -To use this with Flask this is all that is necessary:: +To use this with Flask, wrap the app object with the middleware:: from flask import Flask diff --git a/docs/patterns/mongoengine.rst b/docs/patterns/mongoengine.rst new file mode 100644 index 0000000000..015e7b613b --- /dev/null +++ b/docs/patterns/mongoengine.rst @@ -0,0 +1,103 @@ +MongoDB with MongoEngine +======================== + +Using a document database like MongoDB is a common alternative to +relational SQL databases. This pattern shows how to use +`MongoEngine`_, a document mapper library, to integrate with MongoDB. + +A running MongoDB server and `Flask-MongoEngine`_ are required. :: + + pip install flask-mongoengine + +.. _MongoEngine: http://mongoengine.org +.. _Flask-MongoEngine: https://flask-mongoengine.readthedocs.io + + +Configuration +------------- + +Basic setup can be done by defining ``MONGODB_SETTINGS`` on +``app.config`` and creating a ``MongoEngine`` instance. :: + + from flask import Flask + from flask_mongoengine import MongoEngine + + app = Flask(__name__) + app.config['MONGODB_SETTINGS'] = { + "db": "myapp", + } + db = MongoEngine(app) + + +Mapping Documents +----------------- + +To declare a model that represents a Mongo document, create a class that +inherits from ``Document`` and declare each of the fields. :: + + import mongoengine as me + + class Movie(me.Document): + title = me.StringField(required=True) + year = me.IntField() + rated = me.StringField() + director = me.StringField() + actors = me.ListField() + +If the document has nested fields, use ``EmbeddedDocument`` to +defined the fields of the embedded document and +``EmbeddedDocumentField`` to declare it on the parent document. :: + + class Imdb(me.EmbeddedDocument): + imdb_id = me.StringField() + rating = me.DecimalField() + votes = me.IntField() + + class Movie(me.Document): + ... + imdb = me.EmbeddedDocumentField(Imdb) + + +Creating Data +------------- + +Instantiate your document class with keyword arguments for the fields. +You can also assign values to the field attributes after instantiation. +Then call ``doc.save()``. :: + + bttf = Movie(title="Back To The Future", year=1985) + bttf.actors = [ + "Michael J. Fox", + "Christopher Lloyd" + ] + bttf.imdb = Imdb(imdb_id="tt0088763", rating=8.5) + bttf.save() + + +Queries +------- + +Use the class ``objects`` attribute to make queries. A keyword argument +looks for an equal value on the field. :: + + bttf = Movies.objects(title="Back To The Future").get_or_404() + +Query operators may be used by concatenating them with the field name +using a double-underscore. ``objects``, and queries returned by +calling it, are iterable. :: + + some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first() + + for recents in Movie.objects(year__gte=2017): + print(recents.title) + + +Documentation +------------- + +There are many more ways to define and query documents with MongoEngine. +For more information, check out the `official documentation +`_. + +Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check +out their `documentation `_ as well. diff --git a/docs/patterns/mongokit.rst b/docs/patterns/mongokit.rst deleted file mode 100644 index 9d1b3e2a96..0000000000 --- a/docs/patterns/mongokit.rst +++ /dev/null @@ -1,144 +0,0 @@ -.. mongokit-pattern: - -MongoKit in Flask -================= - -Using a document database rather than a full DBMS gets more common these days. -This pattern shows how to use MongoKit, a document mapper library, to -integrate with MongoDB. - -This pattern requires a running MongoDB server and the MongoKit library -installed. - -There are two very common ways to use MongoKit. I will outline each of them -here: - - -Declarative ------------ - -The default behavior of MongoKit is the declarative one that is based on -common ideas from Django or the SQLAlchemy declarative extension. - -Here an example :file:`app.py` module for your application:: - - from flask import Flask - from mongokit import Connection, Document - - # configuration - MONGODB_HOST = 'localhost' - MONGODB_PORT = 27017 - - # create the little application object - app = Flask(__name__) - app.config.from_object(__name__) - - # connect to the database - connection = Connection(app.config['MONGODB_HOST'], - app.config['MONGODB_PORT']) - - -To define your models, just subclass the `Document` class that is imported -from MongoKit. If you've seen the SQLAlchemy pattern you may wonder why we do -not have a session and even do not define a `init_db` function here. On the -one hand, MongoKit does not have something like a session. This sometimes -makes it more to type but also makes it blazingly fast. On the other hand, -MongoDB is schemaless. This means you can modify the data structure from one -insert query to the next without any problem. MongoKit is just schemaless -too, but implements some validation to ensure data integrity. - -Here is an example document (put this also into :file:`app.py`, e.g.):: - - from mongokit import ValidationError - - def max_length(length): - def validate(value): - if len(value) <= length: - return True - # must have %s in error format string to have mongokit place key in there - raise ValidationError('%s must be at most {} characters long'.format(length)) - return validate - - class User(Document): - structure = { - 'name': unicode, - 'email': unicode, - } - validators = { - 'name': max_length(50), - 'email': max_length(120) - } - use_dot_notation = True - def __repr__(self): - return '' % (self.name) - - # register the User document with our current connection - connection.register([User]) - - -This example shows you how to define your schema (named structure), a -validator for the maximum character length and uses a special MongoKit feature -called `use_dot_notation`. Per default MongoKit behaves like a python -dictionary but with `use_dot_notation` set to ``True`` you can use your -documents like you use models in nearly any other ORM by using dots to -separate between attributes. - -You can insert entries into the database like this: - ->>> from yourapplication.database import connection ->>> from yourapplication.models import User ->>> collection = connection['test'].users ->>> user = collection.User() ->>> user['name'] = u'admin' ->>> user['email'] = u'admin@localhost' ->>> user.save() - -Note that MongoKit is kinda strict with used column types, you must not use a -common `str` type for either `name` or `email` but unicode. - -Querying is simple as well: - ->>> list(collection.User.find()) -[] ->>> collection.User.find_one({'name': u'admin'}) - - -.. _MongoKit: http://bytebucket.org/namlook/mongokit/ - - -PyMongo Compatibility Layer ---------------------------- - -If you just want to use PyMongo, you can do that with MongoKit as well. You -may use this process if you need the best performance to get. Note that this -example does not show how to couple it with Flask, see the above MongoKit code -for examples:: - - from MongoKit import Connection - - connection = Connection() - -To insert data you can use the `insert` method. We have to get a -collection first, this is somewhat the same as a table in the SQL world. - ->>> collection = connection['test'].users ->>> user = {'name': u'admin', 'email': u'admin@localhost'} ->>> collection.insert(user) - -MongoKit will automatically commit for us. - -To query your database, you use the collection directly: - ->>> list(collection.find()) -[{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}] ->>> collection.find_one({'name': u'admin'}) -{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'} - -These results are also dict-like objects: - ->>> r = collection.find_one({'name': u'admin'}) ->>> r['email'] -u'admin@localhost' - -For more information about MongoKit, head over to the -`website `_. diff --git a/docs/patterns/packages.rst b/docs/patterns/packages.rst index f6b5161429..640f33a8e2 100644 --- a/docs/patterns/packages.rst +++ b/docs/patterns/packages.rst @@ -1,11 +1,7 @@ -.. _larger-applications: +Large Applications as Packages +============================== -Larger Applications -=================== - -For larger applications it's a good idea to use a package instead of a -module. That is quite simple. Imagine a small application looks like -this:: +Imagine a simple flask application structure that looks like this:: /yourapplication yourapplication.py @@ -17,8 +13,10 @@ this:: login.html ... -The :ref:`tutorial ` is structured this way, see the -:gh:`example code `. +While this is fine for small applications, for larger applications +it's a good idea to use a package instead of a module. +The :doc:`/tutorial/index` is structured to use the package pattern, +see the :gh:`example code `. Simple Packages --------------- @@ -59,21 +57,57 @@ a big problem, just add a new file called :file:`setup.py` next to the inner ) In order to run the application you need to export an environment variable -that tells Flask where to find the application instance:: +that tells Flask where to find the application instance: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_APP=yourapplication + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_APP=yourapplication + + .. group-tab:: Powershell + + .. code-block:: text - export FLASK_APP=yourapplication + > $env:FLASK_APP = "yourapplication" If you are outside of the project directory make sure to provide the exact path to your application directory. Similarly you can turn on the -development features like this:: +development features like this: - export FLASK_ENV=development +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_ENV=development + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_ENV=development + + .. group-tab:: Powershell + + .. code-block:: text + + > $env:FLASK_ENV = "development" In order to install and run the application you need to issue the following commands:: - pip install -e . - flask run + $ pip install -e . + $ flask run What did we gain from this? Now we can restructure the application a bit into multiple modules. The only thing you have to remember is the @@ -129,10 +163,8 @@ You should then end up with something like that:: 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. - + :doc:`/becomingbig` section for some inspiration how to deal with that. -.. _working-with-modules: Working with Blueprints ----------------------- @@ -140,4 +172,4 @@ Working with Blueprints If you have larger applications it's recommended to divide them into smaller groups where each group is implemented with the help of a blueprint. For a gentle introduction into this topic refer to the -:ref:`blueprints` chapter of the documentation. +:doc:`/blueprints` chapter of the documentation. diff --git a/docs/patterns/requestchecksum.rst b/docs/patterns/requestchecksum.rst index 902be64ab8..25bc38b2a4 100644 --- a/docs/patterns/requestchecksum.rst +++ b/docs/patterns/requestchecksum.rst @@ -52,4 +52,4 @@ Example usage:: files = request.files # At this point the hash is fully constructed. checksum = hash.hexdigest() - return 'Hash was: %s' % checksum + return f"Hash was: {checksum}" diff --git a/docs/patterns/singlepageapplications.rst b/docs/patterns/singlepageapplications.rst new file mode 100644 index 0000000000..1cb779b33b --- /dev/null +++ b/docs/patterns/singlepageapplications.rst @@ -0,0 +1,24 @@ +Single-Page Applications +======================== + +Flask can be used to serve Single-Page Applications (SPA) by placing static +files produced by your frontend framework in a subfolder inside of your +project. You will also need to create a catch-all endpoint that routes all +requests to your SPA. + +The following example demonstrates how to serve an SPA along with an API:: + + from flask import Flask, jsonify + + app = Flask(__name__, static_folder='app', static_url_path="/app") + + + @app.route("/heartbeat") + def heartbeat(): + return jsonify({"status": "healthy"}) + + + @app.route('/', defaults={'path': ''}) + @app.route('/') + def catch_all(path): + return app.send_static_file("index.html") diff --git a/docs/patterns/sqlalchemy.rst b/docs/patterns/sqlalchemy.rst index 831d54f003..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: @@ -22,7 +20,7 @@ if you want to get started quickly. You can download `Flask-SQLAlchemy`_ from `PyPI `_. -.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/ +.. _Flask-SQLAlchemy: https://flask-sqlalchemy.palletsprojects.com/ Declarative @@ -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..8cf596d3b9 100644 --- a/docs/patterns/sqlite3.rst +++ b/docs/patterns/sqlite3.rst @@ -1,5 +1,3 @@ -.. _sqlite3: - Using SQLite 3 with Flask ========================= @@ -62,7 +60,6 @@ the application context by hand:: with app.app_context(): # now you can use get_db() -.. _easy-querying: Easy Querying ------------- diff --git a/docs/patterns/streaming.rst b/docs/patterns/streaming.rst index f5bff3ca01..e8571ffdad 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 app.response_class(generate(), mimetype='text/csv') Each ``yield`` expression is directly sent to the browser. Note though that some WSGI middlewares might break streaming, so be careful there in @@ -35,8 +33,6 @@ 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) @@ -47,7 +43,7 @@ quite uncommon, but you can easily do it yourself:: @app.route('/my-large-page.html') def render_large_template(): rows = iter_all_rows() - return Response(stream_template('the_template.html', rows=rows)) + return app.response_class(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 @@ -70,7 +66,7 @@ moment the function executes. Flask 0.9 provides you with a helper that can keep the request context around during the execution of the generator:: - from flask import stream_with_context, request, Response + from flask import stream_with_context, request @app.route('/stream') def streamed_response(): @@ -78,7 +74,7 @@ generator:: yield 'Hello ' yield request.args['name'] yield '!' - return Response(stream_with_context(generate())) + return app.response_class(stream_with_context(generate())) Without the :func:`~flask.stream_with_context` function you would get a :class:`RuntimeError` at that point. diff --git a/docs/patterns/templateinheritance.rst b/docs/patterns/templateinheritance.rst index 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..b0960b2d72 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..e5fd500d9a 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 @@ -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 8f055d40e2..9418835a58 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -1,76 +1,87 @@ -.. _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 run the application, use the :command:`flask` command or +:command:`python -m flask`. Before you can do that you need to tell your terminal the application to work with by exporting the -``FLASK_APP`` environment variable:: +``FLASK_APP`` environment variable: + +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text - $ export FLASK_APP=hello.py - $ flask run - * Running on http://127.0.0.1:5000/ + $ export FLASK_APP=hello + $ 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:: + .. group-tab:: CMD - C:\path\to\app>set FLASK_APP=hello.py + .. code-block:: text -And on PowerShell:: + > set FLASK_APP=hello + > flask run + * Running on http://127.0.0.1:5000/ - PS C:\path\to\app> $env:FLASK_APP = "hello.py" + .. group-tab:: Powershell -Alternatively you can use :command:`python -m flask`:: + .. code-block:: text - $ export FLASK_APP=hello.py - $ python -m flask run - * Running on http://127.0.0.1:5000/ + > $env:FLASK_APP = "hello" + > flask run + * Running on http://127.0.0.1:5000/ -This launches a very simple builtin server, which is good enough for testing -but probably not what you want to use in production. For deployment options see -:ref:`deployment`. +.. admonition:: Application Discovery Behavior -Now head over to `http://127.0.0.1:5000/ `_, and you -should see your hello world greeting. + As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you + don't have to set the ``FLASK_APP`` environment variable. 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 :doc:`deploying/index`. + +Now head over to http://127.0.0.1:5000/, and you should see your hello +world greeting. .. _public-server: @@ -85,7 +96,7 @@ should see your hello world greeting. you can make the server publicly available simply by adding ``--host=0.0.0.0`` to the command line:: - flask run --host=0.0.0.0 + $ flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs. @@ -93,18 +104,18 @@ should see your hello world greeting. 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. +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 +Versions of Flask older than 0.11 used 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. +either upgrade to newer Flask versions or have a look at :doc:`/server` +to see the alternative method for running a server. Invalid Import Name ``````````````````` @@ -117,59 +128,89 @@ 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 all development features, set the ``FLASK_ENV`` environment +variable to ``development`` before calling ``flask run``. -(On Windows you need to use ``set`` instead of ``export``.) +.. tabs:: -This does the following things: + .. group-tab:: Bash -1. it activates the debugger -2. it activates the automatic reloader -3. it enables the debug mode on the Flask application. + .. code-block:: text -You can also control debug mode separately from the environment by -exporting ``FLASK_DEBUG=1``. + $ export FLASK_ENV=development + $ flask run -There are more parameters that are explained in the :ref:`server` docs. + .. group-tab:: CMD -.. admonition:: Attention + .. code-block:: text - 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**. + > set FLASK_ENV=development + > flask run -Screenshot of the debugger in action: + .. group-tab:: Powershell -.. image:: _static/debugger.png - :align: center - :class: screenshot - :alt: screenshot of debugger in action + .. code-block:: text + + > $env:FLASK_ENV = "development" + > flask run -More information on using the debugger can be found in the `Werkzeug -documentation`_. +See also: -.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger +- :doc:`/server` and :doc:`/cli` for information about running in + development 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. -Have another debugger in mind? See :ref:`working-with-debuggers`. + +HTML Escaping +------------- + +When returning HTML (the default response type in Flask), any +user-provided values rendered in the output must be escaped to protect +from injection attacks. HTML templates rendered with Jinja, introduced +later, will do this automatically. + +:func:`~markupsafe.escape`, shown here, can be used manually. It is +omitted in most examples for brevity, but you should always be aware of +how you're using untrusted data. + +.. code-block:: python + + from markupsafe import escape + + @app.route("/") + def hello(name): + return f"Hello, {escape(name)}!" + +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 +241,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' % username + return f'User {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' % subpath + return f'Subpath {subpath}' Converter types: @@ -225,6 +268,7 @@ Converter types: ``uuid`` accepts UUID strings ========== ========================================== + Unique URLs / Redirection Behavior `````````````````````````````````` @@ -240,14 +284,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: @@ -265,23 +309,22 @@ 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. + manually change hard-coded URLs. +3. URL building handles escaping of special characters transparently. 4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers. 5. If your application is placed outside the URL root, for example, in - ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly - handles that for you. + ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly + handles that for you. For example, here we use the :meth:`~flask.Flask.test_request_context` method to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context` tells Flask to behave as though it's handling a request even while we use a -Python shell. See :ref:`context-locals`. :: +Python shell. See :ref:`context-locals`. - from flask import Flask, url_for +.. code-block:: python - app = Flask(__name__) + from flask import url_for @app.route('/') def index(): @@ -293,7 +336,7 @@ Python shell. See :ref:`context-locals`. :: @app.route('/user/') def profile(username): - return '{}\'s profile'.format(username) + return f'{username}\'s profile' with app.test_request_context(): print(url_for('index')) @@ -301,11 +344,14 @@ Python shell. See :ref:`context-locals`. :: print(url_for('login', next='/')) print(url_for('profile', username='John Doe')) +.. code-block:: text + / /login /login?next=/ /user/John%20Doe + HTTP Methods ```````````` @@ -351,7 +397,7 @@ 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. 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 @@ -384,7 +430,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,26 +449,26 @@ Inside templates you also have access to the :class:`~flask.request`, as well as the :func:`~flask.get_flashed_messages` function. Templates are especially useful if inheritance is used. If you want to -know how that works, head over to the :ref:`template-inheritance` pattern -documentation. Basically template inheritance makes it possible to keep -certain elements on each page (like header, navigation and footer). +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 \xbb HTML' .. versionchanged:: 0.5 @@ -432,9 +478,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 @@ -490,8 +535,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' @@ -555,9 +598,9 @@ filesystem. You can access those files by looking at the :attr:`~flask.request.files` attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python :class:`file` object, but it also has a -:meth:`~werkzeug.datastructures.FileStorage.save` method that allows you to store that -file on the filesystem of the server. Here is a simple example showing how -that works:: +:meth:`~werkzeug.datastructures.FileStorage.save` method that +allows you to store that file on the filesystem of the server. +Here is a simple example showing how that works:: from flask import request @@ -570,23 +613,23 @@ that works:: If you want to know how the file was named on the client before it was uploaded to your application, you can access the -:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. However please keep in -mind that this value can be forged so never ever trust that value. If you -want to use the filename of the client to store the file on the server, -pass it through the :func:`~werkzeug.utils.secure_filename` function that +:attr:`~werkzeug.datastructures.FileStorage.filename` attribute. +However please keep in mind that this value can be forged +so never ever trust that value. If you want to use the filename +of the client to store the file on the server, pass it through the +:func:`~werkzeug.utils.secure_filename` function that Werkzeug provides for you:: - from flask import request from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': - f = request.files['the_file'] - f.save('/var/www/uploads/' + secure_filename(f.filename)) + file = request.files['the_file'] + file.save(f"/var/www/uploads/{secure_filename(f.filename)}") ... -For some better examples, checkout the :ref:`uploading-files` pattern. +For some better examples, see :doc:`patterns/fileuploads`. Cookies ``````` @@ -626,7 +669,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`. @@ -666,29 +709,33 @@ Note the ``404`` after the :func:`~flask.render_template` call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well. -See :ref:`error-handlers` for more details. +See :doc:`errorhandling` for more details. .. _about-responses: About Responses --------------- -The return value from a view function is automatically converted into a -response object for you. If the return value is a string it's converted -into a response object with the string as response body, a ``200 OK`` -status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to -converting return values into response objects is as follows: +The return value from a view function is automatically converted into +a response object for you. If the return value is a string it's +converted into a response object with the string as response body, a +``200 OK`` status code and a :mimetype:`text/html` mimetype. If the +return value is a dict, :func:`jsonify` is called to produce a response. +The logic that Flask applies to converting return values into response +objects is as follows: 1. If a response object of the correct type is returned it's directly returned from the view. -2. If it's a string, a response object is created with that data and the - default parameters. -3. If a tuple is returned the items in the tuple can provide extra - information. Such tuples have to be in the form ``(response, status, - headers)`` or ``(response, headers)`` where at least one item has - to be in the tuple. The ``status`` value will override the status code - and ``headers`` can be a list or dictionary of additional header values. -4. If none of that works, Flask will assume the return value is a +2. If it's a string, a response object is created with that data and + the default parameters. +3. If it's a dict, a response object is created using ``jsonify``. +4. If a tuple is returned the items in the tuple can provide extra + information. Such tuples have to be in the form + ``(response, status)``, ``(response, headers)``, or + ``(response, status, headers)``. The ``status`` value will override + the status code and ``headers`` can be a list or dictionary of + additional header values. +5. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object. If you want to get hold of the resulting response object inside the view @@ -696,6 +743,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 @@ -704,12 +753,49 @@ You just need to wrap the return expression with :func:`~flask.make_response` and get the response object to modify it, then return it:: + from flask import make_response + @app.errorhandler(404) def not_found(error): resp = make_response(render_template('error.html'), 404) resp.headers['X-Something'] = 'A value' return resp + +APIs with JSON +`````````````` + +A common response format when writing an API is JSON. It's easy to get +started writing such an API with Flask. If you return a ``dict`` from a +view, it will be converted to a JSON response. + +.. code-block:: python + + @app.route("/me") + def me_api(): + user = get_current_user() + return { + "username": user.username, + "theme": user.theme, + "image": url_for("user_image", filename=user.image), + } + +Depending on your API design, you may want to create JSON responses for +types other than ``dict``. In that case, use the +:func:`~flask.json.jsonify` function, which will serialize any supported +JSON data type. Or look into Flask community extensions that support +more complex applications. + +.. code-block:: python + + from flask import jsonify + + @app.route("/users") + def users_api(): + users = get_all_users() + return jsonify([user.to_json() for user in users]) + + .. _sessions: Sessions @@ -725,9 +811,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]/' @@ -735,7 +819,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']) @@ -756,9 +840,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 @@ -792,8 +873,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 ------- @@ -801,12 +882,12 @@ Logging .. versionadded:: 0.3 Sometimes you might be in a situation where you deal with data that -should be correct, but actually is not. For example you may have some client-side -code that sends an HTTP request to the server but it's obviously -malformed. This might be caused by a user tampering with the data, or the -client code failing. Most of the time it's okay to reply with ``400 Bad -Request`` in that situation, but sometimes that won't do and the code has -to continue working. +should be correct, but actually is not. For example you may have +some client-side code that sends an HTTP request to the server +but it's obviously malformed. This might be caused by a user tampering +with the data, or the client code failing. Most of the time it's okay +to reply with ``400 Bad Request`` in that situation, but sometimes +that won't do and the code has to continue working. You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you @@ -819,22 +900,28 @@ Here are some example log calls:: app.logger.error('An error occurred') The attached :attr:`~flask.Flask.logger` is a standard logging -:class:`~logging.Logger`, so head over to the official `logging -documentation `_ for more -information. +:class:`~logging.Logger`, so head over to the official :mod:`logging` +docs for more information. + +See :doc:`errorhandling`. + + +Hooking in WSGI Middleware +-------------------------- -Read more on :ref:`application-errors`. +To add WSGI middleware to your Flask application, wrap the application's +``wsgi_app`` attribute. For example, to apply Werkzeug's +:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running +behind Nginx: -Hooking in WSGI Middlewares ---------------------------- +.. code-block:: python -If you want to add a WSGI middleware to your application you can wrap the -internal WSGI application. For example if you want to use one of the -middlewares from the Werkzeug package to work around bugs in lighttpd, you -can do it like this:: + from werkzeug.middleware.proxy_fix import ProxyFix + app.wsgi_app = ProxyFix(app.wsgi_app) - from werkzeug.contrib.fixers import LighttpdCGIRootFix - app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app) +Wrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still +points at your Flask application, not at the middleware, so you can +continue to use and configure ``app`` directly. Using Flask Extensions ---------------------- @@ -843,9 +930,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..31a83cffef 100644 --- a/docs/reqcontext.rst +++ b/docs/reqcontext.rst @@ -1,7 +1,5 @@ .. currentmodule:: flask -.. _request-context: - The Request Context =================== @@ -109,7 +107,7 @@ 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 +168,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,7 +197,7 @@ 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 ~~~~~~~ @@ -251,13 +249,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/security.rst b/docs/security.rst index 44c095acb7..31d006527c 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) -------------------------- @@ -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 ------------- @@ -258,3 +258,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..71704e4a11 100644 --- a/docs/server.rst +++ b/docs/server.rst @@ -1,62 +1,109 @@ -.. _server: +.. currentmodule:: flask Development Server ================== -.. currentmodule:: flask +Flask provides a ``run`` command to run the application with a +development server. In development mode, this server provides an +interactive debugger and will reload when code is changed. + +.. warning:: -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. + Do not use the development server when deploying to production. It + is intended for use only during local development. It is not + designed to be particularly efficient, stable, or secure. + + See :doc:`/deploying/index` for deployment options. 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`` command line script is the recommended way to run the +development server. It requires setting the ``FLASK_APP`` environment +variable to point to your application, and ``FLASK_ENV=development`` to +fully enable development mode. - $ export FLASK_APP=my_application - $ export FLASK_ENV=development - $ flask run +.. tabs:: -This enables the development environment, including the interactive -debugger and reloader, and then starts the server on -*http://localhost:5000/*. + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_APP=hello + $ export FLASK_ENV=development + $ flask run + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_APP=hello + > set FLASK_ENV=development + > flask run + + .. group-tab:: Powershell -The individual features of the server can be controlled by passing more -arguments to the ``run`` option. For instance the reloader can be -disabled:: + .. code-block:: text - $ flask run --no-reload + > $env:FLASK_APP = "hello" + > $env:FLASK_ENV = "development" + > flask run + +This enables the development environment, including the interactive +debugger and reloader, and then starts the server on +http://localhost:5000/. Use ``flask run --help`` to see the available +options, and :doc:`/cli` for detailed instructions about configuring +and using the CLI. .. note:: - Prior to Flask 1.0 the :envvar:`FLASK_ENV` environment variable was - not supported and you needed to enable debug mode by exporting + Prior to Flask 1.0 the ``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. + +Lazy or Eager Loading +~~~~~~~~~~~~~~~~~~~~~ + +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. +This feature is called "lazy loading". + +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. + +To override this behavior and always fail immediately, even on reload, +pass the ``--eager-loading`` option. To always keep the server running, +even on the initial call, pass ``--lazy-loading``. + + 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. +As an alternative to the ``flask run`` command, 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 the debugger and reloader, but +the ``FLASK_ENV=development`` environment variable is still required to +fully enable development mode. + +Place the call in a main block, otherwise it will interfere when trying +to import and run the application with a production server later. -Example:: +.. code-block:: python - if __name__ == '__main__': - app.run() + if __name__ == "__main__": + app.run(debug=True) -This works well for the common case but it does not work well for -development which is why from Flask 0.11 onwards the :command:`flask` -method is recommended. The reason for this is that due to how the reload -mechanism works there are some bizarre side-effects (like executing -certain code twice, sometimes crashing without message or dying when a -syntax or import error happens). +.. code-block:: text -It is however still a perfectly valid method for invoking a non automatic -reloading application. + $ python hello.py diff --git a/docs/shell.rst b/docs/shell.rst index 9d9bb5f9f9..47efba3784 100644 --- a/docs/shell.rst +++ b/docs/shell.rst @@ -1,5 +1,3 @@ -.. _shell: - Working with the Shell ====================== @@ -20,10 +18,10 @@ can you do? This is where some helper functions come in handy. Keep in mind however that these functions are not only there for interactive shell usage, but -also for unittesting and other situations that require a faked request +also for unit testing and other situations that require a faked request context. -Generally it's recommended that you read the :ref:`request-context` +Generally it's recommended that you read the :doc:`reqcontext` chapter of the documentation first. Command Line Interface @@ -34,7 +32,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..1e5cdd65ef 100644 --- a/docs/signals.rst +++ b/docs/signals.rst @@ -1,5 +1,3 @@ -.. _signals: - Signals ======= @@ -162,7 +160,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 @@ -179,7 +177,7 @@ With Blinker 1.1 you can also easily subscribe to signals by using the new @template_rendered.connect_via(app) def when_template_rendered(sender, template, context, **extra): - print 'Template %s is rendered with %s' % (template.name, context) + print f'Template {template.name} is rendered with {context}' Core Signals ------------ 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 c0af663992..b0964df8b1 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 @@ -97,28 +95,6 @@ by default: {% from '_helpers.html' import my_macro with context %} -Standard Filters ----------------- - -These filters are available in Jinja2 additionally to the filters provided -by Jinja2 itself: - -.. function:: tojson - :noindex: - - This function converts the given object into JSON representation. This - is for example very helpful if you try to generate JavaScript on the - fly. - - Note that inside ``script`` tags no escaping must take place, so make - sure to disable escaping with ``|safe`` before Flask 0.10 if you intend - to use it inside ``script`` tags: - - .. sourcecode:: html+jinja - - Controlling Autoescaping ------------------------ @@ -130,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 @@ -213,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 diff --git a/docs/testing.rst b/docs/testing.rst index 50e727620f..2fedc600df 100644 --- a/docs/testing.rst +++ b/docs/testing.rst @@ -1,5 +1,3 @@ -.. _testing: - Testing Flask Applications ========================== @@ -18,17 +16,19 @@ You can then use that with your favourite testing solution. In this documentation we will use the `pytest`_ package as the base framework for our tests. You can install it with ``pip``, like so:: - pip install pytest + $ pip install pytest -.. _pytest: - https://pytest.org +.. _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 :doc:`tutorial/index`. If you don't have that application yet, get +the source code from :gh:`the examples `. + +So that we can import the module ``flaskr`` correctly, we need to run +``pip install -e .`` in the folder ``tutorial``. The Testing Skeleton -------------------- @@ -47,19 +47,18 @@ the application for testing and initializes a new database:: import pytest - from flaskr import flaskr + from flaskr import create_app @pytest.fixture def client(): db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp() flaskr.app.config['TESTING'] = True - client = flaskr.app.test_client() - with flaskr.app.app_context(): - flaskr.init_db() - - yield client + 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']) @@ -73,9 +72,9 @@ 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 +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. @@ -93,9 +92,9 @@ If we now run the test suite, we should see the following output:: =========== 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. +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 @@ -117,11 +116,13 @@ test function to :file:`test_flaskr.py`, like this:: 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. +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.Response.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:: @@ -162,16 +163,19 @@ invalid credentials. Add this new test function:: def test_login_logout(client): """Make sure login and logout works.""" - rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']) + username = flaskr.app.config["USERNAME"] + password = flaskr.app.config["PASSWORD"] + + rv = login(client, username, password) assert b'You were logged in' in rv.data rv = logout(client) assert b'You were logged out' in rv.data - rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD']) + rv = login(client, f"{username}x", password) assert b'Invalid username' in rv.data - rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x') + rv = login(client, username, f'{password}x') assert b'Invalid password' in rv.data Test Adding Messages @@ -233,7 +237,7 @@ way. If you want to test your application with different configurations and there does not seem to be a good way to do that, consider switching to -application factories (see :ref:`app-factories`). +application factories (see :doc:`patterns/appfactories`). Note however that if you are using a test request context, the :meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request` @@ -312,7 +316,7 @@ And then to use it:: with app.test_client() as c: resp = c.get('/users/me') data = json.loads(resp.data) - self.assert_equal(data['username'], my_user.username) + assert data['username'] == my_user.username Keeping the Context Around @@ -333,7 +337,8 @@ happen. With Flask 0.4 this is possible by using the 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). +is no longer available (because you are trying to use it +outside of the actual request). Accessing and Modifying Sessions @@ -354,14 +359,15 @@ This however does not make it possible to also modify the session or to access the session before a request was fired. Starting with Flask 0.8 we provide a so called “session transaction” which simulates the appropriate calls to open a session in the context of the test client and to modify -it. At the end of the transaction the session is stored. This works -independently of the session backend used:: +it. At the end of the transaction the session is stored and ready to be +used by the test client. This works independently of the session backend used:: with app.test_client() as c: with c.session_transaction() as sess: sess['a_key'] = 'a value' - # once this is reached the session was stored + # once this is reached the session was stored and ready to be used by the client + c.get(...) Note that in this case you have to use the ``sess`` object instead of the :data:`flask.session` proxy. The object however itself will provide the @@ -388,7 +394,7 @@ very convenient:: with app.test_client() as c: rv = c.post('/api/auth', json={ - 'username': 'flask', 'password': 'secret' + 'email': 'flask@example.com', 'password': 'secret' }) json_data = rv.get_json() assert verify_token(email, json_data['token']) @@ -418,7 +424,7 @@ command line. :: @app.cli.command('hello') @click.option('--name', default='World') - def hello_command(name) + def hello_command(name): click.echo(f'Hello, {name}!') def test_hello(): @@ -445,12 +451,12 @@ This is useful for testing complex validation rules and custom types. :: @app.cli.command('hello') @click.option('--name', default='World', callback=upper) - def hello_command(name) + def hello_command(name): click.echo(f'Hello, {name}!') def test_hello_params(): context = hello_command.make_context('hello', ['--name', 'flask']) assert context.params['name'] == 'FLASK' -.. _click: http://click.pocoo.org/ -.. _utilities for testing: http://click.pocoo.org/testing +.. _click: https://click.palletsprojects.com/ +.. _utilities for testing: https://click.palletsprojects.com/testing/ diff --git a/docs/tutorial/blog.rst b/docs/tutorial/blog.rst index 4511d61b74..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) @@ -314,7 +314,7 @@ Delete The delete view doesn't have its own template, the delete button is part of ``update.html`` and posts to the ``//delete`` URL. Since there -is no template, it will only handle the ``POST`` method then redirect +is no template, it will only handle the ``POST`` method and then redirect to the ``index`` view. .. code-block:: python diff --git a/docs/tutorial/database.rst b/docs/tutorial/database.rst index 51f20b615c..b094909eca 100644 --- a/docs/tutorial/database.rst +++ b/docs/tutorial/database.rst @@ -142,14 +142,14 @@ read from the file. :func:`click.command` defines a command line command called ``init-db`` that calls the ``init_db`` function and shows a success message to the -user. You can read :ref:`cli` to learn more about writing commands. +user. You can read :doc:`/cli` to learn more about writing commands. Register with the Application ----------------------------- The ``close_db`` and ``init_db_command`` functions need to be registered -with the application instance, otherwise they won't be used by the +with the application instance; otherwise, they won't be used by the application. However, since you're using a factory function, that instance isn't available when writing the functions. Instead, write a function that takes an application and does the registration. @@ -196,15 +196,15 @@ previous page. If you're still running the server from the previous page, you can either stop the server, or run this command in a new terminal. If you use a new terminal, remember to change to your project directory - and activate the env as described in :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`. You'll + also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on the + previous page. Run the ``init-db`` command: .. code-block:: none - flask init-db + $ flask init-db Initialized the database. There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in diff --git a/docs/tutorial/deploy.rst b/docs/tutorial/deploy.rst index a0c052ea6f..d954b5e7e0 100644 --- a/docs/tutorial/deploy.rst +++ b/docs/tutorial/deploy.rst @@ -21,7 +21,7 @@ is installed first: .. code-block:: none - pip install wheel + $ pip install wheel Running ``setup.py`` with Python gives you a command line tool to issue build-related commands. The ``bdist_wheel`` command will build a wheel @@ -29,11 +29,11 @@ distribution file. .. code-block:: none - python setup.py bdist_wheel + $ python setup.py bdist_wheel You can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The -file name is the name of the project, the version, and some tags about -the file can install. +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 @@ -41,17 +41,35 @@ file with ``pip``. .. code-block:: none - pip install flaskr-1.0.0-py3-none-any.whl + $ pip install flaskr-1.0.0-py3-none-any.whl Pip will install your project along with its dependencies. Since this is a different machine, you need to run ``init-db`` again to create the database in the instance folder. -.. code-block:: none +.. tabs:: + + .. group-tab:: Bash + + .. code-block:: text + + $ export FLASK_APP=flaskr + $ flask init-db + + .. group-tab:: CMD + + .. code-block:: text + + > set FLASK_APP=flaskr + > flask init-db + + .. group-tab:: Powershell + + .. code-block:: text - export FLASK_APP=flaskr - flask init-db + > $env:FLASK_APP = "flaskr" + > flask init-db When Flask detects that it's installed (not in editable mode), it uses a different directory for the instance folder. You can find it at @@ -70,7 +88,7 @@ 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 os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/' @@ -99,7 +117,7 @@ first install it in the virtual environment: .. code-block:: none - pip install waitress + $ pip install waitress You need to tell Waitress about your application, but it doesn't use ``FLASK_APP`` like ``flask run`` does. You need to tell it to import and @@ -107,7 +125,7 @@ call the application factory to get an application object. .. code-block:: none - waitress-serve --call 'flaskr:create_app' + $ waitress-serve --call 'flaskr:create_app' Serving on http://0.0.0.0:8080 @@ -116,6 +134,6 @@ your application. Waitress is just an example, chosen for the tutorial because it supports both Windows and Linux. There are many more WSGI servers and deployment options that you may choose for your project. -.. _Waitress: https://docs.pylonsproject.org/projects/waitress/ +.. _Waitress: https://docs.pylonsproject.org/projects/waitress/en/stable/ Continue to :doc:`next`. diff --git a/docs/tutorial/factory.rst b/docs/tutorial/factory.rst index 62462e1cd7..ade5d40bbb 100644 --- a/docs/tutorial/factory.rst +++ b/docs/tutorial/factory.rst @@ -30,7 +30,7 @@ directory should be treated as a package. .. code-block:: none - mkdir flaskr + $ mkdir flaskr .. code-block:: python :caption: ``flaskr/__init__.py`` @@ -127,36 +127,39 @@ 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. +development mode. Remember, you should still be in the top-level +``flask-tutorial`` directory, not the ``flaskr`` package. Development mode shows an interactive debugger whenever a page raises an exception, and restarts the server whenever you make changes to the code. You can leave it running and just reload the browser page as you follow the tutorial. -For Linux and Mac: +.. tabs:: -.. code-block:: none + .. group-tab:: Bash - export FLASK_APP=flaskr - export FLASK_ENV=development - flask run + .. code-block:: text -For Windows cmd, use ``set`` instead of ``export``: + $ export FLASK_APP=flaskr + $ export FLASK_ENV=development + $ flask run -.. code-block:: none + .. group-tab:: CMD - set FLASK_APP=flaskr - set FLASK_ENV=development - flask run + .. code-block:: text -For Windows PowerShell, use ``$env:`` instead of ``export``: + > set FLASK_APP=flaskr + > set FLASK_ENV=development + > flask run -.. code-block:: none + .. group-tab:: Powershell + + .. code-block:: text - $env:FLASK_APP = "flaskr" - $env:FLASK_ENV = "development" - flask run + > $env:FLASK_APP = "flaskr" + > $env:FLASK_ENV = "development" + > flask run You'll see output similar to this: diff --git a/docs/tutorial/index.rst b/docs/tutorial/index.rst index 9b43c510fa..103c27a8c8 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 diff --git a/docs/tutorial/install.rst b/docs/tutorial/install.rst index fff0b52ce4..3d7d7c602b 100644 --- a/docs/tutorial/install.rst +++ b/docs/tutorial/install.rst @@ -70,7 +70,7 @@ files. See the `official packaging guide`_ for another explanation of the files and options used. -.. _official packaging guide: https://packaging.python.org/tutorials/distributing-packages/ +.. _official packaging guide: https://packaging.python.org/tutorials/packaging-projects/ Install the Project @@ -80,7 +80,7 @@ Use ``pip`` to install your project in the virtual environment. .. code-block:: none - pip install -e . + $ 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 @@ -91,7 +91,7 @@ You can observe that the project is now installed with ``pip list``. .. code-block:: none - pip list + $ pip list Package Version Location -------------- --------- ---------------------------------- @@ -108,6 +108,7 @@ You can observe that the project is now installed with ``pip list``. Nothing changes from how you've been running your project so far. ``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs -the application. +the application, but you can call it from anywhere, not just the +``flask-tutorial`` directory. Continue to :doc:`tests`. diff --git a/docs/tutorial/layout.rst b/docs/tutorial/layout.rst index 8133ebfc1f..cb4d74b00d 100644 --- a/docs/tutorial/layout.rst +++ b/docs/tutorial/layout.rst @@ -5,8 +5,8 @@ Create a project directory and enter it: .. code-block:: none - mkdir flask-tutorial - cd flask-tutorial + $ mkdir flask-tutorial + $ cd flask-tutorial Then follow the :doc:`installation instructions ` to set up a Python virtual environment and install Flask for your project. 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 226081c939..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 @@ -73,7 +73,7 @@ specific sections. :data:`g` is automatically available in templates. Based on if ``g.user`` is set (from ``load_logged_in_user``), either the username -and a log out link are displayed, otherwise links to register and log in +and a log out link are displayed, or links to register and log in are displayed. :func:`url_for` is also automatically available, and is used to generate URLs to views instead of writing them out manually. diff --git a/docs/tutorial/tests.rst b/docs/tutorial/tests.rst index 565450f9a4..d8f2a931b3 100644 --- a/docs/tutorial/tests.rst +++ b/docs/tutorial/tests.rst @@ -28,7 +28,7 @@ Install them both: .. code-block:: none - pip install pytest coverage + $ pip install pytest coverage .. _pytest: https://pytest.readthedocs.io/ .. _coverage: https://coverage.readthedocs.io/ @@ -107,7 +107,7 @@ local development configuration. return app.test_cli_runner() :func:`tempfile.mkstemp` creates and opens a temporary file, returning -the file 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 @@ -188,7 +188,7 @@ should be closed. with pytest.raises(sqlite3.ProgrammingError) as e: db.execute('SELECT 1') - assert 'closed' in str(e) + assert 'closed' in str(e.value) The ``init-db`` command should call the ``init_db`` function and output a message. @@ -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 @@ -510,7 +510,7 @@ the test functions you've written. .. code-block:: none - pytest + $ pytest ========================= test session starts ========================== platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0 @@ -532,13 +532,13 @@ to run pytest instead of running it directly. .. code-block:: none - coverage run -m pytest + $ coverage run -m pytest You can either view a simple coverage report in the terminal: .. code-block:: none - coverage report + $ coverage report Name Stmts Miss Branch BrPart Cover ------------------------------------------------------ @@ -553,7 +553,7 @@ An HTML report allows you to see which lines were covered in each file: .. code-block:: none - coverage html + $ coverage html This generates files in the ``htmlcov`` directory. Open ``htmlcov/index.html`` in your browser to see the report. diff --git a/docs/tutorial/views.rst b/docs/tutorial/views.rst index 86689111b7..2d5a01d311 100644 --- a/docs/tutorial/views.rst +++ b/docs/tutorial/views.rst @@ -94,7 +94,7 @@ write templates to generate the HTML form. elif db.execute( 'SELECT id FROM user WHERE username = ?', (username,) ).fetchone() is not None: - error = 'User {} is already registered.'.format(username) + error = f"User {username} is already registered." if error is None: db.execute( diff --git a/docs/unicode.rst b/docs/unicode.rst deleted file mode 100644 index 5aa6e25def..0000000000 --- a/docs/unicode.rst +++ /dev/null @@ -1,107 +0,0 @@ -Unicode in Flask -================ - -Flask, like Jinja2 and Werkzeug, is totally Unicode based when it comes to -text. Not only these libraries, also the majority of web related Python -libraries that deal with text. If you don't know Unicode so far, you -should probably read `The Absolute Minimum Every Software Developer -Absolutely, Positively Must Know About Unicode and Character Sets -`_. This part of the -documentation just tries to cover the very basics so that you have a -pleasant experience with Unicode related things. - -Automatic Conversion --------------------- - -Flask has a few assumptions about your application (which you can change -of course) that give you basic and painless Unicode support: - -- the encoding for text on your website is UTF-8 -- internally you will always use Unicode exclusively for text except - for literal strings with only ASCII character points. -- encoding and decoding happens whenever you are talking over a protocol - that requires bytes to be transmitted. - -So what does this mean to you? - -HTTP is based on bytes. Not only the protocol, also the system used to -address documents on servers (so called URIs or URLs). However HTML which -is usually transmitted on top of HTTP supports a large variety of -character sets and which ones are used, are transmitted in an HTTP header. -To not make this too complex Flask just assumes that if you are sending -Unicode out you want it to be UTF-8 encoded. Flask will do the encoding -and setting of the appropriate headers for you. - -The same is true if you are talking to databases with the help of -SQLAlchemy or a similar ORM system. Some databases have a protocol that -already transmits Unicode and if they do not, SQLAlchemy or your other ORM -should take care of that. - -The Golden Rule ---------------- - -So the rule of thumb: if you are not dealing with binary data, work with -Unicode. What does working with Unicode in Python 2.x mean? - -- as long as you are using ASCII charpoints only (basically numbers, - some special characters of latin letters without umlauts or anything - fancy) you can use regular string literals (``'Hello World'``). -- if you need anything else than ASCII in a string you have to mark - this string as Unicode string by prefixing it with a lowercase `u`. - (like ``u'Hänsel und Gretel'``) -- if you are using non-Unicode characters in your Python files you have - to tell Python which encoding your file uses. Again, I recommend - UTF-8 for this purpose. To tell the interpreter your encoding you can - put the ``# -*- coding: utf-8 -*-`` into the first or second line of - your Python source file. -- Jinja is configured to decode the template files from UTF-8. So make - sure to tell your editor to save the file as UTF-8 there as well. - -Encoding and Decoding Yourself ------------------------------- - -If you are talking with a filesystem or something that is not really based -on Unicode you will have to ensure that you decode properly when working -with Unicode interface. So for example if you want to load a file on the -filesystem and embed it into a Jinja2 template you will have to decode it -from the encoding of that file. Here the old problem that text files do -not specify their encoding comes into play. So do yourself a favour and -limit yourself to UTF-8 for text files as well. - -Anyways. To load such a file with Unicode you can use the built-in -:meth:`str.decode` method:: - - def read_file(filename, charset='utf-8'): - with open(filename, 'r') as f: - return f.read().decode(charset) - -To go from Unicode into a specific charset such as UTF-8 you can use the -:meth:`unicode.encode` method:: - - def write_file(filename, contents, charset='utf-8'): - with open(filename, 'w') as f: - f.write(contents.encode(charset)) - -Configuring Editors -------------------- - -Most editors save as UTF-8 by default nowadays but in case your editor is -not configured to do this you have to change it. Here some common ways to -set your editor to store as UTF-8: - -- Vim: put ``set enc=utf-8`` to your ``.vimrc`` file. - -- Emacs: either use an encoding cookie or put this into your ``.emacs`` - file:: - - (prefer-coding-system 'utf-8) - (setq default-buffer-file-coding-system 'utf-8) - -- Notepad++: - - 1. Go to *Settings -> Preferences ...* - 2. Select the "New Document/Default Directory" tab - 3. Select "UTF-8 without BOM" as encoding - - It is also recommended to use the Unix newline format, you can select - it in the same panel but this is not a requirement. diff --git a/docs/upgrading.rst b/docs/upgrading.rst deleted file mode 100644 index aae5dd2a8f..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..1d2daec74f 100644 --- a/docs/views.rst +++ b/docs/views.rst @@ -1,5 +1,3 @@ -.. _views: - Pluggable Views =============== @@ -231,7 +229,7 @@ registration code:: 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, + app.add_url_rule(f'{url}<{pk_type}:{pk}>', view_func=view_func, methods=['GET', 'PUT', 'DELETE']) register_api(UserAPI, 'user_api', '/users/', pk='user_id') diff --git a/examples/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 fc074284e8..b25bdb4e41 100644 --- a/examples/javascript/README.rst +++ b/examples/javascript/README.rst @@ -15,7 +15,7 @@ page. Demonstrates using |XMLHttpRequest|_, |fetch|_, and .. |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 @@ -23,9 +23,9 @@ Install :: - python3 -m venv venv - . venv/bin/activate - pip install -e . + $ python3 -m venv venv + $ . venv/bin/activate + $ pip install -e . Run @@ -33,8 +33,8 @@ Run :: - export FLASK_APP=js_example - flask run + $ export FLASK_APP=js_example + $ flask run Open http://127.0.0.1:5000 in a browser. @@ -44,6 +44,6 @@ Test :: - pip install -e '.[test]' - coverage run -m pytest - coverage report + $ pip install -e '.[test]' + $ coverage run -m pytest + $ coverage report diff --git a/examples/javascript/js_example/__init__.py b/examples/javascript/js_example/__init__.py index d90fc4d4c4..068b2d98ed 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: F401 diff --git a/examples/javascript/js_example/views.py b/examples/javascript/js_example/views.py index c898e6de2d..6c601a9043 100644 --- a/examples/javascript/js_example/views.py +++ b/examples/javascript/js_example/views.py @@ -1,16 +1,18 @@ -from flask import jsonify, render_template, request +from flask import jsonify +from flask import render_template +from flask import request from js_example import app -@app.route('/', defaults={'js': 'plain'}) -@app.route('/') +@app.route("/", defaults={"js": "plain"}) +@app.route("/") def index(js): - return render_template('{0}.html'.format(js), js=js) + return render_template(f"{js}.html", js=js) -@app.route('/add', methods=['POST']) +@app.route("/add", methods=["POST"]) def add(): - a = request.form.get('a', 0, type=float) - b = request.form.get('b', 0, type=float) + a = request.form.get("a", 0, type=float) + b = request.form.get("b", 0, type=float) return jsonify(result=a + b) diff --git a/examples/javascript/setup.cfg b/examples/javascript/setup.cfg index a14fa80ec2..c4a3efad9f 100644 --- a/examples/javascript/setup.cfg +++ b/examples/javascript/setup.cfg @@ -1,8 +1,24 @@ [metadata] -license_file = LICENSE +name = js_example +version = 1.0.0 +url = https://flask.palletsprojects.com/patterns/jquery/ +license = BSD-3-Clause +maintainer = Pallets +maintainer_email = contact@palletsprojects.com +description = Demonstrates making AJAX requests to Flask. +long_description = file: README.rst +long_description_content_type = text/x-rst -[bdist_wheel] -universal = True +[options] +packages = find: +include_package_data = true +install_requires = + Flask + +[options.extras_require] +test = + pytest + blinker [tool:pytest] testpaths = tests diff --git a/examples/javascript/setup.py b/examples/javascript/setup.py index c699e8f173..606849326a 100644 --- a/examples/javascript/setup.py +++ b/examples/javascript/setup.py @@ -1,30 +1,3 @@ -import io +from setuptools import setup -from setuptools import find_packages, setup - -with io.open('README.rst', 'rt', encoding='utf8') as f: - readme = f.read() - -setup( - name='js_example', - version='1.0.0', - url='http://flask.pocoo.org/docs/patterns/jquery/', - license='BSD', - maintainer='Pallets team', - maintainer_email='contact@palletsprojects.com', - description='Demonstrates making Ajax requests to Flask.', - long_description=readme, - packages=find_packages(), - include_package_data=True, - zip_safe=False, - install_requires=[ - 'flask', - ], - extras_require={ - 'test': [ - 'pytest', - 'coverage', - 'blinker', - ], - }, -) +setup() diff --git a/examples/javascript/tests/conftest.py b/examples/javascript/tests/conftest.py index ea81ba598e..e0cabbfd1d 100644 --- a/examples/javascript/tests/conftest.py +++ b/examples/javascript/tests/conftest.py @@ -3,7 +3,7 @@ from js_example import app -@pytest.fixture(name='app') +@pytest.fixture(name="app") def fixture_app(): app.testing = True yield app diff --git a/examples/javascript/tests/test_js_example.py b/examples/javascript/tests/test_js_example.py index f1bcf96d99..aa0215f133 100644 --- a/examples/javascript/tests/test_js_example.py +++ b/examples/javascript/tests/test_js_example.py @@ -1,14 +1,16 @@ import pytest - from flask import template_rendered -@pytest.mark.parametrize(('path', 'template_name'), ( - ('/', 'plain.html'), - ('/plain', 'plain.html'), - ('/fetch', 'fetch.html'), - ('/jquery', 'jquery.html'), -)) +@pytest.mark.parametrize( + ("path", "template_name"), + ( + ("/", "plain.html"), + ("/plain", "plain.html"), + ("/fetch", "fetch.html"), + ("/jquery", "jquery.html"), + ), +) def test_index(app, client, path, template_name): def check(sender, template, context): assert template.name == template_name @@ -17,12 +19,9 @@ def check(sender, template, context): client.get(path) -@pytest.mark.parametrize(('a', 'b', 'result'), ( - (2, 3, 5), - (2.5, 3, 5.5), - (2, None, 2), - (2, 'b', 2), -)) +@pytest.mark.parametrize( + ("a", "b", "result"), ((2, 3, 5), (2.5, 3, 5.5), (2, None, 2), (2, "b", 2)) +) def test_add(client, a, b, result): - response = client.post('/add', data={'a': a, 'b': b}) - assert response.get_json()['result'] == result + response = client.post("/add", data={"a": a, "b": b}) + assert response.get_json()["result"] == result diff --git a/examples/tutorial/LICENSE b/examples/tutorial/LICENSE deleted file mode 100644 index 8f9252f452..0000000000 --- a/examples/tutorial/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/tutorial/LICENSE.rst b/examples/tutorial/LICENSE.rst new file mode 100644 index 0000000000..9d227a0cc4 --- /dev/null +++ b/examples/tutorial/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/tutorial/MANIFEST.in b/examples/tutorial/MANIFEST.in index a73511ed2a..97d55d517e 100644 --- a/examples/tutorial/MANIFEST.in +++ b/examples/tutorial/MANIFEST.in @@ -1,4 +1,4 @@ -include LICENSE +include LICENSE.rst include flaskr/schema.sql graft flaskr/static graft flaskr/templates diff --git a/examples/tutorial/README.rst b/examples/tutorial/README.rst index 7530e77e2b..7c7255f959 100644 --- a/examples/tutorial/README.rst +++ b/examples/tutorial/README.rst @@ -3,7 +3,7 @@ Flaskr The basic blog app built in the Flask `tutorial`_. -.. _tutorial: http://flask.pocoo.org/docs/tutorial/ +.. _tutorial: https://flask.palletsprojects.com/tutorial/ Install @@ -14,32 +14,32 @@ you're reading.** You probably want the latest tagged version, but the default Git version is the master branch. :: # clone the repository - git clone https://github.com/pallets/flask - cd flask + $ git clone https://github.com/pallets/flask + $ cd flask # checkout the correct version - git tag # shows the tagged versions - git checkout latest-tag-found-above - cd examples/tutorial + $ git tag # shows the tagged versions + $ git checkout latest-tag-found-above + $ cd examples/tutorial Create a virtualenv and activate it:: - python3 -m venv venv - . venv/bin/activate + $ python3 -m venv venv + $ . venv/bin/activate Or on Windows cmd:: - py -3 -m venv venv - venv\Scripts\activate.bat + $ py -3 -m venv venv + $ venv\Scripts\activate.bat Install Flaskr:: - pip install -e . + $ pip install -e . Or if you are using the master branch, install Flask from source before installing Flaskr:: - pip install -e ../.. - pip install -e . + $ pip install -e ../.. + $ pip install -e . Run @@ -47,17 +47,17 @@ Run :: - export FLASK_APP=flaskr - export FLASK_ENV=development - flask init-db - flask run + $ export FLASK_APP=flaskr + $ export FLASK_ENV=development + $ flask init-db + $ flask run Or on Windows cmd:: - set FLASK_APP=flaskr - set FLASK_ENV=development - flask init-db - flask run + > set FLASK_APP=flaskr + > set FLASK_ENV=development + > flask init-db + > flask run Open http://127.0.0.1:5000 in a browser. @@ -67,11 +67,11 @@ Test :: - pip install '.[test]' - pytest + $ pip install '.[test]' + $ pytest Run with coverage report:: - coverage run -m pytest - coverage report - coverage html # open htmlcov/index.html in a browser + $ coverage run -m pytest + $ coverage report + $ coverage html # open htmlcov/index.html in a browser diff --git a/examples/tutorial/flaskr/__init__.py b/examples/tutorial/flaskr/__init__.py index 05316607aa..bb9cce5ab6 100644 --- a/examples/tutorial/flaskr/__init__.py +++ b/examples/tutorial/flaskr/__init__.py @@ -8,14 +8,14 @@ def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # a default secret that should be overridden by instance config - SECRET_KEY='dev', + SECRET_KEY="dev", # store the database in the instance folder - DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), + DATABASE=os.path.join(app.instance_path, "flaskr.sqlite"), ) if test_config is None: # load the instance config, if it exists, when not testing - app.config.from_pyfile('config.py', silent=True) + app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) @@ -26,16 +26,18 @@ def create_app(test_config=None): except OSError: pass - @app.route('/hello') + @app.route("/hello") def hello(): - return 'Hello, World!' + return "Hello, World!" # register the database commands from flaskr import db + db.init_app(app) # apply the blueprints to the app from flaskr import auth, blog + app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) @@ -43,6 +45,6 @@ def hello(): # in another app, you might define a separate main index here with # app.route, while giving the blog blueprint a url_prefix, but for # the tutorial the blog will be the main index - app.add_url_rule('/', endpoint='index') + app.add_url_rule("/", endpoint="index") return app diff --git a/examples/tutorial/flaskr/auth.py b/examples/tutorial/flaskr/auth.py index e8cd2940c5..bcd3c672e4 100644 --- a/examples/tutorial/flaskr/auth.py +++ b/examples/tutorial/flaskr/auth.py @@ -1,21 +1,28 @@ import functools -from flask import ( - Blueprint, flash, g, redirect, render_template, request, session, url_for -) -from werkzeug.security import check_password_hash, generate_password_hash +from flask import Blueprint +from flask import flash +from flask import g +from flask import redirect +from flask import render_template +from flask import request +from flask import session +from flask import url_for +from werkzeug.security import check_password_hash +from werkzeug.security import generate_password_hash from flaskr.db import get_db -bp = Blueprint('auth', __name__, url_prefix='/auth') +bp = Blueprint("auth", __name__, url_prefix="/auth") def login_required(view): """View decorator that redirects anonymous users to the login page.""" + @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: - return redirect(url_for('auth.login')) + return redirect(url_for("auth.login")) return view(**kwargs) @@ -26,83 +33,84 @@ def wrapped_view(**kwargs): def load_logged_in_user(): """If a user id is stored in the session, load the user object from the database into ``g.user``.""" - user_id = session.get('user_id') + user_id = session.get("user_id") if user_id is None: g.user = None else: - g.user = get_db().execute( - 'SELECT * FROM user WHERE id = ?', (user_id,) - ).fetchone() + g.user = ( + get_db().execute("SELECT * FROM user WHERE id = ?", (user_id,)).fetchone() + ) -@bp.route('/register', methods=('GET', 'POST')) +@bp.route("/register", methods=("GET", "POST")) def register(): """Register a new user. Validates that the username is not already taken. Hashes the password for security. """ - if request.method == 'POST': - username = request.form['username'] - password = request.form['password'] + if request.method == "POST": + username = request.form["username"] + password = request.form["password"] db = get_db() error = None if not username: - error = 'Username is required.' + error = "Username is required." elif not password: - error = 'Password is required.' - elif db.execute( - 'SELECT id FROM user WHERE username = ?', (username,) - ).fetchone() is not None: - error = 'User {0} is already registered.'.format(username) + error = "Password is required." + elif ( + db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone() + is not None + ): + error = f"User {username} is already registered." if error is None: # the name is available, store it in the database and go to # the login page db.execute( - 'INSERT INTO user (username, password) VALUES (?, ?)', - (username, generate_password_hash(password)) + "INSERT INTO user (username, password) VALUES (?, ?)", + (username, generate_password_hash(password)), ) db.commit() - return redirect(url_for('auth.login')) + return redirect(url_for("auth.login")) flash(error) - return render_template('auth/register.html') + return render_template("auth/register.html") -@bp.route('/login', methods=('GET', 'POST')) +@bp.route("/login", methods=("GET", "POST")) def login(): """Log in a registered user by adding the user id to the session.""" - if request.method == 'POST': - username = request.form['username'] - password = request.form['password'] + if request.method == "POST": + username = request.form["username"] + password = request.form["password"] db = get_db() error = None user = db.execute( - 'SELECT * FROM user WHERE username = ?', (username,) + "SELECT * FROM user WHERE username = ?", (username,) ).fetchone() if user is None: - error = 'Incorrect username.' - elif not check_password_hash(user['password'], password): - error = 'Incorrect password.' + error = "Incorrect username." + elif not check_password_hash(user["password"], password): + error = "Incorrect password." if error is None: # store the user id in a new session and return to the index session.clear() - session['user_id'] = user['id'] - return redirect(url_for('index')) + session["user_id"] = user["id"] + return redirect(url_for("index")) flash(error) - return render_template('auth/login.html') + return render_template("auth/login.html") -@bp.route('/logout') +@bp.route("/logout") def logout(): """Clear the current session, including the stored user id.""" session.clear() - return redirect(url_for('index')) + return redirect(url_for("index")) diff --git a/examples/tutorial/flaskr/blog.py b/examples/tutorial/flaskr/blog.py index 784b1d8c56..3704626b1c 100644 --- a/examples/tutorial/flaskr/blog.py +++ b/examples/tutorial/flaskr/blog.py @@ -1,24 +1,28 @@ -from flask import ( - Blueprint, flash, g, redirect, render_template, request, url_for -) +from flask import Blueprint +from flask import flash +from flask import g +from flask import redirect +from flask import render_template +from flask import request +from flask import url_for from werkzeug.exceptions import abort from flaskr.auth import login_required from flaskr.db import get_db -bp = Blueprint('blog', __name__) +bp = Blueprint("blog", __name__) -@bp.route('/') +@bp.route("/") def index(): """Show all the posts, most recent first.""" db = get_db() posts = db.execute( - 'SELECT p.id, title, body, created, author_id, username' - ' FROM post p JOIN user u ON p.author_id = u.id' - ' ORDER BY created DESC' + "SELECT p.id, title, body, created, author_id, username" + " FROM post p JOIN user u ON p.author_id = u.id" + " ORDER BY created DESC" ).fetchall() - return render_template('blog/index.html', posts=posts) + return render_template("blog/index.html", posts=posts) def get_post(id, check_author=True): @@ -33,78 +37,80 @@ def get_post(id, check_author=True): :raise 404: if a post with the given id doesn't exist :raise 403: if the current user isn't the author """ - post = get_db().execute( - 'SELECT p.id, title, body, created, author_id, username' - ' FROM post p JOIN user u ON p.author_id = u.id' - ' WHERE p.id = ?', - (id,) - ).fetchone() + post = ( + get_db() + .execute( + "SELECT p.id, title, body, created, author_id, username" + " FROM post p JOIN user u ON p.author_id = u.id" + " WHERE p.id = ?", + (id,), + ) + .fetchone() + ) if post is None: - abort(404, "Post id {0} doesn't exist.".format(id)) + abort(404, f"Post id {id} doesn't exist.") - if check_author and post['author_id'] != g.user['id']: + if check_author and post["author_id"] != g.user["id"]: abort(403) return post -@bp.route('/create', methods=('GET', 'POST')) +@bp.route("/create", methods=("GET", "POST")) @login_required def create(): """Create a new post for the current user.""" - if request.method == 'POST': - title = request.form['title'] - body = request.form['body'] + if request.method == "POST": + title = request.form["title"] + body = request.form["body"] error = None if not title: - error = 'Title is required.' + error = "Title is required." if error is not None: flash(error) else: db = get_db() db.execute( - 'INSERT INTO post (title, body, author_id)' - ' VALUES (?, ?, ?)', - (title, body, g.user['id']) + "INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)", + (title, body, g.user["id"]), ) db.commit() - return redirect(url_for('blog.index')) + return redirect(url_for("blog.index")) - return render_template('blog/create.html') + return render_template("blog/create.html") -@bp.route('//update', methods=('GET', 'POST')) +@bp.route("//update", methods=("GET", "POST")) @login_required def update(id): """Update a post if the current user is the author.""" post = get_post(id) - if request.method == 'POST': - title = request.form['title'] - body = request.form['body'] + if request.method == "POST": + title = request.form["title"] + body = request.form["body"] error = None if not title: - error = 'Title is required.' + error = "Title is required." if error is not None: flash(error) else: db = get_db() db.execute( - 'UPDATE post SET title = ?, body = ? WHERE id = ?', - (title, body, id) + "UPDATE post SET title = ?, body = ? WHERE id = ?", (title, body, id) ) db.commit() - return redirect(url_for('blog.index')) + return redirect(url_for("blog.index")) - return render_template('blog/update.html', post=post) + return render_template("blog/update.html", post=post) -@bp.route('//delete', methods=('POST',)) +@bp.route("//delete", methods=("POST",)) @login_required def delete(id): """Delete a post. @@ -114,6 +120,6 @@ def delete(id): """ get_post(id) db = get_db() - db.execute('DELETE FROM post WHERE id = ?', (id,)) + db.execute("DELETE FROM post WHERE id = ?", (id,)) db.commit() - return redirect(url_for('blog.index')) + return redirect(url_for("blog.index")) diff --git a/examples/tutorial/flaskr/db.py b/examples/tutorial/flaskr/db.py index 03bd3b3c98..f1e2dc3062 100644 --- a/examples/tutorial/flaskr/db.py +++ b/examples/tutorial/flaskr/db.py @@ -1,7 +1,8 @@ import sqlite3 import click -from flask import current_app, g +from flask import current_app +from flask import g from flask.cli import with_appcontext @@ -10,10 +11,9 @@ def get_db(): is unique for each request and will be reused if this is called again. """ - if 'db' not in g: + if "db" not in g: g.db = sqlite3.connect( - current_app.config['DATABASE'], - detect_types=sqlite3.PARSE_DECLTYPES + current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sqlite3.Row @@ -24,7 +24,7 @@ def close_db(e=None): """If this request connected to the database, close the connection. """ - db = g.pop('db', None) + db = g.pop("db", None) if db is not None: db.close() @@ -34,16 +34,16 @@ def init_db(): """Clear existing data and create new tables.""" db = get_db() - with current_app.open_resource('schema.sql') as f: - db.executescript(f.read().decode('utf8')) + with current_app.open_resource("schema.sql") as f: + db.executescript(f.read().decode("utf8")) -@click.command('init-db') +@click.command("init-db") @with_appcontext def init_db_command(): """Clear existing data and create new tables.""" init_db() - click.echo('Initialized the database.') + click.echo("Initialized the database.") def init_app(app): diff --git a/examples/tutorial/setup.cfg b/examples/tutorial/setup.cfg index 3e47794efa..d001093b48 100644 --- a/examples/tutorial/setup.cfg +++ b/examples/tutorial/setup.cfg @@ -1,8 +1,23 @@ [metadata] -license_file = LICENSE +name = flaskr +version = 1.0.0 +url = https://flask.palletsprojects.com/tutorial/ +license = BSD-3-Clause +maintainer = Pallets +maintainer_email = contact@palletsprojects.com +description = The basic blog app built in the Flask tutorial. +long_description = file: README.rst +long_description_content_type = text/x-rst -[bdist_wheel] -universal = True +[options] +packages = find: +include_package_data = true +install_requires = + Flask + +[options.extras_require] +test = + pytest [tool:pytest] testpaths = tests diff --git a/examples/tutorial/setup.py b/examples/tutorial/setup.py index 460d789b27..606849326a 100644 --- a/examples/tutorial/setup.py +++ b/examples/tutorial/setup.py @@ -1,29 +1,3 @@ -import io +from setuptools import setup -from setuptools import find_packages, setup - -with io.open('README.rst', 'rt', encoding='utf8') as f: - readme = f.read() - -setup( - name='flaskr', - version='1.0.0', - url='http://flask.pocoo.org/docs/tutorial/', - license='BSD', - maintainer='Pallets team', - maintainer_email='contact@palletsprojects.com', - description='The basic blog app built in the Flask tutorial.', - long_description=readme, - packages=find_packages(), - include_package_data=True, - zip_safe=False, - install_requires=[ - 'flask', - ], - extras_require={ - 'test': [ - 'pytest', - 'coverage', - ], - }, -) +setup() diff --git a/examples/tutorial/tests/conftest.py b/examples/tutorial/tests/conftest.py index 143d692486..6bf62f0a8f 100644 --- a/examples/tutorial/tests/conftest.py +++ b/examples/tutorial/tests/conftest.py @@ -2,12 +2,14 @@ import tempfile import pytest + from flaskr import create_app -from flaskr.db import get_db, init_db +from flaskr.db import get_db +from flaskr.db import init_db # read in SQL for populating test data -with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f: - _data_sql = f.read().decode('utf8') +with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f: + _data_sql = f.read().decode("utf8") @pytest.fixture @@ -16,10 +18,7 @@ def app(): # create a temporary file to isolate the database for each test db_fd, db_path = tempfile.mkstemp() # create the app with common test config - app = create_app({ - 'TESTING': True, - 'DATABASE': db_path, - }) + app = create_app({"TESTING": True, "DATABASE": db_path}) # create the database and load test data with app.app_context(): @@ -45,18 +44,17 @@ def runner(app): return app.test_cli_runner() -class AuthActions(object): +class AuthActions: def __init__(self, client): self._client = client - def login(self, username='test', password='test'): + def login(self, username="test", password="test"): return self._client.post( - '/auth/login', - data={'username': username, 'password': password} + "/auth/login", data={"username": username, "password": password} ) def logout(self): - return self._client.get('/auth/logout') + return self._client.get("/auth/logout") @pytest.fixture diff --git a/examples/tutorial/tests/test_auth.py b/examples/tutorial/tests/test_auth.py index 884bdf492a..3ac9a12c69 100644 --- a/examples/tutorial/tests/test_auth.py +++ b/examples/tutorial/tests/test_auth.py @@ -1,58 +1,61 @@ import pytest -from flask import g, session +from flask import g +from flask import session + from flaskr.db import get_db def test_register(client, app): # test that viewing the page renders without template errors - assert client.get('/auth/register').status_code == 200 + assert client.get("/auth/register").status_code == 200 # test that successful registration redirects to the login page - response = client.post( - '/auth/register', data={'username': 'a', 'password': 'a'} - ) - assert 'http://localhost/auth/login' == response.headers['Location'] + response = client.post("/auth/register", data={"username": "a", "password": "a"}) + assert "http://localhost/auth/login" == response.headers["Location"] # test that the user was inserted into the database with app.app_context(): - assert get_db().execute( - "select * from user where username = 'a'", - ).fetchone() is not None + assert ( + get_db().execute("select * from user where username = 'a'").fetchone() + is not None + ) -@pytest.mark.parametrize(('username', 'password', 'message'), ( - ('', '', b'Username is required.'), - ('a', '', b'Password is required.'), - ('test', 'test', b'already registered'), -)) +@pytest.mark.parametrize( + ("username", "password", "message"), + ( + ("", "", b"Username is required."), + ("a", "", b"Password is required."), + ("test", "test", b"already registered"), + ), +) def test_register_validate_input(client, username, password, message): response = client.post( - '/auth/register', - data={'username': username, 'password': password} + "/auth/register", data={"username": username, "password": password} ) assert message in response.data def test_login(client, auth): # test that viewing the page renders without template errors - assert client.get('/auth/login').status_code == 200 + assert client.get("/auth/login").status_code == 200 # test that successful login redirects to the index page response = auth.login() - assert response.headers['Location'] == 'http://localhost/' + assert response.headers["Location"] == "http://localhost/" # login request set the user_id in the session # check that the user is loaded from the session with client: - client.get('/') - assert session['user_id'] == 1 - assert g.user['username'] == 'test' + client.get("/") + assert session["user_id"] == 1 + assert g.user["username"] == "test" -@pytest.mark.parametrize(('username', 'password', 'message'), ( - ('a', 'test', b'Incorrect username.'), - ('test', 'a', b'Incorrect password.'), -)) +@pytest.mark.parametrize( + ("username", "password", "message"), + (("a", "test", b"Incorrect username."), ("test", "a", b"Incorrect password.")), +) def test_login_validate_input(auth, username, password, message): response = auth.login(username, password) assert message in response.data @@ -63,4 +66,4 @@ def test_logout(client, auth): with client: auth.logout() - assert 'user_id' not in session + assert "user_id" not in session diff --git a/examples/tutorial/tests/test_blog.py b/examples/tutorial/tests/test_blog.py index 11700458b4..91859686ca 100644 --- a/examples/tutorial/tests/test_blog.py +++ b/examples/tutorial/tests/test_blog.py @@ -1,49 +1,43 @@ import pytest + from flaskr.db import get_db def test_index(client, auth): - response = client.get('/') + response = client.get("/") assert b"Log In" in response.data assert b"Register" in response.data auth.login() - response = client.get('/') - assert b'test title' in response.data - assert b'by test on 2018-01-01' in response.data - assert b'test\nbody' in response.data + response = client.get("/") + assert b"test title" in response.data + assert b"by test on 2018-01-01" in response.data + assert b"test\nbody" in response.data assert b'href="/1/update"' in response.data -@pytest.mark.parametrize('path', ( - '/create', - '/1/update', - '/1/delete', -)) +@pytest.mark.parametrize("path", ("/create", "/1/update", "/1/delete")) def test_login_required(client, path): response = client.post(path) - assert response.headers['Location'] == 'http://localhost/auth/login' + assert response.headers["Location"] == "http://localhost/auth/login" def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db = get_db() - db.execute('UPDATE post SET author_id = 2 WHERE id = 1') + db.execute("UPDATE post SET author_id = 2 WHERE id = 1") db.commit() auth.login() # current user can't modify other user's post - assert client.post('/1/update').status_code == 403 - assert client.post('/1/delete').status_code == 403 + assert client.post("/1/update").status_code == 403 + assert client.post("/1/delete").status_code == 403 # current user doesn't see edit link - assert b'href="/1/update"' not in client.get('/').data + assert b'href="/1/update"' not in client.get("/").data -@pytest.mark.parametrize('path', ( - '/2/update', - '/2/delete', -)) +@pytest.mark.parametrize("path", ("/2/update", "/2/delete")) def test_exists_required(client, auth, path): auth.login() assert client.post(path).status_code == 404 @@ -51,42 +45,39 @@ def test_exists_required(client, auth, path): def test_create(client, auth, app): auth.login() - assert client.get('/create').status_code == 200 - client.post('/create', data={'title': 'created', 'body': ''}) + assert client.get("/create").status_code == 200 + client.post("/create", data={"title": "created", "body": ""}) with app.app_context(): db = get_db() - count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0] + count = db.execute("SELECT COUNT(id) FROM post").fetchone()[0] assert count == 2 def test_update(client, auth, app): auth.login() - assert client.get('/1/update').status_code == 200 - client.post('/1/update', data={'title': 'updated', 'body': ''}) + assert client.get("/1/update").status_code == 200 + client.post("/1/update", data={"title": "updated", "body": ""}) with app.app_context(): db = get_db() - post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() - assert post['title'] == 'updated' + post = db.execute("SELECT * FROM post WHERE id = 1").fetchone() + assert post["title"] == "updated" -@pytest.mark.parametrize('path', ( - '/create', - '/1/update', -)) +@pytest.mark.parametrize("path", ("/create", "/1/update")) def test_create_update_validate(client, auth, path): auth.login() - response = client.post(path, data={'title': '', 'body': ''}) - assert b'Title is required.' in response.data + response = client.post(path, data={"title": "", "body": ""}) + assert b"Title is required." in response.data def test_delete(client, auth, app): auth.login() - response = client.post('/1/delete') - assert response.headers['Location'] == 'http://localhost/' + response = client.post("/1/delete") + assert response.headers["Location"] == "http://localhost/" with app.app_context(): db = get_db() - post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() + post = db.execute("SELECT * FROM post WHERE id = 1").fetchone() assert post is None diff --git a/examples/tutorial/tests/test_db.py b/examples/tutorial/tests/test_db.py index 99c46d049d..2363bf8163 100644 --- a/examples/tutorial/tests/test_db.py +++ b/examples/tutorial/tests/test_db.py @@ -1,6 +1,7 @@ import sqlite3 import pytest + from flaskr.db import get_db @@ -10,19 +11,19 @@ def test_get_close_db(app): assert db is get_db() with pytest.raises(sqlite3.ProgrammingError) as e: - db.execute('SELECT 1') + db.execute("SELECT 1") - assert 'closed' in str(e) + assert "closed" in str(e.value) def test_init_db_command(runner, monkeypatch): - class Recorder(object): + class Recorder: called = False def fake_init_db(): Recorder.called = True - monkeypatch.setattr('flaskr.db.init_db', fake_init_db) - result = runner.invoke(args=['init-db']) - assert 'Initialized' in result.output + monkeypatch.setattr("flaskr.db.init_db", fake_init_db) + result = runner.invoke(args=["init-db"]) + assert "Initialized" in result.output assert Recorder.called diff --git a/examples/tutorial/tests/test_factory.py b/examples/tutorial/tests/test_factory.py index b7afeae712..9b7ca57fd4 100644 --- a/examples/tutorial/tests/test_factory.py +++ b/examples/tutorial/tests/test_factory.py @@ -4,9 +4,9 @@ def test_config(): """Test create_app without passing test config.""" assert not create_app().testing - assert create_app({'TESTING': True}).testing + assert create_app({"TESTING": True}).testing def test_hello(client): - response = client.get('/hello') - assert response.data == b'Hello, World!' + response = client.get("/hello") + assert response.data == b"Hello, World!" diff --git a/flask/__init__.py b/flask/__init__.py deleted file mode 100644 index 2e5670f58a..0000000000 --- a/flask/__init__.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask - ~~~~~ - - A microframework based on Werkzeug. It's extensively documented - and follows best practice patterns. - - :copyright: © 2010 by the Pallets team. - :license: BSD, see LICENSE for more details. -""" - -__version__ = '1.1.dev' - -# utilities we import from Werkzeug and Jinja2 that are unused -# in the module but are exported as public interface. -from werkzeug.exceptions import abort -from werkzeug.utils import redirect -from jinja2 import Markup, escape - -from .app import Flask, Request, Response -from .config import Config -from .helpers import url_for, flash, send_file, send_from_directory, \ - get_flashed_messages, get_template_attribute, make_response, safe_join, \ - stream_with_context -from .globals import current_app, g, request, session, _request_ctx_stack, \ - _app_ctx_stack -from .ctx import has_request_context, has_app_context, \ - after_this_request, copy_current_request_context -from .blueprints import Blueprint -from .templating import render_template, render_template_string - -# the signals -from .signals import signals_available, template_rendered, request_started, \ - request_finished, got_request_exception, request_tearing_down, \ - appcontext_tearing_down, appcontext_pushed, \ - appcontext_popped, message_flashed, before_render_template - -# We're not exposing the actual json module but a convenient wrapper around -# it. -from . import json - -# This was the only thing that Flask used to export at one point and it had -# a more generic name. -jsonify = json.jsonify diff --git a/flask/__main__.py b/flask/__main__.py deleted file mode 100644 index 4aee654374..0000000000 --- a/flask/__main__.py +++ /dev/null @@ -1,14 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.__main__ - ~~~~~~~~~~~~~~ - - Alias for flask.run for the command line. - - :copyright: © 2010 by the Pallets team. - :license: BSD, see LICENSE for more details. -""" - -if __name__ == '__main__': - from .cli import main - main(as_module=True) diff --git a/flask/_compat.py b/flask/_compat.py deleted file mode 100644 index a3b5b9c1c9..0000000000 --- a/flask/_compat.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask._compat - ~~~~~~~~~~~~~ - - Some py2/py3 compatibility support based on a stripped down - version of six so we don't have to depend on a specific version - of it. - - :copyright: © 2010 by the Pallets team. - :license: BSD, see LICENSE for more details. -""" - -import sys - -PY2 = sys.version_info[0] == 2 -_identity = lambda x: x - - -if not PY2: - text_type = str - string_types = (str,) - integer_types = (int,) - - iterkeys = lambda d: iter(d.keys()) - itervalues = lambda d: iter(d.values()) - iteritems = lambda d: iter(d.items()) - - from inspect import getfullargspec as getargspec - from io import StringIO - - def reraise(tp, value, tb=None): - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - - implements_to_string = _identity - -else: - text_type = unicode - string_types = (str, unicode) - integer_types = (int, long) - - iterkeys = lambda d: d.iterkeys() - itervalues = lambda d: d.itervalues() - iteritems = lambda d: d.iteritems() - - from inspect import getargspec - from cStringIO import StringIO - - exec('def reraise(tp, value, tb=None):\n raise tp, value, tb') - - def implements_to_string(cls): - cls.__unicode__ = cls.__str__ - cls.__str__ = lambda x: x.__unicode__().encode('utf-8') - return cls - - -def with_metaclass(meta, *bases): - """Create a base class with a metaclass.""" - # This requires a bit of explanation: the basic idea is to make a - # dummy metaclass for one level of class instantiation that replaces - # itself with the actual metaclass. - class metaclass(type): - def __new__(cls, name, this_bases, d): - return meta(name, bases, d) - return type.__new__(metaclass, 'temporary_class', (), {}) - - -# Certain versions of pypy have a bug where clearing the exception stack -# breaks the __exit__ function in a very peculiar way. The second level of -# exception blocks is necessary because pypy seems to forget to check if an -# exception happened until the next bytecode instruction? -# -# Relevant PyPy bugfix commit: -# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df4003301 -# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later -# versions. -# -# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug. -BROKEN_PYPY_CTXMGR_EXIT = False -if hasattr(sys, 'pypy_version_info'): - class _Mgr(object): - def __enter__(self): - return self - def __exit__(self, *args): - if hasattr(sys, 'exc_clear'): - # Python 3 (PyPy3) doesn't have exc_clear - sys.exc_clear() - try: - try: - with _Mgr(): - raise AssertionError() - except: - raise - except TypeError: - BROKEN_PYPY_CTXMGR_EXIT = True - except AssertionError: - pass diff --git a/flask/blueprints.py b/flask/blueprints.py deleted file mode 100644 index 5ce5561e4e..0000000000 --- a/flask/blueprints.py +++ /dev/null @@ -1,448 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.blueprints - ~~~~~~~~~~~~~~~~ - - Blueprints are the recommended way to implement larger or more - pluggable applications in Flask 0.7 and later. - - :copyright: © 2010 by the Pallets team. - :license: BSD, see LICENSE for more details. -""" -from functools import update_wrapper -from werkzeug.urls import url_join - -from .helpers import _PackageBoundObject, _endpoint_from_view_func - - -class BlueprintSetupState(object): - """Temporary holder object for registering a blueprint with the - application. An instance of this class is created by the - :meth:`~flask.Blueprint.make_setup_state` method and later passed - to all register callback functions. - """ - - def __init__(self, blueprint, app, options, first_registration): - #: a reference to the current application - self.app = app - - #: a reference to the blueprint that created this setup state. - self.blueprint = blueprint - - #: a dictionary with all options that were passed to the - #: :meth:`~flask.Flask.register_blueprint` method. - self.options = options - - #: as blueprints can be registered multiple times with the - #: application and not everything wants to be registered - #: multiple times on it, this attribute can be used to figure - #: out if the blueprint was registered in the past already. - self.first_registration = first_registration - - subdomain = self.options.get('subdomain') - if subdomain is None: - subdomain = self.blueprint.subdomain - - #: The subdomain that the blueprint should be active for, ``None`` - #: otherwise. - self.subdomain = subdomain - - url_prefix = self.options.get('url_prefix') - if url_prefix is None: - url_prefix = self.blueprint.url_prefix - #: The prefix that should be used for all URLs defined on the - #: blueprint. - self.url_prefix = url_prefix - - #: A dictionary with URL defaults that is added to each and every - #: URL that was defined with the blueprint. - self.url_defaults = dict(self.blueprint.url_values_defaults) - self.url_defaults.update(self.options.get('url_defaults', ())) - - def add_url_rule(self, rule, endpoint=None, view_func=None, **options): - """A helper method to register a rule (and optionally a view function) - to the application. The endpoint is automatically prefixed with the - blueprint's name. - """ - if self.url_prefix is not None: - if rule: - rule = '/'.join(( - self.url_prefix.rstrip('/'), rule.lstrip('/'))) - else: - rule = self.url_prefix - options.setdefault('subdomain', self.subdomain) - if endpoint is None: - endpoint = _endpoint_from_view_func(view_func) - defaults = self.url_defaults - if 'defaults' in options: - defaults = dict(defaults, **options.pop('defaults')) - self.app.add_url_rule(rule, '%s.%s' % (self.blueprint.name, endpoint), - view_func, defaults=defaults, **options) - - -class Blueprint(_PackageBoundObject): - """Represents a blueprint. A blueprint is an object that records - functions that will be called with the - :class:`~flask.blueprints.BlueprintSetupState` later to register functions - or other things on the main application. See :ref:`blueprints` for more - information. - - .. versionadded:: 0.7 - """ - - warn_on_modifications = False - _got_registered_once = False - - #: Blueprint local JSON decoder class to use. - #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`. - json_encoder = None - #: Blueprint local JSON decoder class to use. - #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`. - json_decoder = None - - # TODO remove the next three attrs when Sphinx :inherited-members: works - # https://github.com/sphinx-doc/sphinx/issues/741 - - #: The name of the package or module that this app belongs to. Do not - #: change this once it is set by the constructor. - import_name = None - - #: Location of the template files to be added to the template lookup. - #: ``None`` if templates should not be added. - template_folder = None - - #: Absolute path to the package on the filesystem. Used to look up - #: resources contained in the package. - root_path = None - - def __init__(self, name, import_name, static_folder=None, - static_url_path=None, template_folder=None, - url_prefix=None, subdomain=None, url_defaults=None, - root_path=None): - _PackageBoundObject.__init__(self, import_name, template_folder, - root_path=root_path) - self.name = name - self.url_prefix = url_prefix - self.subdomain = subdomain - self.static_folder = static_folder - self.static_url_path = static_url_path - self.deferred_functions = [] - if url_defaults is None: - url_defaults = {} - self.url_values_defaults = url_defaults - - def record(self, func): - """Registers a function that is called when the blueprint is - registered on the application. This function is called with the - state as argument as returned by the :meth:`make_setup_state` - method. - """ - if self._got_registered_once and self.warn_on_modifications: - from warnings import warn - warn(Warning('The blueprint was already registered once ' - 'but is getting modified now. These changes ' - 'will not show up.')) - self.deferred_functions.append(func) - - def record_once(self, func): - """Works like :meth:`record` but wraps the function in another - function that will ensure the function is only called once. If the - blueprint is registered a second time on the application, the - function passed is not called. - """ - def wrapper(state): - if state.first_registration: - func(state) - return self.record(update_wrapper(wrapper, func)) - - def make_setup_state(self, app, options, first_registration=False): - """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState` - object that is later passed to the register callback functions. - Subclasses can override this to return a subclass of the setup state. - """ - return BlueprintSetupState(self, app, options, first_registration) - - def register(self, app, options, first_registration=False): - """Called by :meth:`Flask.register_blueprint` to register all views - and callbacks registered on the blueprint with the application. Creates - a :class:`.BlueprintSetupState` and calls each :meth:`record` callback - with it. - - :param app: The application this blueprint is being registered with. - :param options: Keyword arguments forwarded from - :meth:`~Flask.register_blueprint`. - :param first_registration: Whether this is the first time this - blueprint has been registered on the application. - """ - self._got_registered_once = True - state = self.make_setup_state(app, options, first_registration) - - if self.has_static_folder: - state.add_url_rule( - self.static_url_path + '/', - view_func=self.send_static_file, endpoint='static' - ) - - for deferred in self.deferred_functions: - deferred(state) - - def route(self, rule, **options): - """Like :meth:`Flask.route` but for a blueprint. The endpoint for the - :func:`url_for` function is prefixed with the name of the blueprint. - """ - def decorator(f): - endpoint = options.pop("endpoint", f.__name__) - self.add_url_rule(rule, endpoint, f, **options) - return f - return decorator - - def add_url_rule(self, rule, endpoint=None, view_func=None, **options): - """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for - the :func:`url_for` function is prefixed with the name of the blueprint. - """ - if endpoint: - assert '.' not in endpoint, "Blueprint endpoints should not contain dots" - if view_func and hasattr(view_func, '__name__'): - assert '.' not in view_func.__name__, "Blueprint view function name should not contain dots" - self.record(lambda s: - s.add_url_rule(rule, endpoint, view_func, **options)) - - def endpoint(self, endpoint): - """Like :meth:`Flask.endpoint` but for a blueprint. This does not - prefix the endpoint with the blueprint name, this has to be done - explicitly by the user of this method. If the endpoint is prefixed - with a `.` it will be registered to the current blueprint, otherwise - it's an application independent endpoint. - """ - def decorator(f): - def register_endpoint(state): - state.app.view_functions[endpoint] = f - self.record_once(register_endpoint) - return f - return decorator - - def app_template_filter(self, name=None): - """Register a custom template filter, available application wide. Like - :meth:`Flask.template_filter` but for a blueprint. - - :param name: the optional name of the filter, otherwise the - function name will be used. - """ - def decorator(f): - self.add_app_template_filter(f, name=name) - return f - return decorator - - def add_app_template_filter(self, f, name=None): - """Register a custom template filter, available application wide. Like - :meth:`Flask.add_template_filter` but for a blueprint. Works exactly - like the :meth:`app_template_filter` decorator. - - :param name: the optional name of the filter, otherwise the - function name will be used. - """ - def register_template(state): - state.app.jinja_env.filters[name or f.__name__] = f - self.record_once(register_template) - - def app_template_test(self, name=None): - """Register a custom template test, available application wide. Like - :meth:`Flask.template_test` but for a blueprint. - - .. versionadded:: 0.10 - - :param name: the optional name of the test, otherwise the - function name will be used. - """ - def decorator(f): - self.add_app_template_test(f, name=name) - return f - return decorator - - def add_app_template_test(self, f, name=None): - """Register a custom template test, available application wide. Like - :meth:`Flask.add_template_test` but for a blueprint. Works exactly - like the :meth:`app_template_test` decorator. - - .. versionadded:: 0.10 - - :param name: the optional name of the test, otherwise the - function name will be used. - """ - def register_template(state): - state.app.jinja_env.tests[name or f.__name__] = f - self.record_once(register_template) - - def app_template_global(self, name=None): - """Register a custom template global, available application wide. Like - :meth:`Flask.template_global` but for a blueprint. - - .. versionadded:: 0.10 - - :param name: the optional name of the global, otherwise the - function name will be used. - """ - def decorator(f): - self.add_app_template_global(f, name=name) - return f - return decorator - - def add_app_template_global(self, f, name=None): - """Register a custom template global, available application wide. Like - :meth:`Flask.add_template_global` but for a blueprint. Works exactly - like the :meth:`app_template_global` decorator. - - .. versionadded:: 0.10 - - :param name: the optional name of the global, otherwise the - function name will be used. - """ - def register_template(state): - state.app.jinja_env.globals[name or f.__name__] = f - self.record_once(register_template) - - def before_request(self, f): - """Like :meth:`Flask.before_request` but for a blueprint. This function - is only executed before each request that is handled by a function of - that blueprint. - """ - self.record_once(lambda s: s.app.before_request_funcs - .setdefault(self.name, []).append(f)) - return f - - def before_app_request(self, f): - """Like :meth:`Flask.before_request`. Such a function is executed - before each request, even if outside of a blueprint. - """ - self.record_once(lambda s: s.app.before_request_funcs - .setdefault(None, []).append(f)) - return f - - def before_app_first_request(self, f): - """Like :meth:`Flask.before_first_request`. Such a function is - executed before the first request to the application. - """ - self.record_once(lambda s: s.app.before_first_request_funcs.append(f)) - return f - - def after_request(self, f): - """Like :meth:`Flask.after_request` but for a blueprint. This function - is only executed after each request that is handled by a function of - that blueprint. - """ - self.record_once(lambda s: s.app.after_request_funcs - .setdefault(self.name, []).append(f)) - return f - - def after_app_request(self, f): - """Like :meth:`Flask.after_request` but for a blueprint. Such a function - is executed after each request, even if outside of the blueprint. - """ - self.record_once(lambda s: s.app.after_request_funcs - .setdefault(None, []).append(f)) - return f - - def teardown_request(self, f): - """Like :meth:`Flask.teardown_request` but for a blueprint. This - function is only executed when tearing down requests handled by a - function of that blueprint. Teardown request functions are executed - when the request context is popped, even when no actual request was - performed. - """ - self.record_once(lambda s: s.app.teardown_request_funcs - .setdefault(self.name, []).append(f)) - return f - - def teardown_app_request(self, f): - """Like :meth:`Flask.teardown_request` but for a blueprint. Such a - function is executed when tearing down each request, even if outside of - the blueprint. - """ - self.record_once(lambda s: s.app.teardown_request_funcs - .setdefault(None, []).append(f)) - return f - - def context_processor(self, f): - """Like :meth:`Flask.context_processor` but for a blueprint. This - function is only executed for requests handled by a blueprint. - """ - self.record_once(lambda s: s.app.template_context_processors - .setdefault(self.name, []).append(f)) - return f - - def app_context_processor(self, f): - """Like :meth:`Flask.context_processor` but for a blueprint. Such a - function is executed each request, even if outside of the blueprint. - """ - self.record_once(lambda s: s.app.template_context_processors - .setdefault(None, []).append(f)) - return f - - def app_errorhandler(self, code): - """Like :meth:`Flask.errorhandler` but for a blueprint. This - handler is used for all requests, even if outside of the blueprint. - """ - def decorator(f): - self.record_once(lambda s: s.app.errorhandler(code)(f)) - return f - return decorator - - def url_value_preprocessor(self, f): - """Registers a function as URL value preprocessor for this - blueprint. It's called before the view functions are called and - can modify the url values provided. - """ - self.record_once(lambda s: s.app.url_value_preprocessors - .setdefault(self.name, []).append(f)) - return f - - def url_defaults(self, f): - """Callback function for URL defaults for this blueprint. It's called - with the endpoint and values and should update the values passed - in place. - """ - self.record_once(lambda s: s.app.url_default_functions - .setdefault(self.name, []).append(f)) - return f - - def app_url_value_preprocessor(self, f): - """Same as :meth:`url_value_preprocessor` but application wide. - """ - self.record_once(lambda s: s.app.url_value_preprocessors - .setdefault(None, []).append(f)) - return f - - def app_url_defaults(self, f): - """Same as :meth:`url_defaults` but application wide. - """ - self.record_once(lambda s: s.app.url_default_functions - .setdefault(None, []).append(f)) - return f - - def errorhandler(self, code_or_exception): - """Registers an error handler that becomes active for this blueprint - only. Please be aware that routing does not happen local to a - blueprint so an error handler for 404 usually is not handled by - a blueprint unless it is caused inside a view function. Another - special case is the 500 internal server error which is always looked - up from the application. - - Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator - of the :class:`~flask.Flask` object. - """ - def decorator(f): - self.record_once(lambda s: s.app._register_error_handler( - self.name, code_or_exception, f)) - return f - return decorator - - def register_error_handler(self, code_or_exception, f): - """Non-decorator version of the :meth:`errorhandler` error attach - function, akin to the :meth:`~flask.Flask.register_error_handler` - application-wide function of the :class:`~flask.Flask` object but - for error handlers limited to this blueprint. - - .. versionadded:: 0.11 - """ - self.record_once(lambda s: s.app._register_error_handler( - self.name, code_or_exception, f)) diff --git a/flask/debughelpers.py b/flask/debughelpers.py deleted file mode 100644 index e9765f20d0..0000000000 --- a/flask/debughelpers.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.debughelpers - ~~~~~~~~~~~~~~~~~~ - - Various helpers to make the development experience better. - - :copyright: © 2010 by the Pallets team. - :license: BSD, see LICENSE for more details. -""" - -import os -from warnings import warn - -from ._compat import implements_to_string, text_type -from .app import Flask -from .blueprints import Blueprint -from .globals import _request_ctx_stack - - -class UnexpectedUnicodeError(AssertionError, UnicodeError): - """Raised in places where we want some better error reporting for - unexpected unicode or binary data. - """ - - -@implements_to_string -class DebugFilesKeyError(KeyError, AssertionError): - """Raised from request.files during debugging. The idea is that it can - provide a better error message than just a generic KeyError/BadRequest. - """ - - def __init__(self, request, key): - form_matches = request.form.getlist(key) - buf = ['You tried to access the file "%s" in the request.files ' - 'dictionary but it does not exist. The mimetype for the request ' - 'is "%s" instead of "multipart/form-data" which means that no ' - 'file contents were transmitted. To fix this error you should ' - 'provide enctype="multipart/form-data" in your form.' % - (key, request.mimetype)] - if form_matches: - buf.append('\n\nThe browser instead transmitted some file names. ' - 'This was submitted: %s' % ', '.join('"%s"' % x - for x in form_matches)) - self.msg = ''.join(buf) - - def __str__(self): - return self.msg - - -class FormDataRoutingRedirect(AssertionError): - """This exception is raised by Flask in debug mode if it detects a - redirect caused by the routing system when the request method is not - GET, HEAD or OPTIONS. Reasoning: form data will be dropped. - """ - - def __init__(self, request): - exc = request.routing_exception - buf = ['A request was sent to this URL (%s) but a redirect was ' - 'issued automatically by the routing system to "%s".' - % (request.url, exc.new_url)] - - # In case just a slash was appended we can be extra helpful - if request.base_url + '/' == exc.new_url.split('?')[0]: - buf.append(' The URL was defined with a trailing slash so ' - 'Flask will automatically redirect to the URL ' - 'with the trailing slash if it was accessed ' - 'without one.') - - buf.append(' Make sure to directly send your %s-request to this URL ' - 'since we can\'t make browsers or HTTP clients redirect ' - 'with form data reliably or without user interaction.' % - request.method) - buf.append('\n\nNote: this exception is only raised in debug mode') - AssertionError.__init__(self, ''.join(buf).encode('utf-8')) - - -def attach_enctype_error_multidict(request): - """Since Flask 0.8 we're monkeypatching the files object in case a - request is detected that does not use multipart form data but the files - object is accessed. - """ - oldcls = request.files.__class__ - class newcls(oldcls): - def __getitem__(self, key): - try: - return oldcls.__getitem__(self, key) - except KeyError: - if key not in request.form: - raise - raise DebugFilesKeyError(request, key) - newcls.__name__ = oldcls.__name__ - newcls.__module__ = oldcls.__module__ - request.files.__class__ = newcls - - -def _dump_loader_info(loader): - yield 'class: %s.%s' % (type(loader).__module__, type(loader).__name__) - for key, value in sorted(loader.__dict__.items()): - if key.startswith('_'): - continue - if isinstance(value, (tuple, list)): - if not all(isinstance(x, (str, text_type)) for x in value): - continue - yield '%s:' % key - for item in value: - yield ' - %s' % item - continue - elif not isinstance(value, (str, text_type, int, float, bool)): - continue - yield '%s: %r' % (key, value) - - -def explain_template_loading_attempts(app, template, attempts): - """This should help developers understand what failed""" - info = ['Locating template "%s":' % template] - total_found = 0 - blueprint = None - reqctx = _request_ctx_stack.top - if reqctx is not None and reqctx.request.blueprint is not None: - blueprint = reqctx.request.blueprint - - for idx, (loader, srcobj, triple) in enumerate(attempts): - if isinstance(srcobj, Flask): - src_info = 'application "%s"' % srcobj.import_name - elif isinstance(srcobj, Blueprint): - src_info = 'blueprint "%s" (%s)' % (srcobj.name, - srcobj.import_name) - else: - src_info = repr(srcobj) - - info.append('% 5d: trying loader of %s' % ( - idx + 1, src_info)) - - for line in _dump_loader_info(loader): - info.append(' %s' % line) - - if triple is None: - detail = 'no match' - else: - detail = 'found (%r)' % (triple[1] or '') - total_found += 1 - info.append(' -> %s' % detail) - - seems_fishy = False - if total_found == 0: - info.append('Error: the template could not be found.') - seems_fishy = True - elif total_found > 1: - info.append('Warning: multiple loaders returned a match for the template.') - seems_fishy = True - - if blueprint is not None and seems_fishy: - info.append(' The template was looked up from an endpoint that ' - 'belongs to the blueprint "%s".' % blueprint) - info.append(' Maybe you did not place a template in the right folder?') - info.append(' See http://flask.pocoo.org/docs/blueprints/#templates') - - app.logger.info('\n'.join(info)) - - -def explain_ignored_app_run(): - if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': - warn(Warning('Silently ignoring app.run() because the ' - 'application is run from the flask command line ' - 'executable. Consider putting app.run() behind an ' - 'if __name__ == "__main__" guard to silence this ' - 'warning.'), stacklevel=3) diff --git a/flask/helpers.py b/flask/helpers.py deleted file mode 100644 index 7679a49608..0000000000 --- a/flask/helpers.py +++ /dev/null @@ -1,1048 +0,0 @@ -# -*- coding: utf-8 -*- -""" - flask.helpers - ~~~~~~~~~~~~~ - - Implements various helpers. - - :copyright: © 2010 by the Pallets team. - :license: BSD, see LICENSE for more details. -""" - -import os -import socket -import sys -import pkgutil -import posixpath -import mimetypes -from time import time -from zlib import adler32 -from threading import RLock -import unicodedata -from werkzeug.routing import BuildError -from functools import update_wrapper - -from werkzeug.urls import url_quote -from werkzeug.datastructures import Headers, Range -from werkzeug.exceptions import BadRequest, NotFound, \ - RequestedRangeNotSatisfiable - -from werkzeug.wsgi import wrap_file -from jinja2 import FileSystemLoader - -from .signals import message_flashed -from .globals import session, _request_ctx_stack, _app_ctx_stack, \ - current_app, request -from ._compat import string_types, text_type, PY2 - -# sentinel -_missing = object() - - -# what separators does this operating system provide that are not a slash? -# this is used by the send_from_directory function to ensure that nobody is -# able to access files from outside the filesystem. -_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep] - if sep not in (None, '/')) - - -def get_env(): - """Get the environment the app is running in, indicated by the - :envvar:`FLASK_ENV` environment variable. The default is - ``'production'``. - """ - return os.environ.get('FLASK_ENV') or 'production' - - -def get_debug_flag(): - """Get whether debug mode should be enabled for the app, indicated - by the :envvar:`FLASK_DEBUG` environment variable. The default is - ``True`` if :func:`.get_env` returns ``'development'``, or ``False`` - otherwise. - """ - val = os.environ.get('FLASK_DEBUG') - - if not val: - return get_env() == 'development' - - return val.lower() not in ('0', 'false', 'no') - - -def get_load_dotenv(default=True): - """Get whether the user has disabled loading dotenv files by setting - :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the - files. - - :param default: What to return if the env var isn't set. - """ - val = os.environ.get('FLASK_SKIP_DOTENV') - - if not val: - return default - - return val.lower() in ('0', 'false', 'no') - - -def _endpoint_from_view_func(view_func): - """Internal helper that returns the default endpoint for a given - function. This always is the function name. - """ - assert view_func is not None, 'expected view func if endpoint ' \ - 'is not provided.' - return view_func.__name__ - - -def stream_with_context(generator_or_function): - """Request contexts disappear when the response is started on the server. - This is done for efficiency reasons and to make it less likely to encounter - memory leaks with badly written WSGI middlewares. The downside is that if - you are using streamed responses, the generator cannot access request bound - information any more. - - This function however can help you keep the context around for longer:: - - from flask import stream_with_context, request, Response - - @app.route('/stream') - def streamed_response(): - @stream_with_context - def generate(): - yield 'Hello ' - yield request.args['name'] - yield '!' - return Response(generate()) - - Alternatively it can also be used around a specific generator:: - - from flask import stream_with_context, request, Response - - @app.route('/stream') - def streamed_response(): - def generate(): - yield 'Hello ' - yield request.args['name'] - yield '!' - return Response(stream_with_context(generate())) - - .. versionadded:: 0.9 - """ - try: - gen = iter(generator_or_function) - except TypeError: - def decorator(*args, **kwargs): - gen = generator_or_function(*args, **kwargs) - return stream_with_context(gen) - return update_wrapper(decorator, generator_or_function) - - def generator(): - ctx = _request_ctx_stack.top - if ctx is None: - raise RuntimeError('Attempted to stream with context but ' - 'there was no context in the first place to keep around.') - with ctx: - # Dummy sentinel. Has to be inside the context block or we're - # not actually keeping the context around. - yield None - - # The try/finally is here so that if someone passes a WSGI level - # iterator in we're still running the cleanup logic. Generators - # don't need that because they are closed on their destruction - # automatically. - try: - for item in gen: - yield item - finally: - if hasattr(gen, 'close'): - gen.close() - - # The trick is to start the generator. Then the code execution runs until - # the first dummy None is yielded at which point the context was already - # pushed. This item is discarded. Then when the iteration continues the - # real generator is executed. - wrapped_g = generator() - next(wrapped_g) - return wrapped_g - - -def make_response(*args): - """Sometimes it is necessary to set additional headers in a view. Because - views do not have to return response objects but can return a value that - is converted into a response object by Flask itself, it becomes tricky to - add headers to it. This function can be called instead of using a return - and you will get a response object which you can use to attach headers. - - If view looked like this and you want to add a new header:: - - def index(): - return render_template('index.html', foo=42) - - You can now do something like this:: - - def index(): - response = make_response(render_template('index.html', foo=42)) - response.headers['X-Parachutes'] = 'parachutes are cool' - return response - - This function accepts the very same arguments you can return from a - view function. This for example creates a response with a 404 error - code:: - - response = make_response(render_template('not_found.html'), 404) - - The other use case of this function is to force the return value of a - view function into a response which is helpful with view - decorators:: - - response = make_response(view_function()) - response.headers['X-Parachutes'] = 'parachutes are cool' - - Internally this function does the following things: - - - if no arguments are passed, it creates a new response argument - - if one argument is passed, :meth:`flask.Flask.make_response` - is invoked with it. - - if more than one argument is passed, the arguments are passed - to the :meth:`flask.Flask.make_response` function as tuple. - - .. versionadded:: 0.6 - """ - if not args: - return current_app.response_class() - if len(args) == 1: - args = args[0] - return current_app.make_response(args) - - -def url_for(endpoint, **values): - """Generates a URL to the given endpoint with the method provided. - - Variable arguments that are unknown to the target endpoint are appended - to the generated URL as query arguments. If the value of a query argument - is ``None``, the whole pair is skipped. In case blueprints are active - you can shortcut references to the same blueprint by prefixing the - local endpoint with a dot (``.``). - - This will reference the index function local to the current blueprint:: - - url_for('.index') - - For more information, head over to the :ref:`Quickstart `. - - To integrate applications, :class:`Flask` has a hook to intercept URL build - errors through :attr:`Flask.url_build_error_handlers`. The `url_for` - function results in a :exc:`~werkzeug.routing.BuildError` when the current - app does not have a URL for the given endpoint and values. When it does, the - :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if - it is not ``None``, which can return a string to use as the result of - `url_for` (instead of `url_for`'s default to raise the - :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception. - An example:: - - def external_url_handler(error, endpoint, values): - "Looks up an external URL when `url_for` cannot build a URL." - # This is an example of hooking the build_error_handler. - # Here, lookup_url is some utility function you've built - # which looks up the endpoint in some external URL registry. - url = lookup_url(endpoint, **values) - if url is None: - # External lookup did not have a URL. - # Re-raise the BuildError, in context of original traceback. - exc_type, exc_value, tb = sys.exc_info() - if exc_value is error: - raise exc_type, exc_value, tb - else: - raise error - # url_for will use this result, instead of raising BuildError. - return url - - app.url_build_error_handlers.append(external_url_handler) - - Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and - `endpoint` and `values` are the arguments passed into `url_for`. Note - that this is for building URLs outside the current application, and not for - handling 404 NotFound errors. - - .. versionadded:: 0.10 - The `_scheme` parameter was added. - - .. versionadded:: 0.9 - The `_anchor` and `_method` parameters were added. - - .. versionadded:: 0.9 - Calls :meth:`Flask.handle_build_error` on - :exc:`~werkzeug.routing.BuildError`. - - :param endpoint: the endpoint of the URL (name of the function) - :param values: the variable arguments of the URL rule - :param _external: if set to ``True``, an absolute URL is generated. Server - address can be changed via ``SERVER_NAME`` configuration variable which - defaults to `localhost`. - :param _scheme: a string specifying the desired URL scheme. The `_external` - parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default - behavior uses the same scheme as the current request, or - ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration ` if no - request context is available. As of Werkzeug 0.10, this also can be set - to an empty string to build protocol-relative URLs. - :param _anchor: if provided this is added as anchor to the URL. - :param _method: if provided this explicitly specifies an HTTP method. - """ - appctx = _app_ctx_stack.top - reqctx = _request_ctx_stack.top - - if appctx is None: - raise RuntimeError( - 'Attempted to generate a URL without the application context being' - ' pushed. This has to be executed when application context is' - ' available.' - ) - - # If request specific information is available we have some extra - # features that support "relative" URLs. - if reqctx is not None: - url_adapter = reqctx.url_adapter - blueprint_name = request.blueprint - - if endpoint[:1] == '.': - if blueprint_name is not None: - endpoint = blueprint_name + endpoint - else: - endpoint = endpoint[1:] - - external = values.pop('_external', False) - - # Otherwise go with the url adapter from the appctx and make - # the URLs external by default. - else: - url_adapter = appctx.url_adapter - - if url_adapter is None: - raise RuntimeError( - 'Application was not able to create a URL adapter for request' - ' independent URL generation. You might be able to fix this by' - ' setting the SERVER_NAME config variable.' - ) - - external = values.pop('_external', True) - - anchor = values.pop('_anchor', None) - method = values.pop('_method', None) - scheme = values.pop('_scheme', None) - appctx.app.inject_url_defaults(endpoint, values) - - # This is not the best way to deal with this but currently the - # underlying Werkzeug router does not support overriding the scheme on - # a per build call basis. - old_scheme = None - if scheme is not None: - if not external: - raise ValueError('When specifying _scheme, _external must be True') - old_scheme = url_adapter.url_scheme - url_adapter.url_scheme = scheme - - try: - try: - rv = url_adapter.build(endpoint, values, method=method, - force_external=external) - finally: - if old_scheme is not None: - url_adapter.url_scheme = old_scheme - except BuildError as error: - # We need to inject the values again so that the app callback can - # deal with that sort of stuff. - values['_external'] = external - values['_anchor'] = anchor - values['_method'] = method - values['_scheme'] = scheme - return appctx.app.handle_url_build_error(error, endpoint, values) - - if anchor is not None: - rv += '#' + url_quote(anchor) - return rv - - -def get_template_attribute(template_name, attribute): - """Loads a macro (or variable) a template exports. This can be used to - invoke a macro from within Python code. If you for example have a - template named :file:`_cider.html` with the following contents: - - .. sourcecode:: html+jinja - - {% macro hello(name) %}Hello {{ name }}!{% endmacro %} - - You can access this from Python code like this:: - - hello = get_template_attribute('_cider.html', 'hello') - return hello('World') - - .. versionadded:: 0.2 - - :param template_name: the name of the template - :param attribute: the name of the variable of macro to access - """ - return getattr(current_app.jinja_env.get_template(template_name).module, - attribute) - - -def flash(message, category='message'): - """Flashes a message to the next request. In order to remove the - flashed message from the session and to display it to the user, - the template has to call :func:`get_flashed_messages`. - - .. versionchanged:: 0.3 - `category` parameter added. - - :param message: the message to be flashed. - :param category: the category for the message. The following values - are recommended: ``'message'`` for any kind of message, - ``'error'`` for errors, ``'info'`` for information - messages and ``'warning'`` for warnings. However any - kind of string can be used as category. - """ - # Original implementation: - # - # session.setdefault('_flashes', []).append((category, message)) - # - # This assumed that changes made to mutable structures in the session are - # always in sync with the session object, which is not true for session - # implementations that use external storage for keeping their keys/values. - flashes = session.get('_flashes', []) - flashes.append((category, message)) - session['_flashes'] = flashes - message_flashed.send(current_app._get_current_object(), - message=message, category=category) - - -def get_flashed_messages(with_categories=False, category_filter=[]): - """Pulls all flashed messages from the session and returns them. - Further calls in the same request to the function will return - the same messages. By default just the messages are returned, - but when `with_categories` is set to ``True``, the return value will - be a list of tuples in the form ``(category, message)`` instead. - - Filter the flashed messages to one or more categories by providing those - categories in `category_filter`. This allows rendering categories in - separate html blocks. The `with_categories` and `category_filter` - arguments are distinct: - - * `with_categories` controls whether categories are returned with message - text (``True`` gives a tuple, where ``False`` gives just the message text). - * `category_filter` filters the messages down to only those matching the - provided categories. - - See :ref:`message-flashing-pattern` for examples. - - .. versionchanged:: 0.3 - `with_categories` parameter added. - - .. versionchanged:: 0.9 - `category_filter` parameter added. - - :param with_categories: set to ``True`` to also receive categories. - :param category_filter: whitelist of categories to limit return values - """ - flashes = _request_ctx_stack.top.flashes - if flashes is None: - _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \ - if '_flashes' in session else [] - if category_filter: - flashes = list(filter(lambda f: f[0] in category_filter, flashes)) - if not with_categories: - return [x[1] for x in flashes] - return flashes - - -def send_file(filename_or_fp, mimetype=None, as_attachment=False, - attachment_filename=None, add_etags=True, - cache_timeout=None, conditional=False, last_modified=None): - """Sends the contents of a file to the client. This will use the - most efficient method available and configured. By default it will - try to use the WSGI server's file_wrapper support. Alternatively - you can set the application's :attr:`~Flask.use_x_sendfile` attribute - to ``True`` to directly emit an ``X-Sendfile`` header. This however - requires support of the underlying webserver for ``X-Sendfile``. - - By default it will try to guess the mimetype for you, but you can - also explicitly provide one. For extra security you probably want - to send certain files as attachment (HTML for instance). The mimetype - guessing requires a `filename` or an `attachment_filename` to be - provided. - - ETags will also be attached automatically if a `filename` is provided. You - can turn this off by setting `add_etags=False`. - - If `conditional=True` and `filename` is provided, this method will try to - upgrade the response stream to support range requests. This will allow - the request to be answered with partial content response. - - Please never pass filenames to this function from user sources; - you should use :func:`send_from_directory` instead. - - .. versionadded:: 0.2 - - .. versionadded:: 0.5 - The `add_etags`, `cache_timeout` and `conditional` parameters were - added. The default behavior is now to attach etags. - - .. versionchanged:: 0.7 - mimetype guessing and etag support for file objects was - deprecated because it was unreliable. Pass a filename if you are - able to, otherwise attach an etag yourself. This functionality - will be removed in Flask 1.0 - - .. versionchanged:: 0.9 - cache_timeout pulls its default from application config, when None. - - .. versionchanged:: 0.12 - The filename is no longer automatically inferred from file objects. If - you want to use automatic mimetype and etag support, pass a filepath via - `filename_or_fp` or `attachment_filename`. - - .. versionchanged:: 0.12 - The `attachment_filename` is preferred over `filename` for MIME-type - detection. - - .. versionchanged:: 1.0 - UTF-8 filenames, as specified in `RFC 2231`_, are supported. - - .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4 - - .. versionchanged:: 1.0.3 - Filenames are encoded with ASCII instead of Latin-1 for broader - compatibility with WSGI servers. - - :param filename_or_fp: the filename of the file to send. - This is relative to the :attr:`~Flask.root_path` - if a relative path is specified. - Alternatively a file object might be provided in - which case ``X-Sendfile`` might not work and fall - back to the traditional method. Make sure that the - file pointer is positioned at the start of data to - send before calling :func:`send_file`. - :param mimetype: the mimetype of the file if provided. If a file path is - given, auto detection happens as fallback, otherwise an - error will be raised. - :param as_attachment: set to ``True`` if you want to send this file with - a ``Content-Disposition: attachment`` header. - :param attachment_filename: the filename for the attachment if it - differs from the file's filename. - :param add_etags: set to ``False`` to disable attaching of etags. - :param conditional: set to ``True`` to enable conditional responses. - - :param cache_timeout: the timeout in seconds for the headers. When ``None`` - (default), this value is set by - :meth:`~Flask.get_send_file_max_age` of - :data:`~flask.current_app`. - :param last_modified: set the ``Last-Modified`` header to this value, - a :class:`~datetime.datetime` or timestamp. - If a file was passed, this overrides its mtime. - """ - mtime = None - fsize = None - if isinstance(filename_or_fp, string_types): - filename = filename_or_fp - if not os.path.isabs(filename): - filename = os.path.join(current_app.root_path, filename) - file = None - if attachment_filename is None: - attachment_filename = os.path.basename(filename) - else: - file = filename_or_fp - filename = None - - if mimetype is None: - if attachment_filename is not None: - mimetype = mimetypes.guess_type(attachment_filename)[0] \ - or 'application/octet-stream' - - if mimetype is None: - raise ValueError( - 'Unable to infer MIME-type because no filename is available. ' - 'Please set either `attachment_filename`, pass a filepath to ' - '`filename_or_fp` or set your own MIME-type via `mimetype`.' - ) - - headers = Headers() - if as_attachment: - if attachment_filename is None: - raise TypeError('filename unavailable, required for ' - 'sending as attachment') - - try: - attachment_filename = attachment_filename.encode('ascii') - except UnicodeEncodeError: - filenames = { - 'filename': unicodedata.normalize( - 'NFKD', attachment_filename).encode('ascii', 'ignore'), - 'filename*': "UTF-8''%s" % url_quote(attachment_filename), - } - else: - filenames = {'filename': attachment_filename} - - headers.add('Content-Disposition', 'attachment', **filenames) - - if current_app.use_x_sendfile and filename: - if file is not None: - file.close() - headers['X-Sendfile'] = filename - fsize = os.path.getsize(filename) - headers['Content-Length'] = fsize - data = None - else: - if file is None: - file = open(filename, 'rb') - mtime = os.path.getmtime(filename) - fsize = os.path.getsize(filename) - headers['Content-Length'] = fsize - data = wrap_file(request.environ, file) - - rv = current_app.response_class(data, mimetype=mimetype, headers=headers, - direct_passthrough=True) - - if last_modified is not None: - rv.last_modified = last_modified - elif mtime is not None: - rv.last_modified = mtime - - rv.cache_control.public = True - if cache_timeout is None: - cache_timeout = current_app.get_send_file_max_age(filename) - if cache_timeout is not None: - rv.cache_control.max_age = cache_timeout - rv.expires = int(time() + cache_timeout) - - if add_etags and filename is not None: - from warnings import warn - - try: - rv.set_etag('%s-%s-%s' % ( - os.path.getmtime(filename), - os.path.getsize(filename), - adler32( - filename.encode('utf-8') if isinstance(filename, text_type) - else filename - ) & 0xffffffff - )) - except OSError: - warn('Access %s failed, maybe it does not exist, so ignore etags in ' - 'headers' % filename, stacklevel=2) - - if conditional: - try: - rv = rv.make_conditional(request, accept_ranges=True, - complete_length=fsize) - except RequestedRangeNotSatisfiable: - if file is not None: - file.close() - raise - # make sure we don't send x-sendfile for servers that - # ignore the 304 status code for x-sendfile. - if rv.status_code == 304: - rv.headers.pop('x-sendfile', None) - return rv - - -def safe_join(directory, *pathnames): - """Safely join `directory` and zero or more untrusted `pathnames` - components. - - Example usage:: - - @app.route('/wiki/') - def wiki_page(filename): - filename = safe_join(app.config['WIKI_FOLDER'], filename) - with open(filename, 'rb') as fd: - content = fd.read() # Read and process the file content... - - :param directory: the trusted base directory. - :param pathnames: the untrusted pathnames relative to that directory. - :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed - paths fall out of its boundaries. - """ - - parts = [directory] - - for filename in pathnames: - if filename != '': - filename = posixpath.normpath(filename) - - if ( - any(sep in filename for sep in _os_alt_seps) - or os.path.isabs(filename) - or filename == '..' - or filename.startswith('../') - ): - raise NotFound() - - parts.append(filename) - - return posixpath.join(*parts) - - -def send_from_directory(directory, filename, **options): - """Send a file from a given directory with :func:`send_file`. This - is a secure way to quickly expose static files from an upload folder - or something similar. - - Example usage:: - - @app.route('/uploads/') - def download_file(filename): - return send_from_directory(app.config['UPLOAD_FOLDER'], - filename, as_attachment=True) - - .. admonition:: Sending files and Performance - - It is strongly recommended to activate either ``X-Sendfile`` support in - your webserver or (if no authentication happens) to tell the webserver - to serve files for the given path on its own without calling into the - web application for improved performance. - - .. versionadded:: 0.5 - - :param directory: the directory where all the files are stored. - :param filename: the filename relative to that directory to - download. - :param options: optional keyword arguments that are directly - forwarded to :func:`send_file`. - """ - filename = safe_join(directory, filename) - if not os.path.isabs(filename): - filename = os.path.join(current_app.root_path, filename) - try: - if not os.path.isfile(filename): - raise NotFound() - except (TypeError, ValueError): - raise BadRequest() - options.setdefault('conditional', True) - return send_file(filename, **options) - - -def get_root_path(import_name): - """Returns the path to a package or cwd if that cannot be found. This - returns the path of a package or the folder that contains a module. - - Not to be confused with the package path returned by :func:`find_package`. - """ - # Module already imported and has a file attribute. Use that first. - mod = sys.modules.get(import_name) - if mod is not None and hasattr(mod, '__file__'): - return os.path.dirname(os.path.abspath(mod.__file__)) - - # Next attempt: check the loader. - loader = pkgutil.get_loader(import_name) - - # Loader does not exist or we're referring to an unloaded main module - # or a main module without path (interactive sessions), go with the - # current working directory. - if loader is None or import_name == '__main__': - return os.getcwd() - - # For .egg, zipimporter does not have get_filename until Python 2.7. - # Some other loaders might exhibit the same behavior. - if hasattr(loader, 'get_filename'): - filepath = loader.get_filename(import_name) - else: - # Fall back to imports. - __import__(import_name) - mod = sys.modules[import_name] - filepath = getattr(mod, '__file__', None) - - # If we don't have a filepath it might be because we are a - # namespace package. In this case we pick the root path from the - # first module that is contained in our package. - if filepath is None: - raise RuntimeError('No root path can be found for the provided ' - 'module "%s". This can happen because the ' - 'module came from an import hook that does ' - 'not provide file name information or because ' - 'it\'s a namespace package. In this case ' - 'the root path needs to be explicitly ' - 'provided.' % import_name) - - # filepath is import_name.py for a module, or __init__.py for a package. - return os.path.dirname(os.path.abspath(filepath)) - - -def _matching_loader_thinks_module_is_package(loader, mod_name): - """Given the loader that loaded a module and the module this function - attempts to figure out if the given module is actually a package. - """ - # If the loader can tell us if something is a package, we can - # directly ask the loader. - if hasattr(loader, 'is_package'): - return loader.is_package(mod_name) - # importlib's namespace loaders do not have this functionality but - # all the modules it loads are packages, so we can take advantage of - # this information. - elif (loader.__class__.__module__ == '_frozen_importlib' and - loader.__class__.__name__ == 'NamespaceLoader'): - return True - # Otherwise we need to fail with an error that explains what went - # wrong. - raise AttributeError( - ('%s.is_package() method is missing but is required by Flask of ' - 'PEP 302 import hooks. If you do not use import hooks and ' - 'you encounter this error please file a bug against Flask.') % - loader.__class__.__name__) - - -def find_package(import_name): - """Finds a package and returns the prefix (or None if the package is - not installed) as well as the folder that contains the package or - module as a tuple. The package path returned is the module that would - have to be added to the pythonpath in order to make it possible to - import the module. The prefix is the path below which a UNIX like - folder structure exists (lib, share etc.). - """ - root_mod_name = import_name.split('.')[0] - loader = pkgutil.get_loader(root_mod_name) - if loader is None or import_name == '__main__': - # import name is not found, or interactive/main module - package_path = os.getcwd() - else: - # For .egg, zipimporter does not have get_filename until Python 2.7. - if hasattr(loader, 'get_filename'): - filename = loader.get_filename(root_mod_name) - elif hasattr(loader, 'archive'): - # zipimporter's loader.archive points to the .egg or .zip - # archive filename is dropped in call to dirname below. - filename = loader.archive - else: - # At least one loader is missing both get_filename and archive: - # Google App Engine's HardenedModulesHook - # - # Fall back to imports. - __import__(import_name) - filename = sys.modules[import_name].__file__ - package_path = os.path.abspath(os.path.dirname(filename)) - - # In case the root module is a package we need to chop of the - # rightmost part. This needs to go through a helper function - # because of python 3.3 namespace packages. - if _matching_loader_thinks_module_is_package( - loader, root_mod_name): - package_path = os.path.dirname(package_path) - - site_parent, site_folder = os.path.split(package_path) - py_prefix = os.path.abspath(sys.prefix) - if package_path.startswith(py_prefix): - return py_prefix, package_path - elif site_folder.lower() == 'site-packages': - parent, folder = os.path.split(site_parent) - # Windows like installations - if folder.lower() == 'lib': - base_dir = parent - # UNIX like installations - elif os.path.basename(parent).lower() == 'lib': - base_dir = os.path.dirname(parent) - else: - base_dir = site_parent - return base_dir, package_path - return None, package_path - - -class locked_cached_property(object): - """A decorator that converts a function into a lazy property. The - function wrapped is called the first time to retrieve the result - and then that calculated result is used the next time you access - the value. Works like the one in Werkzeug but has a lock for - thread safety. - """ - - def __init__(self, func, name=None, doc=None): - self.__name__ = name or func.__name__ - self.__module__ = func.__module__ - self.__doc__ = doc or func.__doc__ - self.func = func - self.lock = RLock() - - def __get__(self, obj, type=None): - if obj is None: - return self - with self.lock: - value = obj.__dict__.get(self.__name__, _missing) - if value is _missing: - value = self.func(obj) - obj.__dict__[self.__name__] = value - return value - - -class _PackageBoundObject(object): - #: The name of the package or module that this app belongs to. Do not - #: change this once it is set by the constructor. - import_name = None - - #: Location of the template files to be added to the template lookup. - #: ``None`` if templates should not be added. - template_folder = None - - #: Absolute path to the package on the filesystem. Used to look up - #: resources contained in the package. - root_path = None - - def __init__(self, import_name, template_folder=None, root_path=None): - self.import_name = import_name - self.template_folder = template_folder - - if root_path is None: - root_path = get_root_path(self.import_name) - - self.root_path = root_path - self._static_folder = None - self._static_url_path = None - - def _get_static_folder(self): - if self._static_folder is not None: - return os.path.join(self.root_path, self._static_folder) - - def _set_static_folder(self, value): - self._static_folder = value - - static_folder = property( - _get_static_folder, _set_static_folder, - doc='The absolute path to the configured static folder.' - ) - del _get_static_folder, _set_static_folder - - def _get_static_url_path(self): - if self._static_url_path is not None: - return self._static_url_path - - if self.static_folder is not None: - return '/' + os.path.basename(self.static_folder) - - def _set_static_url_path(self, value): - self._static_url_path = value - - static_url_path = property( - _get_static_url_path, _set_static_url_path, - doc='The URL prefix that the static route will be registered for.' - ) - del _get_static_url_path, _set_static_url_path - - @property - def has_static_folder(self): - """This is ``True`` if the package bound object's container has a - folder for static files. - - .. versionadded:: 0.5 - """ - return self.static_folder is not None - - @locked_cached_property - def jinja_loader(self): - """The Jinja loader for this package bound object. - - .. versionadded:: 0.5 - """ - if self.template_folder is not None: - return FileSystemLoader(os.path.join(self.root_path, - self.template_folder)) - - def get_send_file_max_age(self, filename): - """Provides default cache_timeout for the :func:`send_file` functions. - - By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from - the configuration of :data:`~flask.current_app`. - - Static file functions such as :func:`send_from_directory` use this - function, and :func:`send_file` calls this function on - :data:`~flask.current_app` when the given cache_timeout is ``None``. If a - cache_timeout is given in :func:`send_file`, that timeout is used; - otherwise, this method is called. - - This allows subclasses to change the behavior when sending files based - on the filename. For example, to set the cache timeout for .js files - to 60 seconds:: - - class MyFlask(flask.Flask): - def get_send_file_max_age(self, name): - if name.lower().endswith('.js'): - return 60 - return flask.Flask.get_send_file_max_age(self, name) - - .. versionadded:: 0.9 - """ - return total_seconds(current_app.send_file_max_age_default) - - def send_static_file(self, filename): - """Function used internally to send static files from the static - folder to the browser. - - .. versionadded:: 0.5 - """ - if not self.has_static_folder: - raise RuntimeError('No static folder for this object') - # Ensure get_send_file_max_age is called in all cases. - # Here, we ensure get_send_file_max_age is called for Blueprints. - cache_timeout = self.get_send_file_max_age(filename) - return send_from_directory(self.static_folder, filename, - cache_timeout=cache_timeout) - - def open_resource(self, resource, mode='rb'): - """Opens a resource from the application's resource folder. To see - how this works, consider the following folder structure:: - - /myapplication.py - /schema.sql - /static - /style.css - /templates - /layout.html - /index.html - - If you want to open the :file:`schema.sql` file you would do the - following:: - - with app.open_resource('schema.sql') as f: - contents = f.read() - do_something_with(contents) - - :param resource: the name of the resource. To access resources within - subfolders use forward slashes as separator. - :param mode: resource file opening mode, default is 'rb'. - """ - if mode not in ('r', 'rb'): - raise ValueError('Resources can only be opened for reading') - return open(os.path.join(self.root_path, resource), mode) - - -def total_seconds(td): - """Returns the total seconds from a timedelta object. - - :param timedelta td: the timedelta to be converted in seconds - - :returns: number of seconds - :rtype: int - """ - return td.days * 60 * 60 * 24 + td.seconds - - -def is_ip(value): - """Determine if the given string is an IP address. - - Python 2 on Windows doesn't provide ``inet_pton``, so this only - checks IPv4 addresses in that environment. - - :param value: value to check - :type value: str - - :return: True if string is an IP address - :rtype: bool - """ - if PY2 and os.name == 'nt': - try: - socket.inet_aton(value) - return True - except socket.error: - return False - - for family in (socket.AF_INET, socket.AF_INET6): - try: - socket.inet_pton(family, value) - except socket.error: - pass - else: - return True - - return False diff --git a/flask/json/__init__.py b/flask/json/__init__.py deleted file mode 100644 index fbe6b92f0a..0000000000 --- a/flask/json/__init__.py +++ /dev/null @@ -1,327 +0,0 @@ -# -*- coding: utf-8 -*- -""" -flask.json -~~~~~~~~~~ - -:copyright: © 2010 by the Pallets team. -:license: BSD, see LICENSE for more details. -""" -import codecs -import io -import uuid -from datetime import date, datetime -from flask.globals import current_app, request -from flask._compat import text_type, PY2 - -from werkzeug.http import http_date -from jinja2 import Markup - -# Use the same json implementation as itsdangerous on which we -# depend anyways. -from itsdangerous import json as _json - - -# Figure out if simplejson escapes slashes. This behavior was changed -# from one version to another without reason. -_slash_escape = '\\/' not in _json.dumps('/') - - -__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump', - 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder', - 'jsonify'] - - -def _wrap_reader_for_text(fp, encoding): - if isinstance(fp.read(0), bytes): - fp = io.TextIOWrapper(io.BufferedReader(fp), encoding) - return fp - - -def _wrap_writer_for_text(fp, encoding): - try: - fp.write('') - except TypeError: - fp = io.TextIOWrapper(fp, encoding) - return fp - - -class JSONEncoder(_json.JSONEncoder): - """The default Flask JSON encoder. This one extends the default simplejson - encoder by also supporting ``datetime`` objects, ``UUID`` as well as - ``Markup`` objects which are serialized as RFC 822 datetime strings (same - as the HTTP date format). In order to support more data types override the - :meth:`default` method. - """ - - def default(self, o): - """Implement this method in a subclass such that it returns a - serializable object for ``o``, or calls the base implementation (to - raise a :exc:`TypeError`). - - For example, to support arbitrary iterators, you could implement - default like this:: - - def default(self, o): - try: - iterable = iter(o) - except TypeError: - pass - else: - return list(iterable) - return JSONEncoder.default(self, o) - """ - if isinstance(o, datetime): - return http_date(o.utctimetuple()) - if isinstance(o, date): - return http_date(o.timetuple()) - if isinstance(o, uuid.UUID): - return str(o) - if hasattr(o, '__html__'): - return text_type(o.__html__()) - return _json.JSONEncoder.default(self, o) - - -class JSONDecoder(_json.JSONDecoder): - """The default JSON decoder. This one does not change the behavior from - the default simplejson decoder. Consult the :mod:`json` documentation - for more information. This decoder is not only used for the load - functions of this module but also :attr:`~flask.Request`. - """ - - -def _dump_arg_defaults(kwargs): - """Inject default arguments for dump functions.""" - if current_app: - bp = current_app.blueprints.get(request.blueprint) if request else None - kwargs.setdefault( - 'cls', - bp.json_encoder if bp and bp.json_encoder - else current_app.json_encoder - ) - - if not current_app.config['JSON_AS_ASCII']: - kwargs.setdefault('ensure_ascii', False) - - kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS']) - else: - kwargs.setdefault('sort_keys', True) - kwargs.setdefault('cls', JSONEncoder) - - -def _load_arg_defaults(kwargs): - """Inject default arguments for load functions.""" - if current_app: - bp = current_app.blueprints.get(request.blueprint) if request else None - kwargs.setdefault( - 'cls', - bp.json_decoder if bp and bp.json_decoder - else current_app.json_decoder - ) - else: - kwargs.setdefault('cls', JSONDecoder) - - -def detect_encoding(data): - """Detect which UTF codec was used to encode the given bytes. - - The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is - accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big - or little endian. Some editors or libraries may prepend a BOM. - - :param data: Bytes in unknown UTF encoding. - :return: UTF encoding name - """ - head = data[:4] - - if head[:3] == codecs.BOM_UTF8: - return 'utf-8-sig' - - if b'\x00' not in head: - return 'utf-8' - - if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE): - return 'utf-32' - - if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE): - return 'utf-16' - - if len(head) == 4: - if head[:3] == b'\x00\x00\x00': - return 'utf-32-be' - - if head[::2] == b'\x00\x00': - return 'utf-16-be' - - if head[1:] == b'\x00\x00\x00': - return 'utf-32-le' - - if head[1::2] == b'\x00\x00': - return 'utf-16-le' - - if len(head) == 2: - return 'utf-16-be' if head.startswith(b'\x00') else 'utf-16-le' - - return 'utf-8' - - -def dumps(obj, **kwargs): - """Serialize ``obj`` to a JSON formatted ``str`` by using the application's - configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an - application on the stack. - - This function can return ``unicode`` strings or ascii-only bytestrings by - default which coerce into unicode strings automatically. That behavior by - default is controlled by the ``JSON_AS_ASCII`` configuration variable - and can be overridden by the simplejson ``ensure_ascii`` parameter. - """ - _dump_arg_defaults(kwargs) - encoding = kwargs.pop('encoding', None) - rv = _json.dumps(obj, **kwargs) - if encoding is not None and isinstance(rv, text_type): - rv = rv.encode(encoding) - return rv - - -def dump(obj, fp, **kwargs): - """Like :func:`dumps` but writes into a file object.""" - _dump_arg_defaults(kwargs) - encoding = kwargs.pop('encoding', None) - if encoding is not None: - fp = _wrap_writer_for_text(fp, encoding) - _json.dump(obj, fp, **kwargs) - - -def loads(s, **kwargs): - """Unserialize a JSON object from a string ``s`` by using the application's - configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an - application on the stack. - """ - _load_arg_defaults(kwargs) - if isinstance(s, bytes): - encoding = kwargs.pop('encoding', None) - if encoding is None: - encoding = detect_encoding(s) - s = s.decode(encoding) - return _json.loads(s, **kwargs) - - -def load(fp, **kwargs): - """Like :func:`loads` but reads from a file object. - """ - _load_arg_defaults(kwargs) - if not PY2: - fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8') - return _json.load(fp, **kwargs) - - -def htmlsafe_dumps(obj, **kwargs): - """Works exactly like :func:`dumps` but is safe for use in ``') - assert rv == u'"\\u003c/script\\u003e"' - assert type(rv) == text_type - rv = render('{{ ""|tojson }}') - assert rv == '"\\u003c/script\\u003e"' - rv = render('{{ "<\0/script>"|tojson }}') - assert rv == '"\\u003c\\u0000/script\\u003e"' - rv = render('{{ "