hc99 commited on
Commit
93d7919
·
verified ·
1 Parent(s): e4f7c80

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/pallets__flask/.editorconfig +13 -0
  2. testbed/pallets__flask/.gitignore +26 -0
  3. testbed/pallets__flask/.pre-commit-config.yaml +38 -0
  4. testbed/pallets__flask/.readthedocs.yaml +13 -0
  5. testbed/pallets__flask/CHANGES.rst +1260 -0
  6. testbed/pallets__flask/CODE_OF_CONDUCT.md +76 -0
  7. testbed/pallets__flask/CONTRIBUTING.rst +229 -0
  8. testbed/pallets__flask/LICENSE.rst +28 -0
  9. testbed/pallets__flask/MANIFEST.in +11 -0
  10. testbed/pallets__flask/README.rst +82 -0
  11. testbed/pallets__flask/artwork/LICENSE.rst +19 -0
  12. testbed/pallets__flask/artwork/logo-full.svg +290 -0
  13. testbed/pallets__flask/artwork/logo-lineart.svg +165 -0
  14. testbed/pallets__flask/examples/tutorial/LICENSE.rst +28 -0
  15. testbed/pallets__flask/examples/tutorial/README.rst +77 -0
  16. testbed/pallets__flask/examples/tutorial/flaskr/__init__.py +50 -0
  17. testbed/pallets__flask/examples/tutorial/flaskr/db.py +54 -0
  18. testbed/pallets__flask/examples/tutorial/flaskr/schema.sql +20 -0
  19. testbed/pallets__flask/examples/tutorial/setup.cfg +28 -0
  20. testbed/pallets__flask/examples/tutorial/setup.py +3 -0
  21. testbed/pallets__flask/examples/tutorial/tests/test_blog.py +83 -0
  22. testbed/pallets__flask/examples/tutorial/tests/test_factory.py +12 -0
  23. testbed/pallets__flask/requirements/dev.in +6 -0
  24. testbed/pallets__flask/requirements/dev.txt +62 -0
  25. testbed/pallets__flask/requirements/docs.in +5 -0
  26. testbed/pallets__flask/requirements/docs.txt +72 -0
  27. testbed/pallets__flask/requirements/tests-pallets-dev.in +5 -0
  28. testbed/pallets__flask/requirements/tests-pallets-dev.txt +19 -0
  29. testbed/pallets__flask/requirements/tests-pallets-min.in +5 -0
  30. testbed/pallets__flask/requirements/tests-pallets-min.txt +19 -0
  31. testbed/pallets__flask/requirements/tests.in +5 -0
  32. testbed/pallets__flask/requirements/tests.txt +31 -0
  33. testbed/pallets__flask/requirements/typing.in +5 -0
  34. testbed/pallets__flask/requirements/typing.txt +27 -0
  35. testbed/pallets__flask/setup.cfg +118 -0
  36. testbed/pallets__flask/setup.py +17 -0
  37. testbed/pallets__flask/src/flask/app.py +2095 -0
  38. testbed/pallets__flask/src/flask/blueprints.py +597 -0
  39. testbed/pallets__flask/src/flask/cli.py +989 -0
  40. testbed/pallets__flask/src/flask/config.py +272 -0
  41. testbed/pallets__flask/src/flask/ctx.py +513 -0
  42. testbed/pallets__flask/src/flask/debughelpers.py +174 -0
  43. testbed/pallets__flask/src/flask/globals.py +59 -0
  44. testbed/pallets__flask/src/flask/helpers.py +790 -0
  45. testbed/pallets__flask/src/flask/json/__init__.py +299 -0
  46. testbed/pallets__flask/src/flask/logging.py +74 -0
  47. testbed/pallets__flask/src/flask/py.typed +0 -0
  48. testbed/pallets__flask/src/flask/scaffold.py +869 -0
  49. testbed/pallets__flask/src/flask/sessions.py +421 -0
  50. testbed/pallets__flask/src/flask/signals.py +56 -0
testbed/pallets__flask/.editorconfig ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = space
5
+ indent_size = 4
6
+ insert_final_newline = true
7
+ trim_trailing_whitespace = true
8
+ end_of_line = lf
9
+ charset = utf-8
10
+ max_line_length = 88
11
+
12
+ [*.{yml,yaml,json,js,css,html}]
13
+ indent_size = 2
testbed/pallets__flask/.gitignore ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ .env
3
+ .flaskenv
4
+ *.pyc
5
+ *.pyo
6
+ env/
7
+ venv/
8
+ .venv/
9
+ env*
10
+ dist/
11
+ build/
12
+ *.egg
13
+ *.egg-info/
14
+ _mailinglist
15
+ .tox/
16
+ .cache/
17
+ .pytest_cache/
18
+ .idea/
19
+ docs/_build/
20
+ .vscode
21
+
22
+ # Coverage reports
23
+ htmlcov/
24
+ .coverage
25
+ .coverage.*
26
+ *,cover
testbed/pallets__flask/.pre-commit-config.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ci:
2
+ autoupdate_branch: "2.0.x"
3
+ autoupdate_schedule: monthly
4
+ repos:
5
+ - repo: https://github.com/asottile/pyupgrade
6
+ rev: v2.31.0
7
+ hooks:
8
+ - id: pyupgrade
9
+ args: ["--py36-plus"]
10
+ - repo: https://github.com/asottile/reorder_python_imports
11
+ rev: v2.7.1
12
+ hooks:
13
+ - id: reorder-python-imports
14
+ name: Reorder Python imports (src, tests)
15
+ files: "^(?!examples/)"
16
+ args: ["--application-directories", "src"]
17
+ additional_dependencies: ["setuptools>60.9"]
18
+ - repo: https://github.com/psf/black
19
+ rev: 22.1.0
20
+ hooks:
21
+ - id: black
22
+ - repo: https://github.com/PyCQA/flake8
23
+ rev: 4.0.1
24
+ hooks:
25
+ - id: flake8
26
+ additional_dependencies:
27
+ - flake8-bugbear
28
+ - flake8-implicit-str-concat
29
+ - repo: https://github.com/peterdemin/pip-compile-multi
30
+ rev: v2.4.3
31
+ hooks:
32
+ - id: pip-compile-multi-verify
33
+ - repo: https://github.com/pre-commit/pre-commit-hooks
34
+ rev: v4.1.0
35
+ hooks:
36
+ - id: fix-byte-order-marker
37
+ - id: trailing-whitespace
38
+ - id: end-of-file-fixer
testbed/pallets__flask/.readthedocs.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ build:
3
+ os: ubuntu-20.04
4
+ tools:
5
+ python: "3.10"
6
+ python:
7
+ install:
8
+ - requirements: requirements/docs.txt
9
+ - method: pip
10
+ path: .
11
+ sphinx:
12
+ builder: dirhtml
13
+ fail_on_warning: true
testbed/pallets__flask/CHANGES.rst ADDED
@@ -0,0 +1,1260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. currentmodule:: flask
2
+
3
+ Version 2.1.0
4
+ -------------
5
+
6
+ Unreleased
7
+
8
+ - Drop support for Python 3.6. :pr:`4335`
9
+ - Update Click dependency to >= 8.0. :pr:`4008`
10
+ - Remove previously deprecated code. :pr:`4337`
11
+
12
+ - The CLI does not pass ``script_info`` to app factory functions.
13
+ - ``config.from_json`` is replaced by
14
+ ``config.from_file(name, load=json.load)``.
15
+ - ``json`` functions no longer take an ``encoding`` parameter.
16
+ - ``safe_join`` is removed, use ``werkzeug.utils.safe_join``
17
+ instead.
18
+ - ``total_seconds`` is removed, use ``timedelta.total_seconds``
19
+ instead.
20
+ - The same blueprint cannot be registered with the same name. Use
21
+ ``name=`` when registering to specify a unique name.
22
+ - The test client's ``as_tuple`` parameter is removed. Use
23
+ ``response.request.environ`` instead. :pr:`4417`
24
+
25
+ - Some parameters in ``send_file`` and ``send_from_directory`` were
26
+ renamed in 2.0. The deprecation period for the old names is extended
27
+ to 2.2. Be sure to test with deprecation warnings visible.
28
+
29
+ - ``attachment_filename`` is renamed to ``download_name``.
30
+ - ``cache_timeout`` is renamed to ``max_age``.
31
+ - ``add_etags`` is renamed to ``etag``.
32
+ - ``filename`` is renamed to ``path``.
33
+
34
+ - The ``RequestContext.g`` property is deprecated. Use ``g`` directly
35
+ or ``AppContext.g`` instead. :issue:`3898`
36
+ - ``copy_current_request_context`` can decorate async functions.
37
+ :pr:`4303`
38
+ - The CLI uses ``importlib.metadata`` instead of ``setuptools`` to
39
+ load command entry points. :issue:`4419`
40
+ - Overriding ``FlaskClient.open`` will not cause an error on redirect.
41
+ :issue:`3396`
42
+ - Add an ``--exclude-patterns`` option to the ``flask run`` CLI
43
+ command to specify patterns that will be ignored by the reloader.
44
+ :issue:`4188`
45
+ - When using lazy loading (the default with the debugger), the Click
46
+ context from the ``flask run`` command remains available in the
47
+ loader thread. :issue:`4460`
48
+ - Deleting the session cookie uses the ``httponly`` flag.
49
+ :issue:`4485`
50
+ - Relax typing for ``errorhandler`` to allow the user to use more
51
+ precise types and decorate the same function multiple times.
52
+ :issue:`4095, 4295, 4297`
53
+ - Fix typing for ``__exit__`` methods for better compatibility with
54
+ ``ExitStack``. :issue:`4474`
55
+ - From Werkzeug, for redirect responses the ``Location`` header URL
56
+ will remain relative, and exclude the scheme and domain, by default.
57
+ :pr:`4496`
58
+
59
+
60
+ Version 2.0.3
61
+ -------------
62
+
63
+ Released 2022-02-14
64
+
65
+ - The test client's ``as_tuple`` parameter is deprecated and will be
66
+ removed in Werkzeug 2.1. It is now also deprecated in Flask, to be
67
+ removed in Flask 2.1, while remaining compatible with both in
68
+ 2.0.x. Use ``response.request.environ`` instead. :pr:`4341`
69
+ - Fix type annotation for ``errorhandler`` decorator. :issue:`4295`
70
+ - Revert a change to the CLI that caused it to hide ``ImportError``
71
+ tracebacks when importing the application. :issue:`4307`
72
+ - ``app.json_encoder`` and ``json_decoder`` are only passed to
73
+ ``dumps`` and ``loads`` if they have custom behavior. This improves
74
+ performance, mainly on PyPy. :issue:`4349`
75
+ - Clearer error message when ``after_this_request`` is used outside a
76
+ request context. :issue:`4333`
77
+
78
+
79
+ Version 2.0.2
80
+ -------------
81
+
82
+ Released 2021-10-04
83
+
84
+ - Fix type annotation for ``teardown_*`` methods. :issue:`4093`
85
+ - Fix type annotation for ``before_request`` and ``before_app_request``
86
+ decorators. :issue:`4104`
87
+ - Fixed the issue where typing requires template global
88
+ decorators to accept functions with no arguments. :issue:`4098`
89
+ - Support View and MethodView instances with async handlers. :issue:`4112`
90
+ - Enhance typing of ``app.errorhandler`` decorator. :issue:`4095`
91
+ - Fix registering a blueprint twice with differing names. :issue:`4124`
92
+ - Fix the type of ``static_folder`` to accept ``pathlib.Path``.
93
+ :issue:`4150`
94
+ - ``jsonify`` handles ``decimal.Decimal`` by encoding to ``str``.
95
+ :issue:`4157`
96
+ - Correctly handle raising deferred errors in CLI lazy loading.
97
+ :issue:`4096`
98
+ - The CLI loader handles ``**kwargs`` in a ``create_app`` function.
99
+ :issue:`4170`
100
+ - Fix the order of ``before_request`` and other callbacks that trigger
101
+ before the view returns. They are called from the app down to the
102
+ closest nested blueprint. :issue:`4229`
103
+
104
+
105
+ Version 2.0.1
106
+ -------------
107
+
108
+ Released 2021-05-21
109
+
110
+ - Re-add the ``filename`` parameter in ``send_from_directory``. The
111
+ ``filename`` parameter has been renamed to ``path``, the old name
112
+ is deprecated. :pr:`4019`
113
+ - Mark top-level names as exported so type checking understands
114
+ imports in user projects. :issue:`4024`
115
+ - Fix type annotation for ``g`` and inform mypy that it is a namespace
116
+ object that has arbitrary attributes. :issue:`4020`
117
+ - Fix some types that weren't available in Python 3.6.0. :issue:`4040`
118
+ - Improve typing for ``send_file``, ``send_from_directory``, and
119
+ ``get_send_file_max_age``. :issue:`4044`, :pr:`4026`
120
+ - Show an error when a blueprint name contains a dot. The ``.`` has
121
+ special meaning, it is used to separate (nested) blueprint names and
122
+ the endpoint name. :issue:`4041`
123
+ - Combine URL prefixes when nesting blueprints that were created with
124
+ a ``url_prefix`` value. :issue:`4037`
125
+ - Roll back a change to the order that URL matching was done. The
126
+ URL is again matched after the session is loaded, so the session is
127
+ available in custom URL converters. :issue:`4053`
128
+ - Re-add deprecated ``Config.from_json``, which was accidentally
129
+ removed early. :issue:`4078`
130
+ - Improve typing for some functions using ``Callable`` in their type
131
+ signatures, focusing on decorator factories. :issue:`4060`
132
+ - Nested blueprints are registered with their dotted name. This allows
133
+ different blueprints with the same name to be nested at different
134
+ locations. :issue:`4069`
135
+ - ``register_blueprint`` takes a ``name`` option to change the
136
+ (pre-dotted) name the blueprint is registered with. This allows the
137
+ same blueprint to be registered multiple times with unique names for
138
+ ``url_for``. Registering the same blueprint with the same name
139
+ multiple times is deprecated. :issue:`1091`
140
+ - Improve typing for ``stream_with_context``. :issue:`4052`
141
+
142
+
143
+ Version 2.0.0
144
+ -------------
145
+
146
+ Released 2021-05-11
147
+
148
+ - Drop support for Python 2 and 3.5.
149
+ - Bump minimum versions of other Pallets projects: Werkzeug >= 2,
150
+ Jinja2 >= 3, MarkupSafe >= 2, ItsDangerous >= 2, Click >= 8. Be sure
151
+ to check the change logs for each project. For better compatibility
152
+ with other applications (e.g. Celery) that still require Click 7,
153
+ there is no hard dependency on Click 8 yet, but using Click 7 will
154
+ trigger a DeprecationWarning and Flask 2.1 will depend on Click 8.
155
+ - JSON support no longer uses simplejson. To use another JSON module,
156
+ override ``app.json_encoder`` and ``json_decoder``. :issue:`3555`
157
+ - The ``encoding`` option to JSON functions is deprecated. :pr:`3562`
158
+ - Passing ``script_info`` to app factory functions is deprecated. This
159
+ was not portable outside the ``flask`` command. Use
160
+ ``click.get_current_context().obj`` if it's needed. :issue:`3552`
161
+ - The CLI shows better error messages when the app failed to load
162
+ when looking up commands. :issue:`2741`
163
+ - Add :meth:`sessions.SessionInterface.get_cookie_name` to allow
164
+ setting the session cookie name dynamically. :pr:`3369`
165
+ - Add :meth:`Config.from_file` to load config using arbitrary file
166
+ loaders, such as ``toml.load`` or ``json.load``.
167
+ :meth:`Config.from_json` is deprecated in favor of this. :pr:`3398`
168
+ - The ``flask run`` command will only defer errors on reload. Errors
169
+ present during the initial call will cause the server to exit with
170
+ the traceback immediately. :issue:`3431`
171
+ - :func:`send_file` raises a :exc:`ValueError` when passed an
172
+ :mod:`io` object in text mode. Previously, it would respond with
173
+ 200 OK and an empty file. :issue:`3358`
174
+ - When using ad-hoc certificates, check for the cryptography library
175
+ instead of PyOpenSSL. :pr:`3492`
176
+ - When specifying a factory function with ``FLASK_APP``, keyword
177
+ argument can be passed. :issue:`3553`
178
+ - When loading a ``.env`` or ``.flaskenv`` file, the current working
179
+ directory is no longer changed to the location of the file.
180
+ :pr:`3560`
181
+ - When returning a ``(response, headers)`` tuple from a view, the
182
+ headers replace rather than extend existing headers on the response.
183
+ For example, this allows setting the ``Content-Type`` for
184
+ ``jsonify()``. Use ``response.headers.extend()`` if extending is
185
+ desired. :issue:`3628`
186
+ - The ``Scaffold`` class provides a common API for the ``Flask`` and
187
+ ``Blueprint`` classes. ``Blueprint`` information is stored in
188
+ attributes just like ``Flask``, rather than opaque lambda functions.
189
+ This is intended to improve consistency and maintainability.
190
+ :issue:`3215`
191
+ - Include ``samesite`` and ``secure`` options when removing the
192
+ session cookie. :pr:`3726`
193
+ - Support passing a ``pathlib.Path`` to ``static_folder``. :pr:`3579`
194
+ - ``send_file`` and ``send_from_directory`` are wrappers around the
195
+ implementations in ``werkzeug.utils``. :pr:`3828`
196
+ - Some ``send_file`` parameters have been renamed, the old names are
197
+ deprecated. ``attachment_filename`` is renamed to ``download_name``.
198
+ ``cache_timeout`` is renamed to ``max_age``. ``add_etags`` is
199
+ renamed to ``etag``. :pr:`3828, 3883`
200
+ - ``send_file`` passes ``download_name`` even if
201
+ ``as_attachment=False`` by using ``Content-Disposition: inline``.
202
+ :pr:`3828`
203
+ - ``send_file`` sets ``conditional=True`` and ``max_age=None`` by
204
+ default. ``Cache-Control`` is set to ``no-cache`` if ``max_age`` is
205
+ not set, otherwise ``public``. This tells browsers to validate
206
+ conditional requests instead of using a timed cache. :pr:`3828`
207
+ - ``helpers.safe_join`` is deprecated. Use
208
+ ``werkzeug.utils.safe_join`` instead. :pr:`3828`
209
+ - The request context does route matching before opening the session.
210
+ This could allow a session interface to change behavior based on
211
+ ``request.endpoint``. :issue:`3776`
212
+ - Use Jinja's implementation of the ``|tojson`` filter. :issue:`3881`
213
+ - Add route decorators for common HTTP methods. For example,
214
+ ``@app.post("/login")`` is a shortcut for
215
+ ``@app.route("/login", methods=["POST"])``. :pr:`3907`
216
+ - Support async views, error handlers, before and after request, and
217
+ teardown functions. :pr:`3412`
218
+ - Support nesting blueprints. :issue:`593, 1548`, :pr:`3923`
219
+ - Set the default encoding to "UTF-8" when loading ``.env`` and
220
+ ``.flaskenv`` files to allow to use non-ASCII characters. :issue:`3931`
221
+ - ``flask shell`` sets up tab and history completion like the default
222
+ ``python`` shell if ``readline`` is installed. :issue:`3941`
223
+ - ``helpers.total_seconds()`` is deprecated. Use
224
+ ``timedelta.total_seconds()`` instead. :pr:`3962`
225
+ - Add type hinting. :pr:`3973`.
226
+
227
+
228
+ Version 1.1.4
229
+ -------------
230
+
231
+ Released 2021-05-13
232
+
233
+ - Update ``static_folder`` to use ``_compat.fspath`` instead of
234
+ ``os.fspath`` to continue supporting Python < 3.6 :issue:`4050`
235
+
236
+
237
+ Version 1.1.3
238
+ -------------
239
+
240
+ Released 2021-05-13
241
+
242
+ - Set maximum versions of Werkzeug, Jinja, Click, and ItsDangerous.
243
+ :issue:`4043`
244
+ - Re-add support for passing a ``pathlib.Path`` for ``static_folder``.
245
+ :pr:`3579`
246
+
247
+
248
+ Version 1.1.2
249
+ -------------
250
+
251
+ Released 2020-04-03
252
+
253
+ - Work around an issue when running the ``flask`` command with an
254
+ external debugger on Windows. :issue:`3297`
255
+ - The static route will not catch all URLs if the ``Flask``
256
+ ``static_folder`` argument ends with a slash. :issue:`3452`
257
+
258
+
259
+ Version 1.1.1
260
+ -------------
261
+
262
+ Released 2019-07-08
263
+
264
+ - The ``flask.json_available`` flag was added back for compatibility
265
+ with some extensions. It will raise a deprecation warning when used,
266
+ and will be removed in version 2.0.0. :issue:`3288`
267
+
268
+
269
+ Version 1.1.0
270
+ -------------
271
+
272
+ Released 2019-07-04
273
+
274
+ - Bump minimum Werkzeug version to >= 0.15.
275
+ - Drop support for Python 3.4.
276
+ - Error handlers for ``InternalServerError`` or ``500`` will always be
277
+ passed an instance of ``InternalServerError``. If they are invoked
278
+ due to an unhandled exception, that original exception is now
279
+ available as ``e.original_exception`` rather than being passed
280
+ directly to the handler. The same is true if the handler is for the
281
+ base ``HTTPException``. This makes error handler behavior more
282
+ consistent. :pr:`3266`
283
+
284
+ - :meth:`Flask.finalize_request` is called for all unhandled
285
+ exceptions even if there is no ``500`` error handler.
286
+
287
+ - :attr:`Flask.logger` takes the same name as
288
+ :attr:`Flask.name` (the value passed as
289
+ ``Flask(import_name)``. This reverts 1.0's behavior of always
290
+ logging to ``"flask.app"``, in order to support multiple apps in the
291
+ same process. A warning will be shown if old configuration is
292
+ detected that needs to be moved. :issue:`2866`
293
+ - :meth:`flask.RequestContext.copy` includes the current session
294
+ object in the request context copy. This prevents ``session``
295
+ pointing to an out-of-date object. :issue:`2935`
296
+ - Using built-in RequestContext, unprintable Unicode characters in
297
+ Host header will result in a HTTP 400 response and not HTTP 500 as
298
+ previously. :pr:`2994`
299
+ - :func:`send_file` supports :class:`~os.PathLike` objects as
300
+ described in PEP 0519, to support :mod:`pathlib` in Python 3.
301
+ :pr:`3059`
302
+ - :func:`send_file` supports :class:`~io.BytesIO` partial content.
303
+ :issue:`2957`
304
+ - :func:`open_resource` accepts the "rt" file mode. This still does
305
+ the same thing as "r". :issue:`3163`
306
+ - The :attr:`MethodView.methods` attribute set in a base class is used
307
+ by subclasses. :issue:`3138`
308
+ - :attr:`Flask.jinja_options` is a ``dict`` instead of an
309
+ ``ImmutableDict`` to allow easier configuration. Changes must still
310
+ be made before creating the environment. :pr:`3190`
311
+ - Flask's ``JSONMixin`` for the request and response wrappers was
312
+ moved into Werkzeug. Use Werkzeug's version with Flask-specific
313
+ support. This bumps the Werkzeug dependency to >= 0.15.
314
+ :issue:`3125`
315
+ - The ``flask`` command entry point is simplified to take advantage
316
+ of Werkzeug 0.15's better reloader support. This bumps the Werkzeug
317
+ dependency to >= 0.15. :issue:`3022`
318
+ - Support ``static_url_path`` that ends with a forward slash.
319
+ :issue:`3134`
320
+ - Support empty ``static_folder`` without requiring setting an empty
321
+ ``static_url_path`` as well. :pr:`3124`
322
+ - :meth:`jsonify` supports :class:`dataclasses.dataclass` objects.
323
+ :pr:`3195`
324
+ - Allow customizing the :attr:`Flask.url_map_class` used for routing.
325
+ :pr:`3069`
326
+ - The development server port can be set to 0, which tells the OS to
327
+ pick an available port. :issue:`2926`
328
+ - The return value from :meth:`cli.load_dotenv` is more consistent
329
+ with the documentation. It will return ``False`` if python-dotenv is
330
+ not installed, or if the given path isn't a file. :issue:`2937`
331
+ - Signaling support has a stub for the ``connect_via`` method when
332
+ the Blinker library is not installed. :pr:`3208`
333
+ - Add an ``--extra-files`` option to the ``flask run`` CLI command to
334
+ specify extra files that will trigger the reloader on change.
335
+ :issue:`2897`
336
+ - Allow returning a dictionary from a view function. Similar to how
337
+ returning a string will produce a ``text/html`` response, returning
338
+ a dict will call ``jsonify`` to produce a ``application/json``
339
+ response. :pr:`3111`
340
+ - Blueprints have a ``cli`` Click group like ``app.cli``. CLI commands
341
+ registered with a blueprint will be available as a group under the
342
+ ``flask`` command. :issue:`1357`.
343
+ - When using the test client as a context manager (``with client:``),
344
+ all preserved request contexts are popped when the block exits,
345
+ ensuring nested contexts are cleaned up correctly. :pr:`3157`
346
+ - Show a better error message when the view return type is not
347
+ supported. :issue:`3214`
348
+ - ``flask.testing.make_test_environ_builder()`` has been deprecated in
349
+ favour of a new class ``flask.testing.EnvironBuilder``. :pr:`3232`
350
+ - The ``flask run`` command no longer fails if Python is not built
351
+ with SSL support. Using the ``--cert`` option will show an
352
+ appropriate error message. :issue:`3211`
353
+ - URL matching now occurs after the request context is pushed, rather
354
+ than when it's created. This allows custom URL converters to access
355
+ the app and request contexts, such as to query a database for an id.
356
+ :issue:`3088`
357
+
358
+
359
+ Version 1.0.4
360
+ -------------
361
+
362
+ Released 2019-07-04
363
+
364
+ - The key information for ``BadRequestKeyError`` is no longer cleared
365
+ outside debug mode, so error handlers can still access it. This
366
+ requires upgrading to Werkzeug 0.15.5. :issue:`3249`
367
+ - ``send_file`` url quotes the ":" and "/" characters for more
368
+ compatible UTF-8 filename support in some browsers. :issue:`3074`
369
+ - Fixes for PEP451 import loaders and pytest 5.x. :issue:`3275`
370
+ - Show message about dotenv on stderr instead of stdout. :issue:`3285`
371
+
372
+
373
+ Version 1.0.3
374
+ -------------
375
+
376
+ Released 2019-05-17
377
+
378
+ - :func:`send_file` encodes filenames as ASCII instead of Latin-1
379
+ (ISO-8859-1). This fixes compatibility with Gunicorn, which is
380
+ stricter about header encodings than PEP 3333. :issue:`2766`
381
+ - Allow custom CLIs using ``FlaskGroup`` to set the debug flag without
382
+ it always being overwritten based on environment variables.
383
+ :pr:`2765`
384
+ - ``flask --version`` outputs Werkzeug's version and simplifies the
385
+ Python version. :pr:`2825`
386
+ - :func:`send_file` handles an ``attachment_filename`` that is a
387
+ native Python 2 string (bytes) with UTF-8 coded bytes. :issue:`2933`
388
+ - A catch-all error handler registered for ``HTTPException`` will not
389
+ handle ``RoutingException``, which is used internally during
390
+ routing. This fixes the unexpected behavior that had been introduced
391
+ in 1.0. :pr:`2986`
392
+ - Passing the ``json`` argument to ``app.test_client`` does not
393
+ push/pop an extra app context. :issue:`2900`
394
+
395
+
396
+ Version 1.0.2
397
+ -------------
398
+
399
+ Released 2018-05-02
400
+
401
+ - Fix more backwards compatibility issues with merging slashes between
402
+ a blueprint prefix and route. :pr:`2748`
403
+ - Fix error with ``flask routes`` command when there are no routes.
404
+ :issue:`2751`
405
+
406
+
407
+ Version 1.0.1
408
+ -------------
409
+
410
+ Released 2018-04-29
411
+
412
+ - Fix registering partials (with no ``__name__``) as view functions.
413
+ :pr:`2730`
414
+ - Don't treat lists returned from view functions the same as tuples.
415
+ Only tuples are interpreted as response data. :issue:`2736`
416
+ - Extra slashes between a blueprint's ``url_prefix`` and a route URL
417
+ are merged. This fixes some backwards compatibility issues with the
418
+ change in 1.0. :issue:`2731`, :issue:`2742`
419
+ - Only trap ``BadRequestKeyError`` errors in debug mode, not all
420
+ ``BadRequest`` errors. This allows ``abort(400)`` to continue
421
+ working as expected. :issue:`2735`
422
+ - The ``FLASK_SKIP_DOTENV`` environment variable can be set to ``1``
423
+ to skip automatically loading dotenv files. :issue:`2722`
424
+
425
+
426
+ Version 1.0
427
+ -----------
428
+
429
+ Released 2018-04-26
430
+
431
+ - Python 2.6 and 3.3 are no longer supported.
432
+ - Bump minimum dependency versions to the latest stable versions:
433
+ Werkzeug >= 0.14, Jinja >= 2.10, itsdangerous >= 0.24, Click >= 5.1.
434
+ :issue:`2586`
435
+ - Skip :meth:`app.run <Flask.run>` when a Flask application is run
436
+ from the command line. This avoids some behavior that was confusing
437
+ to debug.
438
+ - Change the default for :data:`JSONIFY_PRETTYPRINT_REGULAR` to
439
+ ``False``. :func:`~json.jsonify` returns a compact format by
440
+ default, and an indented format in debug mode. :pr:`2193`
441
+ - :meth:`Flask.__init__ <Flask>` accepts the ``host_matching``
442
+ argument and sets it on :attr:`~Flask.url_map`. :issue:`1559`
443
+ - :meth:`Flask.__init__ <Flask>` accepts the ``static_host`` argument
444
+ and passes it as the ``host`` argument when defining the static
445
+ route. :issue:`1559`
446
+ - :func:`send_file` supports Unicode in ``attachment_filename``.
447
+ :pr:`2223`
448
+ - Pass ``_scheme`` argument from :func:`url_for` to
449
+ :meth:`~Flask.handle_url_build_error`. :pr:`2017`
450
+ - :meth:`~Flask.add_url_rule` accepts the
451
+ ``provide_automatic_options`` argument to disable adding the
452
+ ``OPTIONS`` method. :pr:`1489`
453
+ - :class:`~views.MethodView` subclasses inherit method handlers from
454
+ base classes. :pr:`1936`
455
+ - Errors caused while opening the session at the beginning of the
456
+ request are handled by the app's error handlers. :pr:`2254`
457
+ - Blueprints gained :attr:`~Blueprint.json_encoder` and
458
+ :attr:`~Blueprint.json_decoder` attributes to override the app's
459
+ encoder and decoder. :pr:`1898`
460
+ - :meth:`Flask.make_response` raises ``TypeError`` instead of
461
+ ``ValueError`` for bad response types. The error messages have been
462
+ improved to describe why the type is invalid. :pr:`2256`
463
+ - Add ``routes`` CLI command to output routes registered on the
464
+ application. :pr:`2259`
465
+ - Show warning when session cookie domain is a bare hostname or an IP
466
+ address, as these may not behave properly in some browsers, such as
467
+ Chrome. :pr:`2282`
468
+ - Allow IP address as exact session cookie domain. :pr:`2282`
469
+ - ``SESSION_COOKIE_DOMAIN`` is set if it is detected through
470
+ ``SERVER_NAME``. :pr:`2282`
471
+ - Auto-detect zero-argument app factory called ``create_app`` or
472
+ ``make_app`` from ``FLASK_APP``. :pr:`2297`
473
+ - Factory functions are not required to take a ``script_info``
474
+ parameter to work with the ``flask`` command. If they take a single
475
+ parameter or a parameter named ``script_info``, the
476
+ :class:`~cli.ScriptInfo` object will be passed. :pr:`2319`
477
+ - ``FLASK_APP`` can be set to an app factory, with arguments if
478
+ needed, for example ``FLASK_APP=myproject.app:create_app('dev')``.
479
+ :pr:`2326`
480
+ - ``FLASK_APP`` can point to local packages that are not installed in
481
+ editable mode, although ``pip install -e`` is still preferred.
482
+ :pr:`2414`
483
+ - The :class:`~views.View` class attribute
484
+ :attr:`~views.View.provide_automatic_options` is set in
485
+ :meth:`~views.View.as_view`, to be detected by
486
+ :meth:`~Flask.add_url_rule`. :pr:`2316`
487
+ - Error handling will try handlers registered for ``blueprint, code``,
488
+ ``app, code``, ``blueprint, exception``, ``app, exception``.
489
+ :pr:`2314`
490
+ - ``Cookie`` is added to the response's ``Vary`` header if the session
491
+ is accessed at all during the request (and not deleted). :pr:`2288`
492
+ - :meth:`~Flask.test_request_context` accepts ``subdomain`` and
493
+ ``url_scheme`` arguments for use when building the base URL.
494
+ :pr:`1621`
495
+ - Set :data:`APPLICATION_ROOT` to ``'/'`` by default. This was already
496
+ the implicit default when it was set to ``None``.
497
+ - :data:`TRAP_BAD_REQUEST_ERRORS` is enabled by default in debug mode.
498
+ ``BadRequestKeyError`` has a message with the bad key in debug mode
499
+ instead of the generic bad request message. :pr:`2348`
500
+ - Allow registering new tags with
501
+ :class:`~json.tag.TaggedJSONSerializer` to support storing other
502
+ types in the session cookie. :pr:`2352`
503
+ - Only open the session if the request has not been pushed onto the
504
+ context stack yet. This allows :func:`~stream_with_context`
505
+ generators to access the same session that the containing view uses.
506
+ :pr:`2354`
507
+ - Add ``json`` keyword argument for the test client request methods.
508
+ This will dump the given object as JSON and set the appropriate
509
+ content type. :pr:`2358`
510
+ - Extract JSON handling to a mixin applied to both the
511
+ :class:`Request` and :class:`Response` classes. This adds the
512
+ :meth:`~Response.is_json` and :meth:`~Response.get_json` methods to
513
+ the response to make testing JSON response much easier. :pr:`2358`
514
+ - Removed error handler caching because it caused unexpected results
515
+ for some exception inheritance hierarchies. Register handlers
516
+ explicitly for each exception if you want to avoid traversing the
517
+ MRO. :pr:`2362`
518
+ - Fix incorrect JSON encoding of aware, non-UTC datetimes. :pr:`2374`
519
+ - Template auto reloading will honor debug mode even even if
520
+ :attr:`~Flask.jinja_env` was already accessed. :pr:`2373`
521
+ - The following old deprecated code was removed. :issue:`2385`
522
+
523
+ - ``flask.ext`` - import extensions directly by their name instead
524
+ of through the ``flask.ext`` namespace. For example,
525
+ ``import flask.ext.sqlalchemy`` becomes
526
+ ``import flask_sqlalchemy``.
527
+ - ``Flask.init_jinja_globals`` - extend
528
+ :meth:`Flask.create_jinja_environment` instead.
529
+ - ``Flask.error_handlers`` - tracked by
530
+ :attr:`Flask.error_handler_spec`, use :meth:`Flask.errorhandler`
531
+ to register handlers.
532
+ - ``Flask.request_globals_class`` - use
533
+ :attr:`Flask.app_ctx_globals_class` instead.
534
+ - ``Flask.static_path`` - use :attr:`Flask.static_url_path`
535
+ instead.
536
+ - ``Request.module`` - use :attr:`Request.blueprint` instead.
537
+
538
+ - The :attr:`Request.json` property is no longer deprecated.
539
+ :issue:`1421`
540
+ - Support passing a :class:`~werkzeug.test.EnvironBuilder` or ``dict``
541
+ to :meth:`test_client.open <werkzeug.test.Client.open>`. :pr:`2412`
542
+ - The ``flask`` command and :meth:`Flask.run` will load environment
543
+ variables from ``.env`` and ``.flaskenv`` files if python-dotenv is
544
+ installed. :pr:`2416`
545
+ - When passing a full URL to the test client, the scheme in the URL is
546
+ used instead of :data:`PREFERRED_URL_SCHEME`. :pr:`2430`
547
+ - :attr:`Flask.logger` has been simplified. ``LOGGER_NAME`` and
548
+ ``LOGGER_HANDLER_POLICY`` config was removed. The logger is always
549
+ named ``flask.app``. The level is only set on first access, it
550
+ doesn't check :attr:`Flask.debug` each time. Only one format is
551
+ used, not different ones depending on :attr:`Flask.debug`. No
552
+ handlers are removed, and a handler is only added if no handlers are
553
+ already configured. :pr:`2436`
554
+ - Blueprint view function names may not contain dots. :pr:`2450`
555
+ - Fix a ``ValueError`` caused by invalid ``Range`` requests in some
556
+ cases. :issue:`2526`
557
+ - The development server uses threads by default. :pr:`2529`
558
+ - Loading config files with ``silent=True`` will ignore
559
+ :data:`~errno.ENOTDIR` errors. :pr:`2581`
560
+ - Pass ``--cert`` and ``--key`` options to ``flask run`` to run the
561
+ development server over HTTPS. :pr:`2606`
562
+ - Added :data:`SESSION_COOKIE_SAMESITE` to control the ``SameSite``
563
+ attribute on the session cookie. :pr:`2607`
564
+ - Added :meth:`~flask.Flask.test_cli_runner` to create a Click runner
565
+ that can invoke Flask CLI commands for testing. :pr:`2636`
566
+ - Subdomain matching is disabled by default and setting
567
+ :data:`SERVER_NAME` does not implicitly enable it. It can be enabled
568
+ by passing ``subdomain_matching=True`` to the ``Flask`` constructor.
569
+ :pr:`2635`
570
+ - A single trailing slash is stripped from the blueprint
571
+ ``url_prefix`` when it is registered with the app. :pr:`2629`
572
+ - :meth:`Request.get_json` doesn't cache the result if parsing fails
573
+ when ``silent`` is true. :issue:`2651`
574
+ - :func:`Request.get_json` no longer accepts arbitrary encodings.
575
+ Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but
576
+ Flask will autodetect UTF-8, -16, or -32. :pr:`2691`
577
+ - Added :data:`MAX_COOKIE_SIZE` and :attr:`Response.max_cookie_size`
578
+ to control when Werkzeug warns about large cookies that browsers may
579
+ ignore. :pr:`2693`
580
+ - Updated documentation theme to make docs look better in small
581
+ windows. :pr:`2709`
582
+ - Rewrote the tutorial docs and example project to take a more
583
+ structured approach to help new users avoid common pitfalls.
584
+ :pr:`2676`
585
+
586
+
587
+ Version 0.12.5
588
+ --------------
589
+
590
+ Released 2020-02-10
591
+
592
+ - Pin Werkzeug to < 1.0.0. :issue:`3497`
593
+
594
+
595
+ Version 0.12.4
596
+ --------------
597
+
598
+ Released 2018-04-29
599
+
600
+ - Repackage 0.12.3 to fix package layout issue. :issue:`2728`
601
+
602
+
603
+ Version 0.12.3
604
+ --------------
605
+
606
+ Released 2018-04-26
607
+
608
+ - :func:`Request.get_json` no longer accepts arbitrary encodings.
609
+ Incoming JSON should be encoded using UTF-8 per :rfc:`8259`, but
610
+ Flask will autodetect UTF-8, -16, or -32. :issue:`2692`
611
+ - Fix a Python warning about imports when using ``python -m flask``.
612
+ :issue:`2666`
613
+ - Fix a ``ValueError`` caused by invalid ``Range`` requests in some
614
+ cases.
615
+
616
+
617
+ Version 0.12.2
618
+ --------------
619
+
620
+ Released 2017-05-16
621
+
622
+ - Fix a bug in ``safe_join`` on Windows.
623
+
624
+
625
+ Version 0.12.1
626
+ --------------
627
+
628
+ Released 2017-03-31
629
+
630
+ - Prevent ``flask run`` from showing a ``NoAppException`` when an
631
+ ``ImportError`` occurs within the imported application module.
632
+ - Fix encoding behavior of ``app.config.from_pyfile`` for Python 3.
633
+ :issue:`2118`
634
+ - Use the ``SERVER_NAME`` config if it is present as default values
635
+ for ``app.run``. :issue:`2109`, :pr:`2152`
636
+ - Call ``ctx.auto_pop`` with the exception object instead of ``None``,
637
+ in the event that a ``BaseException`` such as ``KeyboardInterrupt``
638
+ is raised in a request handler.
639
+
640
+
641
+ Version 0.12
642
+ ------------
643
+
644
+ Released 2016-12-21, codename Punsch
645
+
646
+ - The cli command now responds to ``--version``.
647
+ - Mimetype guessing and ETag generation for file-like objects in
648
+ ``send_file`` has been removed. :issue:`104`, :pr`1849`
649
+ - Mimetype guessing in ``send_file`` now fails loudly and doesn't fall
650
+ back to ``application/octet-stream``. :pr:`1988`
651
+ - Make ``flask.safe_join`` able to join multiple paths like
652
+ ``os.path.join`` :pr:`1730`
653
+ - Revert a behavior change that made the dev server crash instead of
654
+ returning an Internal Server Error. :pr:`2006`
655
+ - Correctly invoke response handlers for both regular request
656
+ dispatching as well as error handlers.
657
+ - Disable logger propagation by default for the app logger.
658
+ - Add support for range requests in ``send_file``.
659
+ - ``app.test_client`` includes preset default environment, which can
660
+ now be directly set, instead of per ``client.get``.
661
+ - Fix crash when running under PyPy3. :pr:`1814`
662
+
663
+
664
+ Version 0.11.1
665
+ --------------
666
+
667
+ Released 2016-06-07
668
+
669
+ - Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from
670
+ working. :pr:`1872`
671
+
672
+
673
+ Version 0.11
674
+ ------------
675
+
676
+ Released 2016-05-29, codename Absinthe
677
+
678
+ - Added support to serializing top-level arrays to
679
+ :func:`flask.jsonify`. This introduces a security risk in ancient
680
+ browsers.
681
+ - Added before_render_template signal.
682
+ - Added ``**kwargs`` to :meth:`flask.Test.test_client` to support
683
+ passing additional keyword arguments to the constructor of
684
+ :attr:`flask.Flask.test_client_class`.
685
+ - Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the
686
+ set-cookie behavior. If set to ``True`` a permanent session will be
687
+ refreshed each request and get their lifetime extended, if set to
688
+ ``False`` it will only be modified if the session actually modifies.
689
+ Non permanent sessions are not affected by this and will always
690
+ expire if the browser window closes.
691
+ - Made Flask support custom JSON mimetypes for incoming data.
692
+ - Added support for returning tuples in the form ``(response,
693
+ headers)`` from a view function.
694
+ - Added :meth:`flask.Config.from_json`.
695
+ - Added :attr:`flask.Flask.config_class`.
696
+ - Added :meth:`flask.Config.get_namespace`.
697
+ - Templates are no longer automatically reloaded outside of debug
698
+ mode. This can be configured with the new ``TEMPLATES_AUTO_RELOAD``
699
+ config key.
700
+ - Added a workaround for a limitation in Python 3.3's namespace
701
+ loader.
702
+ - Added support for explicit root paths when using Python 3.3's
703
+ namespace packages.
704
+ - Added :command:`flask` and the ``flask.cli`` module to start the
705
+ local debug server through the click CLI system. This is recommended
706
+ over the old ``flask.run()`` method as it works faster and more
707
+ reliable due to a different design and also replaces
708
+ ``Flask-Script``.
709
+ - Error handlers that match specific classes are now checked first,
710
+ thereby allowing catching exceptions that are subclasses of HTTP
711
+ exceptions (in ``werkzeug.exceptions``). This makes it possible for
712
+ an extension author to create exceptions that will by default result
713
+ in the HTTP error of their choosing, but may be caught with a custom
714
+ error handler if desired.
715
+ - Added :meth:`flask.Config.from_mapping`.
716
+ - Flask will now log by default even if debug is disabled. The log
717
+ format is now hardcoded but the default log handling can be disabled
718
+ through the ``LOGGER_HANDLER_POLICY`` configuration key.
719
+ - Removed deprecated module functionality.
720
+ - Added the ``EXPLAIN_TEMPLATE_LOADING`` config flag which when
721
+ enabled will instruct Flask to explain how it locates templates.
722
+ This should help users debug when the wrong templates are loaded.
723
+ - Enforce blueprint handling in the order they were registered for
724
+ template loading.
725
+ - Ported test suite to py.test.
726
+ - Deprecated ``request.json`` in favour of ``request.get_json()``.
727
+ - Add "pretty" and "compressed" separators definitions in jsonify()
728
+ method. Reduces JSON response size when
729
+ ``JSONIFY_PRETTYPRINT_REGULAR=False`` by removing unnecessary white
730
+ space included by default after separators.
731
+ - JSON responses are now terminated with a newline character, because
732
+ it is a convention that UNIX text files end with a newline and some
733
+ clients don't deal well when this newline is missing. This came up
734
+ originally as a part of
735
+ https://github.com/postmanlabs/httpbin/issues/168. :pr:`1262`
736
+ - The automatically provided ``OPTIONS`` method is now correctly
737
+ disabled if the user registered an overriding rule with the
738
+ lowercase-version ``options``. :issue:`1288`
739
+ - ``flask.json.jsonify`` now supports the ``datetime.date`` type.
740
+ :pr:`1326`
741
+ - Don't leak exception info of already caught exceptions to context
742
+ teardown handlers. :pr:`1393`
743
+ - Allow custom Jinja environment subclasses. :pr:`1422`
744
+ - Updated extension dev guidelines.
745
+ - ``flask.g`` now has ``pop()`` and ``setdefault`` methods.
746
+ - Turn on autoescape for ``flask.templating.render_template_string``
747
+ by default. :pr:`1515`
748
+ - ``flask.ext`` is now deprecated. :pr:`1484`
749
+ - ``send_from_directory`` now raises BadRequest if the filename is
750
+ invalid on the server OS. :pr:`1763`
751
+ - Added the ``JSONIFY_MIMETYPE`` configuration variable. :pr:`1728`
752
+ - Exceptions during teardown handling will no longer leave bad
753
+ application contexts lingering around.
754
+ - Fixed broken ``test_appcontext_signals()`` test case.
755
+ - Raise an :exc:`AttributeError` in :func:`flask.helpers.find_package`
756
+ with a useful message explaining why it is raised when a PEP 302
757
+ import hook is used without an ``is_package()`` method.
758
+ - Fixed an issue causing exceptions raised before entering a request
759
+ or app context to be passed to teardown handlers.
760
+ - Fixed an issue with query parameters getting removed from requests
761
+ in the test client when absolute URLs were requested.
762
+ - Made ``@before_first_request`` into a decorator as intended.
763
+ - Fixed an etags bug when sending a file streams with a name.
764
+ - Fixed ``send_from_directory`` not expanding to the application root
765
+ path correctly.
766
+ - Changed logic of before first request handlers to flip the flag
767
+ after invoking. This will allow some uses that are potentially
768
+ dangerous but should probably be permitted.
769
+ - Fixed Python 3 bug when a handler from
770
+ ``app.url_build_error_handlers`` reraises the ``BuildError``.
771
+
772
+
773
+ Version 0.10.1
774
+ --------------
775
+
776
+ Released 2013-06-14
777
+
778
+ - Fixed an issue where ``|tojson`` was not quoting single quotes which
779
+ made the filter not work properly in HTML attributes. Now it's
780
+ possible to use that filter in single quoted attributes. This should
781
+ make using that filter with angular.js easier.
782
+ - Added support for byte strings back to the session system. This
783
+ broke compatibility with the common case of people putting binary
784
+ data for token verification into the session.
785
+ - Fixed an issue where registering the same method twice for the same
786
+ endpoint would trigger an exception incorrectly.
787
+
788
+
789
+ Version 0.10
790
+ ------------
791
+
792
+ Released 2013-06-13, codename Limoncello
793
+
794
+ - Changed default cookie serialization format from pickle to JSON to
795
+ limit the impact an attacker can do if the secret key leaks.
796
+ - Added ``template_test`` methods in addition to the already existing
797
+ ``template_filter`` method family.
798
+ - Added ``template_global`` methods in addition to the already
799
+ existing ``template_filter`` method family.
800
+ - Set the content-length header for x-sendfile.
801
+ - ``tojson`` filter now does not escape script blocks in HTML5
802
+ parsers.
803
+ - ``tojson`` used in templates is now safe by default due. This was
804
+ allowed due to the different escaping behavior.
805
+ - Flask will now raise an error if you attempt to register a new
806
+ function on an already used endpoint.
807
+ - Added wrapper module around simplejson and added default
808
+ serialization of datetime objects. This allows much easier
809
+ customization of how JSON is handled by Flask or any Flask
810
+ extension.
811
+ - Removed deprecated internal ``flask.session`` module alias. Use
812
+ ``flask.sessions`` instead to get the session module. This is not to
813
+ be confused with ``flask.session`` the session proxy.
814
+ - Templates can now be rendered without request context. The behavior
815
+ is slightly different as the ``request``, ``session`` and ``g``
816
+ objects will not be available and blueprint's context processors are
817
+ not called.
818
+ - The config object is now available to the template as a real global
819
+ and not through a context processor which makes it available even in
820
+ imported templates by default.
821
+ - Added an option to generate non-ascii encoded JSON which should
822
+ result in less bytes being transmitted over the network. It's
823
+ disabled by default to not cause confusion with existing libraries
824
+ that might expect ``flask.json.dumps`` to return bytes by default.
825
+ - ``flask.g`` is now stored on the app context instead of the request
826
+ context.
827
+ - ``flask.g`` now gained a ``get()`` method for not erroring out on
828
+ non existing items.
829
+ - ``flask.g`` now can be used with the ``in`` operator to see what's
830
+ defined and it now is iterable and will yield all attributes stored.
831
+ - ``flask.Flask.request_globals_class`` got renamed to
832
+ ``flask.Flask.app_ctx_globals_class`` which is a better name to what
833
+ it does since 0.10.
834
+ - ``request``, ``session`` and ``g`` are now also added as proxies to
835
+ the template context which makes them available in imported
836
+ templates. One has to be very careful with those though because
837
+ usage outside of macros might cause caching.
838
+ - Flask will no longer invoke the wrong error handlers if a proxy
839
+ exception is passed through.
840
+ - Added a workaround for chrome's cookies in localhost not working as
841
+ intended with domain names.
842
+ - Changed logic for picking defaults for cookie values from sessions
843
+ to work better with Google Chrome.
844
+ - Added ``message_flashed`` signal that simplifies flashing testing.
845
+ - Added support for copying of request contexts for better working
846
+ with greenlets.
847
+ - Removed custom JSON HTTP exception subclasses. If you were relying
848
+ on them you can reintroduce them again yourself trivially. Using
849
+ them however is strongly discouraged as the interface was flawed.
850
+ - Python requirements changed: requiring Python 2.6 or 2.7 now to
851
+ prepare for Python 3.3 port.
852
+ - Changed how the teardown system is informed about exceptions. This
853
+ is now more reliable in case something handles an exception halfway
854
+ through the error handling process.
855
+ - Request context preservation in debug mode now keeps the exception
856
+ information around which means that teardown handlers are able to
857
+ distinguish error from success cases.
858
+ - Added the ``JSONIFY_PRETTYPRINT_REGULAR`` configuration variable.
859
+ - Flask now orders JSON keys by default to not trash HTTP caches due
860
+ to different hash seeds between different workers.
861
+ - Added ``appcontext_pushed`` and ``appcontext_popped`` signals.
862
+ - The builtin run method now takes the ``SERVER_NAME`` into account
863
+ when picking the default port to run on.
864
+ - Added ``flask.request.get_json()`` as a replacement for the old
865
+ ``flask.request.json`` property.
866
+
867
+
868
+ Version 0.9
869
+ -----------
870
+
871
+ Released 2012-07-01, codename Campari
872
+
873
+ - The :func:`flask.Request.on_json_loading_failed` now returns a JSON
874
+ formatted response by default.
875
+ - The :func:`flask.url_for` function now can generate anchors to the
876
+ generated links.
877
+ - The :func:`flask.url_for` function now can also explicitly generate
878
+ URL rules specific to a given HTTP method.
879
+ - Logger now only returns the debug log setting if it was not set
880
+ explicitly.
881
+ - Unregister a circular dependency between the WSGI environment and
882
+ the request object when shutting down the request. This means that
883
+ environ ``werkzeug.request`` will be ``None`` after the response was
884
+ returned to the WSGI server but has the advantage that the garbage
885
+ collector is not needed on CPython to tear down the request unless
886
+ the user created circular dependencies themselves.
887
+ - Session is now stored after callbacks so that if the session payload
888
+ is stored in the session you can still modify it in an after request
889
+ callback.
890
+ - The :class:`flask.Flask` class will avoid importing the provided
891
+ import name if it can (the required first parameter), to benefit
892
+ tools which build Flask instances programmatically. The Flask class
893
+ will fall back to using import on systems with custom module hooks,
894
+ e.g. Google App Engine, or when the import name is inside a zip
895
+ archive (usually a .egg) prior to Python 2.7.
896
+ - Blueprints now have a decorator to add custom template filters
897
+ application wide, :meth:`flask.Blueprint.app_template_filter`.
898
+ - The Flask and Blueprint classes now have a non-decorator method for
899
+ adding custom template filters application wide,
900
+ :meth:`flask.Flask.add_template_filter` and
901
+ :meth:`flask.Blueprint.add_app_template_filter`.
902
+ - The :func:`flask.get_flashed_messages` function now allows rendering
903
+ flashed message categories in separate blocks, through a
904
+ ``category_filter`` argument.
905
+ - The :meth:`flask.Flask.run` method now accepts ``None`` for ``host``
906
+ and ``port`` arguments, using default values when ``None``. This
907
+ allows for calling run using configuration values, e.g.
908
+ ``app.run(app.config.get('MYHOST'), app.config.get('MYPORT'))``,
909
+ with proper behavior whether or not a config file is provided.
910
+ - The :meth:`flask.render_template` method now accepts a either an
911
+ iterable of template names or a single template name. Previously, it
912
+ only accepted a single template name. On an iterable, the first
913
+ template found is rendered.
914
+ - Added :meth:`flask.Flask.app_context` which works very similar to
915
+ the request context but only provides access to the current
916
+ application. This also adds support for URL generation without an
917
+ active request context.
918
+ - View functions can now return a tuple with the first instance being
919
+ an instance of :class:`flask.Response`. This allows for returning
920
+ ``jsonify(error="error msg"), 400`` from a view function.
921
+ - :class:`~flask.Flask` and :class:`~flask.Blueprint` now provide a
922
+ :meth:`~flask.Flask.get_send_file_max_age` hook for subclasses to
923
+ override behavior of serving static files from Flask when using
924
+ :meth:`flask.Flask.send_static_file` (used for the default static
925
+ file handler) and :func:`~flask.helpers.send_file`. This hook is
926
+ provided a filename, which for example allows changing cache
927
+ controls by file extension. The default max-age for ``send_file``
928
+ and static files can be configured through a new
929
+ ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, which is used
930
+ in the default ``get_send_file_max_age`` implementation.
931
+ - Fixed an assumption in sessions implementation which could break
932
+ message flashing on sessions implementations which use external
933
+ storage.
934
+ - Changed the behavior of tuple return values from functions. They are
935
+ no longer arguments to the response object, they now have a defined
936
+ meaning.
937
+ - Added :attr:`flask.Flask.request_globals_class` to allow a specific
938
+ class to be used on creation of the :data:`~flask.g` instance of
939
+ each request.
940
+ - Added ``required_methods`` attribute to view functions to force-add
941
+ methods on registration.
942
+ - Added :func:`flask.after_this_request`.
943
+ - Added :func:`flask.stream_with_context` and the ability to push
944
+ contexts multiple times without producing unexpected behavior.
945
+
946
+
947
+ Version 0.8.1
948
+ -------------
949
+
950
+ Released 2012-07-01
951
+
952
+ - Fixed an issue with the undocumented ``flask.session`` module to not
953
+ work properly on Python 2.5. It should not be used but did cause
954
+ some problems for package managers.
955
+
956
+
957
+ Version 0.8
958
+ -----------
959
+
960
+ Released 2011-09-29, codename Rakija
961
+
962
+ - Refactored session support into a session interface so that the
963
+ implementation of the sessions can be changed without having to
964
+ override the Flask class.
965
+ - Empty session cookies are now deleted properly automatically.
966
+ - View functions can now opt out of getting the automatic OPTIONS
967
+ implementation.
968
+ - HTTP exceptions and Bad Request errors can now be trapped so that
969
+ they show up normally in the traceback.
970
+ - Flask in debug mode is now detecting some common problems and tries
971
+ to warn you about them.
972
+ - Flask in debug mode will now complain with an assertion error if a
973
+ view was attached after the first request was handled. This gives
974
+ earlier feedback when users forget to import view code ahead of
975
+ time.
976
+ - Added the ability to register callbacks that are only triggered once
977
+ at the beginning of the first request.
978
+ (:meth:`Flask.before_first_request`)
979
+ - Malformed JSON data will now trigger a bad request HTTP exception
980
+ instead of a value error which usually would result in a 500
981
+ internal server error if not handled. This is a backwards
982
+ incompatible change.
983
+ - Applications now not only have a root path where the resources and
984
+ modules are located but also an instance path which is the
985
+ designated place to drop files that are modified at runtime (uploads
986
+ etc.). Also this is conceptually only instance depending and outside
987
+ version control so it's the perfect place to put configuration files
988
+ etc.
989
+ - Added the ``APPLICATION_ROOT`` configuration variable.
990
+ - Implemented :meth:`~flask.testing.TestClient.session_transaction` to
991
+ easily modify sessions from the test environment.
992
+ - Refactored test client internally. The ``APPLICATION_ROOT``
993
+ configuration variable as well as ``SERVER_NAME`` are now properly
994
+ used by the test client as defaults.
995
+ - Added :attr:`flask.views.View.decorators` to support simpler
996
+ decorating of pluggable (class-based) views.
997
+ - Fixed an issue where the test client if used with the "with"
998
+ statement did not trigger the execution of the teardown handlers.
999
+ - Added finer control over the session cookie parameters.
1000
+ - HEAD requests to a method view now automatically dispatch to the
1001
+ ``get`` method if no handler was implemented.
1002
+ - Implemented the virtual :mod:`flask.ext` package to import
1003
+ extensions from.
1004
+ - The context preservation on exceptions is now an integral component
1005
+ of Flask itself and no longer of the test client. This cleaned up
1006
+ some internal logic and lowers the odds of runaway request contexts
1007
+ in unittests.
1008
+ - Fixed the Jinja2 environment's ``list_templates`` method not
1009
+ returning the correct names when blueprints or modules were
1010
+ involved.
1011
+
1012
+
1013
+ Version 0.7.2
1014
+ -------------
1015
+
1016
+ Released 2011-07-06
1017
+
1018
+ - Fixed an issue with URL processors not properly working on
1019
+ blueprints.
1020
+
1021
+
1022
+ Version 0.7.1
1023
+ -------------
1024
+
1025
+ Released 2011-06-29
1026
+
1027
+ - Added missing future import that broke 2.5 compatibility.
1028
+ - Fixed an infinite redirect issue with blueprints.
1029
+
1030
+
1031
+ Version 0.7
1032
+ -----------
1033
+
1034
+ Released 2011-06-28, codename Grappa
1035
+
1036
+ - Added :meth:`~flask.Flask.make_default_options_response` which can
1037
+ be used by subclasses to alter the default behavior for ``OPTIONS``
1038
+ responses.
1039
+ - Unbound locals now raise a proper :exc:`RuntimeError` instead of an
1040
+ :exc:`AttributeError`.
1041
+ - Mimetype guessing and etag support based on file objects is now
1042
+ deprecated for :func:`flask.send_file` because it was unreliable.
1043
+ Pass filenames instead or attach your own etags and provide a proper
1044
+ mimetype by hand.
1045
+ - Static file handling for modules now requires the name of the static
1046
+ folder to be supplied explicitly. The previous autodetection was not
1047
+ reliable and caused issues on Google's App Engine. Until 1.0 the old
1048
+ behavior will continue to work but issue dependency warnings.
1049
+ - Fixed a problem for Flask to run on jython.
1050
+ - Added a ``PROPAGATE_EXCEPTIONS`` configuration variable that can be
1051
+ used to flip the setting of exception propagation which previously
1052
+ was linked to ``DEBUG`` alone and is now linked to either ``DEBUG``
1053
+ or ``TESTING``.
1054
+ - Flask no longer internally depends on rules being added through the
1055
+ ``add_url_rule`` function and can now also accept regular werkzeug
1056
+ rules added to the url map.
1057
+ - Added an ``endpoint`` method to the flask application object which
1058
+ allows one to register a callback to an arbitrary endpoint with a
1059
+ decorator.
1060
+ - Use Last-Modified for static file sending instead of Date which was
1061
+ incorrectly introduced in 0.6.
1062
+ - Added ``create_jinja_loader`` to override the loader creation
1063
+ process.
1064
+ - Implemented a silent flag for ``config.from_pyfile``.
1065
+ - Added ``teardown_request`` decorator, for functions that should run
1066
+ at the end of a request regardless of whether an exception occurred.
1067
+ Also the behavior for ``after_request`` was changed. It's now no
1068
+ longer executed when an exception is raised.
1069
+ - Implemented :func:`flask.has_request_context`
1070
+ - Deprecated ``init_jinja_globals``. Override the
1071
+ :meth:`~flask.Flask.create_jinja_environment` method instead to
1072
+ achieve the same functionality.
1073
+ - Added :func:`flask.safe_join`
1074
+ - The automatic JSON request data unpacking now looks at the charset
1075
+ mimetype parameter.
1076
+ - Don't modify the session on :func:`flask.get_flashed_messages` if
1077
+ there are no messages in the session.
1078
+ - ``before_request`` handlers are now able to abort requests with
1079
+ errors.
1080
+ - It is not possible to define user exception handlers. That way you
1081
+ can provide custom error messages from a central hub for certain
1082
+ errors that might occur during request processing (for instance
1083
+ database connection errors, timeouts from remote resources etc.).
1084
+ - Blueprints can provide blueprint specific error handlers.
1085
+ - Implemented generic class-based views.
1086
+
1087
+
1088
+ Version 0.6.1
1089
+ -------------
1090
+
1091
+ Released 2010-12-31
1092
+
1093
+ - Fixed an issue where the default ``OPTIONS`` response was not
1094
+ exposing all valid methods in the ``Allow`` header.
1095
+ - Jinja2 template loading syntax now allows "./" in front of a
1096
+ template load path. Previously this caused issues with module
1097
+ setups.
1098
+ - Fixed an issue where the subdomain setting for modules was ignored
1099
+ for the static folder.
1100
+ - Fixed a security problem that allowed clients to download arbitrary
1101
+ files if the host server was a windows based operating system and
1102
+ the client uses backslashes to escape the directory the files where
1103
+ exposed from.
1104
+
1105
+
1106
+ Version 0.6
1107
+ -----------
1108
+
1109
+ Released 2010-07-27, codename Whisky
1110
+
1111
+ - After request functions are now called in reverse order of
1112
+ registration.
1113
+ - OPTIONS is now automatically implemented by Flask unless the
1114
+ application explicitly adds 'OPTIONS' as method to the URL rule. In
1115
+ this case no automatic OPTIONS handling kicks in.
1116
+ - Static rules are now even in place if there is no static folder for
1117
+ the module. This was implemented to aid GAE which will remove the
1118
+ static folder if it's part of a mapping in the .yml file.
1119
+ - The :attr:`~flask.Flask.config` is now available in the templates as
1120
+ ``config``.
1121
+ - Context processors will no longer override values passed directly to
1122
+ the render function.
1123
+ - Added the ability to limit the incoming request data with the new
1124
+ ``MAX_CONTENT_LENGTH`` configuration value.
1125
+ - The endpoint for the :meth:`flask.Module.add_url_rule` method is now
1126
+ optional to be consistent with the function of the same name on the
1127
+ application object.
1128
+ - Added a :func:`flask.make_response` function that simplifies
1129
+ creating response object instances in views.
1130
+ - Added signalling support based on blinker. This feature is currently
1131
+ optional and supposed to be used by extensions and applications. If
1132
+ you want to use it, make sure to have `blinker`_ installed.
1133
+ - Refactored the way URL adapters are created. This process is now
1134
+ fully customizable with the :meth:`~flask.Flask.create_url_adapter`
1135
+ method.
1136
+ - Modules can now register for a subdomain instead of just an URL
1137
+ prefix. This makes it possible to bind a whole module to a
1138
+ configurable subdomain.
1139
+
1140
+ .. _blinker: https://pypi.org/project/blinker/
1141
+
1142
+
1143
+ Version 0.5.2
1144
+ -------------
1145
+
1146
+ Released 2010-07-15
1147
+
1148
+ - Fixed another issue with loading templates from directories when
1149
+ modules were used.
1150
+
1151
+
1152
+ Version 0.5.1
1153
+ -------------
1154
+
1155
+ Released 2010-07-06
1156
+
1157
+ - Fixes an issue with template loading from directories when modules
1158
+ where used.
1159
+
1160
+
1161
+ Version 0.5
1162
+ -----------
1163
+
1164
+ Released 2010-07-06, codename Calvados
1165
+
1166
+ - Fixed a bug with subdomains that was caused by the inability to
1167
+ specify the server name. The server name can now be set with the
1168
+ ``SERVER_NAME`` config key. This key is now also used to set the
1169
+ session cookie cross-subdomain wide.
1170
+ - Autoescaping is no longer active for all templates. Instead it is
1171
+ only active for ``.html``, ``.htm``, ``.xml`` and ``.xhtml``. Inside
1172
+ templates this behavior can be changed with the ``autoescape`` tag.
1173
+ - Refactored Flask internally. It now consists of more than a single
1174
+ file.
1175
+ - :func:`flask.send_file` now emits etags and has the ability to do
1176
+ conditional responses builtin.
1177
+ - (temporarily) dropped support for zipped applications. This was a
1178
+ rarely used feature and led to some confusing behavior.
1179
+ - Added support for per-package template and static-file directories.
1180
+ - Removed support for ``create_jinja_loader`` which is no longer used
1181
+ in 0.5 due to the improved module support.
1182
+ - Added a helper function to expose files from any directory.
1183
+
1184
+
1185
+ Version 0.4
1186
+ -----------
1187
+
1188
+ Released 2010-06-18, codename Rakia
1189
+
1190
+ - Added the ability to register application wide error handlers from
1191
+ modules.
1192
+ - :meth:`~flask.Flask.after_request` handlers are now also invoked if
1193
+ the request dies with an exception and an error handling page kicks
1194
+ in.
1195
+ - Test client has not the ability to preserve the request context for
1196
+ a little longer. This can also be used to trigger custom requests
1197
+ that do not pop the request stack for testing.
1198
+ - Because the Python standard library caches loggers, the name of the
1199
+ logger is configurable now to better support unittests.
1200
+ - Added ``TESTING`` switch that can activate unittesting helpers.
1201
+ - The logger switches to ``DEBUG`` mode now if debug is enabled.
1202
+
1203
+
1204
+ Version 0.3.1
1205
+ -------------
1206
+
1207
+ Released 2010-05-28
1208
+
1209
+ - Fixed a error reporting bug with :meth:`flask.Config.from_envvar`
1210
+ - Removed some unused code from flask
1211
+ - Release does no longer include development leftover files (.git
1212
+ folder for themes, built documentation in zip and pdf file and some
1213
+ .pyc files)
1214
+
1215
+
1216
+ Version 0.3
1217
+ -----------
1218
+
1219
+ Released 2010-05-28, codename Schnaps
1220
+
1221
+ - Added support for categories for flashed messages.
1222
+ - The application now configures a :class:`logging.Handler` and will
1223
+ log request handling exceptions to that logger when not in debug
1224
+ mode. This makes it possible to receive mails on server errors for
1225
+ example.
1226
+ - Added support for context binding that does not require the use of
1227
+ the with statement for playing in the console.
1228
+ - The request context is now available within the with statement
1229
+ making it possible to further push the request context or pop it.
1230
+ - Added support for configurations.
1231
+
1232
+
1233
+ Version 0.2
1234
+ -----------
1235
+
1236
+ Released 2010-05-12, codename J?germeister
1237
+
1238
+ - Various bugfixes
1239
+ - Integrated JSON support
1240
+ - Added :func:`~flask.get_template_attribute` helper function.
1241
+ - :meth:`~flask.Flask.add_url_rule` can now also register a view
1242
+ function.
1243
+ - Refactored internal request dispatching.
1244
+ - Server listens on 127.0.0.1 by default now to fix issues with
1245
+ chrome.
1246
+ - Added external URL support.
1247
+ - Added support for :func:`~flask.send_file`
1248
+ - Module support and internal request handling refactoring to better
1249
+ support pluggable applications.
1250
+ - Sessions can be set to be permanent now on a per-session basis.
1251
+ - Better error reporting on missing secret keys.
1252
+ - Added support for Google Appengine.
1253
+
1254
+
1255
+ Version 0.1
1256
+ -----------
1257
+
1258
+ Released 2010-04-16
1259
+
1260
+ - First public preview release.
testbed/pallets__flask/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at report@palletsprojects.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
+
73
+ [homepage]: https://www.contributor-covenant.org
74
+
75
+ For answers to common questions about this code of conduct, see
76
+ https://www.contributor-covenant.org/faq
testbed/pallets__flask/CONTRIBUTING.rst ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ How to contribute to Flask
2
+ ==========================
3
+
4
+ Thank you for considering contributing to Flask!
5
+
6
+
7
+ Support questions
8
+ -----------------
9
+
10
+ Please don't use the issue tracker for this. The issue tracker is a tool
11
+ to address bugs and feature requests in Flask itself. Use one of the
12
+ following resources for questions about using Flask or issues with your
13
+ own code:
14
+
15
+ - The ``#questions`` channel on our Discord chat:
16
+ https://discord.gg/pallets
17
+ - The mailing list flask@python.org for long term discussion or larger
18
+ issues.
19
+ - Ask on `Stack Overflow`_. Search with Google first using:
20
+ ``site:stackoverflow.com flask {search term, exception message, etc.}``
21
+ - Ask on our `GitHub Discussions`_.
22
+
23
+ .. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?tab=Frequent
24
+ .. _GitHub Discussions: https://github.com/pallets/flask/discussions
25
+
26
+
27
+ Reporting issues
28
+ ----------------
29
+
30
+ Include the following information in your post:
31
+
32
+ - Describe what you expected to happen.
33
+ - If possible, include a `minimal reproducible example`_ to help us
34
+ identify the issue. This also helps check that the issue is not with
35
+ your own code.
36
+ - Describe what actually happened. Include the full traceback if there
37
+ was an exception.
38
+ - List your Python and Flask versions. If possible, check if this
39
+ issue is already fixed in the latest releases or the latest code in
40
+ the repository.
41
+
42
+ .. _minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example
43
+
44
+
45
+ Submitting patches
46
+ ------------------
47
+
48
+ If there is not an open issue for what you want to submit, prefer
49
+ opening one for discussion before working on a PR. You can work on any
50
+ issue that doesn't have an open PR linked to it or a maintainer assigned
51
+ to it. These show up in the sidebar. No need to ask if you can work on
52
+ an issue that interests you.
53
+
54
+ Include the following in your patch:
55
+
56
+ - Use `Black`_ to format your code. This and other tools will run
57
+ automatically if you install `pre-commit`_ using the instructions
58
+ below.
59
+ - Include tests if your patch adds or changes code. Make sure the test
60
+ fails without your patch.
61
+ - Update any relevant docs pages and docstrings. Docs pages and
62
+ docstrings should be wrapped at 72 characters.
63
+ - Add an entry in ``CHANGES.rst``. Use the same style as other
64
+ entries. Also include ``.. versionchanged::`` inline changelogs in
65
+ relevant docstrings.
66
+
67
+ .. _Black: https://black.readthedocs.io
68
+ .. _pre-commit: https://pre-commit.com
69
+
70
+
71
+ First time setup
72
+ ~~~~~~~~~~~~~~~~
73
+
74
+ - Download and install the `latest version of git`_.
75
+ - Configure git with your `username`_ and `email`_.
76
+
77
+ .. code-block:: text
78
+
79
+ $ git config --global user.name 'your name'
80
+ $ git config --global user.email 'your email'
81
+
82
+ - Make sure you have a `GitHub account`_.
83
+ - Fork Flask to your GitHub account by clicking the `Fork`_ button.
84
+ - `Clone`_ the main repository locally.
85
+
86
+ .. code-block:: text
87
+
88
+ $ git clone https://github.com/pallets/flask
89
+ $ cd flask
90
+
91
+ - Add your fork as a remote to push your work to. Replace
92
+ ``{username}`` with your username. This names the remote "fork", the
93
+ default Pallets remote is "origin".
94
+
95
+ .. code-block:: text
96
+
97
+ $ git remote add fork https://github.com/{username}/flask
98
+
99
+ - Create a virtualenv.
100
+
101
+ .. tabs::
102
+
103
+ .. group-tab:: Linux/macOS
104
+
105
+ .. code-block:: text
106
+
107
+ $ python3 -m venv env
108
+ $ . env/bin/activate
109
+
110
+ .. group-tab:: Windows
111
+
112
+ .. code-block:: text
113
+
114
+ > py -3 -m venv env
115
+ > env\Scripts\activate
116
+
117
+ - Upgrade pip and setuptools.
118
+
119
+ .. code-block:: text
120
+
121
+ $ python -m pip install --upgrade pip setuptools
122
+
123
+ - Install the development dependencies, then install Flask in editable
124
+ mode.
125
+
126
+ .. code-block:: text
127
+
128
+ $ pip install -r requirements/dev.txt && pip install -e .
129
+
130
+ - Install the pre-commit hooks.
131
+
132
+ .. code-block:: text
133
+
134
+ $ pre-commit install
135
+
136
+ .. _latest version of git: https://git-scm.com/downloads
137
+ .. _username: https://docs.github.com/en/github/using-git/setting-your-username-in-git
138
+ .. _email: https://docs.github.com/en/github/setting-up-and-managing-your-github-user-account/setting-your-commit-email-address
139
+ .. _GitHub account: https://github.com/join
140
+ .. _Fork: https://github.com/pallets/flask/fork
141
+ .. _Clone: https://docs.github.com/en/github/getting-started-with-github/fork-a-repo#step-2-create-a-local-clone-of-your-fork
142
+
143
+
144
+ Start coding
145
+ ~~~~~~~~~~~~
146
+
147
+ - Create a branch to identify the issue you would like to work on. If
148
+ you're submitting a bug or documentation fix, branch off of the
149
+ latest ".x" branch.
150
+
151
+ .. code-block:: text
152
+
153
+ $ git fetch origin
154
+ $ git checkout -b your-branch-name origin/2.0.x
155
+
156
+ If you're submitting a feature addition or change, branch off of the
157
+ "main" branch.
158
+
159
+ .. code-block:: text
160
+
161
+ $ git fetch origin
162
+ $ git checkout -b your-branch-name origin/main
163
+
164
+ - Using your favorite editor, make your changes,
165
+ `committing as you go`_.
166
+ - Include tests that cover any code changes you make. Make sure the
167
+ test fails without your patch. Run the tests as described below.
168
+ - Push your commits to your fork on GitHub and
169
+ `create a pull request`_. Link to the issue being addressed with
170
+ ``fixes #123`` in the pull request.
171
+
172
+ .. code-block:: text
173
+
174
+ $ git push --set-upstream fork your-branch-name
175
+
176
+ .. _committing as you go: https://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes
177
+ .. _create a pull request: https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request
178
+
179
+
180
+ Running the tests
181
+ ~~~~~~~~~~~~~~~~~
182
+
183
+ Run the basic test suite with pytest.
184
+
185
+ .. code-block:: text
186
+
187
+ $ pytest
188
+
189
+ This runs the tests for the current environment, which is usually
190
+ sufficient. CI will run the full suite when you submit your pull
191
+ request. You can run the full test suite with tox if you don't want to
192
+ wait.
193
+
194
+ .. code-block:: text
195
+
196
+ $ tox
197
+
198
+
199
+ Running test coverage
200
+ ~~~~~~~~~~~~~~~~~~~~~
201
+
202
+ Generating a report of lines that do not have test coverage can indicate
203
+ where to start contributing. Run ``pytest`` using ``coverage`` and
204
+ generate a report.
205
+
206
+ .. code-block:: text
207
+
208
+ $ pip install coverage
209
+ $ coverage run -m pytest
210
+ $ coverage html
211
+
212
+ Open ``htmlcov/index.html`` in your browser to explore the report.
213
+
214
+ Read more about `coverage <https://coverage.readthedocs.io>`__.
215
+
216
+
217
+ Building the docs
218
+ ~~~~~~~~~~~~~~~~~
219
+
220
+ Build the docs in the ``docs`` directory using Sphinx.
221
+
222
+ .. code-block:: text
223
+
224
+ $ cd docs
225
+ $ make html
226
+
227
+ Open ``_build/html/index.html`` in your browser to view the docs.
228
+
229
+ Read more about `Sphinx <https://www.sphinx-doc.org/en/stable/>`__.
testbed/pallets__flask/LICENSE.rst ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2010 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
testbed/pallets__flask/MANIFEST.in ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ include CHANGES.rst
2
+ include CONTRIBUTING.rst
3
+ include tox.ini
4
+ include requirements/*.txt
5
+ graft artwork
6
+ graft docs
7
+ prune docs/_build
8
+ graft examples
9
+ graft tests
10
+ include src/flask/py.typed
11
+ global-exclude *.pyc
testbed/pallets__flask/README.rst ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flask
2
+ =====
3
+
4
+ Flask is a lightweight `WSGI`_ web application framework. It is designed
5
+ to make getting started quick and easy, with the ability to scale up to
6
+ complex applications. It began as a simple wrapper around `Werkzeug`_
7
+ and `Jinja`_ and has become one of the most popular Python web
8
+ application frameworks.
9
+
10
+ Flask offers suggestions, but doesn't enforce any dependencies or
11
+ project layout. It is up to the developer to choose the tools and
12
+ libraries they want to use. There are many extensions provided by the
13
+ community that make adding new functionality easy.
14
+
15
+ .. _WSGI: https://wsgi.readthedocs.io/
16
+ .. _Werkzeug: https://werkzeug.palletsprojects.com/
17
+ .. _Jinja: https://jinja.palletsprojects.com/
18
+
19
+
20
+ Installing
21
+ ----------
22
+
23
+ Install and update using `pip`_:
24
+
25
+ .. code-block:: text
26
+
27
+ $ pip install -U Flask
28
+
29
+ .. _pip: https://pip.pypa.io/en/stable/getting-started/
30
+
31
+
32
+ A Simple Example
33
+ ----------------
34
+
35
+ .. code-block:: python
36
+
37
+ # save this as app.py
38
+ from flask import Flask
39
+
40
+ app = Flask(__name__)
41
+
42
+ @app.route("/")
43
+ def hello():
44
+ return "Hello, World!"
45
+
46
+ .. code-block:: text
47
+
48
+ $ flask run
49
+ * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
50
+
51
+
52
+ Contributing
53
+ ------------
54
+
55
+ For guidance on setting up a development environment and how to make a
56
+ contribution to Flask, see the `contributing guidelines`_.
57
+
58
+ .. _contributing guidelines: https://github.com/pallets/flask/blob/main/CONTRIBUTING.rst
59
+
60
+
61
+ Donate
62
+ ------
63
+
64
+ The Pallets organization develops and supports Flask and the libraries
65
+ it uses. In order to grow the community of contributors and users, and
66
+ allow the maintainers to devote more time to the projects, `please
67
+ donate today`_.
68
+
69
+ .. _please donate today: https://palletsprojects.com/donate
70
+
71
+
72
+ Links
73
+ -----
74
+
75
+ - Documentation: https://flask.palletsprojects.com/
76
+ - Changes: https://flask.palletsprojects.com/changes/
77
+ - PyPI Releases: https://pypi.org/project/Flask/
78
+ - Source Code: https://github.com/pallets/flask/
79
+ - Issue Tracker: https://github.com/pallets/flask/issues/
80
+ - Website: https://palletsprojects.com/p/flask/
81
+ - Twitter: https://twitter.com/PalletsTeam
82
+ - Chat: https://discord.gg/pallets
testbed/pallets__flask/artwork/LICENSE.rst ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2010 Pallets
2
+
3
+ This logo or a modified version may be used by anyone to refer to the
4
+ Flask project, but does not indicate endorsement by the project.
5
+
6
+ Redistribution and use in source (SVG) and binary (renders in PNG, etc.)
7
+ forms, with or without modification, are permitted provided that the
8
+ following conditions are met:
9
+
10
+ 1. Redistributions of source code must retain the above copyright
11
+ notice and this list of conditions.
12
+
13
+ 2. Neither the name of the copyright holder nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ We would appreciate that you make the image a link to
18
+ https://palletsprojects.com/p/flask/ if you use it in a medium that
19
+ supports links.
testbed/pallets__flask/artwork/logo-full.svg ADDED
testbed/pallets__flask/artwork/logo-lineart.svg ADDED
testbed/pallets__flask/examples/tutorial/LICENSE.rst ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2010 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
testbed/pallets__flask/examples/tutorial/README.rst ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flaskr
2
+ ======
3
+
4
+ The basic blog app built in the Flask `tutorial`_.
5
+
6
+ .. _tutorial: https://flask.palletsprojects.com/tutorial/
7
+
8
+
9
+ Install
10
+ -------
11
+
12
+ **Be sure to use the same version of the code as the version of the docs
13
+ you're reading.** You probably want the latest tagged version, but the
14
+ default Git version is the main branch. ::
15
+
16
+ # clone the repository
17
+ $ git clone https://github.com/pallets/flask
18
+ $ cd flask
19
+ # checkout the correct version
20
+ $ git tag # shows the tagged versions
21
+ $ git checkout latest-tag-found-above
22
+ $ cd examples/tutorial
23
+
24
+ Create a virtualenv and activate it::
25
+
26
+ $ python3 -m venv venv
27
+ $ . venv/bin/activate
28
+
29
+ Or on Windows cmd::
30
+
31
+ $ py -3 -m venv venv
32
+ $ venv\Scripts\activate.bat
33
+
34
+ Install Flaskr::
35
+
36
+ $ pip install -e .
37
+
38
+ Or if you are using the main branch, install Flask from source before
39
+ installing Flaskr::
40
+
41
+ $ pip install -e ../..
42
+ $ pip install -e .
43
+
44
+
45
+ Run
46
+ ---
47
+
48
+ ::
49
+
50
+ $ export FLASK_APP=flaskr
51
+ $ export FLASK_ENV=development
52
+ $ flask init-db
53
+ $ flask run
54
+
55
+ Or on Windows cmd::
56
+
57
+ > set FLASK_APP=flaskr
58
+ > set FLASK_ENV=development
59
+ > flask init-db
60
+ > flask run
61
+
62
+ Open http://127.0.0.1:5000 in a browser.
63
+
64
+
65
+ Test
66
+ ----
67
+
68
+ ::
69
+
70
+ $ pip install '.[test]'
71
+ $ pytest
72
+
73
+ Run with coverage report::
74
+
75
+ $ coverage run -m pytest
76
+ $ coverage report
77
+ $ coverage html # open htmlcov/index.html in a browser
testbed/pallets__flask/examples/tutorial/flaskr/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from flask import Flask
4
+
5
+
6
+ def create_app(test_config=None):
7
+ """Create and configure an instance of the Flask application."""
8
+ app = Flask(__name__, instance_relative_config=True)
9
+ app.config.from_mapping(
10
+ # a default secret that should be overridden by instance config
11
+ SECRET_KEY="dev",
12
+ # store the database in the instance folder
13
+ DATABASE=os.path.join(app.instance_path, "flaskr.sqlite"),
14
+ )
15
+
16
+ if test_config is None:
17
+ # load the instance config, if it exists, when not testing
18
+ app.config.from_pyfile("config.py", silent=True)
19
+ else:
20
+ # load the test config if passed in
21
+ app.config.update(test_config)
22
+
23
+ # ensure the instance folder exists
24
+ try:
25
+ os.makedirs(app.instance_path)
26
+ except OSError:
27
+ pass
28
+
29
+ @app.route("/hello")
30
+ def hello():
31
+ return "Hello, World!"
32
+
33
+ # register the database commands
34
+ from flaskr import db
35
+
36
+ db.init_app(app)
37
+
38
+ # apply the blueprints to the app
39
+ from flaskr import auth, blog
40
+
41
+ app.register_blueprint(auth.bp)
42
+ app.register_blueprint(blog.bp)
43
+
44
+ # make url_for('index') == url_for('blog.index')
45
+ # in another app, you might define a separate main index here with
46
+ # app.route, while giving the blog blueprint a url_prefix, but for
47
+ # the tutorial the blog will be the main index
48
+ app.add_url_rule("/", endpoint="index")
49
+
50
+ return app
testbed/pallets__flask/examples/tutorial/flaskr/db.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+
3
+ import click
4
+ from flask import current_app
5
+ from flask import g
6
+ from flask.cli import with_appcontext
7
+
8
+
9
+ def get_db():
10
+ """Connect to the application's configured database. The connection
11
+ is unique for each request and will be reused if this is called
12
+ again.
13
+ """
14
+ if "db" not in g:
15
+ g.db = sqlite3.connect(
16
+ current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES
17
+ )
18
+ g.db.row_factory = sqlite3.Row
19
+
20
+ return g.db
21
+
22
+
23
+ def close_db(e=None):
24
+ """If this request connected to the database, close the
25
+ connection.
26
+ """
27
+ db = g.pop("db", None)
28
+
29
+ if db is not None:
30
+ db.close()
31
+
32
+
33
+ def init_db():
34
+ """Clear existing data and create new tables."""
35
+ db = get_db()
36
+
37
+ with current_app.open_resource("schema.sql") as f:
38
+ db.executescript(f.read().decode("utf8"))
39
+
40
+
41
+ @click.command("init-db")
42
+ @with_appcontext
43
+ def init_db_command():
44
+ """Clear existing data and create new tables."""
45
+ init_db()
46
+ click.echo("Initialized the database.")
47
+
48
+
49
+ def init_app(app):
50
+ """Register database functions with the Flask app. This is called by
51
+ the application factory.
52
+ """
53
+ app.teardown_appcontext(close_db)
54
+ app.cli.add_command(init_db_command)
testbed/pallets__flask/examples/tutorial/flaskr/schema.sql ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Initialize the database.
2
+ -- Drop any existing data and create empty tables.
3
+
4
+ DROP TABLE IF EXISTS user;
5
+ DROP TABLE IF EXISTS post;
6
+
7
+ CREATE TABLE user (
8
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
9
+ username TEXT UNIQUE NOT NULL,
10
+ password TEXT NOT NULL
11
+ );
12
+
13
+ CREATE TABLE post (
14
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
15
+ author_id INTEGER NOT NULL,
16
+ created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
17
+ title TEXT NOT NULL,
18
+ body TEXT NOT NULL,
19
+ FOREIGN KEY (author_id) REFERENCES user (id)
20
+ );
testbed/pallets__flask/examples/tutorial/setup.cfg ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [metadata]
2
+ name = flaskr
3
+ version = 1.0.0
4
+ url = https://flask.palletsprojects.com/tutorial/
5
+ license = BSD-3-Clause
6
+ maintainer = Pallets
7
+ maintainer_email = contact@palletsprojects.com
8
+ description = The basic blog app built in the Flask tutorial.
9
+ long_description = file: README.rst
10
+ long_description_content_type = text/x-rst
11
+
12
+ [options]
13
+ packages = find:
14
+ include_package_data = true
15
+ install_requires =
16
+ Flask
17
+
18
+ [options.extras_require]
19
+ test =
20
+ pytest
21
+
22
+ [tool:pytest]
23
+ testpaths = tests
24
+
25
+ [coverage:run]
26
+ branch = True
27
+ source =
28
+ flaskr
testbed/pallets__flask/examples/tutorial/setup.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from setuptools import setup
2
+
3
+ setup()
testbed/pallets__flask/examples/tutorial/tests/test_blog.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from flaskr.db import get_db
4
+
5
+
6
+ def test_index(client, auth):
7
+ response = client.get("/")
8
+ assert b"Log In" in response.data
9
+ assert b"Register" in response.data
10
+
11
+ auth.login()
12
+ response = client.get("/")
13
+ assert b"test title" in response.data
14
+ assert b"by test on 2018-01-01" in response.data
15
+ assert b"test\nbody" in response.data
16
+ assert b'href="/1/update"' in response.data
17
+
18
+
19
+ @pytest.mark.parametrize("path", ("/create", "/1/update", "/1/delete"))
20
+ def test_login_required(client, path):
21
+ response = client.post(path)
22
+ assert response.headers["Location"] == "/auth/login"
23
+
24
+
25
+ def test_author_required(app, client, auth):
26
+ # change the post author to another user
27
+ with app.app_context():
28
+ db = get_db()
29
+ db.execute("UPDATE post SET author_id = 2 WHERE id = 1")
30
+ db.commit()
31
+
32
+ auth.login()
33
+ # current user can't modify other user's post
34
+ assert client.post("/1/update").status_code == 403
35
+ assert client.post("/1/delete").status_code == 403
36
+ # current user doesn't see edit link
37
+ assert b'href="/1/update"' not in client.get("/").data
38
+
39
+
40
+ @pytest.mark.parametrize("path", ("/2/update", "/2/delete"))
41
+ def test_exists_required(client, auth, path):
42
+ auth.login()
43
+ assert client.post(path).status_code == 404
44
+
45
+
46
+ def test_create(client, auth, app):
47
+ auth.login()
48
+ assert client.get("/create").status_code == 200
49
+ client.post("/create", data={"title": "created", "body": ""})
50
+
51
+ with app.app_context():
52
+ db = get_db()
53
+ count = db.execute("SELECT COUNT(id) FROM post").fetchone()[0]
54
+ assert count == 2
55
+
56
+
57
+ def test_update(client, auth, app):
58
+ auth.login()
59
+ assert client.get("/1/update").status_code == 200
60
+ client.post("/1/update", data={"title": "updated", "body": ""})
61
+
62
+ with app.app_context():
63
+ db = get_db()
64
+ post = db.execute("SELECT * FROM post WHERE id = 1").fetchone()
65
+ assert post["title"] == "updated"
66
+
67
+
68
+ @pytest.mark.parametrize("path", ("/create", "/1/update"))
69
+ def test_create_update_validate(client, auth, path):
70
+ auth.login()
71
+ response = client.post(path, data={"title": "", "body": ""})
72
+ assert b"Title is required." in response.data
73
+
74
+
75
+ def test_delete(client, auth, app):
76
+ auth.login()
77
+ response = client.post("/1/delete")
78
+ assert response.headers["Location"] == "/"
79
+
80
+ with app.app_context():
81
+ db = get_db()
82
+ post = db.execute("SELECT * FROM post WHERE id = 1").fetchone()
83
+ assert post is None
testbed/pallets__flask/examples/tutorial/tests/test_factory.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flaskr import create_app
2
+
3
+
4
+ def test_config():
5
+ """Test create_app without passing test config."""
6
+ assert not create_app().testing
7
+ assert create_app({"TESTING": True}).testing
8
+
9
+
10
+ def test_hello(client):
11
+ response = client.get("/hello")
12
+ assert response.data == b"Hello, World!"
testbed/pallets__flask/requirements/dev.in ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ -r docs.in
2
+ -r tests.in
3
+ -r typing.in
4
+ pip-compile-multi
5
+ pre-commit
6
+ tox
testbed/pallets__flask/requirements/dev.txt ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SHA1:54b5b77ec8c7a0064ffa93b2fd16cb0130ba177c
2
+ #
3
+ # This file is autogenerated by pip-compile-multi
4
+ # To update, run:
5
+ #
6
+ # pip-compile-multi
7
+ #
8
+ -r docs.txt
9
+ -r tests.txt
10
+ -r typing.txt
11
+ cfgv==3.3.1
12
+ # via pre-commit
13
+ click==8.0.3
14
+ # via
15
+ # pip-compile-multi
16
+ # pip-tools
17
+ distlib==0.3.4
18
+ # via virtualenv
19
+ filelock==3.4.2
20
+ # via
21
+ # tox
22
+ # virtualenv
23
+ greenlet==1.1.2 ; python_version < "3.11"
24
+ # via -r requirements/tests.in
25
+ identify==2.4.8
26
+ # via pre-commit
27
+ nodeenv==1.6.0
28
+ # via pre-commit
29
+ pep517==0.12.0
30
+ # via pip-tools
31
+ pip-compile-multi==2.4.3
32
+ # via -r requirements/dev.in
33
+ pip-tools==6.5.1
34
+ # via pip-compile-multi
35
+ platformdirs==2.4.1
36
+ # via virtualenv
37
+ pre-commit==2.17.0
38
+ # via -r requirements/dev.in
39
+ pyyaml==6.0
40
+ # via pre-commit
41
+ six==1.16.0
42
+ # via
43
+ # tox
44
+ # virtualenv
45
+ toml==0.10.2
46
+ # via
47
+ # pre-commit
48
+ # tox
49
+ toposort==1.7
50
+ # via pip-compile-multi
51
+ tox==3.24.5
52
+ # via -r requirements/dev.in
53
+ virtualenv==20.13.1
54
+ # via
55
+ # pre-commit
56
+ # tox
57
+ wheel==0.37.1
58
+ # via pip-tools
59
+
60
+ # The following packages are considered to be unsafe in a requirements file:
61
+ # pip
62
+ # setuptools
testbed/pallets__flask/requirements/docs.in ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Pallets-Sphinx-Themes
2
+ Sphinx
3
+ sphinx-issues
4
+ sphinxcontrib-log-cabinet
5
+ sphinx-tabs
testbed/pallets__flask/requirements/docs.txt ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SHA1:34fd4ca6516e97c7348e6facdd9c4ebb68209d1c
2
+ #
3
+ # This file is autogenerated by pip-compile-multi
4
+ # To update, run:
5
+ #
6
+ # pip-compile-multi
7
+ #
8
+ alabaster==0.7.12
9
+ # via sphinx
10
+ babel==2.9.1
11
+ # via sphinx
12
+ certifi==2021.10.8
13
+ # via requests
14
+ charset-normalizer==2.0.11
15
+ # via requests
16
+ docutils==0.16
17
+ # via
18
+ # sphinx
19
+ # sphinx-tabs
20
+ idna==3.3
21
+ # via requests
22
+ imagesize==1.3.0
23
+ # via sphinx
24
+ jinja2==3.0.3
25
+ # via sphinx
26
+ markupsafe==2.0.1
27
+ # via jinja2
28
+ packaging==21.3
29
+ # via
30
+ # pallets-sphinx-themes
31
+ # sphinx
32
+ pallets-sphinx-themes==2.0.2
33
+ # via -r requirements/docs.in
34
+ pygments==2.11.2
35
+ # via
36
+ # sphinx
37
+ # sphinx-tabs
38
+ pyparsing==3.0.7
39
+ # via packaging
40
+ pytz==2021.3
41
+ # via babel
42
+ requests==2.27.1
43
+ # via sphinx
44
+ snowballstemmer==2.2.0
45
+ # via sphinx
46
+ sphinx==4.4.0
47
+ # via
48
+ # -r requirements/docs.in
49
+ # pallets-sphinx-themes
50
+ # sphinx-issues
51
+ # sphinx-tabs
52
+ # sphinxcontrib-log-cabinet
53
+ sphinx-issues==3.0.1
54
+ # via -r requirements/docs.in
55
+ sphinx-tabs==3.2.0
56
+ # via -r requirements/docs.in
57
+ sphinxcontrib-applehelp==1.0.2
58
+ # via sphinx
59
+ sphinxcontrib-devhelp==1.0.2
60
+ # via sphinx
61
+ sphinxcontrib-htmlhelp==2.0.0
62
+ # via sphinx
63
+ sphinxcontrib-jsmath==1.0.1
64
+ # via sphinx
65
+ sphinxcontrib-log-cabinet==1.0.1
66
+ # via -r requirements/docs.in
67
+ sphinxcontrib-qthelp==1.0.3
68
+ # via sphinx
69
+ sphinxcontrib-serializinghtml==1.1.5
70
+ # via sphinx
71
+ urllib3==1.26.8
72
+ # via requests
testbed/pallets__flask/requirements/tests-pallets-dev.in ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ https://github.com/pallets/werkzeug/archive/refs/heads/main.tar.gz
2
+ https://github.com/pallets/jinja/archive/refs/heads/main.tar.gz
3
+ https://github.com/pallets/markupsafe/archive/refs/heads/main.tar.gz
4
+ https://github.com/pallets/itsdangerous/archive/refs/heads/main.tar.gz
5
+ https://github.com/pallets/click/archive/refs/heads/main.tar.gz
testbed/pallets__flask/requirements/tests-pallets-dev.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SHA1:692b640e7f835e536628f76de0afff1296524122
2
+ #
3
+ # This file is autogenerated by pip-compile-multi
4
+ # To update, run:
5
+ #
6
+ # pip-compile-multi
7
+ #
8
+ click @ https://github.com/pallets/click/archive/refs/heads/main.tar.gz
9
+ # via -r requirements/tests-pallets-dev.in
10
+ itsdangerous @ https://github.com/pallets/itsdangerous/archive/refs/heads/main.tar.gz
11
+ # via -r requirements/tests-pallets-dev.in
12
+ jinja2 @ https://github.com/pallets/jinja/archive/refs/heads/main.tar.gz
13
+ # via -r requirements/tests-pallets-dev.in
14
+ markupsafe @ https://github.com/pallets/markupsafe/archive/refs/heads/main.tar.gz
15
+ # via
16
+ # -r requirements/tests-pallets-dev.in
17
+ # jinja2
18
+ werkzeug @ https://github.com/pallets/werkzeug/archive/refs/heads/main.tar.gz
19
+ # via -r requirements/tests-pallets-dev.in
testbed/pallets__flask/requirements/tests-pallets-min.in ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Werkzeug==2.0.0
2
+ Jinja2==3.0.0
3
+ MarkupSafe==2.0.0
4
+ itsdangerous==2.0.0
5
+ click==8.0.0
testbed/pallets__flask/requirements/tests-pallets-min.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SHA1:4de7d9e6254a945fd97ec10880dd23b6cd43b70d
2
+ #
3
+ # This file is autogenerated by pip-compile-multi
4
+ # To update, run:
5
+ #
6
+ # pip-compile-multi
7
+ #
8
+ click==8.0.0
9
+ # via -r requirements/tests-pallets-min.in
10
+ itsdangerous==2.0.0
11
+ # via -r requirements/tests-pallets-min.in
12
+ jinja2==3.0.0
13
+ # via -r requirements/tests-pallets-min.in
14
+ markupsafe==2.0.0
15
+ # via
16
+ # -r requirements/tests-pallets-min.in
17
+ # jinja2
18
+ werkzeug==2.0.0
19
+ # via -r requirements/tests-pallets-min.in
testbed/pallets__flask/requirements/tests.in ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ pytest
2
+ asgiref
3
+ blinker
4
+ greenlet ; python_version < "3.11"
5
+ python-dotenv
testbed/pallets__flask/requirements/tests.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SHA1:69cf1e101a60350e9933c6f1f3b129bd9ed1ea7c
2
+ #
3
+ # This file is autogenerated by pip-compile-multi
4
+ # To update, run:
5
+ #
6
+ # pip-compile-multi
7
+ #
8
+ asgiref==3.5.0
9
+ # via -r requirements/tests.in
10
+ attrs==21.4.0
11
+ # via pytest
12
+ blinker==1.4
13
+ # via -r requirements/tests.in
14
+ greenlet==1.1.2 ; python_version < "3.11"
15
+ # via -r requirements/tests.in
16
+ iniconfig==1.1.1
17
+ # via pytest
18
+ packaging==21.3
19
+ # via pytest
20
+ pluggy==1.0.0
21
+ # via pytest
22
+ py==1.11.0
23
+ # via pytest
24
+ pyparsing==3.0.7
25
+ # via packaging
26
+ pytest==7.0.0
27
+ # via -r requirements/tests.in
28
+ python-dotenv==0.19.2
29
+ # via -r requirements/tests.in
30
+ tomli==2.0.1
31
+ # via pytest
testbed/pallets__flask/requirements/typing.in ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ mypy
2
+ types-contextvars
3
+ types-dataclasses
4
+ types-setuptools
5
+ cryptography
testbed/pallets__flask/requirements/typing.txt ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SHA1:7cc3f64d4e78db89d81680ac81503d5ac35d31a9
2
+ #
3
+ # This file is autogenerated by pip-compile-multi
4
+ # To update, run:
5
+ #
6
+ # pip-compile-multi
7
+ #
8
+ cffi==1.15.0
9
+ # via cryptography
10
+ cryptography==36.0.1
11
+ # via -r requirements/typing.in
12
+ mypy==0.931
13
+ # via -r requirements/typing.in
14
+ mypy-extensions==0.4.3
15
+ # via mypy
16
+ pycparser==2.21
17
+ # via cffi
18
+ tomli==2.0.1
19
+ # via mypy
20
+ types-contextvars==2.4.2
21
+ # via -r requirements/typing.in
22
+ types-dataclasses==0.6.4
23
+ # via -r requirements/typing.in
24
+ types-setuptools==57.4.9
25
+ # via -r requirements/typing.in
26
+ typing-extensions==4.0.1
27
+ # via mypy
testbed/pallets__flask/setup.cfg ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [metadata]
2
+ name = Flask
3
+ version = attr: flask.__version__
4
+ url = https://palletsprojects.com/p/flask
5
+ project_urls =
6
+ Donate = https://palletsprojects.com/donate
7
+ Documentation = https://flask.palletsprojects.com/
8
+ Changes = https://flask.palletsprojects.com/changes/
9
+ Source Code = https://github.com/pallets/flask/
10
+ Issue Tracker = https://github.com/pallets/flask/issues/
11
+ Twitter = https://twitter.com/PalletsTeam
12
+ Chat = https://discord.gg/pallets
13
+ license = BSD-3-Clause
14
+ author = Armin Ronacher
15
+ author_email = armin.ronacher@active-4.com
16
+ maintainer = Pallets
17
+ maintainer_email = contact@palletsprojects.com
18
+ description = A simple framework for building complex web applications.
19
+ long_description = file: README.rst
20
+ long_description_content_type = text/x-rst
21
+ classifiers =
22
+ Development Status :: 5 - Production/Stable
23
+ Environment :: Web Environment
24
+ Framework :: Flask
25
+ Intended Audience :: Developers
26
+ License :: OSI Approved :: BSD License
27
+ Operating System :: OS Independent
28
+ Programming Language :: Python
29
+ Topic :: Internet :: WWW/HTTP :: Dynamic Content
30
+ Topic :: Internet :: WWW/HTTP :: WSGI
31
+ Topic :: Internet :: WWW/HTTP :: WSGI :: Application
32
+ Topic :: Software Development :: Libraries :: Application Frameworks
33
+
34
+ [options]
35
+ packages = find:
36
+ package_dir = = src
37
+ include_package_data = True
38
+ python_requires = >= 3.7
39
+ # Dependencies are in setup.py for GitHub's dependency graph.
40
+
41
+ [options.packages.find]
42
+ where = src
43
+
44
+ [options.entry_points]
45
+ console_scripts =
46
+ flask = flask.cli:main
47
+
48
+ [tool:pytest]
49
+ testpaths = tests
50
+ filterwarnings =
51
+ error
52
+
53
+ [coverage:run]
54
+ branch = True
55
+ source =
56
+ flask
57
+ tests
58
+
59
+ [coverage:paths]
60
+ source =
61
+ src
62
+ */site-packages
63
+
64
+ [flake8]
65
+ # B = bugbear
66
+ # E = pycodestyle errors
67
+ # F = flake8 pyflakes
68
+ # W = pycodestyle warnings
69
+ # B9 = bugbear opinions
70
+ # ISC = implicit str concat
71
+ select = B, E, F, W, B9, ISC
72
+ ignore =
73
+ # slice notation whitespace, invalid
74
+ E203
75
+ # import at top, too many circular import fixes
76
+ E402
77
+ # line length, handled by bugbear B950
78
+ E501
79
+ # bare except, handled by bugbear B001
80
+ E722
81
+ # bin op line break, invalid
82
+ W503
83
+ # up to 88 allowed by bugbear B950
84
+ max-line-length = 80
85
+ per-file-ignores =
86
+ # __init__ exports names
87
+ src/flask/__init__.py: F401
88
+
89
+ [mypy]
90
+ files = src/flask
91
+ python_version = 3.7
92
+ show_error_codes = True
93
+ allow_redefinition = True
94
+ disallow_subclassing_any = True
95
+ # disallow_untyped_calls = True
96
+ # disallow_untyped_defs = True
97
+ # disallow_incomplete_defs = True
98
+ no_implicit_optional = True
99
+ local_partial_types = True
100
+ # no_implicit_reexport = True
101
+ strict_equality = True
102
+ warn_redundant_casts = True
103
+ warn_unused_configs = True
104
+ warn_unused_ignores = True
105
+ # warn_return_any = True
106
+ # warn_unreachable = True
107
+
108
+ [mypy-asgiref.*]
109
+ ignore_missing_imports = True
110
+
111
+ [mypy-blinker.*]
112
+ ignore_missing_imports = True
113
+
114
+ [mypy-dotenv.*]
115
+ ignore_missing_imports = True
116
+
117
+ [mypy-cryptography.*]
118
+ ignore_missing_imports = True
testbed/pallets__flask/setup.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import setup
2
+
3
+ # Metadata goes in setup.cfg. These are here for GitHub's dependency graph.
4
+ setup(
5
+ name="Flask",
6
+ install_requires=[
7
+ "Werkzeug >= 2.0",
8
+ "Jinja2 >= 3.0",
9
+ "itsdangerous >= 2.0",
10
+ "click >= 8.0",
11
+ "importlib-metadata; python_version < '3.10'",
12
+ ],
13
+ extras_require={
14
+ "async": ["asgiref >= 3.2"],
15
+ "dotenv": ["python-dotenv"],
16
+ },
17
+ )
testbed/pallets__flask/src/flask/app.py ADDED
@@ -0,0 +1,2095 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import inspect
3
+ import logging
4
+ import os
5
+ import sys
6
+ import typing as t
7
+ import weakref
8
+ from datetime import timedelta
9
+ from itertools import chain
10
+ from threading import Lock
11
+ from types import TracebackType
12
+
13
+ from werkzeug.datastructures import Headers
14
+ from werkzeug.datastructures import ImmutableDict
15
+ from werkzeug.exceptions import BadRequest
16
+ from werkzeug.exceptions import BadRequestKeyError
17
+ from werkzeug.exceptions import HTTPException
18
+ from werkzeug.exceptions import InternalServerError
19
+ from werkzeug.routing import BuildError
20
+ from werkzeug.routing import Map
21
+ from werkzeug.routing import MapAdapter
22
+ from werkzeug.routing import RequestRedirect
23
+ from werkzeug.routing import RoutingException
24
+ from werkzeug.routing import Rule
25
+ from werkzeug.wrappers import Response as BaseResponse
26
+
27
+ from . import cli
28
+ from . import json
29
+ from .config import Config
30
+ from .config import ConfigAttribute
31
+ from .ctx import _AppCtxGlobals
32
+ from .ctx import AppContext
33
+ from .ctx import RequestContext
34
+ from .globals import _request_ctx_stack
35
+ from .globals import g
36
+ from .globals import request
37
+ from .globals import session
38
+ from .helpers import _split_blueprint_path
39
+ from .helpers import get_debug_flag
40
+ from .helpers import get_env
41
+ from .helpers import get_flashed_messages
42
+ from .helpers import get_load_dotenv
43
+ from .helpers import locked_cached_property
44
+ from .helpers import url_for
45
+ from .json import jsonify
46
+ from .logging import create_logger
47
+ from .scaffold import _endpoint_from_view_func
48
+ from .scaffold import _sentinel
49
+ from .scaffold import find_package
50
+ from .scaffold import Scaffold
51
+ from .scaffold import setupmethod
52
+ from .sessions import SecureCookieSessionInterface
53
+ from .sessions import SessionInterface
54
+ from .signals import appcontext_tearing_down
55
+ from .signals import got_request_exception
56
+ from .signals import request_finished
57
+ from .signals import request_started
58
+ from .signals import request_tearing_down
59
+ from .templating import DispatchingJinjaLoader
60
+ from .templating import Environment
61
+ from .typing import BeforeFirstRequestCallable
62
+ from .typing import ResponseReturnValue
63
+ from .typing import TeardownCallable
64
+ from .typing import TemplateFilterCallable
65
+ from .typing import TemplateGlobalCallable
66
+ from .typing import TemplateTestCallable
67
+ from .wrappers import Request
68
+ from .wrappers import Response
69
+
70
+ if t.TYPE_CHECKING:
71
+ import typing_extensions as te
72
+ from .blueprints import Blueprint
73
+ from .testing import FlaskClient
74
+ from .testing import FlaskCliRunner
75
+ from .typing import ErrorHandlerCallable
76
+
77
+ if sys.version_info >= (3, 8):
78
+ iscoroutinefunction = inspect.iscoroutinefunction
79
+ else:
80
+
81
+ def iscoroutinefunction(func: t.Any) -> bool:
82
+ while inspect.ismethod(func):
83
+ func = func.__func__
84
+
85
+ while isinstance(func, functools.partial):
86
+ func = func.func
87
+
88
+ return inspect.iscoroutinefunction(func)
89
+
90
+
91
+ def _make_timedelta(value: t.Optional[timedelta]) -> t.Optional[timedelta]:
92
+ if value is None or isinstance(value, timedelta):
93
+ return value
94
+
95
+ return timedelta(seconds=value)
96
+
97
+
98
+ class Flask(Scaffold):
99
+ """The flask object implements a WSGI application and acts as the central
100
+ object. It is passed the name of the module or package of the
101
+ application. Once it is created it will act as a central registry for
102
+ the view functions, the URL rules, template configuration and much more.
103
+
104
+ The name of the package is used to resolve resources from inside the
105
+ package or the folder the module is contained in depending on if the
106
+ package parameter resolves to an actual python package (a folder with
107
+ an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
108
+
109
+ For more information about resource loading, see :func:`open_resource`.
110
+
111
+ Usually you create a :class:`Flask` instance in your main module or
112
+ in the :file:`__init__.py` file of your package like this::
113
+
114
+ from flask import Flask
115
+ app = Flask(__name__)
116
+
117
+ .. admonition:: About the First Parameter
118
+
119
+ The idea of the first parameter is to give Flask an idea of what
120
+ belongs to your application. This name is used to find resources
121
+ on the filesystem, can be used by extensions to improve debugging
122
+ information and a lot more.
123
+
124
+ So it's important what you provide there. If you are using a single
125
+ module, `__name__` is always the correct value. If you however are
126
+ using a package, it's usually recommended to hardcode the name of
127
+ your package there.
128
+
129
+ For example if your application is defined in :file:`yourapplication/app.py`
130
+ you should create it with one of the two versions below::
131
+
132
+ app = Flask('yourapplication')
133
+ app = Flask(__name__.split('.')[0])
134
+
135
+ Why is that? The application will work even with `__name__`, thanks
136
+ to how resources are looked up. However it will make debugging more
137
+ painful. Certain extensions can make assumptions based on the
138
+ import name of your application. For example the Flask-SQLAlchemy
139
+ extension will look for the code in your application that triggered
140
+ an SQL query in debug mode. If the import name is not properly set
141
+ up, that debugging information is lost. (For example it would only
142
+ pick up SQL queries in `yourapplication.app` and not
143
+ `yourapplication.views.frontend`)
144
+
145
+ .. versionadded:: 0.7
146
+ The `static_url_path`, `static_folder`, and `template_folder`
147
+ parameters were added.
148
+
149
+ .. versionadded:: 0.8
150
+ The `instance_path` and `instance_relative_config` parameters were
151
+ added.
152
+
153
+ .. versionadded:: 0.11
154
+ The `root_path` parameter was added.
155
+
156
+ .. versionadded:: 1.0
157
+ The ``host_matching`` and ``static_host`` parameters were added.
158
+
159
+ .. versionadded:: 1.0
160
+ The ``subdomain_matching`` parameter was added. Subdomain
161
+ matching needs to be enabled manually now. Setting
162
+ :data:`SERVER_NAME` does not implicitly enable it.
163
+
164
+ :param import_name: the name of the application package
165
+ :param static_url_path: can be used to specify a different path for the
166
+ static files on the web. Defaults to the name
167
+ of the `static_folder` folder.
168
+ :param static_folder: The folder with static files that is served at
169
+ ``static_url_path``. Relative to the application ``root_path``
170
+ or an absolute path. Defaults to ``'static'``.
171
+ :param static_host: the host to use when adding the static route.
172
+ Defaults to None. Required when using ``host_matching=True``
173
+ with a ``static_folder`` configured.
174
+ :param host_matching: set ``url_map.host_matching`` attribute.
175
+ Defaults to False.
176
+ :param subdomain_matching: consider the subdomain relative to
177
+ :data:`SERVER_NAME` when matching routes. Defaults to False.
178
+ :param template_folder: the folder that contains the templates that should
179
+ be used by the application. Defaults to
180
+ ``'templates'`` folder in the root path of the
181
+ application.
182
+ :param instance_path: An alternative instance path for the application.
183
+ By default the folder ``'instance'`` next to the
184
+ package or module is assumed to be the instance
185
+ path.
186
+ :param instance_relative_config: if set to ``True`` relative filenames
187
+ for loading the config are assumed to
188
+ be relative to the instance path instead
189
+ of the application root.
190
+ :param root_path: The path to the root of the application files.
191
+ This should only be set manually when it can't be detected
192
+ automatically, such as for namespace packages.
193
+ """
194
+
195
+ #: The class that is used for request objects. See :class:`~flask.Request`
196
+ #: for more information.
197
+ request_class = Request
198
+
199
+ #: The class that is used for response objects. See
200
+ #: :class:`~flask.Response` for more information.
201
+ response_class = Response
202
+
203
+ #: The class that is used for the Jinja environment.
204
+ #:
205
+ #: .. versionadded:: 0.11
206
+ jinja_environment = Environment
207
+
208
+ #: The class that is used for the :data:`~flask.g` instance.
209
+ #:
210
+ #: Example use cases for a custom class:
211
+ #:
212
+ #: 1. Store arbitrary attributes on flask.g.
213
+ #: 2. Add a property for lazy per-request database connectors.
214
+ #: 3. Return None instead of AttributeError on unexpected attributes.
215
+ #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
216
+ #:
217
+ #: In Flask 0.9 this property was called `request_globals_class` but it
218
+ #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
219
+ #: flask.g object is now application context scoped.
220
+ #:
221
+ #: .. versionadded:: 0.10
222
+ app_ctx_globals_class = _AppCtxGlobals
223
+
224
+ #: The class that is used for the ``config`` attribute of this app.
225
+ #: Defaults to :class:`~flask.Config`.
226
+ #:
227
+ #: Example use cases for a custom class:
228
+ #:
229
+ #: 1. Default values for certain config options.
230
+ #: 2. Access to config values through attributes in addition to keys.
231
+ #:
232
+ #: .. versionadded:: 0.11
233
+ config_class = Config
234
+
235
+ #: The testing flag. Set this to ``True`` to enable the test mode of
236
+ #: Flask extensions (and in the future probably also Flask itself).
237
+ #: For example this might activate test helpers that have an
238
+ #: additional runtime cost which should not be enabled by default.
239
+ #:
240
+ #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
241
+ #: default it's implicitly enabled.
242
+ #:
243
+ #: This attribute can also be configured from the config with the
244
+ #: ``TESTING`` configuration key. Defaults to ``False``.
245
+ testing = ConfigAttribute("TESTING")
246
+
247
+ #: If a secret key is set, cryptographic components can use this to
248
+ #: sign cookies and other things. Set this to a complex random value
249
+ #: when you want to use the secure cookie for instance.
250
+ #:
251
+ #: This attribute can also be configured from the config with the
252
+ #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.
253
+ secret_key = ConfigAttribute("SECRET_KEY")
254
+
255
+ #: The secure cookie uses this for the name of the session cookie.
256
+ #:
257
+ #: This attribute can also be configured from the config with the
258
+ #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``
259
+ session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")
260
+
261
+ #: A :class:`~datetime.timedelta` which is used to set the expiration
262
+ #: date of a permanent session. The default is 31 days which makes a
263
+ #: permanent session survive for roughly one month.
264
+ #:
265
+ #: This attribute can also be configured from the config with the
266
+ #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
267
+ #: ``timedelta(days=31)``
268
+ permanent_session_lifetime = ConfigAttribute(
269
+ "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta
270
+ )
271
+
272
+ #: A :class:`~datetime.timedelta` or number of seconds which is used
273
+ #: as the default ``max_age`` for :func:`send_file`. The default is
274
+ #: ``None``, which tells the browser to use conditional requests
275
+ #: instead of a timed cache.
276
+ #:
277
+ #: Configured with the :data:`SEND_FILE_MAX_AGE_DEFAULT`
278
+ #: configuration key.
279
+ #:
280
+ #: .. versionchanged:: 2.0
281
+ #: Defaults to ``None`` instead of 12 hours.
282
+ send_file_max_age_default = ConfigAttribute(
283
+ "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta
284
+ )
285
+
286
+ #: Enable this if you want to use the X-Sendfile feature. Keep in
287
+ #: mind that the server has to support this. This only affects files
288
+ #: sent with the :func:`send_file` method.
289
+ #:
290
+ #: .. versionadded:: 0.2
291
+ #:
292
+ #: This attribute can also be configured from the config with the
293
+ #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.
294
+ use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")
295
+
296
+ #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.
297
+ #:
298
+ #: .. versionadded:: 0.10
299
+ json_encoder = json.JSONEncoder
300
+
301
+ #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.
302
+ #:
303
+ #: .. versionadded:: 0.10
304
+ json_decoder = json.JSONDecoder
305
+
306
+ #: Options that are passed to the Jinja environment in
307
+ #: :meth:`create_jinja_environment`. Changing these options after
308
+ #: the environment is created (accessing :attr:`jinja_env`) will
309
+ #: have no effect.
310
+ #:
311
+ #: .. versionchanged:: 1.1.0
312
+ #: This is a ``dict`` instead of an ``ImmutableDict`` to allow
313
+ #: easier configuration.
314
+ #:
315
+ jinja_options: dict = {}
316
+
317
+ #: Default configuration parameters.
318
+ default_config = ImmutableDict(
319
+ {
320
+ "ENV": None,
321
+ "DEBUG": None,
322
+ "TESTING": False,
323
+ "PROPAGATE_EXCEPTIONS": None,
324
+ "PRESERVE_CONTEXT_ON_EXCEPTION": None,
325
+ "SECRET_KEY": None,
326
+ "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
327
+ "USE_X_SENDFILE": False,
328
+ "SERVER_NAME": None,
329
+ "APPLICATION_ROOT": "/",
330
+ "SESSION_COOKIE_NAME": "session",
331
+ "SESSION_COOKIE_DOMAIN": None,
332
+ "SESSION_COOKIE_PATH": None,
333
+ "SESSION_COOKIE_HTTPONLY": True,
334
+ "SESSION_COOKIE_SECURE": False,
335
+ "SESSION_COOKIE_SAMESITE": None,
336
+ "SESSION_REFRESH_EACH_REQUEST": True,
337
+ "MAX_CONTENT_LENGTH": None,
338
+ "SEND_FILE_MAX_AGE_DEFAULT": None,
339
+ "TRAP_BAD_REQUEST_ERRORS": None,
340
+ "TRAP_HTTP_EXCEPTIONS": False,
341
+ "EXPLAIN_TEMPLATE_LOADING": False,
342
+ "PREFERRED_URL_SCHEME": "http",
343
+ "JSON_AS_ASCII": True,
344
+ "JSON_SORT_KEYS": True,
345
+ "JSONIFY_PRETTYPRINT_REGULAR": False,
346
+ "JSONIFY_MIMETYPE": "application/json",
347
+ "TEMPLATES_AUTO_RELOAD": None,
348
+ "MAX_COOKIE_SIZE": 4093,
349
+ }
350
+ )
351
+
352
+ #: The rule object to use for URL rules created. This is used by
353
+ #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
354
+ #:
355
+ #: .. versionadded:: 0.7
356
+ url_rule_class = Rule
357
+
358
+ #: The map object to use for storing the URL rules and routing
359
+ #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.
360
+ #:
361
+ #: .. versionadded:: 1.1.0
362
+ url_map_class = Map
363
+
364
+ #: The :meth:`test_client` method creates an instance of this test
365
+ #: client class. Defaults to :class:`~flask.testing.FlaskClient`.
366
+ #:
367
+ #: .. versionadded:: 0.7
368
+ test_client_class: t.Optional[t.Type["FlaskClient"]] = None
369
+
370
+ #: The :class:`~click.testing.CliRunner` subclass, by default
371
+ #: :class:`~flask.testing.FlaskCliRunner` that is used by
372
+ #: :meth:`test_cli_runner`. Its ``__init__`` method should take a
373
+ #: Flask app object as the first argument.
374
+ #:
375
+ #: .. versionadded:: 1.0
376
+ test_cli_runner_class: t.Optional[t.Type["FlaskCliRunner"]] = None
377
+
378
+ #: the session interface to use. By default an instance of
379
+ #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
380
+ #:
381
+ #: .. versionadded:: 0.8
382
+ session_interface: SessionInterface = SecureCookieSessionInterface()
383
+
384
+ def __init__(
385
+ self,
386
+ import_name: str,
387
+ static_url_path: t.Optional[str] = None,
388
+ static_folder: t.Optional[t.Union[str, os.PathLike]] = "static",
389
+ static_host: t.Optional[str] = None,
390
+ host_matching: bool = False,
391
+ subdomain_matching: bool = False,
392
+ template_folder: t.Optional[str] = "templates",
393
+ instance_path: t.Optional[str] = None,
394
+ instance_relative_config: bool = False,
395
+ root_path: t.Optional[str] = None,
396
+ ):
397
+ super().__init__(
398
+ import_name=import_name,
399
+ static_folder=static_folder,
400
+ static_url_path=static_url_path,
401
+ template_folder=template_folder,
402
+ root_path=root_path,
403
+ )
404
+
405
+ if instance_path is None:
406
+ instance_path = self.auto_find_instance_path()
407
+ elif not os.path.isabs(instance_path):
408
+ raise ValueError(
409
+ "If an instance path is provided it must be absolute."
410
+ " A relative path was given instead."
411
+ )
412
+
413
+ #: Holds the path to the instance folder.
414
+ #:
415
+ #: .. versionadded:: 0.8
416
+ self.instance_path = instance_path
417
+
418
+ #: The configuration dictionary as :class:`Config`. This behaves
419
+ #: exactly like a regular dictionary but supports additional methods
420
+ #: to load a config from files.
421
+ self.config = self.make_config(instance_relative_config)
422
+
423
+ #: A list of functions that are called when :meth:`url_for` raises a
424
+ #: :exc:`~werkzeug.routing.BuildError`. Each function registered here
425
+ #: is called with `error`, `endpoint` and `values`. If a function
426
+ #: returns ``None`` or raises a :exc:`BuildError` the next function is
427
+ #: tried.
428
+ #:
429
+ #: .. versionadded:: 0.9
430
+ self.url_build_error_handlers: t.List[
431
+ t.Callable[[Exception, str, dict], str]
432
+ ] = []
433
+
434
+ #: A list of functions that will be called at the beginning of the
435
+ #: first request to this instance. To register a function, use the
436
+ #: :meth:`before_first_request` decorator.
437
+ #:
438
+ #: .. versionadded:: 0.8
439
+ self.before_first_request_funcs: t.List[BeforeFirstRequestCallable] = []
440
+
441
+ #: A list of functions that are called when the application context
442
+ #: is destroyed. Since the application context is also torn down
443
+ #: if the request ends this is the place to store code that disconnects
444
+ #: from databases.
445
+ #:
446
+ #: .. versionadded:: 0.9
447
+ self.teardown_appcontext_funcs: t.List[TeardownCallable] = []
448
+
449
+ #: A list of shell context processor functions that should be run
450
+ #: when a shell context is created.
451
+ #:
452
+ #: .. versionadded:: 0.11
453
+ self.shell_context_processors: t.List[t.Callable[[], t.Dict[str, t.Any]]] = []
454
+
455
+ #: Maps registered blueprint names to blueprint objects. The
456
+ #: dict retains the order the blueprints were registered in.
457
+ #: Blueprints can be registered multiple times, this dict does
458
+ #: not track how often they were attached.
459
+ #:
460
+ #: .. versionadded:: 0.7
461
+ self.blueprints: t.Dict[str, "Blueprint"] = {}
462
+
463
+ #: a place where extensions can store application specific state. For
464
+ #: example this is where an extension could store database engines and
465
+ #: similar things.
466
+ #:
467
+ #: The key must match the name of the extension module. For example in
468
+ #: case of a "Flask-Foo" extension in `flask_foo`, the key would be
469
+ #: ``'foo'``.
470
+ #:
471
+ #: .. versionadded:: 0.7
472
+ self.extensions: dict = {}
473
+
474
+ #: The :class:`~werkzeug.routing.Map` for this instance. You can use
475
+ #: this to change the routing converters after the class was created
476
+ #: but before any routes are connected. Example::
477
+ #:
478
+ #: from werkzeug.routing import BaseConverter
479
+ #:
480
+ #: class ListConverter(BaseConverter):
481
+ #: def to_python(self, value):
482
+ #: return value.split(',')
483
+ #: def to_url(self, values):
484
+ #: return ','.join(super(ListConverter, self).to_url(value)
485
+ #: for value in values)
486
+ #:
487
+ #: app = Flask(__name__)
488
+ #: app.url_map.converters['list'] = ListConverter
489
+ self.url_map = self.url_map_class()
490
+
491
+ self.url_map.host_matching = host_matching
492
+ self.subdomain_matching = subdomain_matching
493
+
494
+ # tracks internally if the application already handled at least one
495
+ # request.
496
+ self._got_first_request = False
497
+ self._before_request_lock = Lock()
498
+
499
+ # Add a static route using the provided static_url_path, static_host,
500
+ # and static_folder if there is a configured static_folder.
501
+ # Note we do this without checking if static_folder exists.
502
+ # For one, it might be created while the server is running (e.g. during
503
+ # development). Also, Google App Engine stores static files somewhere
504
+ if self.has_static_folder:
505
+ assert (
506
+ bool(static_host) == host_matching
507
+ ), "Invalid static_host/host_matching combination"
508
+ # Use a weakref to avoid creating a reference cycle between the app
509
+ # and the view function (see #3761).
510
+ self_ref = weakref.ref(self)
511
+ self.add_url_rule(
512
+ f"{self.static_url_path}/<path:filename>",
513
+ endpoint="static",
514
+ host=static_host,
515
+ view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950
516
+ )
517
+
518
+ # Set the name of the Click group in case someone wants to add
519
+ # the app's commands to another CLI tool.
520
+ self.cli.name = self.name
521
+
522
+ def _is_setup_finished(self) -> bool:
523
+ return self.debug and self._got_first_request
524
+
525
+ @locked_cached_property
526
+ def name(self) -> str: # type: ignore
527
+ """The name of the application. This is usually the import name
528
+ with the difference that it's guessed from the run file if the
529
+ import name is main. This name is used as a display name when
530
+ Flask needs the name of the application. It can be set and overridden
531
+ to change the value.
532
+
533
+ .. versionadded:: 0.8
534
+ """
535
+ if self.import_name == "__main__":
536
+ fn = getattr(sys.modules["__main__"], "__file__", None)
537
+ if fn is None:
538
+ return "__main__"
539
+ return os.path.splitext(os.path.basename(fn))[0]
540
+ return self.import_name
541
+
542
+ @property
543
+ def propagate_exceptions(self) -> bool:
544
+ """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration
545
+ value in case it's set, otherwise a sensible default is returned.
546
+
547
+ .. versionadded:: 0.7
548
+ """
549
+ rv = self.config["PROPAGATE_EXCEPTIONS"]
550
+ if rv is not None:
551
+ return rv
552
+ return self.testing or self.debug
553
+
554
+ @property
555
+ def preserve_context_on_exception(self) -> bool:
556
+ """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``
557
+ configuration value in case it's set, otherwise a sensible default
558
+ is returned.
559
+
560
+ .. versionadded:: 0.7
561
+ """
562
+ rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]
563
+ if rv is not None:
564
+ return rv
565
+ return self.debug
566
+
567
+ @locked_cached_property
568
+ def logger(self) -> logging.Logger:
569
+ """A standard Python :class:`~logging.Logger` for the app, with
570
+ the same name as :attr:`name`.
571
+
572
+ In debug mode, the logger's :attr:`~logging.Logger.level` will
573
+ be set to :data:`~logging.DEBUG`.
574
+
575
+ If there are no handlers configured, a default handler will be
576
+ added. See :doc:`/logging` for more information.
577
+
578
+ .. versionchanged:: 1.1.0
579
+ The logger takes the same name as :attr:`name` rather than
580
+ hard-coding ``"flask.app"``.
581
+
582
+ .. versionchanged:: 1.0.0
583
+ Behavior was simplified. The logger is always named
584
+ ``"flask.app"``. The level is only set during configuration,
585
+ it doesn't check ``app.debug`` each time. Only one format is
586
+ used, not different ones depending on ``app.debug``. No
587
+ handlers are removed, and a handler is only added if no
588
+ handlers are already configured.
589
+
590
+ .. versionadded:: 0.3
591
+ """
592
+ return create_logger(self)
593
+
594
+ @locked_cached_property
595
+ def jinja_env(self) -> Environment:
596
+ """The Jinja environment used to load templates.
597
+
598
+ The environment is created the first time this property is
599
+ accessed. Changing :attr:`jinja_options` after that will have no
600
+ effect.
601
+ """
602
+ return self.create_jinja_environment()
603
+
604
+ @property
605
+ def got_first_request(self) -> bool:
606
+ """This attribute is set to ``True`` if the application started
607
+ handling the first request.
608
+
609
+ .. versionadded:: 0.8
610
+ """
611
+ return self._got_first_request
612
+
613
+ def make_config(self, instance_relative: bool = False) -> Config:
614
+ """Used to create the config attribute by the Flask constructor.
615
+ The `instance_relative` parameter is passed in from the constructor
616
+ of Flask (there named `instance_relative_config`) and indicates if
617
+ the config should be relative to the instance path or the root path
618
+ of the application.
619
+
620
+ .. versionadded:: 0.8
621
+ """
622
+ root_path = self.root_path
623
+ if instance_relative:
624
+ root_path = self.instance_path
625
+ defaults = dict(self.default_config)
626
+ defaults["ENV"] = get_env()
627
+ defaults["DEBUG"] = get_debug_flag()
628
+ return self.config_class(root_path, defaults)
629
+
630
+ def auto_find_instance_path(self) -> str:
631
+ """Tries to locate the instance path if it was not provided to the
632
+ constructor of the application class. It will basically calculate
633
+ the path to a folder named ``instance`` next to your main file or
634
+ the package.
635
+
636
+ .. versionadded:: 0.8
637
+ """
638
+ prefix, package_path = find_package(self.import_name)
639
+ if prefix is None:
640
+ return os.path.join(package_path, "instance")
641
+ return os.path.join(prefix, "var", f"{self.name}-instance")
642
+
643
+ def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
644
+ """Opens a resource from the application's instance folder
645
+ (:attr:`instance_path`). Otherwise works like
646
+ :meth:`open_resource`. Instance resources can also be opened for
647
+ writing.
648
+
649
+ :param resource: the name of the resource. To access resources within
650
+ subfolders use forward slashes as separator.
651
+ :param mode: resource file opening mode, default is 'rb'.
652
+ """
653
+ return open(os.path.join(self.instance_path, resource), mode)
654
+
655
+ @property
656
+ def templates_auto_reload(self) -> bool:
657
+ """Reload templates when they are changed. Used by
658
+ :meth:`create_jinja_environment`.
659
+
660
+ This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If
661
+ not set, it will be enabled in debug mode.
662
+
663
+ .. versionadded:: 1.0
664
+ This property was added but the underlying config and behavior
665
+ already existed.
666
+ """
667
+ rv = self.config["TEMPLATES_AUTO_RELOAD"]
668
+ return rv if rv is not None else self.debug
669
+
670
+ @templates_auto_reload.setter
671
+ def templates_auto_reload(self, value: bool) -> None:
672
+ self.config["TEMPLATES_AUTO_RELOAD"] = value
673
+
674
+ def create_jinja_environment(self) -> Environment:
675
+ """Create the Jinja environment based on :attr:`jinja_options`
676
+ and the various Jinja-related methods of the app. Changing
677
+ :attr:`jinja_options` after this will have no effect. Also adds
678
+ Flask-related globals and filters to the environment.
679
+
680
+ .. versionchanged:: 0.11
681
+ ``Environment.auto_reload`` set in accordance with
682
+ ``TEMPLATES_AUTO_RELOAD`` configuration option.
683
+
684
+ .. versionadded:: 0.5
685
+ """
686
+ options = dict(self.jinja_options)
687
+
688
+ if "autoescape" not in options:
689
+ options["autoescape"] = self.select_jinja_autoescape
690
+
691
+ if "auto_reload" not in options:
692
+ options["auto_reload"] = self.templates_auto_reload
693
+
694
+ rv = self.jinja_environment(self, **options)
695
+ rv.globals.update(
696
+ url_for=url_for,
697
+ get_flashed_messages=get_flashed_messages,
698
+ config=self.config,
699
+ # request, session and g are normally added with the
700
+ # context processor for efficiency reasons but for imported
701
+ # templates we also want the proxies in there.
702
+ request=request,
703
+ session=session,
704
+ g=g,
705
+ )
706
+ rv.policies["json.dumps_function"] = json.dumps
707
+ return rv
708
+
709
+ def create_global_jinja_loader(self) -> DispatchingJinjaLoader:
710
+ """Creates the loader for the Jinja2 environment. Can be used to
711
+ override just the loader and keeping the rest unchanged. It's
712
+ discouraged to override this function. Instead one should override
713
+ the :meth:`jinja_loader` function instead.
714
+
715
+ The global loader dispatches between the loaders of the application
716
+ and the individual blueprints.
717
+
718
+ .. versionadded:: 0.7
719
+ """
720
+ return DispatchingJinjaLoader(self)
721
+
722
+ def select_jinja_autoescape(self, filename: str) -> bool:
723
+ """Returns ``True`` if autoescaping should be active for the given
724
+ template name. If no template name is given, returns `True`.
725
+
726
+ .. versionadded:: 0.5
727
+ """
728
+ if filename is None:
729
+ return True
730
+ return filename.endswith((".html", ".htm", ".xml", ".xhtml"))
731
+
732
+ def update_template_context(self, context: dict) -> None:
733
+ """Update the template context with some commonly used variables.
734
+ This injects request, session, config and g into the template
735
+ context as well as everything template context processors want
736
+ to inject. Note that the as of Flask 0.6, the original values
737
+ in the context will not be overridden if a context processor
738
+ decides to return a value with the same key.
739
+
740
+ :param context: the context as a dictionary that is updated in place
741
+ to add extra variables.
742
+ """
743
+ names: t.Iterable[t.Optional[str]] = (None,)
744
+
745
+ # A template may be rendered outside a request context.
746
+ if request:
747
+ names = chain(names, reversed(request.blueprints))
748
+
749
+ # The values passed to render_template take precedence. Keep a
750
+ # copy to re-apply after all context functions.
751
+ orig_ctx = context.copy()
752
+
753
+ for name in names:
754
+ if name in self.template_context_processors:
755
+ for func in self.template_context_processors[name]:
756
+ context.update(func())
757
+
758
+ context.update(orig_ctx)
759
+
760
+ def make_shell_context(self) -> dict:
761
+ """Returns the shell context for an interactive shell for this
762
+ application. This runs all the registered shell context
763
+ processors.
764
+
765
+ .. versionadded:: 0.11
766
+ """
767
+ rv = {"app": self, "g": g}
768
+ for processor in self.shell_context_processors:
769
+ rv.update(processor())
770
+ return rv
771
+
772
+ #: What environment the app is running in. Flask and extensions may
773
+ #: enable behaviors based on the environment, such as enabling debug
774
+ #: mode. This maps to the :data:`ENV` config key. This is set by the
775
+ #: :envvar:`FLASK_ENV` environment variable and may not behave as
776
+ #: expected if set in code.
777
+ #:
778
+ #: **Do not enable development when deploying in production.**
779
+ #:
780
+ #: Default: ``'production'``
781
+ env = ConfigAttribute("ENV")
782
+
783
+ @property
784
+ def debug(self) -> bool:
785
+ """Whether debug mode is enabled. When using ``flask run`` to start
786
+ the development server, an interactive debugger will be shown for
787
+ unhandled exceptions, and the server will be reloaded when code
788
+ changes. This maps to the :data:`DEBUG` config key. This is
789
+ enabled when :attr:`env` is ``'development'`` and is overridden
790
+ by the ``FLASK_DEBUG`` environment variable. It may not behave as
791
+ expected if set in code.
792
+
793
+ **Do not enable debug mode when deploying in production.**
794
+
795
+ Default: ``True`` if :attr:`env` is ``'development'``, or
796
+ ``False`` otherwise.
797
+ """
798
+ return self.config["DEBUG"]
799
+
800
+ @debug.setter
801
+ def debug(self, value: bool) -> None:
802
+ self.config["DEBUG"] = value
803
+ self.jinja_env.auto_reload = self.templates_auto_reload
804
+
805
+ def run(
806
+ self,
807
+ host: t.Optional[str] = None,
808
+ port: t.Optional[int] = None,
809
+ debug: t.Optional[bool] = None,
810
+ load_dotenv: bool = True,
811
+ **options: t.Any,
812
+ ) -> None:
813
+ """Runs the application on a local development server.
814
+
815
+ Do not use ``run()`` in a production setting. It is not intended to
816
+ meet security and performance requirements for a production server.
817
+ Instead, see :doc:`/deploying/index` for WSGI server recommendations.
818
+
819
+ If the :attr:`debug` flag is set the server will automatically reload
820
+ for code changes and show a debugger in case an exception happened.
821
+
822
+ If you want to run the application in debug mode, but disable the
823
+ code execution on the interactive debugger, you can pass
824
+ ``use_evalex=False`` as parameter. This will keep the debugger's
825
+ traceback screen active, but disable code execution.
826
+
827
+ It is not recommended to use this function for development with
828
+ automatic reloading as this is badly supported. Instead you should
829
+ be using the :command:`flask` command line script's ``run`` support.
830
+
831
+ .. admonition:: Keep in Mind
832
+
833
+ Flask will suppress any server error with a generic error page
834
+ unless it is in debug mode. As such to enable just the
835
+ interactive debugger without the code reloading, you have to
836
+ invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
837
+ Setting ``use_debugger`` to ``True`` without being in debug mode
838
+ won't catch any exceptions because there won't be any to
839
+ catch.
840
+
841
+ :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
842
+ have the server available externally as well. Defaults to
843
+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
844
+ if present.
845
+ :param port: the port of the webserver. Defaults to ``5000`` or the
846
+ port defined in the ``SERVER_NAME`` config variable if present.
847
+ :param debug: if given, enable or disable debug mode. See
848
+ :attr:`debug`.
849
+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
850
+ files to set environment variables. Will also change the working
851
+ directory to the directory containing the first file found.
852
+ :param options: the options to be forwarded to the underlying Werkzeug
853
+ server. See :func:`werkzeug.serving.run_simple` for more
854
+ information.
855
+
856
+ .. versionchanged:: 1.0
857
+ If installed, python-dotenv will be used to load environment
858
+ variables from :file:`.env` and :file:`.flaskenv` files.
859
+
860
+ If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`
861
+ environment variables will override :attr:`env` and
862
+ :attr:`debug`.
863
+
864
+ Threaded mode is enabled by default.
865
+
866
+ .. versionchanged:: 0.10
867
+ The default port is now picked from the ``SERVER_NAME``
868
+ variable.
869
+ """
870
+ # Change this into a no-op if the server is invoked from the
871
+ # command line. Have a look at cli.py for more information.
872
+ if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
873
+ from .debughelpers import explain_ignored_app_run
874
+
875
+ explain_ignored_app_run()
876
+ return
877
+
878
+ if get_load_dotenv(load_dotenv):
879
+ cli.load_dotenv()
880
+
881
+ # if set, let env vars override previous values
882
+ if "FLASK_ENV" in os.environ:
883
+ self.env = get_env()
884
+ self.debug = get_debug_flag()
885
+ elif "FLASK_DEBUG" in os.environ:
886
+ self.debug = get_debug_flag()
887
+
888
+ # debug passed to method overrides all other sources
889
+ if debug is not None:
890
+ self.debug = bool(debug)
891
+
892
+ server_name = self.config.get("SERVER_NAME")
893
+ sn_host = sn_port = None
894
+
895
+ if server_name:
896
+ sn_host, _, sn_port = server_name.partition(":")
897
+
898
+ if not host:
899
+ if sn_host:
900
+ host = sn_host
901
+ else:
902
+ host = "127.0.0.1"
903
+
904
+ if port or port == 0:
905
+ port = int(port)
906
+ elif sn_port:
907
+ port = int(sn_port)
908
+ else:
909
+ port = 5000
910
+
911
+ options.setdefault("use_reloader", self.debug)
912
+ options.setdefault("use_debugger", self.debug)
913
+ options.setdefault("threaded", True)
914
+
915
+ cli.show_server_banner(self.env, self.debug, self.name, False)
916
+
917
+ from werkzeug.serving import run_simple
918
+
919
+ try:
920
+ run_simple(t.cast(str, host), port, self, **options)
921
+ finally:
922
+ # reset the first request information if the development server
923
+ # reset normally. This makes it possible to restart the server
924
+ # without reloader and that stuff from an interactive shell.
925
+ self._got_first_request = False
926
+
927
+ def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> "FlaskClient":
928
+ """Creates a test client for this application. For information
929
+ about unit testing head over to :doc:`/testing`.
930
+
931
+ Note that if you are testing for assertions or exceptions in your
932
+ application code, you must set ``app.testing = True`` in order for the
933
+ exceptions to propagate to the test client. Otherwise, the exception
934
+ will be handled by the application (not visible to the test client) and
935
+ the only indication of an AssertionError or other exception will be a
936
+ 500 status code response to the test client. See the :attr:`testing`
937
+ attribute. For example::
938
+
939
+ app.testing = True
940
+ client = app.test_client()
941
+
942
+ The test client can be used in a ``with`` block to defer the closing down
943
+ of the context until the end of the ``with`` block. This is useful if
944
+ you want to access the context locals for testing::
945
+
946
+ with app.test_client() as c:
947
+ rv = c.get('/?vodka=42')
948
+ assert request.args['vodka'] == '42'
949
+
950
+ Additionally, you may pass optional keyword arguments that will then
951
+ be passed to the application's :attr:`test_client_class` constructor.
952
+ For example::
953
+
954
+ from flask.testing import FlaskClient
955
+
956
+ class CustomClient(FlaskClient):
957
+ def __init__(self, *args, **kwargs):
958
+ self._authentication = kwargs.pop("authentication")
959
+ super(CustomClient,self).__init__( *args, **kwargs)
960
+
961
+ app.test_client_class = CustomClient
962
+ client = app.test_client(authentication='Basic ....')
963
+
964
+ See :class:`~flask.testing.FlaskClient` for more information.
965
+
966
+ .. versionchanged:: 0.4
967
+ added support for ``with`` block usage for the client.
968
+
969
+ .. versionadded:: 0.7
970
+ The `use_cookies` parameter was added as well as the ability
971
+ to override the client to be used by setting the
972
+ :attr:`test_client_class` attribute.
973
+
974
+ .. versionchanged:: 0.11
975
+ Added `**kwargs` to support passing additional keyword arguments to
976
+ the constructor of :attr:`test_client_class`.
977
+ """
978
+ cls = self.test_client_class
979
+ if cls is None:
980
+ from .testing import FlaskClient as cls # type: ignore
981
+ return cls( # type: ignore
982
+ self, self.response_class, use_cookies=use_cookies, **kwargs
983
+ )
984
+
985
+ def test_cli_runner(self, **kwargs: t.Any) -> "FlaskCliRunner":
986
+ """Create a CLI runner for testing CLI commands.
987
+ See :ref:`testing-cli`.
988
+
989
+ Returns an instance of :attr:`test_cli_runner_class`, by default
990
+ :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
991
+ passed as the first argument.
992
+
993
+ .. versionadded:: 1.0
994
+ """
995
+ cls = self.test_cli_runner_class
996
+
997
+ if cls is None:
998
+ from .testing import FlaskCliRunner as cls # type: ignore
999
+
1000
+ return cls(self, **kwargs) # type: ignore
1001
+
1002
+ @setupmethod
1003
+ def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:
1004
+ """Register a :class:`~flask.Blueprint` on the application. Keyword
1005
+ arguments passed to this method will override the defaults set on the
1006
+ blueprint.
1007
+
1008
+ Calls the blueprint's :meth:`~flask.Blueprint.register` method after
1009
+ recording the blueprint in the application's :attr:`blueprints`.
1010
+
1011
+ :param blueprint: The blueprint to register.
1012
+ :param url_prefix: Blueprint routes will be prefixed with this.
1013
+ :param subdomain: Blueprint routes will match on this subdomain.
1014
+ :param url_defaults: Blueprint routes will use these default values for
1015
+ view arguments.
1016
+ :param options: Additional keyword arguments are passed to
1017
+ :class:`~flask.blueprints.BlueprintSetupState`. They can be
1018
+ accessed in :meth:`~flask.Blueprint.record` callbacks.
1019
+
1020
+ .. versionchanged:: 2.0.1
1021
+ The ``name`` option can be used to change the (pre-dotted)
1022
+ name the blueprint is registered with. This allows the same
1023
+ blueprint to be registered multiple times with unique names
1024
+ for ``url_for``.
1025
+
1026
+ .. versionadded:: 0.7
1027
+ """
1028
+ blueprint.register(self, options)
1029
+
1030
+ def iter_blueprints(self) -> t.ValuesView["Blueprint"]:
1031
+ """Iterates over all blueprints by the order they were registered.
1032
+
1033
+ .. versionadded:: 0.11
1034
+ """
1035
+ return self.blueprints.values()
1036
+
1037
+ @setupmethod
1038
+ def add_url_rule(
1039
+ self,
1040
+ rule: str,
1041
+ endpoint: t.Optional[str] = None,
1042
+ view_func: t.Optional[t.Callable] = None,
1043
+ provide_automatic_options: t.Optional[bool] = None,
1044
+ **options: t.Any,
1045
+ ) -> None:
1046
+ if endpoint is None:
1047
+ endpoint = _endpoint_from_view_func(view_func) # type: ignore
1048
+ options["endpoint"] = endpoint
1049
+ methods = options.pop("methods", None)
1050
+
1051
+ # if the methods are not given and the view_func object knows its
1052
+ # methods we can use that instead. If neither exists, we go with
1053
+ # a tuple of only ``GET`` as default.
1054
+ if methods is None:
1055
+ methods = getattr(view_func, "methods", None) or ("GET",)
1056
+ if isinstance(methods, str):
1057
+ raise TypeError(
1058
+ "Allowed methods must be a list of strings, for"
1059
+ ' example: @app.route(..., methods=["POST"])'
1060
+ )
1061
+ methods = {item.upper() for item in methods}
1062
+
1063
+ # Methods that should always be added
1064
+ required_methods = set(getattr(view_func, "required_methods", ()))
1065
+
1066
+ # starting with Flask 0.8 the view_func object can disable and
1067
+ # force-enable the automatic options handling.
1068
+ if provide_automatic_options is None:
1069
+ provide_automatic_options = getattr(
1070
+ view_func, "provide_automatic_options", None
1071
+ )
1072
+
1073
+ if provide_automatic_options is None:
1074
+ if "OPTIONS" not in methods:
1075
+ provide_automatic_options = True
1076
+ required_methods.add("OPTIONS")
1077
+ else:
1078
+ provide_automatic_options = False
1079
+
1080
+ # Add the required methods now.
1081
+ methods |= required_methods
1082
+
1083
+ rule = self.url_rule_class(rule, methods=methods, **options)
1084
+ rule.provide_automatic_options = provide_automatic_options # type: ignore
1085
+
1086
+ self.url_map.add(rule)
1087
+ if view_func is not None:
1088
+ old_func = self.view_functions.get(endpoint)
1089
+ if old_func is not None and old_func != view_func:
1090
+ raise AssertionError(
1091
+ "View function mapping is overwriting an existing"
1092
+ f" endpoint function: {endpoint}"
1093
+ )
1094
+ self.view_functions[endpoint] = view_func
1095
+
1096
+ @setupmethod
1097
+ def template_filter(
1098
+ self, name: t.Optional[str] = None
1099
+ ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]:
1100
+ """A decorator that is used to register custom template filter.
1101
+ You can specify a name for the filter, otherwise the function
1102
+ name will be used. Example::
1103
+
1104
+ @app.template_filter()
1105
+ def reverse(s):
1106
+ return s[::-1]
1107
+
1108
+ :param name: the optional name of the filter, otherwise the
1109
+ function name will be used.
1110
+ """
1111
+
1112
+ def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:
1113
+ self.add_template_filter(f, name=name)
1114
+ return f
1115
+
1116
+ return decorator
1117
+
1118
+ @setupmethod
1119
+ def add_template_filter(
1120
+ self, f: TemplateFilterCallable, name: t.Optional[str] = None
1121
+ ) -> None:
1122
+ """Register a custom template filter. Works exactly like the
1123
+ :meth:`template_filter` decorator.
1124
+
1125
+ :param name: the optional name of the filter, otherwise the
1126
+ function name will be used.
1127
+ """
1128
+ self.jinja_env.filters[name or f.__name__] = f
1129
+
1130
+ @setupmethod
1131
+ def template_test(
1132
+ self, name: t.Optional[str] = None
1133
+ ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]:
1134
+ """A decorator that is used to register custom template test.
1135
+ You can specify a name for the test, otherwise the function
1136
+ name will be used. Example::
1137
+
1138
+ @app.template_test()
1139
+ def is_prime(n):
1140
+ if n == 2:
1141
+ return True
1142
+ for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
1143
+ if n % i == 0:
1144
+ return False
1145
+ return True
1146
+
1147
+ .. versionadded:: 0.10
1148
+
1149
+ :param name: the optional name of the test, otherwise the
1150
+ function name will be used.
1151
+ """
1152
+
1153
+ def decorator(f: TemplateTestCallable) -> TemplateTestCallable:
1154
+ self.add_template_test(f, name=name)
1155
+ return f
1156
+
1157
+ return decorator
1158
+
1159
+ @setupmethod
1160
+ def add_template_test(
1161
+ self, f: TemplateTestCallable, name: t.Optional[str] = None
1162
+ ) -> None:
1163
+ """Register a custom template test. Works exactly like the
1164
+ :meth:`template_test` decorator.
1165
+
1166
+ .. versionadded:: 0.10
1167
+
1168
+ :param name: the optional name of the test, otherwise the
1169
+ function name will be used.
1170
+ """
1171
+ self.jinja_env.tests[name or f.__name__] = f
1172
+
1173
+ @setupmethod
1174
+ def template_global(
1175
+ self, name: t.Optional[str] = None
1176
+ ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]:
1177
+ """A decorator that is used to register a custom template global function.
1178
+ You can specify a name for the global function, otherwise the function
1179
+ name will be used. Example::
1180
+
1181
+ @app.template_global()
1182
+ def double(n):
1183
+ return 2 * n
1184
+
1185
+ .. versionadded:: 0.10
1186
+
1187
+ :param name: the optional name of the global function, otherwise the
1188
+ function name will be used.
1189
+ """
1190
+
1191
+ def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:
1192
+ self.add_template_global(f, name=name)
1193
+ return f
1194
+
1195
+ return decorator
1196
+
1197
+ @setupmethod
1198
+ def add_template_global(
1199
+ self, f: TemplateGlobalCallable, name: t.Optional[str] = None
1200
+ ) -> None:
1201
+ """Register a custom template global function. Works exactly like the
1202
+ :meth:`template_global` decorator.
1203
+
1204
+ .. versionadded:: 0.10
1205
+
1206
+ :param name: the optional name of the global function, otherwise the
1207
+ function name will be used.
1208
+ """
1209
+ self.jinja_env.globals[name or f.__name__] = f
1210
+
1211
+ @setupmethod
1212
+ def before_first_request(
1213
+ self, f: BeforeFirstRequestCallable
1214
+ ) -> BeforeFirstRequestCallable:
1215
+ """Registers a function to be run before the first request to this
1216
+ instance of the application.
1217
+
1218
+ The function will be called without any arguments and its return
1219
+ value is ignored.
1220
+
1221
+ .. versionadded:: 0.8
1222
+ """
1223
+ self.before_first_request_funcs.append(f)
1224
+ return f
1225
+
1226
+ @setupmethod
1227
+ def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable:
1228
+ """Registers a function to be called when the application context
1229
+ ends. These functions are typically also called when the request
1230
+ context is popped.
1231
+
1232
+ Example::
1233
+
1234
+ ctx = app.app_context()
1235
+ ctx.push()
1236
+ ...
1237
+ ctx.pop()
1238
+
1239
+ When ``ctx.pop()`` is executed in the above example, the teardown
1240
+ functions are called just before the app context moves from the
1241
+ stack of active contexts. This becomes relevant if you are using
1242
+ such constructs in tests.
1243
+
1244
+ Since a request context typically also manages an application
1245
+ context it would also be called when you pop a request context.
1246
+
1247
+ When a teardown function was called because of an unhandled exception
1248
+ it will be passed an error object. If an :meth:`errorhandler` is
1249
+ registered, it will handle the exception and the teardown will not
1250
+ receive it.
1251
+
1252
+ The return values of teardown functions are ignored.
1253
+
1254
+ .. versionadded:: 0.9
1255
+ """
1256
+ self.teardown_appcontext_funcs.append(f)
1257
+ return f
1258
+
1259
+ @setupmethod
1260
+ def shell_context_processor(self, f: t.Callable) -> t.Callable:
1261
+ """Registers a shell context processor function.
1262
+
1263
+ .. versionadded:: 0.11
1264
+ """
1265
+ self.shell_context_processors.append(f)
1266
+ return f
1267
+
1268
+ def _find_error_handler(self, e: Exception) -> t.Optional["ErrorHandlerCallable"]:
1269
+ """Return a registered error handler for an exception in this order:
1270
+ blueprint handler for a specific code, app handler for a specific code,
1271
+ blueprint handler for an exception class, app handler for an exception
1272
+ class, or ``None`` if a suitable handler is not found.
1273
+ """
1274
+ exc_class, code = self._get_exc_class_and_code(type(e))
1275
+ names = (*request.blueprints, None)
1276
+
1277
+ for c in (code, None) if code is not None else (None,):
1278
+ for name in names:
1279
+ handler_map = self.error_handler_spec[name][c]
1280
+
1281
+ if not handler_map:
1282
+ continue
1283
+
1284
+ for cls in exc_class.__mro__:
1285
+ handler = handler_map.get(cls)
1286
+
1287
+ if handler is not None:
1288
+ return handler
1289
+ return None
1290
+
1291
+ def handle_http_exception(
1292
+ self, e: HTTPException
1293
+ ) -> t.Union[HTTPException, ResponseReturnValue]:
1294
+ """Handles an HTTP exception. By default this will invoke the
1295
+ registered error handlers and fall back to returning the
1296
+ exception as response.
1297
+
1298
+ .. versionchanged:: 1.0.3
1299
+ ``RoutingException``, used internally for actions such as
1300
+ slash redirects during routing, is not passed to error
1301
+ handlers.
1302
+
1303
+ .. versionchanged:: 1.0
1304
+ Exceptions are looked up by code *and* by MRO, so
1305
+ ``HTTPException`` subclasses can be handled with a catch-all
1306
+ handler for the base ``HTTPException``.
1307
+
1308
+ .. versionadded:: 0.3
1309
+ """
1310
+ # Proxy exceptions don't have error codes. We want to always return
1311
+ # those unchanged as errors
1312
+ if e.code is None:
1313
+ return e
1314
+
1315
+ # RoutingExceptions are used internally to trigger routing
1316
+ # actions, such as slash redirects raising RequestRedirect. They
1317
+ # are not raised or handled in user code.
1318
+ if isinstance(e, RoutingException):
1319
+ return e
1320
+
1321
+ handler = self._find_error_handler(e)
1322
+ if handler is None:
1323
+ return e
1324
+ return self.ensure_sync(handler)(e)
1325
+
1326
+ def trap_http_exception(self, e: Exception) -> bool:
1327
+ """Checks if an HTTP exception should be trapped or not. By default
1328
+ this will return ``False`` for all exceptions except for a bad request
1329
+ key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
1330
+ also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
1331
+
1332
+ This is called for all HTTP exceptions raised by a view function.
1333
+ If it returns ``True`` for any exception the error handler for this
1334
+ exception is not called and it shows up as regular exception in the
1335
+ traceback. This is helpful for debugging implicitly raised HTTP
1336
+ exceptions.
1337
+
1338
+ .. versionchanged:: 1.0
1339
+ Bad request errors are not trapped by default in debug mode.
1340
+
1341
+ .. versionadded:: 0.8
1342
+ """
1343
+ if self.config["TRAP_HTTP_EXCEPTIONS"]:
1344
+ return True
1345
+
1346
+ trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]
1347
+
1348
+ # if unset, trap key errors in debug mode
1349
+ if (
1350
+ trap_bad_request is None
1351
+ and self.debug
1352
+ and isinstance(e, BadRequestKeyError)
1353
+ ):
1354
+ return True
1355
+
1356
+ if trap_bad_request:
1357
+ return isinstance(e, BadRequest)
1358
+
1359
+ return False
1360
+
1361
+ def handle_user_exception(
1362
+ self, e: Exception
1363
+ ) -> t.Union[HTTPException, ResponseReturnValue]:
1364
+ """This method is called whenever an exception occurs that
1365
+ should be handled. A special case is :class:`~werkzeug
1366
+ .exceptions.HTTPException` which is forwarded to the
1367
+ :meth:`handle_http_exception` method. This function will either
1368
+ return a response value or reraise the exception with the same
1369
+ traceback.
1370
+
1371
+ .. versionchanged:: 1.0
1372
+ Key errors raised from request data like ``form`` show the
1373
+ bad key in debug mode rather than a generic bad request
1374
+ message.
1375
+
1376
+ .. versionadded:: 0.7
1377
+ """
1378
+ if isinstance(e, BadRequestKeyError) and (
1379
+ self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]
1380
+ ):
1381
+ e.show_exception = True
1382
+
1383
+ if isinstance(e, HTTPException) and not self.trap_http_exception(e):
1384
+ return self.handle_http_exception(e)
1385
+
1386
+ handler = self._find_error_handler(e)
1387
+
1388
+ if handler is None:
1389
+ raise
1390
+
1391
+ return self.ensure_sync(handler)(e)
1392
+
1393
+ def handle_exception(self, e: Exception) -> Response:
1394
+ """Handle an exception that did not have an error handler
1395
+ associated with it, or that was raised from an error handler.
1396
+ This always causes a 500 ``InternalServerError``.
1397
+
1398
+ Always sends the :data:`got_request_exception` signal.
1399
+
1400
+ If :attr:`propagate_exceptions` is ``True``, such as in debug
1401
+ mode, the error will be re-raised so that the debugger can
1402
+ display it. Otherwise, the original exception is logged, and
1403
+ an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
1404
+
1405
+ If an error handler is registered for ``InternalServerError`` or
1406
+ ``500``, it will be used. For consistency, the handler will
1407
+ always receive the ``InternalServerError``. The original
1408
+ unhandled exception is available as ``e.original_exception``.
1409
+
1410
+ .. versionchanged:: 1.1.0
1411
+ Always passes the ``InternalServerError`` instance to the
1412
+ handler, setting ``original_exception`` to the unhandled
1413
+ error.
1414
+
1415
+ .. versionchanged:: 1.1.0
1416
+ ``after_request`` functions and other finalization is done
1417
+ even for the default 500 response when there is no handler.
1418
+
1419
+ .. versionadded:: 0.3
1420
+ """
1421
+ exc_info = sys.exc_info()
1422
+ got_request_exception.send(self, exception=e)
1423
+
1424
+ if self.propagate_exceptions:
1425
+ # Re-raise if called with an active exception, otherwise
1426
+ # raise the passed in exception.
1427
+ if exc_info[1] is e:
1428
+ raise
1429
+
1430
+ raise e
1431
+
1432
+ self.log_exception(exc_info)
1433
+ server_error: t.Union[InternalServerError, ResponseReturnValue]
1434
+ server_error = InternalServerError(original_exception=e)
1435
+ handler = self._find_error_handler(server_error)
1436
+
1437
+ if handler is not None:
1438
+ server_error = self.ensure_sync(handler)(server_error)
1439
+
1440
+ return self.finalize_request(server_error, from_error_handler=True)
1441
+
1442
+ def log_exception(
1443
+ self,
1444
+ exc_info: t.Union[
1445
+ t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]
1446
+ ],
1447
+ ) -> None:
1448
+ """Logs an exception. This is called by :meth:`handle_exception`
1449
+ if debugging is disabled and right before the handler is called.
1450
+ The default implementation logs the exception as error on the
1451
+ :attr:`logger`.
1452
+
1453
+ .. versionadded:: 0.8
1454
+ """
1455
+ self.logger.error(
1456
+ f"Exception on {request.path} [{request.method}]", exc_info=exc_info
1457
+ )
1458
+
1459
+ def raise_routing_exception(self, request: Request) -> "te.NoReturn":
1460
+ """Intercept routing exceptions and possibly do something else.
1461
+
1462
+ In debug mode, intercept a routing redirect and replace it with
1463
+ an error if the body will be discarded.
1464
+
1465
+ With modern Werkzeug this shouldn't occur, since it now uses a
1466
+ 308 status which tells the browser to resend the method and
1467
+ body.
1468
+
1469
+ .. versionchanged:: 2.1
1470
+ Don't intercept 307 and 308 redirects.
1471
+
1472
+ :meta private:
1473
+ :internal:
1474
+ """
1475
+ if (
1476
+ not self.debug
1477
+ or not isinstance(request.routing_exception, RequestRedirect)
1478
+ or request.routing_exception.code in {307, 308}
1479
+ or request.method in {"GET", "HEAD", "OPTIONS"}
1480
+ ):
1481
+ raise request.routing_exception # type: ignore
1482
+
1483
+ from .debughelpers import FormDataRoutingRedirect
1484
+
1485
+ raise FormDataRoutingRedirect(request)
1486
+
1487
+ def dispatch_request(self) -> ResponseReturnValue:
1488
+ """Does the request dispatching. Matches the URL and returns the
1489
+ return value of the view or error handler. This does not have to
1490
+ be a response object. In order to convert the return value to a
1491
+ proper response object, call :func:`make_response`.
1492
+
1493
+ .. versionchanged:: 0.7
1494
+ This no longer does the exception handling, this code was
1495
+ moved to the new :meth:`full_dispatch_request`.
1496
+ """
1497
+ req = _request_ctx_stack.top.request
1498
+ if req.routing_exception is not None:
1499
+ self.raise_routing_exception(req)
1500
+ rule = req.url_rule
1501
+ # if we provide automatic options for this URL and the
1502
+ # request came with the OPTIONS method, reply automatically
1503
+ if (
1504
+ getattr(rule, "provide_automatic_options", False)
1505
+ and req.method == "OPTIONS"
1506
+ ):
1507
+ return self.make_default_options_response()
1508
+ # otherwise dispatch to the handler for that endpoint
1509
+ return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
1510
+
1511
+ def full_dispatch_request(self) -> Response:
1512
+ """Dispatches the request and on top of that performs request
1513
+ pre and postprocessing as well as HTTP exception catching and
1514
+ error handling.
1515
+
1516
+ .. versionadded:: 0.7
1517
+ """
1518
+ self.try_trigger_before_first_request_functions()
1519
+ try:
1520
+ request_started.send(self)
1521
+ rv = self.preprocess_request()
1522
+ if rv is None:
1523
+ rv = self.dispatch_request()
1524
+ except Exception as e:
1525
+ rv = self.handle_user_exception(e)
1526
+ return self.finalize_request(rv)
1527
+
1528
+ def finalize_request(
1529
+ self,
1530
+ rv: t.Union[ResponseReturnValue, HTTPException],
1531
+ from_error_handler: bool = False,
1532
+ ) -> Response:
1533
+ """Given the return value from a view function this finalizes
1534
+ the request by converting it into a response and invoking the
1535
+ postprocessing functions. This is invoked for both normal
1536
+ request dispatching as well as error handlers.
1537
+
1538
+ Because this means that it might be called as a result of a
1539
+ failure a special safe mode is available which can be enabled
1540
+ with the `from_error_handler` flag. If enabled, failures in
1541
+ response processing will be logged and otherwise ignored.
1542
+
1543
+ :internal:
1544
+ """
1545
+ response = self.make_response(rv)
1546
+ try:
1547
+ response = self.process_response(response)
1548
+ request_finished.send(self, response=response)
1549
+ except Exception:
1550
+ if not from_error_handler:
1551
+ raise
1552
+ self.logger.exception(
1553
+ "Request finalizing failed with an error while handling an error"
1554
+ )
1555
+ return response
1556
+
1557
+ def try_trigger_before_first_request_functions(self) -> None:
1558
+ """Called before each request and will ensure that it triggers
1559
+ the :attr:`before_first_request_funcs` and only exactly once per
1560
+ application instance (which means process usually).
1561
+
1562
+ :internal:
1563
+ """
1564
+ if self._got_first_request:
1565
+ return
1566
+ with self._before_request_lock:
1567
+ if self._got_first_request:
1568
+ return
1569
+ for func in self.before_first_request_funcs:
1570
+ self.ensure_sync(func)()
1571
+ self._got_first_request = True
1572
+
1573
+ def make_default_options_response(self) -> Response:
1574
+ """This method is called to create the default ``OPTIONS`` response.
1575
+ This can be changed through subclassing to change the default
1576
+ behavior of ``OPTIONS`` responses.
1577
+
1578
+ .. versionadded:: 0.7
1579
+ """
1580
+ adapter = _request_ctx_stack.top.url_adapter
1581
+ methods = adapter.allowed_methods()
1582
+ rv = self.response_class()
1583
+ rv.allow.update(methods)
1584
+ return rv
1585
+
1586
+ def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:
1587
+ """This is called to figure out if an error should be ignored
1588
+ or not as far as the teardown system is concerned. If this
1589
+ function returns ``True`` then the teardown handlers will not be
1590
+ passed the error.
1591
+
1592
+ .. versionadded:: 0.10
1593
+ """
1594
+ return False
1595
+
1596
+ def ensure_sync(self, func: t.Callable) -> t.Callable:
1597
+ """Ensure that the function is synchronous for WSGI workers.
1598
+ Plain ``def`` functions are returned as-is. ``async def``
1599
+ functions are wrapped to run and wait for the response.
1600
+
1601
+ Override this method to change how the app runs async views.
1602
+
1603
+ .. versionadded:: 2.0
1604
+ """
1605
+ if iscoroutinefunction(func):
1606
+ return self.async_to_sync(func)
1607
+
1608
+ return func
1609
+
1610
+ def async_to_sync(
1611
+ self, func: t.Callable[..., t.Coroutine]
1612
+ ) -> t.Callable[..., t.Any]:
1613
+ """Return a sync function that will run the coroutine function.
1614
+
1615
+ .. code-block:: python
1616
+
1617
+ result = app.async_to_sync(func)(*args, **kwargs)
1618
+
1619
+ Override this method to change how the app converts async code
1620
+ to be synchronously callable.
1621
+
1622
+ .. versionadded:: 2.0
1623
+ """
1624
+ try:
1625
+ from asgiref.sync import async_to_sync as asgiref_async_to_sync
1626
+ except ImportError:
1627
+ raise RuntimeError(
1628
+ "Install Flask with the 'async' extra in order to use async views."
1629
+ ) from None
1630
+
1631
+ return asgiref_async_to_sync(func)
1632
+
1633
+ def make_response(self, rv: ResponseReturnValue) -> Response:
1634
+ """Convert the return value from a view function to an instance of
1635
+ :attr:`response_class`.
1636
+
1637
+ :param rv: the return value from the view function. The view function
1638
+ must return a response. Returning ``None``, or the view ending
1639
+ without returning, is not allowed. The following types are allowed
1640
+ for ``view_rv``:
1641
+
1642
+ ``str``
1643
+ A response object is created with the string encoded to UTF-8
1644
+ as the body.
1645
+
1646
+ ``bytes``
1647
+ A response object is created with the bytes as the body.
1648
+
1649
+ ``dict``
1650
+ A dictionary that will be jsonify'd before being returned.
1651
+
1652
+ ``tuple``
1653
+ Either ``(body, status, headers)``, ``(body, status)``, or
1654
+ ``(body, headers)``, where ``body`` is any of the other types
1655
+ allowed here, ``status`` is a string or an integer, and
1656
+ ``headers`` is a dictionary or a list of ``(key, value)``
1657
+ tuples. If ``body`` is a :attr:`response_class` instance,
1658
+ ``status`` overwrites the exiting value and ``headers`` are
1659
+ extended.
1660
+
1661
+ :attr:`response_class`
1662
+ The object is returned unchanged.
1663
+
1664
+ other :class:`~werkzeug.wrappers.Response` class
1665
+ The object is coerced to :attr:`response_class`.
1666
+
1667
+ :func:`callable`
1668
+ The function is called as a WSGI application. The result is
1669
+ used to create a response object.
1670
+
1671
+ .. versionchanged:: 0.9
1672
+ Previously a tuple was interpreted as the arguments for the
1673
+ response object.
1674
+ """
1675
+
1676
+ status = headers = None
1677
+
1678
+ # unpack tuple returns
1679
+ if isinstance(rv, tuple):
1680
+ len_rv = len(rv)
1681
+
1682
+ # a 3-tuple is unpacked directly
1683
+ if len_rv == 3:
1684
+ rv, status, headers = rv # type: ignore[misc]
1685
+ # decide if a 2-tuple has status or headers
1686
+ elif len_rv == 2:
1687
+ if isinstance(rv[1], (Headers, dict, tuple, list)):
1688
+ rv, headers = rv
1689
+ else:
1690
+ rv, status = rv # type: ignore[misc]
1691
+ # other sized tuples are not allowed
1692
+ else:
1693
+ raise TypeError(
1694
+ "The view function did not return a valid response tuple."
1695
+ " The tuple must have the form (body, status, headers),"
1696
+ " (body, status), or (body, headers)."
1697
+ )
1698
+
1699
+ # the body must not be None
1700
+ if rv is None:
1701
+ raise TypeError(
1702
+ f"The view function for {request.endpoint!r} did not"
1703
+ " return a valid response. The function either returned"
1704
+ " None or ended without a return statement."
1705
+ )
1706
+
1707
+ # make sure the body is an instance of the response class
1708
+ if not isinstance(rv, self.response_class):
1709
+ if isinstance(rv, (str, bytes, bytearray)):
1710
+ # let the response class set the status and headers instead of
1711
+ # waiting to do it manually, so that the class can handle any
1712
+ # special logic
1713
+ rv = self.response_class(
1714
+ rv,
1715
+ status=status,
1716
+ headers=headers, # type: ignore[arg-type]
1717
+ )
1718
+ status = headers = None
1719
+ elif isinstance(rv, dict):
1720
+ rv = jsonify(rv)
1721
+ elif isinstance(rv, BaseResponse) or callable(rv):
1722
+ # evaluate a WSGI callable, or coerce a different response
1723
+ # class to the correct type
1724
+ try:
1725
+ rv = self.response_class.force_type(rv, request.environ) # type: ignore # noqa: B950
1726
+ except TypeError as e:
1727
+ raise TypeError(
1728
+ f"{e}\nThe view function did not return a valid"
1729
+ " response. The return type must be a string,"
1730
+ " dict, tuple, Response instance, or WSGI"
1731
+ f" callable, but it was a {type(rv).__name__}."
1732
+ ).with_traceback(sys.exc_info()[2]) from None
1733
+ else:
1734
+ raise TypeError(
1735
+ "The view function did not return a valid"
1736
+ " response. The return type must be a string,"
1737
+ " dict, tuple, Response instance, or WSGI"
1738
+ f" callable, but it was a {type(rv).__name__}."
1739
+ )
1740
+
1741
+ rv = t.cast(Response, rv)
1742
+ # prefer the status if it was provided
1743
+ if status is not None:
1744
+ if isinstance(status, (str, bytes, bytearray)):
1745
+ rv.status = status
1746
+ else:
1747
+ rv.status_code = status
1748
+
1749
+ # extend existing headers with provided headers
1750
+ if headers:
1751
+ rv.headers.update(headers) # type: ignore[arg-type]
1752
+
1753
+ return rv
1754
+
1755
+ def create_url_adapter(
1756
+ self, request: t.Optional[Request]
1757
+ ) -> t.Optional[MapAdapter]:
1758
+ """Creates a URL adapter for the given request. The URL adapter
1759
+ is created at a point where the request context is not yet set
1760
+ up so the request is passed explicitly.
1761
+
1762
+ .. versionadded:: 0.6
1763
+
1764
+ .. versionchanged:: 0.9
1765
+ This can now also be called without a request object when the
1766
+ URL adapter is created for the application context.
1767
+
1768
+ .. versionchanged:: 1.0
1769
+ :data:`SERVER_NAME` no longer implicitly enables subdomain
1770
+ matching. Use :attr:`subdomain_matching` instead.
1771
+ """
1772
+ if request is not None:
1773
+ # If subdomain matching is disabled (the default), use the
1774
+ # default subdomain in all cases. This should be the default
1775
+ # in Werkzeug but it currently does not have that feature.
1776
+ if not self.subdomain_matching:
1777
+ subdomain = self.url_map.default_subdomain or None
1778
+ else:
1779
+ subdomain = None
1780
+
1781
+ return self.url_map.bind_to_environ(
1782
+ request.environ,
1783
+ server_name=self.config["SERVER_NAME"],
1784
+ subdomain=subdomain,
1785
+ )
1786
+ # We need at the very least the server name to be set for this
1787
+ # to work.
1788
+ if self.config["SERVER_NAME"] is not None:
1789
+ return self.url_map.bind(
1790
+ self.config["SERVER_NAME"],
1791
+ script_name=self.config["APPLICATION_ROOT"],
1792
+ url_scheme=self.config["PREFERRED_URL_SCHEME"],
1793
+ )
1794
+
1795
+ return None
1796
+
1797
+ def inject_url_defaults(self, endpoint: str, values: dict) -> None:
1798
+ """Injects the URL defaults for the given endpoint directly into
1799
+ the values dictionary passed. This is used internally and
1800
+ automatically called on URL building.
1801
+
1802
+ .. versionadded:: 0.7
1803
+ """
1804
+ names: t.Iterable[t.Optional[str]] = (None,)
1805
+
1806
+ # url_for may be called outside a request context, parse the
1807
+ # passed endpoint instead of using request.blueprints.
1808
+ if "." in endpoint:
1809
+ names = chain(
1810
+ names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))
1811
+ )
1812
+
1813
+ for name in names:
1814
+ if name in self.url_default_functions:
1815
+ for func in self.url_default_functions[name]:
1816
+ func(endpoint, values)
1817
+
1818
+ def handle_url_build_error(
1819
+ self, error: Exception, endpoint: str, values: dict
1820
+ ) -> str:
1821
+ """Handle :class:`~werkzeug.routing.BuildError` on
1822
+ :meth:`url_for`.
1823
+ """
1824
+ for handler in self.url_build_error_handlers:
1825
+ try:
1826
+ rv = handler(error, endpoint, values)
1827
+ except BuildError as e:
1828
+ # make error available outside except block
1829
+ error = e
1830
+ else:
1831
+ if rv is not None:
1832
+ return rv
1833
+
1834
+ # Re-raise if called with an active exception, otherwise raise
1835
+ # the passed in exception.
1836
+ if error is sys.exc_info()[1]:
1837
+ raise
1838
+
1839
+ raise error
1840
+
1841
+ def preprocess_request(self) -> t.Optional[ResponseReturnValue]:
1842
+ """Called before the request is dispatched. Calls
1843
+ :attr:`url_value_preprocessors` registered with the app and the
1844
+ current blueprint (if any). Then calls :attr:`before_request_funcs`
1845
+ registered with the app and the blueprint.
1846
+
1847
+ If any :meth:`before_request` handler returns a non-None value, the
1848
+ value is handled as if it was the return value from the view, and
1849
+ further request handling is stopped.
1850
+ """
1851
+ names = (None, *reversed(request.blueprints))
1852
+
1853
+ for name in names:
1854
+ if name in self.url_value_preprocessors:
1855
+ for url_func in self.url_value_preprocessors[name]:
1856
+ url_func(request.endpoint, request.view_args)
1857
+
1858
+ for name in names:
1859
+ if name in self.before_request_funcs:
1860
+ for before_func in self.before_request_funcs[name]:
1861
+ rv = self.ensure_sync(before_func)()
1862
+
1863
+ if rv is not None:
1864
+ return rv
1865
+
1866
+ return None
1867
+
1868
+ def process_response(self, response: Response) -> Response:
1869
+ """Can be overridden in order to modify the response object
1870
+ before it's sent to the WSGI server. By default this will
1871
+ call all the :meth:`after_request` decorated functions.
1872
+
1873
+ .. versionchanged:: 0.5
1874
+ As of Flask 0.5 the functions registered for after request
1875
+ execution are called in reverse order of registration.
1876
+
1877
+ :param response: a :attr:`response_class` object.
1878
+ :return: a new response object or the same, has to be an
1879
+ instance of :attr:`response_class`.
1880
+ """
1881
+ ctx = _request_ctx_stack.top
1882
+
1883
+ for func in ctx._after_request_functions:
1884
+ response = self.ensure_sync(func)(response)
1885
+
1886
+ for name in chain(request.blueprints, (None,)):
1887
+ if name in self.after_request_funcs:
1888
+ for func in reversed(self.after_request_funcs[name]):
1889
+ response = self.ensure_sync(func)(response)
1890
+
1891
+ if not self.session_interface.is_null_session(ctx.session):
1892
+ self.session_interface.save_session(self, ctx.session, response)
1893
+
1894
+ return response
1895
+
1896
+ def do_teardown_request(
1897
+ self, exc: t.Optional[BaseException] = _sentinel # type: ignore
1898
+ ) -> None:
1899
+ """Called after the request is dispatched and the response is
1900
+ returned, right before the request context is popped.
1901
+
1902
+ This calls all functions decorated with
1903
+ :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
1904
+ if a blueprint handled the request. Finally, the
1905
+ :data:`request_tearing_down` signal is sent.
1906
+
1907
+ This is called by
1908
+ :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
1909
+ which may be delayed during testing to maintain access to
1910
+ resources.
1911
+
1912
+ :param exc: An unhandled exception raised while dispatching the
1913
+ request. Detected from the current exception information if
1914
+ not passed. Passed to each teardown function.
1915
+
1916
+ .. versionchanged:: 0.9
1917
+ Added the ``exc`` argument.
1918
+ """
1919
+ if exc is _sentinel:
1920
+ exc = sys.exc_info()[1]
1921
+
1922
+ for name in chain(request.blueprints, (None,)):
1923
+ if name in self.teardown_request_funcs:
1924
+ for func in reversed(self.teardown_request_funcs[name]):
1925
+ self.ensure_sync(func)(exc)
1926
+
1927
+ request_tearing_down.send(self, exc=exc)
1928
+
1929
+ def do_teardown_appcontext(
1930
+ self, exc: t.Optional[BaseException] = _sentinel # type: ignore
1931
+ ) -> None:
1932
+ """Called right before the application context is popped.
1933
+
1934
+ When handling a request, the application context is popped
1935
+ after the request context. See :meth:`do_teardown_request`.
1936
+
1937
+ This calls all functions decorated with
1938
+ :meth:`teardown_appcontext`. Then the
1939
+ :data:`appcontext_tearing_down` signal is sent.
1940
+
1941
+ This is called by
1942
+ :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
1943
+
1944
+ .. versionadded:: 0.9
1945
+ """
1946
+ if exc is _sentinel:
1947
+ exc = sys.exc_info()[1]
1948
+
1949
+ for func in reversed(self.teardown_appcontext_funcs):
1950
+ self.ensure_sync(func)(exc)
1951
+
1952
+ appcontext_tearing_down.send(self, exc=exc)
1953
+
1954
+ def app_context(self) -> AppContext:
1955
+ """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
1956
+ block to push the context, which will make :data:`current_app`
1957
+ point at this application.
1958
+
1959
+ An application context is automatically pushed by
1960
+ :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
1961
+ when handling a request, and when running a CLI command. Use
1962
+ this to manually create a context outside of these situations.
1963
+
1964
+ ::
1965
+
1966
+ with app.app_context():
1967
+ init_db()
1968
+
1969
+ See :doc:`/appcontext`.
1970
+
1971
+ .. versionadded:: 0.9
1972
+ """
1973
+ return AppContext(self)
1974
+
1975
+ def request_context(self, environ: dict) -> RequestContext:
1976
+ """Create a :class:`~flask.ctx.RequestContext` representing a
1977
+ WSGI environment. Use a ``with`` block to push the context,
1978
+ which will make :data:`request` point at this request.
1979
+
1980
+ See :doc:`/reqcontext`.
1981
+
1982
+ Typically you should not call this from your own code. A request
1983
+ context is automatically pushed by the :meth:`wsgi_app` when
1984
+ handling a request. Use :meth:`test_request_context` to create
1985
+ an environment and context instead of this method.
1986
+
1987
+ :param environ: a WSGI environment
1988
+ """
1989
+ return RequestContext(self, environ)
1990
+
1991
+ def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:
1992
+ """Create a :class:`~flask.ctx.RequestContext` for a WSGI
1993
+ environment created from the given values. This is mostly useful
1994
+ during testing, where you may want to run a function that uses
1995
+ request data without dispatching a full request.
1996
+
1997
+ See :doc:`/reqcontext`.
1998
+
1999
+ Use a ``with`` block to push the context, which will make
2000
+ :data:`request` point at the request for the created
2001
+ environment. ::
2002
+
2003
+ with test_request_context(...):
2004
+ generate_report()
2005
+
2006
+ When using the shell, it may be easier to push and pop the
2007
+ context manually to avoid indentation. ::
2008
+
2009
+ ctx = app.test_request_context(...)
2010
+ ctx.push()
2011
+ ...
2012
+ ctx.pop()
2013
+
2014
+ Takes the same arguments as Werkzeug's
2015
+ :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
2016
+ the application. See the linked Werkzeug docs for most of the
2017
+ available arguments. Flask-specific behavior is listed here.
2018
+
2019
+ :param path: URL path being requested.
2020
+ :param base_url: Base URL where the app is being served, which
2021
+ ``path`` is relative to. If not given, built from
2022
+ :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
2023
+ :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
2024
+ :param subdomain: Subdomain name to append to
2025
+ :data:`SERVER_NAME`.
2026
+ :param url_scheme: Scheme to use instead of
2027
+ :data:`PREFERRED_URL_SCHEME`.
2028
+ :param data: The request body, either as a string or a dict of
2029
+ form keys and values.
2030
+ :param json: If given, this is serialized as JSON and passed as
2031
+ ``data``. Also defaults ``content_type`` to
2032
+ ``application/json``.
2033
+ :param args: other positional arguments passed to
2034
+ :class:`~werkzeug.test.EnvironBuilder`.
2035
+ :param kwargs: other keyword arguments passed to
2036
+ :class:`~werkzeug.test.EnvironBuilder`.
2037
+ """
2038
+ from .testing import EnvironBuilder
2039
+
2040
+ builder = EnvironBuilder(self, *args, **kwargs)
2041
+
2042
+ try:
2043
+ return self.request_context(builder.get_environ())
2044
+ finally:
2045
+ builder.close()
2046
+
2047
+ def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:
2048
+ """The actual WSGI application. This is not implemented in
2049
+ :meth:`__call__` so that middlewares can be applied without
2050
+ losing a reference to the app object. Instead of doing this::
2051
+
2052
+ app = MyMiddleware(app)
2053
+
2054
+ It's a better idea to do this instead::
2055
+
2056
+ app.wsgi_app = MyMiddleware(app.wsgi_app)
2057
+
2058
+ Then you still have the original application object around and
2059
+ can continue to call methods on it.
2060
+
2061
+ .. versionchanged:: 0.7
2062
+ Teardown events for the request and app contexts are called
2063
+ even if an unhandled error occurs. Other events may not be
2064
+ called depending on when an error occurs during dispatch.
2065
+ See :ref:`callbacks-and-errors`.
2066
+
2067
+ :param environ: A WSGI environment.
2068
+ :param start_response: A callable accepting a status code,
2069
+ a list of headers, and an optional exception context to
2070
+ start the response.
2071
+ """
2072
+ ctx = self.request_context(environ)
2073
+ error: t.Optional[BaseException] = None
2074
+ try:
2075
+ try:
2076
+ ctx.push()
2077
+ response = self.full_dispatch_request()
2078
+ except Exception as e:
2079
+ error = e
2080
+ response = self.handle_exception(e)
2081
+ except: # noqa: B001
2082
+ error = sys.exc_info()[1]
2083
+ raise
2084
+ return response(environ, start_response)
2085
+ finally:
2086
+ if self.should_ignore_error(error):
2087
+ error = None
2088
+ ctx.auto_pop(error)
2089
+
2090
+ def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:
2091
+ """The WSGI server calls the Flask application object as the
2092
+ WSGI application. This calls :meth:`wsgi_app`, which can be
2093
+ wrapped to apply middleware.
2094
+ """
2095
+ return self.wsgi_app(environ, start_response)
testbed/pallets__flask/src/flask/blueprints.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import typing as t
3
+ from collections import defaultdict
4
+ from functools import update_wrapper
5
+
6
+ from .scaffold import _endpoint_from_view_func
7
+ from .scaffold import _sentinel
8
+ from .scaffold import Scaffold
9
+ from .typing import AfterRequestCallable
10
+ from .typing import BeforeFirstRequestCallable
11
+ from .typing import BeforeRequestCallable
12
+ from .typing import TeardownCallable
13
+ from .typing import TemplateContextProcessorCallable
14
+ from .typing import TemplateFilterCallable
15
+ from .typing import TemplateGlobalCallable
16
+ from .typing import TemplateTestCallable
17
+ from .typing import URLDefaultCallable
18
+ from .typing import URLValuePreprocessorCallable
19
+
20
+ if t.TYPE_CHECKING:
21
+ from .app import Flask
22
+ from .typing import ErrorHandlerCallable
23
+
24
+ DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]
25
+
26
+
27
+ class BlueprintSetupState:
28
+ """Temporary holder object for registering a blueprint with the
29
+ application. An instance of this class is created by the
30
+ :meth:`~flask.Blueprint.make_setup_state` method and later passed
31
+ to all register callback functions.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ blueprint: "Blueprint",
37
+ app: "Flask",
38
+ options: t.Any,
39
+ first_registration: bool,
40
+ ) -> None:
41
+ #: a reference to the current application
42
+ self.app = app
43
+
44
+ #: a reference to the blueprint that created this setup state.
45
+ self.blueprint = blueprint
46
+
47
+ #: a dictionary with all options that were passed to the
48
+ #: :meth:`~flask.Flask.register_blueprint` method.
49
+ self.options = options
50
+
51
+ #: as blueprints can be registered multiple times with the
52
+ #: application and not everything wants to be registered
53
+ #: multiple times on it, this attribute can be used to figure
54
+ #: out if the blueprint was registered in the past already.
55
+ self.first_registration = first_registration
56
+
57
+ subdomain = self.options.get("subdomain")
58
+ if subdomain is None:
59
+ subdomain = self.blueprint.subdomain
60
+
61
+ #: The subdomain that the blueprint should be active for, ``None``
62
+ #: otherwise.
63
+ self.subdomain = subdomain
64
+
65
+ url_prefix = self.options.get("url_prefix")
66
+ if url_prefix is None:
67
+ url_prefix = self.blueprint.url_prefix
68
+ #: The prefix that should be used for all URLs defined on the
69
+ #: blueprint.
70
+ self.url_prefix = url_prefix
71
+
72
+ self.name = self.options.get("name", blueprint.name)
73
+ self.name_prefix = self.options.get("name_prefix", "")
74
+
75
+ #: A dictionary with URL defaults that is added to each and every
76
+ #: URL that was defined with the blueprint.
77
+ self.url_defaults = dict(self.blueprint.url_values_defaults)
78
+ self.url_defaults.update(self.options.get("url_defaults", ()))
79
+
80
+ def add_url_rule(
81
+ self,
82
+ rule: str,
83
+ endpoint: t.Optional[str] = None,
84
+ view_func: t.Optional[t.Callable] = None,
85
+ **options: t.Any,
86
+ ) -> None:
87
+ """A helper method to register a rule (and optionally a view function)
88
+ to the application. The endpoint is automatically prefixed with the
89
+ blueprint's name.
90
+ """
91
+ if self.url_prefix is not None:
92
+ if rule:
93
+ rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))
94
+ else:
95
+ rule = self.url_prefix
96
+ options.setdefault("subdomain", self.subdomain)
97
+ if endpoint is None:
98
+ endpoint = _endpoint_from_view_func(view_func) # type: ignore
99
+ defaults = self.url_defaults
100
+ if "defaults" in options:
101
+ defaults = dict(defaults, **options.pop("defaults"))
102
+
103
+ self.app.add_url_rule(
104
+ rule,
105
+ f"{self.name_prefix}.{self.name}.{endpoint}".lstrip("."),
106
+ view_func,
107
+ defaults=defaults,
108
+ **options,
109
+ )
110
+
111
+
112
+ class Blueprint(Scaffold):
113
+ """Represents a blueprint, a collection of routes and other
114
+ app-related functions that can be registered on a real application
115
+ later.
116
+
117
+ A blueprint is an object that allows defining application functions
118
+ without requiring an application object ahead of time. It uses the
119
+ same decorators as :class:`~flask.Flask`, but defers the need for an
120
+ application by recording them for later registration.
121
+
122
+ Decorating a function with a blueprint creates a deferred function
123
+ that is called with :class:`~flask.blueprints.BlueprintSetupState`
124
+ when the blueprint is registered on an application.
125
+
126
+ See :doc:`/blueprints` for more information.
127
+
128
+ :param name: The name of the blueprint. Will be prepended to each
129
+ endpoint name.
130
+ :param import_name: The name of the blueprint package, usually
131
+ ``__name__``. This helps locate the ``root_path`` for the
132
+ blueprint.
133
+ :param static_folder: A folder with static files that should be
134
+ served by the blueprint's static route. The path is relative to
135
+ the blueprint's root path. Blueprint static files are disabled
136
+ by default.
137
+ :param static_url_path: The url to serve static files from.
138
+ Defaults to ``static_folder``. If the blueprint does not have
139
+ a ``url_prefix``, the app's static route will take precedence,
140
+ and the blueprint's static files won't be accessible.
141
+ :param template_folder: A folder with templates that should be added
142
+ to the app's template search path. The path is relative to the
143
+ blueprint's root path. Blueprint templates are disabled by
144
+ default. Blueprint templates have a lower precedence than those
145
+ in the app's templates folder.
146
+ :param url_prefix: A path to prepend to all of the blueprint's URLs,
147
+ to make them distinct from the rest of the app's routes.
148
+ :param subdomain: A subdomain that blueprint routes will match on by
149
+ default.
150
+ :param url_defaults: A dict of default values that blueprint routes
151
+ will receive by default.
152
+ :param root_path: By default, the blueprint will automatically set
153
+ this based on ``import_name``. In certain situations this
154
+ automatic detection can fail, so the path can be specified
155
+ manually instead.
156
+
157
+ .. versionchanged:: 1.1.0
158
+ Blueprints have a ``cli`` group to register nested CLI commands.
159
+ The ``cli_group`` parameter controls the name of the group under
160
+ the ``flask`` command.
161
+
162
+ .. versionadded:: 0.7
163
+ """
164
+
165
+ warn_on_modifications = False
166
+ _got_registered_once = False
167
+
168
+ #: Blueprint local JSON encoder class to use. Set to ``None`` to use
169
+ #: the app's :class:`~flask.Flask.json_encoder`.
170
+ json_encoder = None
171
+ #: Blueprint local JSON decoder class to use. Set to ``None`` to use
172
+ #: the app's :class:`~flask.Flask.json_decoder`.
173
+ json_decoder = None
174
+
175
+ def __init__(
176
+ self,
177
+ name: str,
178
+ import_name: str,
179
+ static_folder: t.Optional[t.Union[str, os.PathLike]] = None,
180
+ static_url_path: t.Optional[str] = None,
181
+ template_folder: t.Optional[str] = None,
182
+ url_prefix: t.Optional[str] = None,
183
+ subdomain: t.Optional[str] = None,
184
+ url_defaults: t.Optional[dict] = None,
185
+ root_path: t.Optional[str] = None,
186
+ cli_group: t.Optional[str] = _sentinel, # type: ignore
187
+ ):
188
+ super().__init__(
189
+ import_name=import_name,
190
+ static_folder=static_folder,
191
+ static_url_path=static_url_path,
192
+ template_folder=template_folder,
193
+ root_path=root_path,
194
+ )
195
+
196
+ if "." in name:
197
+ raise ValueError("'name' may not contain a dot '.' character.")
198
+
199
+ self.name = name
200
+ self.url_prefix = url_prefix
201
+ self.subdomain = subdomain
202
+ self.deferred_functions: t.List[DeferredSetupFunction] = []
203
+
204
+ if url_defaults is None:
205
+ url_defaults = {}
206
+
207
+ self.url_values_defaults = url_defaults
208
+ self.cli_group = cli_group
209
+ self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []
210
+
211
+ def _is_setup_finished(self) -> bool:
212
+ return self.warn_on_modifications and self._got_registered_once
213
+
214
+ def record(self, func: t.Callable) -> None:
215
+ """Registers a function that is called when the blueprint is
216
+ registered on the application. This function is called with the
217
+ state as argument as returned by the :meth:`make_setup_state`
218
+ method.
219
+ """
220
+ if self._got_registered_once and self.warn_on_modifications:
221
+ from warnings import warn
222
+
223
+ warn(
224
+ Warning(
225
+ "The blueprint was already registered once but is"
226
+ " getting modified now. These changes will not show"
227
+ " up."
228
+ )
229
+ )
230
+ self.deferred_functions.append(func)
231
+
232
+ def record_once(self, func: t.Callable) -> None:
233
+ """Works like :meth:`record` but wraps the function in another
234
+ function that will ensure the function is only called once. If the
235
+ blueprint is registered a second time on the application, the
236
+ function passed is not called.
237
+ """
238
+
239
+ def wrapper(state: BlueprintSetupState) -> None:
240
+ if state.first_registration:
241
+ func(state)
242
+
243
+ return self.record(update_wrapper(wrapper, func))
244
+
245
+ def make_setup_state(
246
+ self, app: "Flask", options: dict, first_registration: bool = False
247
+ ) -> BlueprintSetupState:
248
+ """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
249
+ object that is later passed to the register callback functions.
250
+ Subclasses can override this to return a subclass of the setup state.
251
+ """
252
+ return BlueprintSetupState(self, app, options, first_registration)
253
+
254
+ def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:
255
+ """Register a :class:`~flask.Blueprint` on this blueprint. Keyword
256
+ arguments passed to this method will override the defaults set
257
+ on the blueprint.
258
+
259
+ .. versionchanged:: 2.0.1
260
+ The ``name`` option can be used to change the (pre-dotted)
261
+ name the blueprint is registered with. This allows the same
262
+ blueprint to be registered multiple times with unique names
263
+ for ``url_for``.
264
+
265
+ .. versionadded:: 2.0
266
+ """
267
+ if blueprint is self:
268
+ raise ValueError("Cannot register a blueprint on itself")
269
+ self._blueprints.append((blueprint, options))
270
+
271
+ def register(self, app: "Flask", options: dict) -> None:
272
+ """Called by :meth:`Flask.register_blueprint` to register all
273
+ views and callbacks registered on the blueprint with the
274
+ application. Creates a :class:`.BlueprintSetupState` and calls
275
+ each :meth:`record` callback with it.
276
+
277
+ :param app: The application this blueprint is being registered
278
+ with.
279
+ :param options: Keyword arguments forwarded from
280
+ :meth:`~Flask.register_blueprint`.
281
+
282
+ .. versionchanged:: 2.0.1
283
+ Nested blueprints are registered with their dotted name.
284
+ This allows different blueprints with the same name to be
285
+ nested at different locations.
286
+
287
+ .. versionchanged:: 2.0.1
288
+ The ``name`` option can be used to change the (pre-dotted)
289
+ name the blueprint is registered with. This allows the same
290
+ blueprint to be registered multiple times with unique names
291
+ for ``url_for``.
292
+
293
+ .. versionchanged:: 2.0.1
294
+ Registering the same blueprint with the same name multiple
295
+ times is deprecated and will become an error in Flask 2.1.
296
+ """
297
+ name_prefix = options.get("name_prefix", "")
298
+ self_name = options.get("name", self.name)
299
+ name = f"{name_prefix}.{self_name}".lstrip(".")
300
+
301
+ if name in app.blueprints:
302
+ bp_desc = "this" if app.blueprints[name] is self else "a different"
303
+ existing_at = f" '{name}'" if self_name != name else ""
304
+
305
+ raise ValueError(
306
+ f"The name '{self_name}' is already registered for"
307
+ f" {bp_desc} blueprint{existing_at}. Use 'name=' to"
308
+ f" provide a unique name."
309
+ )
310
+
311
+ first_bp_registration = not any(bp is self for bp in app.blueprints.values())
312
+ first_name_registration = name not in app.blueprints
313
+
314
+ app.blueprints[name] = self
315
+ self._got_registered_once = True
316
+ state = self.make_setup_state(app, options, first_bp_registration)
317
+
318
+ if self.has_static_folder:
319
+ state.add_url_rule(
320
+ f"{self.static_url_path}/<path:filename>",
321
+ view_func=self.send_static_file,
322
+ endpoint="static",
323
+ )
324
+
325
+ # Merge blueprint data into parent.
326
+ if first_bp_registration or first_name_registration:
327
+
328
+ def extend(bp_dict, parent_dict):
329
+ for key, values in bp_dict.items():
330
+ key = name if key is None else f"{name}.{key}"
331
+ parent_dict[key].extend(values)
332
+
333
+ for key, value in self.error_handler_spec.items():
334
+ key = name if key is None else f"{name}.{key}"
335
+ value = defaultdict(
336
+ dict,
337
+ {
338
+ code: {
339
+ exc_class: func for exc_class, func in code_values.items()
340
+ }
341
+ for code, code_values in value.items()
342
+ },
343
+ )
344
+ app.error_handler_spec[key] = value
345
+
346
+ for endpoint, func in self.view_functions.items():
347
+ app.view_functions[endpoint] = func
348
+
349
+ extend(self.before_request_funcs, app.before_request_funcs)
350
+ extend(self.after_request_funcs, app.after_request_funcs)
351
+ extend(
352
+ self.teardown_request_funcs,
353
+ app.teardown_request_funcs,
354
+ )
355
+ extend(self.url_default_functions, app.url_default_functions)
356
+ extend(self.url_value_preprocessors, app.url_value_preprocessors)
357
+ extend(self.template_context_processors, app.template_context_processors)
358
+
359
+ for deferred in self.deferred_functions:
360
+ deferred(state)
361
+
362
+ cli_resolved_group = options.get("cli_group", self.cli_group)
363
+
364
+ if self.cli.commands:
365
+ if cli_resolved_group is None:
366
+ app.cli.commands.update(self.cli.commands)
367
+ elif cli_resolved_group is _sentinel:
368
+ self.cli.name = name
369
+ app.cli.add_command(self.cli)
370
+ else:
371
+ self.cli.name = cli_resolved_group
372
+ app.cli.add_command(self.cli)
373
+
374
+ for blueprint, bp_options in self._blueprints:
375
+ bp_options = bp_options.copy()
376
+ bp_url_prefix = bp_options.get("url_prefix")
377
+
378
+ if bp_url_prefix is None:
379
+ bp_url_prefix = blueprint.url_prefix
380
+
381
+ if state.url_prefix is not None and bp_url_prefix is not None:
382
+ bp_options["url_prefix"] = (
383
+ state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/")
384
+ )
385
+ elif bp_url_prefix is not None:
386
+ bp_options["url_prefix"] = bp_url_prefix
387
+ elif state.url_prefix is not None:
388
+ bp_options["url_prefix"] = state.url_prefix
389
+
390
+ bp_options["name_prefix"] = name
391
+ blueprint.register(app, bp_options)
392
+
393
+ def add_url_rule(
394
+ self,
395
+ rule: str,
396
+ endpoint: t.Optional[str] = None,
397
+ view_func: t.Optional[t.Callable] = None,
398
+ provide_automatic_options: t.Optional[bool] = None,
399
+ **options: t.Any,
400
+ ) -> None:
401
+ """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for
402
+ the :func:`url_for` function is prefixed with the name of the blueprint.
403
+ """
404
+ if endpoint and "." in endpoint:
405
+ raise ValueError("'endpoint' may not contain a dot '.' character.")
406
+
407
+ if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__:
408
+ raise ValueError("'view_func' name may not contain a dot '.' character.")
409
+
410
+ self.record(
411
+ lambda s: s.add_url_rule(
412
+ rule,
413
+ endpoint,
414
+ view_func,
415
+ provide_automatic_options=provide_automatic_options,
416
+ **options,
417
+ )
418
+ )
419
+
420
+ def app_template_filter(
421
+ self, name: t.Optional[str] = None
422
+ ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]:
423
+ """Register a custom template filter, available application wide. Like
424
+ :meth:`Flask.template_filter` but for a blueprint.
425
+
426
+ :param name: the optional name of the filter, otherwise the
427
+ function name will be used.
428
+ """
429
+
430
+ def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:
431
+ self.add_app_template_filter(f, name=name)
432
+ return f
433
+
434
+ return decorator
435
+
436
+ def add_app_template_filter(
437
+ self, f: TemplateFilterCallable, name: t.Optional[str] = None
438
+ ) -> None:
439
+ """Register a custom template filter, available application wide. Like
440
+ :meth:`Flask.add_template_filter` but for a blueprint. Works exactly
441
+ like the :meth:`app_template_filter` decorator.
442
+
443
+ :param name: the optional name of the filter, otherwise the
444
+ function name will be used.
445
+ """
446
+
447
+ def register_template(state: BlueprintSetupState) -> None:
448
+ state.app.jinja_env.filters[name or f.__name__] = f
449
+
450
+ self.record_once(register_template)
451
+
452
+ def app_template_test(
453
+ self, name: t.Optional[str] = None
454
+ ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]:
455
+ """Register a custom template test, available application wide. Like
456
+ :meth:`Flask.template_test` but for a blueprint.
457
+
458
+ .. versionadded:: 0.10
459
+
460
+ :param name: the optional name of the test, otherwise the
461
+ function name will be used.
462
+ """
463
+
464
+ def decorator(f: TemplateTestCallable) -> TemplateTestCallable:
465
+ self.add_app_template_test(f, name=name)
466
+ return f
467
+
468
+ return decorator
469
+
470
+ def add_app_template_test(
471
+ self, f: TemplateTestCallable, name: t.Optional[str] = None
472
+ ) -> None:
473
+ """Register a custom template test, available application wide. Like
474
+ :meth:`Flask.add_template_test` but for a blueprint. Works exactly
475
+ like the :meth:`app_template_test` decorator.
476
+
477
+ .. versionadded:: 0.10
478
+
479
+ :param name: the optional name of the test, otherwise the
480
+ function name will be used.
481
+ """
482
+
483
+ def register_template(state: BlueprintSetupState) -> None:
484
+ state.app.jinja_env.tests[name or f.__name__] = f
485
+
486
+ self.record_once(register_template)
487
+
488
+ def app_template_global(
489
+ self, name: t.Optional[str] = None
490
+ ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]:
491
+ """Register a custom template global, available application wide. Like
492
+ :meth:`Flask.template_global` but for a blueprint.
493
+
494
+ .. versionadded:: 0.10
495
+
496
+ :param name: the optional name of the global, otherwise the
497
+ function name will be used.
498
+ """
499
+
500
+ def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:
501
+ self.add_app_template_global(f, name=name)
502
+ return f
503
+
504
+ return decorator
505
+
506
+ def add_app_template_global(
507
+ self, f: TemplateGlobalCallable, name: t.Optional[str] = None
508
+ ) -> None:
509
+ """Register a custom template global, available application wide. Like
510
+ :meth:`Flask.add_template_global` but for a blueprint. Works exactly
511
+ like the :meth:`app_template_global` decorator.
512
+
513
+ .. versionadded:: 0.10
514
+
515
+ :param name: the optional name of the global, otherwise the
516
+ function name will be used.
517
+ """
518
+
519
+ def register_template(state: BlueprintSetupState) -> None:
520
+ state.app.jinja_env.globals[name or f.__name__] = f
521
+
522
+ self.record_once(register_template)
523
+
524
+ def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:
525
+ """Like :meth:`Flask.before_request`. Such a function is executed
526
+ before each request, even if outside of a blueprint.
527
+ """
528
+ self.record_once(
529
+ lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)
530
+ )
531
+ return f
532
+
533
+ def before_app_first_request(
534
+ self, f: BeforeFirstRequestCallable
535
+ ) -> BeforeFirstRequestCallable:
536
+ """Like :meth:`Flask.before_first_request`. Such a function is
537
+ executed before the first request to the application.
538
+ """
539
+ self.record_once(lambda s: s.app.before_first_request_funcs.append(f))
540
+ return f
541
+
542
+ def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable:
543
+ """Like :meth:`Flask.after_request` but for a blueprint. Such a function
544
+ is executed after each request, even if outside of the blueprint.
545
+ """
546
+ self.record_once(
547
+ lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)
548
+ )
549
+ return f
550
+
551
+ def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:
552
+ """Like :meth:`Flask.teardown_request` but for a blueprint. Such a
553
+ function is executed when tearing down each request, even if outside of
554
+ the blueprint.
555
+ """
556
+ self.record_once(
557
+ lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)
558
+ )
559
+ return f
560
+
561
+ def app_context_processor(
562
+ self, f: TemplateContextProcessorCallable
563
+ ) -> TemplateContextProcessorCallable:
564
+ """Like :meth:`Flask.context_processor` but for a blueprint. Such a
565
+ function is executed each request, even if outside of the blueprint.
566
+ """
567
+ self.record_once(
568
+ lambda s: s.app.template_context_processors.setdefault(None, []).append(f)
569
+ )
570
+ return f
571
+
572
+ def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable:
573
+ """Like :meth:`Flask.errorhandler` but for a blueprint. This
574
+ handler is used for all requests, even if outside of the blueprint.
575
+ """
576
+
577
+ def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":
578
+ self.record_once(lambda s: s.app.errorhandler(code)(f))
579
+ return f
580
+
581
+ return decorator
582
+
583
+ def app_url_value_preprocessor(
584
+ self, f: URLValuePreprocessorCallable
585
+ ) -> URLValuePreprocessorCallable:
586
+ """Same as :meth:`url_value_preprocessor` but application wide."""
587
+ self.record_once(
588
+ lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)
589
+ )
590
+ return f
591
+
592
+ def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:
593
+ """Same as :meth:`url_defaults` but application wide."""
594
+ self.record_once(
595
+ lambda s: s.app.url_default_functions.setdefault(None, []).append(f)
596
+ )
597
+ return f
testbed/pallets__flask/src/flask/cli.py ADDED
@@ -0,0 +1,989 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import inspect
3
+ import os
4
+ import platform
5
+ import re
6
+ import sys
7
+ import traceback
8
+ from functools import update_wrapper
9
+ from operator import attrgetter
10
+ from threading import Lock
11
+ from threading import Thread
12
+
13
+ import click
14
+ from werkzeug.utils import import_string
15
+
16
+ from .globals import current_app
17
+ from .helpers import get_debug_flag
18
+ from .helpers import get_env
19
+ from .helpers import get_load_dotenv
20
+
21
+ try:
22
+ import dotenv
23
+ except ImportError:
24
+ dotenv = None
25
+
26
+ try:
27
+ import ssl
28
+ except ImportError:
29
+ ssl = None # type: ignore
30
+
31
+ if sys.version_info >= (3, 10):
32
+ from importlib import metadata
33
+ else:
34
+ # Use a backport on Python < 3.10.
35
+ #
36
+ # We technically have importlib.metadata on 3.8+,
37
+ # but the API changed in 3.10, so use the backport
38
+ # for consistency.
39
+ import importlib_metadata as metadata # type: ignore
40
+
41
+
42
+ class NoAppException(click.UsageError):
43
+ """Raised if an application cannot be found or loaded."""
44
+
45
+
46
+ def find_best_app(module):
47
+ """Given a module instance this tries to find the best possible
48
+ application in the module or raises an exception.
49
+ """
50
+ from . import Flask
51
+
52
+ # Search for the most common names first.
53
+ for attr_name in ("app", "application"):
54
+ app = getattr(module, attr_name, None)
55
+
56
+ if isinstance(app, Flask):
57
+ return app
58
+
59
+ # Otherwise find the only object that is a Flask instance.
60
+ matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]
61
+
62
+ if len(matches) == 1:
63
+ return matches[0]
64
+ elif len(matches) > 1:
65
+ raise NoAppException(
66
+ "Detected multiple Flask applications in module"
67
+ f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"
68
+ f" to specify the correct one."
69
+ )
70
+
71
+ # Search for app factory functions.
72
+ for attr_name in ("create_app", "make_app"):
73
+ app_factory = getattr(module, attr_name, None)
74
+
75
+ if inspect.isfunction(app_factory):
76
+ try:
77
+ app = app_factory()
78
+
79
+ if isinstance(app, Flask):
80
+ return app
81
+ except TypeError as e:
82
+ if not _called_with_wrong_args(app_factory):
83
+ raise
84
+
85
+ raise NoAppException(
86
+ f"Detected factory {attr_name!r} in module {module.__name__!r},"
87
+ " but could not call it without arguments. Use"
88
+ f" \"FLASK_APP='{module.__name__}:{attr_name}(args)'\""
89
+ " to specify arguments."
90
+ ) from e
91
+
92
+ raise NoAppException(
93
+ "Failed to find Flask application or factory in module"
94
+ f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"
95
+ " to specify one."
96
+ )
97
+
98
+
99
+ def _called_with_wrong_args(f):
100
+ """Check whether calling a function raised a ``TypeError`` because
101
+ the call failed or because something in the factory raised the
102
+ error.
103
+
104
+ :param f: The function that was called.
105
+ :return: ``True`` if the call failed.
106
+ """
107
+ tb = sys.exc_info()[2]
108
+
109
+ try:
110
+ while tb is not None:
111
+ if tb.tb_frame.f_code is f.__code__:
112
+ # In the function, it was called successfully.
113
+ return False
114
+
115
+ tb = tb.tb_next
116
+
117
+ # Didn't reach the function.
118
+ return True
119
+ finally:
120
+ # Delete tb to break a circular reference.
121
+ # https://docs.python.org/2/library/sys.html#sys.exc_info
122
+ del tb
123
+
124
+
125
+ def find_app_by_string(module, app_name):
126
+ """Check if the given string is a variable name or a function. Call
127
+ a function to get the app instance, or return the variable directly.
128
+ """
129
+ from . import Flask
130
+
131
+ # Parse app_name as a single expression to determine if it's a valid
132
+ # attribute name or function call.
133
+ try:
134
+ expr = ast.parse(app_name.strip(), mode="eval").body
135
+ except SyntaxError:
136
+ raise NoAppException(
137
+ f"Failed to parse {app_name!r} as an attribute name or function call."
138
+ ) from None
139
+
140
+ if isinstance(expr, ast.Name):
141
+ name = expr.id
142
+ args = []
143
+ kwargs = {}
144
+ elif isinstance(expr, ast.Call):
145
+ # Ensure the function name is an attribute name only.
146
+ if not isinstance(expr.func, ast.Name):
147
+ raise NoAppException(
148
+ f"Function reference must be a simple name: {app_name!r}."
149
+ )
150
+
151
+ name = expr.func.id
152
+
153
+ # Parse the positional and keyword arguments as literals.
154
+ try:
155
+ args = [ast.literal_eval(arg) for arg in expr.args]
156
+ kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}
157
+ except ValueError:
158
+ # literal_eval gives cryptic error messages, show a generic
159
+ # message with the full expression instead.
160
+ raise NoAppException(
161
+ f"Failed to parse arguments as literal values: {app_name!r}."
162
+ ) from None
163
+ else:
164
+ raise NoAppException(
165
+ f"Failed to parse {app_name!r} as an attribute name or function call."
166
+ )
167
+
168
+ try:
169
+ attr = getattr(module, name)
170
+ except AttributeError as e:
171
+ raise NoAppException(
172
+ f"Failed to find attribute {name!r} in {module.__name__!r}."
173
+ ) from e
174
+
175
+ # If the attribute is a function, call it with any args and kwargs
176
+ # to get the real application.
177
+ if inspect.isfunction(attr):
178
+ try:
179
+ app = attr(*args, **kwargs)
180
+ except TypeError as e:
181
+ if not _called_with_wrong_args(attr):
182
+ raise
183
+
184
+ raise NoAppException(
185
+ f"The factory {app_name!r} in module"
186
+ f" {module.__name__!r} could not be called with the"
187
+ " specified arguments."
188
+ ) from e
189
+ else:
190
+ app = attr
191
+
192
+ if isinstance(app, Flask):
193
+ return app
194
+
195
+ raise NoAppException(
196
+ "A valid Flask application was not obtained from"
197
+ f" '{module.__name__}:{app_name}'."
198
+ )
199
+
200
+
201
+ def prepare_import(path):
202
+ """Given a filename this will try to calculate the python path, add it
203
+ to the search path and return the actual module name that is expected.
204
+ """
205
+ path = os.path.realpath(path)
206
+
207
+ fname, ext = os.path.splitext(path)
208
+ if ext == ".py":
209
+ path = fname
210
+
211
+ if os.path.basename(path) == "__init__":
212
+ path = os.path.dirname(path)
213
+
214
+ module_name = []
215
+
216
+ # move up until outside package structure (no __init__.py)
217
+ while True:
218
+ path, name = os.path.split(path)
219
+ module_name.append(name)
220
+
221
+ if not os.path.exists(os.path.join(path, "__init__.py")):
222
+ break
223
+
224
+ if sys.path[0] != path:
225
+ sys.path.insert(0, path)
226
+
227
+ return ".".join(module_name[::-1])
228
+
229
+
230
+ def locate_app(module_name, app_name, raise_if_not_found=True):
231
+ __traceback_hide__ = True # noqa: F841
232
+
233
+ try:
234
+ __import__(module_name)
235
+ except ImportError:
236
+ # Reraise the ImportError if it occurred within the imported module.
237
+ # Determine this by checking whether the trace has a depth > 1.
238
+ if sys.exc_info()[2].tb_next:
239
+ raise NoAppException(
240
+ f"While importing {module_name!r}, an ImportError was"
241
+ f" raised:\n\n{traceback.format_exc()}"
242
+ ) from None
243
+ elif raise_if_not_found:
244
+ raise NoAppException(f"Could not import {module_name!r}.") from None
245
+ else:
246
+ return
247
+
248
+ module = sys.modules[module_name]
249
+
250
+ if app_name is None:
251
+ return find_best_app(module)
252
+ else:
253
+ return find_app_by_string(module, app_name)
254
+
255
+
256
+ def get_version(ctx, param, value):
257
+ if not value or ctx.resilient_parsing:
258
+ return
259
+
260
+ import werkzeug
261
+ from . import __version__
262
+
263
+ click.echo(
264
+ f"Python {platform.python_version()}\n"
265
+ f"Flask {__version__}\n"
266
+ f"Werkzeug {werkzeug.__version__}",
267
+ color=ctx.color,
268
+ )
269
+ ctx.exit()
270
+
271
+
272
+ version_option = click.Option(
273
+ ["--version"],
274
+ help="Show the flask version",
275
+ expose_value=False,
276
+ callback=get_version,
277
+ is_flag=True,
278
+ is_eager=True,
279
+ )
280
+
281
+
282
+ class DispatchingApp:
283
+ """Special application that dispatches to a Flask application which
284
+ is imported by name in a background thread. If an error happens
285
+ it is recorded and shown as part of the WSGI handling which in case
286
+ of the Werkzeug debugger means that it shows up in the browser.
287
+ """
288
+
289
+ def __init__(self, loader, use_eager_loading=None):
290
+ self.loader = loader
291
+ self._app = None
292
+ self._lock = Lock()
293
+ self._bg_loading_exc = None
294
+
295
+ if use_eager_loading is None:
296
+ use_eager_loading = os.environ.get("WERKZEUG_RUN_MAIN") != "true"
297
+
298
+ if use_eager_loading:
299
+ self._load_unlocked()
300
+ else:
301
+ self._load_in_background()
302
+
303
+ def _load_in_background(self):
304
+ # Store the Click context and push it in the loader thread so
305
+ # script_info is still available.
306
+ ctx = click.get_current_context(silent=True)
307
+
308
+ def _load_app():
309
+ __traceback_hide__ = True # noqa: F841
310
+
311
+ with self._lock:
312
+ if ctx is not None:
313
+ click.globals.push_context(ctx)
314
+
315
+ try:
316
+ self._load_unlocked()
317
+ except Exception as e:
318
+ self._bg_loading_exc = e
319
+
320
+ t = Thread(target=_load_app, args=())
321
+ t.start()
322
+
323
+ def _flush_bg_loading_exception(self):
324
+ __traceback_hide__ = True # noqa: F841
325
+ exc = self._bg_loading_exc
326
+
327
+ if exc is not None:
328
+ self._bg_loading_exc = None
329
+ raise exc
330
+
331
+ def _load_unlocked(self):
332
+ __traceback_hide__ = True # noqa: F841
333
+ self._app = rv = self.loader()
334
+ self._bg_loading_exc = None
335
+ return rv
336
+
337
+ def __call__(self, environ, start_response):
338
+ __traceback_hide__ = True # noqa: F841
339
+ if self._app is not None:
340
+ return self._app(environ, start_response)
341
+ self._flush_bg_loading_exception()
342
+ with self._lock:
343
+ if self._app is not None:
344
+ rv = self._app
345
+ else:
346
+ rv = self._load_unlocked()
347
+ return rv(environ, start_response)
348
+
349
+
350
+ class ScriptInfo:
351
+ """Helper object to deal with Flask applications. This is usually not
352
+ necessary to interface with as it's used internally in the dispatching
353
+ to click. In future versions of Flask this object will most likely play
354
+ a bigger role. Typically it's created automatically by the
355
+ :class:`FlaskGroup` but you can also manually create it and pass it
356
+ onwards as click object.
357
+ """
358
+
359
+ def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):
360
+ #: Optionally the import path for the Flask application.
361
+ self.app_import_path = app_import_path or os.environ.get("FLASK_APP")
362
+ #: Optionally a function that is passed the script info to create
363
+ #: the instance of the application.
364
+ self.create_app = create_app
365
+ #: A dictionary with arbitrary data that can be associated with
366
+ #: this script info.
367
+ self.data = {}
368
+ self.set_debug_flag = set_debug_flag
369
+ self._loaded_app = None
370
+
371
+ def load_app(self):
372
+ """Loads the Flask app (if not yet loaded) and returns it. Calling
373
+ this multiple times will just result in the already loaded app to
374
+ be returned.
375
+ """
376
+ __traceback_hide__ = True # noqa: F841
377
+
378
+ if self._loaded_app is not None:
379
+ return self._loaded_app
380
+
381
+ if self.create_app is not None:
382
+ app = self.create_app()
383
+ else:
384
+ if self.app_import_path:
385
+ path, name = (
386
+ re.split(r":(?![\\/])", self.app_import_path, 1) + [None]
387
+ )[:2]
388
+ import_name = prepare_import(path)
389
+ app = locate_app(import_name, name)
390
+ else:
391
+ for path in ("wsgi.py", "app.py"):
392
+ import_name = prepare_import(path)
393
+ app = locate_app(import_name, None, raise_if_not_found=False)
394
+
395
+ if app:
396
+ break
397
+
398
+ if not app:
399
+ raise NoAppException(
400
+ "Could not locate a Flask application. You did not provide "
401
+ 'the "FLASK_APP" environment variable, and a "wsgi.py" or '
402
+ '"app.py" module was not found in the current directory.'
403
+ )
404
+
405
+ if self.set_debug_flag:
406
+ # Update the app's debug flag through the descriptor so that
407
+ # other values repopulate as well.
408
+ app.debug = get_debug_flag()
409
+
410
+ self._loaded_app = app
411
+ return app
412
+
413
+
414
+ pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)
415
+
416
+
417
+ def with_appcontext(f):
418
+ """Wraps a callback so that it's guaranteed to be executed with the
419
+ script's application context. If callbacks are registered directly
420
+ to the ``app.cli`` object then they are wrapped with this function
421
+ by default unless it's disabled.
422
+ """
423
+
424
+ @click.pass_context
425
+ def decorator(__ctx, *args, **kwargs):
426
+ with __ctx.ensure_object(ScriptInfo).load_app().app_context():
427
+ return __ctx.invoke(f, *args, **kwargs)
428
+
429
+ return update_wrapper(decorator, f)
430
+
431
+
432
+ class AppGroup(click.Group):
433
+ """This works similar to a regular click :class:`~click.Group` but it
434
+ changes the behavior of the :meth:`command` decorator so that it
435
+ automatically wraps the functions in :func:`with_appcontext`.
436
+
437
+ Not to be confused with :class:`FlaskGroup`.
438
+ """
439
+
440
+ def command(self, *args, **kwargs):
441
+ """This works exactly like the method of the same name on a regular
442
+ :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
443
+ unless it's disabled by passing ``with_appcontext=False``.
444
+ """
445
+ wrap_for_ctx = kwargs.pop("with_appcontext", True)
446
+
447
+ def decorator(f):
448
+ if wrap_for_ctx:
449
+ f = with_appcontext(f)
450
+ return click.Group.command(self, *args, **kwargs)(f)
451
+
452
+ return decorator
453
+
454
+ def group(self, *args, **kwargs):
455
+ """This works exactly like the method of the same name on a regular
456
+ :class:`click.Group` but it defaults the group class to
457
+ :class:`AppGroup`.
458
+ """
459
+ kwargs.setdefault("cls", AppGroup)
460
+ return click.Group.group(self, *args, **kwargs)
461
+
462
+
463
+ class FlaskGroup(AppGroup):
464
+ """Special subclass of the :class:`AppGroup` group that supports
465
+ loading more commands from the configured Flask app. Normally a
466
+ developer does not have to interface with this class but there are
467
+ some very advanced use cases for which it makes sense to create an
468
+ instance of this. see :ref:`custom-scripts`.
469
+
470
+ :param add_default_commands: if this is True then the default run and
471
+ shell commands will be added.
472
+ :param add_version_option: adds the ``--version`` option.
473
+ :param create_app: an optional callback that is passed the script info and
474
+ returns the loaded app.
475
+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
476
+ files to set environment variables. Will also change the working
477
+ directory to the directory containing the first file found.
478
+ :param set_debug_flag: Set the app's debug flag based on the active
479
+ environment
480
+
481
+ .. versionchanged:: 1.0
482
+ If installed, python-dotenv will be used to load environment variables
483
+ from :file:`.env` and :file:`.flaskenv` files.
484
+ """
485
+
486
+ def __init__(
487
+ self,
488
+ add_default_commands=True,
489
+ create_app=None,
490
+ add_version_option=True,
491
+ load_dotenv=True,
492
+ set_debug_flag=True,
493
+ **extra,
494
+ ):
495
+ params = list(extra.pop("params", None) or ())
496
+
497
+ if add_version_option:
498
+ params.append(version_option)
499
+
500
+ AppGroup.__init__(self, params=params, **extra)
501
+ self.create_app = create_app
502
+ self.load_dotenv = load_dotenv
503
+ self.set_debug_flag = set_debug_flag
504
+
505
+ if add_default_commands:
506
+ self.add_command(run_command)
507
+ self.add_command(shell_command)
508
+ self.add_command(routes_command)
509
+
510
+ self._loaded_plugin_commands = False
511
+
512
+ def _load_plugin_commands(self):
513
+ if self._loaded_plugin_commands:
514
+ return
515
+
516
+ for ep in metadata.entry_points(group="flask.commands"):
517
+ self.add_command(ep.load(), ep.name)
518
+
519
+ self._loaded_plugin_commands = True
520
+
521
+ def get_command(self, ctx, name):
522
+ self._load_plugin_commands()
523
+ # Look up built-in and plugin commands, which should be
524
+ # available even if the app fails to load.
525
+ rv = super().get_command(ctx, name)
526
+
527
+ if rv is not None:
528
+ return rv
529
+
530
+ info = ctx.ensure_object(ScriptInfo)
531
+
532
+ # Look up commands provided by the app, showing an error and
533
+ # continuing if the app couldn't be loaded.
534
+ try:
535
+ return info.load_app().cli.get_command(ctx, name)
536
+ except NoAppException as e:
537
+ click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
538
+
539
+ def list_commands(self, ctx):
540
+ self._load_plugin_commands()
541
+ # Start with the built-in and plugin commands.
542
+ rv = set(super().list_commands(ctx))
543
+ info = ctx.ensure_object(ScriptInfo)
544
+
545
+ # Add commands provided by the app, showing an error and
546
+ # continuing if the app couldn't be loaded.
547
+ try:
548
+ rv.update(info.load_app().cli.list_commands(ctx))
549
+ except NoAppException as e:
550
+ # When an app couldn't be loaded, show the error message
551
+ # without the traceback.
552
+ click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
553
+ except Exception:
554
+ # When any other errors occurred during loading, show the
555
+ # full traceback.
556
+ click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")
557
+
558
+ return sorted(rv)
559
+
560
+ def main(self, *args, **kwargs):
561
+ # Set a global flag that indicates that we were invoked from the
562
+ # command line interface. This is detected by Flask.run to make the
563
+ # call into a no-op. This is necessary to avoid ugly errors when the
564
+ # script that is loaded here also attempts to start a server.
565
+ os.environ["FLASK_RUN_FROM_CLI"] = "true"
566
+
567
+ if get_load_dotenv(self.load_dotenv):
568
+ load_dotenv()
569
+
570
+ obj = kwargs.get("obj")
571
+
572
+ if obj is None:
573
+ obj = ScriptInfo(
574
+ create_app=self.create_app, set_debug_flag=self.set_debug_flag
575
+ )
576
+
577
+ kwargs["obj"] = obj
578
+ kwargs.setdefault("auto_envvar_prefix", "FLASK")
579
+ return super().main(*args, **kwargs)
580
+
581
+
582
+ def _path_is_ancestor(path, other):
583
+ """Take ``other`` and remove the length of ``path`` from it. Then join it
584
+ to ``path``. If it is the original value, ``path`` is an ancestor of
585
+ ``other``."""
586
+ return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other
587
+
588
+
589
+ def load_dotenv(path=None):
590
+ """Load "dotenv" files in order of precedence to set environment variables.
591
+
592
+ If an env var is already set it is not overwritten, so earlier files in the
593
+ list are preferred over later files.
594
+
595
+ This is a no-op if `python-dotenv`_ is not installed.
596
+
597
+ .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme
598
+
599
+ :param path: Load the file at this location instead of searching.
600
+ :return: ``True`` if a file was loaded.
601
+
602
+ .. versionchanged:: 1.1.0
603
+ Returns ``False`` when python-dotenv is not installed, or when
604
+ the given path isn't a file.
605
+
606
+ .. versionchanged:: 2.0
607
+ When loading the env files, set the default encoding to UTF-8.
608
+
609
+ .. versionadded:: 1.0
610
+ """
611
+ if dotenv is None:
612
+ if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):
613
+ click.secho(
614
+ " * Tip: There are .env or .flaskenv files present."
615
+ ' Do "pip install python-dotenv" to use them.',
616
+ fg="yellow",
617
+ err=True,
618
+ )
619
+
620
+ return False
621
+
622
+ # if the given path specifies the actual file then return True,
623
+ # else False
624
+ if path is not None:
625
+ if os.path.isfile(path):
626
+ return dotenv.load_dotenv(path, encoding="utf-8")
627
+
628
+ return False
629
+
630
+ new_dir = None
631
+
632
+ for name in (".env", ".flaskenv"):
633
+ path = dotenv.find_dotenv(name, usecwd=True)
634
+
635
+ if not path:
636
+ continue
637
+
638
+ if new_dir is None:
639
+ new_dir = os.path.dirname(path)
640
+
641
+ dotenv.load_dotenv(path, encoding="utf-8")
642
+
643
+ return new_dir is not None # at least one file was located and loaded
644
+
645
+
646
+ def show_server_banner(env, debug, app_import_path, eager_loading):
647
+ """Show extra startup messages the first time the server is run,
648
+ ignoring the reloader.
649
+ """
650
+ if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
651
+ return
652
+
653
+ if app_import_path is not None:
654
+ message = f" * Serving Flask app {app_import_path!r}"
655
+
656
+ if not eager_loading:
657
+ message += " (lazy loading)"
658
+
659
+ click.echo(message)
660
+
661
+ click.echo(f" * Environment: {env}")
662
+
663
+ if env == "production":
664
+ click.secho(
665
+ " WARNING: This is a development server. Do not use it in"
666
+ " a production deployment.",
667
+ fg="red",
668
+ )
669
+ click.secho(" Use a production WSGI server instead.", dim=True)
670
+
671
+ if debug is not None:
672
+ click.echo(f" * Debug mode: {'on' if debug else 'off'}")
673
+
674
+
675
+ class CertParamType(click.ParamType):
676
+ """Click option type for the ``--cert`` option. Allows either an
677
+ existing file, the string ``'adhoc'``, or an import for a
678
+ :class:`~ssl.SSLContext` object.
679
+ """
680
+
681
+ name = "path"
682
+
683
+ def __init__(self):
684
+ self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)
685
+
686
+ def convert(self, value, param, ctx):
687
+ if ssl is None:
688
+ raise click.BadParameter(
689
+ 'Using "--cert" requires Python to be compiled with SSL support.',
690
+ ctx,
691
+ param,
692
+ )
693
+
694
+ try:
695
+ return self.path_type(value, param, ctx)
696
+ except click.BadParameter:
697
+ value = click.STRING(value, param, ctx).lower()
698
+
699
+ if value == "adhoc":
700
+ try:
701
+ import cryptography # noqa: F401
702
+ except ImportError:
703
+ raise click.BadParameter(
704
+ "Using ad-hoc certificates requires the cryptography library.",
705
+ ctx,
706
+ param,
707
+ ) from None
708
+
709
+ return value
710
+
711
+ obj = import_string(value, silent=True)
712
+
713
+ if isinstance(obj, ssl.SSLContext):
714
+ return obj
715
+
716
+ raise
717
+
718
+
719
+ def _validate_key(ctx, param, value):
720
+ """The ``--key`` option must be specified when ``--cert`` is a file.
721
+ Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
722
+ """
723
+ cert = ctx.params.get("cert")
724
+ is_adhoc = cert == "adhoc"
725
+ is_context = ssl and isinstance(cert, ssl.SSLContext)
726
+
727
+ if value is not None:
728
+ if is_adhoc:
729
+ raise click.BadParameter(
730
+ 'When "--cert" is "adhoc", "--key" is not used.', ctx, param
731
+ )
732
+
733
+ if is_context:
734
+ raise click.BadParameter(
735
+ 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param
736
+ )
737
+
738
+ if not cert:
739
+ raise click.BadParameter('"--cert" must also be specified.', ctx, param)
740
+
741
+ ctx.params["cert"] = cert, value
742
+
743
+ else:
744
+ if cert and not (is_adhoc or is_context):
745
+ raise click.BadParameter('Required when using "--cert".', ctx, param)
746
+
747
+ return value
748
+
749
+
750
+ class SeparatedPathType(click.Path):
751
+ """Click option type that accepts a list of values separated by the
752
+ OS's path separator (``:``, ``;`` on Windows). Each value is
753
+ validated as a :class:`click.Path` type.
754
+ """
755
+
756
+ def convert(self, value, param, ctx):
757
+ items = self.split_envvar_value(value)
758
+ super_convert = super().convert
759
+ return [super_convert(item, param, ctx) for item in items]
760
+
761
+
762
+ @click.command("run", short_help="Run a development server.")
763
+ @click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")
764
+ @click.option("--port", "-p", default=5000, help="The port to bind to.")
765
+ @click.option(
766
+ "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS."
767
+ )
768
+ @click.option(
769
+ "--key",
770
+ type=click.Path(exists=True, dir_okay=False, resolve_path=True),
771
+ callback=_validate_key,
772
+ expose_value=False,
773
+ help="The key file to use when specifying a certificate.",
774
+ )
775
+ @click.option(
776
+ "--reload/--no-reload",
777
+ default=None,
778
+ help="Enable or disable the reloader. By default the reloader "
779
+ "is active if debug is enabled.",
780
+ )
781
+ @click.option(
782
+ "--debugger/--no-debugger",
783
+ default=None,
784
+ help="Enable or disable the debugger. By default the debugger "
785
+ "is active if debug is enabled.",
786
+ )
787
+ @click.option(
788
+ "--eager-loading/--lazy-loading",
789
+ default=None,
790
+ help="Enable or disable eager loading. By default eager "
791
+ "loading is enabled if the reloader is disabled.",
792
+ )
793
+ @click.option(
794
+ "--with-threads/--without-threads",
795
+ default=True,
796
+ help="Enable or disable multithreading.",
797
+ )
798
+ @click.option(
799
+ "--extra-files",
800
+ default=None,
801
+ type=SeparatedPathType(),
802
+ help=(
803
+ "Extra files that trigger a reload on change. Multiple paths"
804
+ f" are separated by {os.path.pathsep!r}."
805
+ ),
806
+ )
807
+ @click.option(
808
+ "--exclude-patterns",
809
+ default=None,
810
+ type=SeparatedPathType(),
811
+ help=(
812
+ "Files matching these fnmatch patterns will not trigger a reload"
813
+ " on change. Multiple patterns are separated by"
814
+ f" {os.path.pathsep!r}."
815
+ ),
816
+ )
817
+ @pass_script_info
818
+ def run_command(
819
+ info,
820
+ host,
821
+ port,
822
+ reload,
823
+ debugger,
824
+ eager_loading,
825
+ with_threads,
826
+ cert,
827
+ extra_files,
828
+ exclude_patterns,
829
+ ):
830
+ """Run a local development server.
831
+
832
+ This server is for development purposes only. It does not provide
833
+ the stability, security, or performance of production WSGI servers.
834
+
835
+ The reloader and debugger are enabled by default if
836
+ FLASK_ENV=development or FLASK_DEBUG=1.
837
+ """
838
+ debug = get_debug_flag()
839
+
840
+ if reload is None:
841
+ reload = debug
842
+
843
+ if debugger is None:
844
+ debugger = debug
845
+
846
+ show_server_banner(get_env(), debug, info.app_import_path, eager_loading)
847
+ app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
848
+
849
+ from werkzeug.serving import run_simple
850
+
851
+ run_simple(
852
+ host,
853
+ port,
854
+ app,
855
+ use_reloader=reload,
856
+ use_debugger=debugger,
857
+ threaded=with_threads,
858
+ ssl_context=cert,
859
+ extra_files=extra_files,
860
+ exclude_patterns=exclude_patterns,
861
+ )
862
+
863
+
864
+ @click.command("shell", short_help="Run a shell in the app context.")
865
+ @with_appcontext
866
+ def shell_command() -> None:
867
+ """Run an interactive Python shell in the context of a given
868
+ Flask application. The application will populate the default
869
+ namespace of this shell according to its configuration.
870
+
871
+ This is useful for executing small snippets of management code
872
+ without having to manually configure the application.
873
+ """
874
+ import code
875
+ from .globals import _app_ctx_stack
876
+
877
+ app = _app_ctx_stack.top.app
878
+ banner = (
879
+ f"Python {sys.version} on {sys.platform}\n"
880
+ f"App: {app.import_name} [{app.env}]\n"
881
+ f"Instance: {app.instance_path}"
882
+ )
883
+ ctx: dict = {}
884
+
885
+ # Support the regular Python interpreter startup script if someone
886
+ # is using it.
887
+ startup = os.environ.get("PYTHONSTARTUP")
888
+ if startup and os.path.isfile(startup):
889
+ with open(startup) as f:
890
+ eval(compile(f.read(), startup, "exec"), ctx)
891
+
892
+ ctx.update(app.make_shell_context())
893
+
894
+ # Site, customize, or startup script can set a hook to call when
895
+ # entering interactive mode. The default one sets up readline with
896
+ # tab and history completion.
897
+ interactive_hook = getattr(sys, "__interactivehook__", None)
898
+
899
+ if interactive_hook is not None:
900
+ try:
901
+ import readline
902
+ from rlcompleter import Completer
903
+ except ImportError:
904
+ pass
905
+ else:
906
+ # rlcompleter uses __main__.__dict__ by default, which is
907
+ # flask.__main__. Use the shell context instead.
908
+ readline.set_completer(Completer(ctx).complete)
909
+
910
+ interactive_hook()
911
+
912
+ code.interact(banner=banner, local=ctx)
913
+
914
+
915
+ @click.command("routes", short_help="Show the routes for the app.")
916
+ @click.option(
917
+ "--sort",
918
+ "-s",
919
+ type=click.Choice(("endpoint", "methods", "rule", "match")),
920
+ default="endpoint",
921
+ help=(
922
+ 'Method to sort routes by. "match" is the order that Flask will match '
923
+ "routes when dispatching a request."
924
+ ),
925
+ )
926
+ @click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")
927
+ @with_appcontext
928
+ def routes_command(sort: str, all_methods: bool) -> None:
929
+ """Show all registered routes with endpoints and methods."""
930
+
931
+ rules = list(current_app.url_map.iter_rules())
932
+ if not rules:
933
+ click.echo("No routes were registered.")
934
+ return
935
+
936
+ ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))
937
+
938
+ if sort in ("endpoint", "rule"):
939
+ rules = sorted(rules, key=attrgetter(sort))
940
+ elif sort == "methods":
941
+ rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore
942
+
943
+ rule_methods = [
944
+ ", ".join(sorted(rule.methods - ignored_methods)) # type: ignore
945
+ for rule in rules
946
+ ]
947
+
948
+ headers = ("Endpoint", "Methods", "Rule")
949
+ widths = (
950
+ max(len(rule.endpoint) for rule in rules),
951
+ max(len(methods) for methods in rule_methods),
952
+ max(len(rule.rule) for rule in rules),
953
+ )
954
+ widths = [max(len(h), w) for h, w in zip(headers, widths)]
955
+ row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)
956
+
957
+ click.echo(row.format(*headers).strip())
958
+ click.echo(row.format(*("-" * width for width in widths)))
959
+
960
+ for rule, methods in zip(rules, rule_methods):
961
+ click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())
962
+
963
+
964
+ cli = FlaskGroup(
965
+ help="""\
966
+ A general utility script for Flask applications.
967
+
968
+ Provides commands from Flask, extensions, and the application. Loads the
969
+ application defined in the FLASK_APP environment variable, or from a wsgi.py
970
+ file. Setting the FLASK_ENV environment variable to 'development' will enable
971
+ debug mode.
972
+
973
+ \b
974
+ {prefix}{cmd} FLASK_APP=hello.py
975
+ {prefix}{cmd} FLASK_ENV=development
976
+ {prefix}flask run
977
+ """.format(
978
+ cmd="export" if os.name == "posix" else "set",
979
+ prefix="$ " if os.name == "posix" else "> ",
980
+ )
981
+ )
982
+
983
+
984
+ def main() -> None:
985
+ cli.main()
986
+
987
+
988
+ if __name__ == "__main__":
989
+ main()
testbed/pallets__flask/src/flask/config.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import errno
2
+ import os
3
+ import types
4
+ import typing as t
5
+
6
+ from werkzeug.utils import import_string
7
+
8
+
9
+ class ConfigAttribute:
10
+ """Makes an attribute forward to the config"""
11
+
12
+ def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:
13
+ self.__name__ = name
14
+ self.get_converter = get_converter
15
+
16
+ def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any:
17
+ if obj is None:
18
+ return self
19
+ rv = obj.config[self.__name__]
20
+ if self.get_converter is not None:
21
+ rv = self.get_converter(rv)
22
+ return rv
23
+
24
+ def __set__(self, obj: t.Any, value: t.Any) -> None:
25
+ obj.config[self.__name__] = value
26
+
27
+
28
+ class Config(dict):
29
+ """Works exactly like a dict but provides ways to fill it from files
30
+ or special dictionaries. There are two common patterns to populate the
31
+ config.
32
+
33
+ Either you can fill the config from a config file::
34
+
35
+ app.config.from_pyfile('yourconfig.cfg')
36
+
37
+ Or alternatively you can define the configuration options in the
38
+ module that calls :meth:`from_object` or provide an import path to
39
+ a module that should be loaded. It is also possible to tell it to
40
+ use the same module and with that provide the configuration values
41
+ just before the call::
42
+
43
+ DEBUG = True
44
+ SECRET_KEY = 'development key'
45
+ app.config.from_object(__name__)
46
+
47
+ In both cases (loading from any Python file or loading from modules),
48
+ only uppercase keys are added to the config. This makes it possible to use
49
+ lowercase values in the config file for temporary values that are not added
50
+ to the config or to define the config keys in the same file that implements
51
+ the application.
52
+
53
+ Probably the most interesting way to load configurations is from an
54
+ environment variable pointing to a file::
55
+
56
+ app.config.from_envvar('YOURAPPLICATION_SETTINGS')
57
+
58
+ In this case before launching the application you have to set this
59
+ environment variable to the file you want to use. On Linux and OS X
60
+ use the export statement::
61
+
62
+ export YOURAPPLICATION_SETTINGS='/path/to/config/file'
63
+
64
+ On windows use `set` instead.
65
+
66
+ :param root_path: path to which files are read relative from. When the
67
+ config object is created by the application, this is
68
+ the application's :attr:`~flask.Flask.root_path`.
69
+ :param defaults: an optional dictionary of default values
70
+ """
71
+
72
+ def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:
73
+ dict.__init__(self, defaults or {})
74
+ self.root_path = root_path
75
+
76
+ def from_envvar(self, variable_name: str, silent: bool = False) -> bool:
77
+ """Loads a configuration from an environment variable pointing to
78
+ a configuration file. This is basically just a shortcut with nicer
79
+ error messages for this line of code::
80
+
81
+ app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
82
+
83
+ :param variable_name: name of the environment variable
84
+ :param silent: set to ``True`` if you want silent failure for missing
85
+ files.
86
+ :return: ``True`` if the file was loaded successfully.
87
+ """
88
+ rv = os.environ.get(variable_name)
89
+ if not rv:
90
+ if silent:
91
+ return False
92
+ raise RuntimeError(
93
+ f"The environment variable {variable_name!r} is not set"
94
+ " and as such configuration could not be loaded. Set"
95
+ " this variable and make it point to a configuration"
96
+ " file"
97
+ )
98
+ return self.from_pyfile(rv, silent=silent)
99
+
100
+ def from_pyfile(self, filename: str, silent: bool = False) -> bool:
101
+ """Updates the values in the config from a Python file. This function
102
+ behaves as if the file was imported as module with the
103
+ :meth:`from_object` function.
104
+
105
+ :param filename: the filename of the config. This can either be an
106
+ absolute filename or a filename relative to the
107
+ root path.
108
+ :param silent: set to ``True`` if you want silent failure for missing
109
+ files.
110
+ :return: ``True`` if the file was loaded successfully.
111
+
112
+ .. versionadded:: 0.7
113
+ `silent` parameter.
114
+ """
115
+ filename = os.path.join(self.root_path, filename)
116
+ d = types.ModuleType("config")
117
+ d.__file__ = filename
118
+ try:
119
+ with open(filename, mode="rb") as config_file:
120
+ exec(compile(config_file.read(), filename, "exec"), d.__dict__)
121
+ except OSError as e:
122
+ if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
123
+ return False
124
+ e.strerror = f"Unable to load configuration file ({e.strerror})"
125
+ raise
126
+ self.from_object(d)
127
+ return True
128
+
129
+ def from_object(self, obj: t.Union[object, str]) -> None:
130
+ """Updates the values from the given object. An object can be of one
131
+ of the following two types:
132
+
133
+ - a string: in this case the object with that name will be imported
134
+ - an actual object reference: that object is used directly
135
+
136
+ Objects are usually either modules or classes. :meth:`from_object`
137
+ loads only the uppercase attributes of the module/class. A ``dict``
138
+ object will not work with :meth:`from_object` because the keys of a
139
+ ``dict`` are not attributes of the ``dict`` class.
140
+
141
+ Example of module-based configuration::
142
+
143
+ app.config.from_object('yourapplication.default_config')
144
+ from yourapplication import default_config
145
+ app.config.from_object(default_config)
146
+
147
+ Nothing is done to the object before loading. If the object is a
148
+ class and has ``@property`` attributes, it needs to be
149
+ instantiated before being passed to this method.
150
+
151
+ You should not use this function to load the actual configuration but
152
+ rather configuration defaults. The actual config should be loaded
153
+ with :meth:`from_pyfile` and ideally from a location not within the
154
+ package because the package might be installed system wide.
155
+
156
+ See :ref:`config-dev-prod` for an example of class-based configuration
157
+ using :meth:`from_object`.
158
+
159
+ :param obj: an import name or object
160
+ """
161
+ if isinstance(obj, str):
162
+ obj = import_string(obj)
163
+ for key in dir(obj):
164
+ if key.isupper():
165
+ self[key] = getattr(obj, key)
166
+
167
+ def from_file(
168
+ self,
169
+ filename: str,
170
+ load: t.Callable[[t.IO[t.Any]], t.Mapping],
171
+ silent: bool = False,
172
+ ) -> bool:
173
+ """Update the values in the config from a file that is loaded
174
+ using the ``load`` parameter. The loaded data is passed to the
175
+ :meth:`from_mapping` method.
176
+
177
+ .. code-block:: python
178
+
179
+ import json
180
+ app.config.from_file("config.json", load=json.load)
181
+
182
+ import toml
183
+ app.config.from_file("config.toml", load=toml.load)
184
+
185
+ :param filename: The path to the data file. This can be an
186
+ absolute path or relative to the config root path.
187
+ :param load: A callable that takes a file handle and returns a
188
+ mapping of loaded data from the file.
189
+ :type load: ``Callable[[Reader], Mapping]`` where ``Reader``
190
+ implements a ``read`` method.
191
+ :param silent: Ignore the file if it doesn't exist.
192
+ :return: ``True`` if the file was loaded successfully.
193
+
194
+ .. versionadded:: 2.0
195
+ """
196
+ filename = os.path.join(self.root_path, filename)
197
+
198
+ try:
199
+ with open(filename) as f:
200
+ obj = load(f)
201
+ except OSError as e:
202
+ if silent and e.errno in (errno.ENOENT, errno.EISDIR):
203
+ return False
204
+
205
+ e.strerror = f"Unable to load configuration file ({e.strerror})"
206
+ raise
207
+
208
+ return self.from_mapping(obj)
209
+
210
+ def from_mapping(
211
+ self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any
212
+ ) -> bool:
213
+ """Updates the config like :meth:`update` ignoring items with non-upper
214
+ keys.
215
+ :return: Always returns ``True``.
216
+
217
+ .. versionadded:: 0.11
218
+ """
219
+ mappings: t.Dict[str, t.Any] = {}
220
+ if mapping is not None:
221
+ mappings.update(mapping)
222
+ mappings.update(kwargs)
223
+ for key, value in mappings.items():
224
+ if key.isupper():
225
+ self[key] = value
226
+ return True
227
+
228
+ def get_namespace(
229
+ self, namespace: str, lowercase: bool = True, trim_namespace: bool = True
230
+ ) -> t.Dict[str, t.Any]:
231
+ """Returns a dictionary containing a subset of configuration options
232
+ that match the specified namespace/prefix. Example usage::
233
+
234
+ app.config['IMAGE_STORE_TYPE'] = 'fs'
235
+ app.config['IMAGE_STORE_PATH'] = '/var/app/images'
236
+ app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
237
+ image_store_config = app.config.get_namespace('IMAGE_STORE_')
238
+
239
+ The resulting dictionary `image_store_config` would look like::
240
+
241
+ {
242
+ 'type': 'fs',
243
+ 'path': '/var/app/images',
244
+ 'base_url': 'http://img.website.com'
245
+ }
246
+
247
+ This is often useful when configuration options map directly to
248
+ keyword arguments in functions or class constructors.
249
+
250
+ :param namespace: a configuration namespace
251
+ :param lowercase: a flag indicating if the keys of the resulting
252
+ dictionary should be lowercase
253
+ :param trim_namespace: a flag indicating if the keys of the resulting
254
+ dictionary should not include the namespace
255
+
256
+ .. versionadded:: 0.11
257
+ """
258
+ rv = {}
259
+ for k, v in self.items():
260
+ if not k.startswith(namespace):
261
+ continue
262
+ if trim_namespace:
263
+ key = k[len(namespace) :]
264
+ else:
265
+ key = k
266
+ if lowercase:
267
+ key = key.lower()
268
+ rv[key] = v
269
+ return rv
270
+
271
+ def __repr__(self) -> str:
272
+ return f"<{type(self).__name__} {dict.__repr__(self)}>"
testbed/pallets__flask/src/flask/ctx.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import typing as t
3
+ from functools import update_wrapper
4
+ from types import TracebackType
5
+
6
+ from werkzeug.exceptions import HTTPException
7
+
8
+ from .globals import _app_ctx_stack
9
+ from .globals import _request_ctx_stack
10
+ from .signals import appcontext_popped
11
+ from .signals import appcontext_pushed
12
+ from .typing import AfterRequestCallable
13
+
14
+ if t.TYPE_CHECKING:
15
+ from .app import Flask
16
+ from .sessions import SessionMixin
17
+ from .wrappers import Request
18
+
19
+
20
+ # a singleton sentinel value for parameter defaults
21
+ _sentinel = object()
22
+
23
+
24
+ class _AppCtxGlobals:
25
+ """A plain object. Used as a namespace for storing data during an
26
+ application context.
27
+
28
+ Creating an app context automatically creates this object, which is
29
+ made available as the :data:`g` proxy.
30
+
31
+ .. describe:: 'key' in g
32
+
33
+ Check whether an attribute is present.
34
+
35
+ .. versionadded:: 0.10
36
+
37
+ .. describe:: iter(g)
38
+
39
+ Return an iterator over the attribute names.
40
+
41
+ .. versionadded:: 0.10
42
+ """
43
+
44
+ # Define attr methods to let mypy know this is a namespace object
45
+ # that has arbitrary attributes.
46
+
47
+ def __getattr__(self, name: str) -> t.Any:
48
+ try:
49
+ return self.__dict__[name]
50
+ except KeyError:
51
+ raise AttributeError(name) from None
52
+
53
+ def __setattr__(self, name: str, value: t.Any) -> None:
54
+ self.__dict__[name] = value
55
+
56
+ def __delattr__(self, name: str) -> None:
57
+ try:
58
+ del self.__dict__[name]
59
+ except KeyError:
60
+ raise AttributeError(name) from None
61
+
62
+ def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any:
63
+ """Get an attribute by name, or a default value. Like
64
+ :meth:`dict.get`.
65
+
66
+ :param name: Name of attribute to get.
67
+ :param default: Value to return if the attribute is not present.
68
+
69
+ .. versionadded:: 0.10
70
+ """
71
+ return self.__dict__.get(name, default)
72
+
73
+ def pop(self, name: str, default: t.Any = _sentinel) -> t.Any:
74
+ """Get and remove an attribute by name. Like :meth:`dict.pop`.
75
+
76
+ :param name: Name of attribute to pop.
77
+ :param default: Value to return if the attribute is not present,
78
+ instead of raising a ``KeyError``.
79
+
80
+ .. versionadded:: 0.11
81
+ """
82
+ if default is _sentinel:
83
+ return self.__dict__.pop(name)
84
+ else:
85
+ return self.__dict__.pop(name, default)
86
+
87
+ def setdefault(self, name: str, default: t.Any = None) -> t.Any:
88
+ """Get the value of an attribute if it is present, otherwise
89
+ set and return a default value. Like :meth:`dict.setdefault`.
90
+
91
+ :param name: Name of attribute to get.
92
+ :param default: Value to set and return if the attribute is not
93
+ present.
94
+
95
+ .. versionadded:: 0.11
96
+ """
97
+ return self.__dict__.setdefault(name, default)
98
+
99
+ def __contains__(self, item: str) -> bool:
100
+ return item in self.__dict__
101
+
102
+ def __iter__(self) -> t.Iterator[str]:
103
+ return iter(self.__dict__)
104
+
105
+ def __repr__(self) -> str:
106
+ top = _app_ctx_stack.top
107
+ if top is not None:
108
+ return f"<flask.g of {top.app.name!r}>"
109
+ return object.__repr__(self)
110
+
111
+
112
+ def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable:
113
+ """Executes a function after this request. This is useful to modify
114
+ response objects. The function is passed the response object and has
115
+ to return the same or a new one.
116
+
117
+ Example::
118
+
119
+ @app.route('/')
120
+ def index():
121
+ @after_this_request
122
+ def add_header(response):
123
+ response.headers['X-Foo'] = 'Parachute'
124
+ return response
125
+ return 'Hello World!'
126
+
127
+ This is more useful if a function other than the view function wants to
128
+ modify a response. For instance think of a decorator that wants to add
129
+ some headers without converting the return value into a response object.
130
+
131
+ .. versionadded:: 0.9
132
+ """
133
+ top = _request_ctx_stack.top
134
+
135
+ if top is None:
136
+ raise RuntimeError(
137
+ "This decorator can only be used when a request context is"
138
+ " active, such as within a view function."
139
+ )
140
+
141
+ top._after_request_functions.append(f)
142
+ return f
143
+
144
+
145
+ def copy_current_request_context(f: t.Callable) -> t.Callable:
146
+ """A helper function that decorates a function to retain the current
147
+ request context. This is useful when working with greenlets. The moment
148
+ the function is decorated a copy of the request context is created and
149
+ then pushed when the function is called. The current session is also
150
+ included in the copied request context.
151
+
152
+ Example::
153
+
154
+ import gevent
155
+ from flask import copy_current_request_context
156
+
157
+ @app.route('/')
158
+ def index():
159
+ @copy_current_request_context
160
+ def do_some_work():
161
+ # do some work here, it can access flask.request or
162
+ # flask.session like you would otherwise in the view function.
163
+ ...
164
+ gevent.spawn(do_some_work)
165
+ return 'Regular response'
166
+
167
+ .. versionadded:: 0.10
168
+ """
169
+ top = _request_ctx_stack.top
170
+
171
+ if top is None:
172
+ raise RuntimeError(
173
+ "This decorator can only be used when a request context is"
174
+ " active, such as within a view function."
175
+ )
176
+
177
+ reqctx = top.copy()
178
+
179
+ def wrapper(*args, **kwargs):
180
+ with reqctx:
181
+ return reqctx.app.ensure_sync(f)(*args, **kwargs)
182
+
183
+ return update_wrapper(wrapper, f)
184
+
185
+
186
+ def has_request_context() -> bool:
187
+ """If you have code that wants to test if a request context is there or
188
+ not this function can be used. For instance, you may want to take advantage
189
+ of request information if the request object is available, but fail
190
+ silently if it is unavailable.
191
+
192
+ ::
193
+
194
+ class User(db.Model):
195
+
196
+ def __init__(self, username, remote_addr=None):
197
+ self.username = username
198
+ if remote_addr is None and has_request_context():
199
+ remote_addr = request.remote_addr
200
+ self.remote_addr = remote_addr
201
+
202
+ Alternatively you can also just test any of the context bound objects
203
+ (such as :class:`request` or :class:`g`) for truthness::
204
+
205
+ class User(db.Model):
206
+
207
+ def __init__(self, username, remote_addr=None):
208
+ self.username = username
209
+ if remote_addr is None and request:
210
+ remote_addr = request.remote_addr
211
+ self.remote_addr = remote_addr
212
+
213
+ .. versionadded:: 0.7
214
+ """
215
+ return _request_ctx_stack.top is not None
216
+
217
+
218
+ def has_app_context() -> bool:
219
+ """Works like :func:`has_request_context` but for the application
220
+ context. You can also just do a boolean check on the
221
+ :data:`current_app` object instead.
222
+
223
+ .. versionadded:: 0.9
224
+ """
225
+ return _app_ctx_stack.top is not None
226
+
227
+
228
+ class AppContext:
229
+ """The application context binds an application object implicitly
230
+ to the current thread or greenlet, similar to how the
231
+ :class:`RequestContext` binds request information. The application
232
+ context is also implicitly created if a request context is created
233
+ but the application is not on top of the individual application
234
+ context.
235
+ """
236
+
237
+ def __init__(self, app: "Flask") -> None:
238
+ self.app = app
239
+ self.url_adapter = app.create_url_adapter(None)
240
+ self.g = app.app_ctx_globals_class()
241
+
242
+ # Like request context, app contexts can be pushed multiple times
243
+ # but there a basic "refcount" is enough to track them.
244
+ self._refcnt = 0
245
+
246
+ def push(self) -> None:
247
+ """Binds the app context to the current context."""
248
+ self._refcnt += 1
249
+ _app_ctx_stack.push(self)
250
+ appcontext_pushed.send(self.app)
251
+
252
+ def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore
253
+ """Pops the app context."""
254
+ try:
255
+ self._refcnt -= 1
256
+ if self._refcnt <= 0:
257
+ if exc is _sentinel:
258
+ exc = sys.exc_info()[1]
259
+ self.app.do_teardown_appcontext(exc)
260
+ finally:
261
+ rv = _app_ctx_stack.pop()
262
+ assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"
263
+ appcontext_popped.send(self.app)
264
+
265
+ def __enter__(self) -> "AppContext":
266
+ self.push()
267
+ return self
268
+
269
+ def __exit__(
270
+ self,
271
+ exc_type: t.Optional[type],
272
+ exc_value: t.Optional[BaseException],
273
+ tb: t.Optional[TracebackType],
274
+ ) -> None:
275
+ self.pop(exc_value)
276
+
277
+
278
+ class RequestContext:
279
+ """The request context contains all request relevant information. It is
280
+ created at the beginning of the request and pushed to the
281
+ `_request_ctx_stack` and removed at the end of it. It will create the
282
+ URL adapter and request object for the WSGI environment provided.
283
+
284
+ Do not attempt to use this class directly, instead use
285
+ :meth:`~flask.Flask.test_request_context` and
286
+ :meth:`~flask.Flask.request_context` to create this object.
287
+
288
+ When the request context is popped, it will evaluate all the
289
+ functions registered on the application for teardown execution
290
+ (:meth:`~flask.Flask.teardown_request`).
291
+
292
+ The request context is automatically popped at the end of the request
293
+ for you. In debug mode the request context is kept around if
294
+ exceptions happen so that interactive debuggers have a chance to
295
+ introspect the data. With 0.4 this can also be forced for requests
296
+ that did not fail and outside of ``DEBUG`` mode. By setting
297
+ ``'flask._preserve_context'`` to ``True`` on the WSGI environment the
298
+ context will not pop itself at the end of the request. This is used by
299
+ the :meth:`~flask.Flask.test_client` for example to implement the
300
+ deferred cleanup functionality.
301
+
302
+ You might find this helpful for unittests where you need the
303
+ information from the context local around for a little longer. Make
304
+ sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in
305
+ that situation, otherwise your unittests will leak memory.
306
+ """
307
+
308
+ def __init__(
309
+ self,
310
+ app: "Flask",
311
+ environ: dict,
312
+ request: t.Optional["Request"] = None,
313
+ session: t.Optional["SessionMixin"] = None,
314
+ ) -> None:
315
+ self.app = app
316
+ if request is None:
317
+ request = app.request_class(environ)
318
+ self.request = request
319
+ self.url_adapter = None
320
+ try:
321
+ self.url_adapter = app.create_url_adapter(self.request)
322
+ except HTTPException as e:
323
+ self.request.routing_exception = e
324
+ self.flashes = None
325
+ self.session = session
326
+
327
+ # Request contexts can be pushed multiple times and interleaved with
328
+ # other request contexts. Now only if the last level is popped we
329
+ # get rid of them. Additionally if an application context is missing
330
+ # one is created implicitly so for each level we add this information
331
+ self._implicit_app_ctx_stack: t.List[t.Optional["AppContext"]] = []
332
+
333
+ # indicator if the context was preserved. Next time another context
334
+ # is pushed the preserved context is popped.
335
+ self.preserved = False
336
+
337
+ # remembers the exception for pop if there is one in case the context
338
+ # preservation kicks in.
339
+ self._preserved_exc = None
340
+
341
+ # Functions that should be executed after the request on the response
342
+ # object. These will be called before the regular "after_request"
343
+ # functions.
344
+ self._after_request_functions: t.List[AfterRequestCallable] = []
345
+
346
+ @property
347
+ def g(self) -> _AppCtxGlobals:
348
+ import warnings
349
+
350
+ warnings.warn(
351
+ "Accessing 'g' on the request context is deprecated and"
352
+ " will be removed in Flask 2.2. Access `g` directly or from"
353
+ "the application context instead.",
354
+ DeprecationWarning,
355
+ stacklevel=2,
356
+ )
357
+ return _app_ctx_stack.top.g
358
+
359
+ @g.setter
360
+ def g(self, value: _AppCtxGlobals) -> None:
361
+ import warnings
362
+
363
+ warnings.warn(
364
+ "Setting 'g' on the request context is deprecated and"
365
+ " will be removed in Flask 2.2. Set it on the application"
366
+ " context instead.",
367
+ DeprecationWarning,
368
+ stacklevel=2,
369
+ )
370
+ _app_ctx_stack.top.g = value
371
+
372
+ def copy(self) -> "RequestContext":
373
+ """Creates a copy of this request context with the same request object.
374
+ This can be used to move a request context to a different greenlet.
375
+ Because the actual request object is the same this cannot be used to
376
+ move a request context to a different thread unless access to the
377
+ request object is locked.
378
+
379
+ .. versionadded:: 0.10
380
+
381
+ .. versionchanged:: 1.1
382
+ The current session object is used instead of reloading the original
383
+ data. This prevents `flask.session` pointing to an out-of-date object.
384
+ """
385
+ return self.__class__(
386
+ self.app,
387
+ environ=self.request.environ,
388
+ request=self.request,
389
+ session=self.session,
390
+ )
391
+
392
+ def match_request(self) -> None:
393
+ """Can be overridden by a subclass to hook into the matching
394
+ of the request.
395
+ """
396
+ try:
397
+ result = self.url_adapter.match(return_rule=True) # type: ignore
398
+ self.request.url_rule, self.request.view_args = result # type: ignore
399
+ except HTTPException as e:
400
+ self.request.routing_exception = e
401
+
402
+ def push(self) -> None:
403
+ """Binds the request context to the current context."""
404
+ # If an exception occurs in debug mode or if context preservation is
405
+ # activated under exception situations exactly one context stays
406
+ # on the stack. The rationale is that you want to access that
407
+ # information under debug situations. However if someone forgets to
408
+ # pop that context again we want to make sure that on the next push
409
+ # it's invalidated, otherwise we run at risk that something leaks
410
+ # memory. This is usually only a problem in test suite since this
411
+ # functionality is not active in production environments.
412
+ top = _request_ctx_stack.top
413
+ if top is not None and top.preserved:
414
+ top.pop(top._preserved_exc)
415
+
416
+ # Before we push the request context we have to ensure that there
417
+ # is an application context.
418
+ app_ctx = _app_ctx_stack.top
419
+ if app_ctx is None or app_ctx.app != self.app:
420
+ app_ctx = self.app.app_context()
421
+ app_ctx.push()
422
+ self._implicit_app_ctx_stack.append(app_ctx)
423
+ else:
424
+ self._implicit_app_ctx_stack.append(None)
425
+
426
+ _request_ctx_stack.push(self)
427
+
428
+ # Open the session at the moment that the request context is available.
429
+ # This allows a custom open_session method to use the request context.
430
+ # Only open a new session if this is the first time the request was
431
+ # pushed, otherwise stream_with_context loses the session.
432
+ if self.session is None:
433
+ session_interface = self.app.session_interface
434
+ self.session = session_interface.open_session(self.app, self.request)
435
+
436
+ if self.session is None:
437
+ self.session = session_interface.make_null_session(self.app)
438
+
439
+ # Match the request URL after loading the session, so that the
440
+ # session is available in custom URL converters.
441
+ if self.url_adapter is not None:
442
+ self.match_request()
443
+
444
+ def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore
445
+ """Pops the request context and unbinds it by doing that. This will
446
+ also trigger the execution of functions registered by the
447
+ :meth:`~flask.Flask.teardown_request` decorator.
448
+
449
+ .. versionchanged:: 0.9
450
+ Added the `exc` argument.
451
+ """
452
+ app_ctx = self._implicit_app_ctx_stack.pop()
453
+ clear_request = False
454
+
455
+ try:
456
+ if not self._implicit_app_ctx_stack:
457
+ self.preserved = False
458
+ self._preserved_exc = None
459
+ if exc is _sentinel:
460
+ exc = sys.exc_info()[1]
461
+ self.app.do_teardown_request(exc)
462
+
463
+ request_close = getattr(self.request, "close", None)
464
+ if request_close is not None:
465
+ request_close()
466
+ clear_request = True
467
+ finally:
468
+ rv = _request_ctx_stack.pop()
469
+
470
+ # get rid of circular dependencies at the end of the request
471
+ # so that we don't require the GC to be active.
472
+ if clear_request:
473
+ rv.request.environ["werkzeug.request"] = None
474
+
475
+ # Get rid of the app as well if necessary.
476
+ if app_ctx is not None:
477
+ app_ctx.pop(exc)
478
+
479
+ assert (
480
+ rv is self
481
+ ), f"Popped wrong request context. ({rv!r} instead of {self!r})"
482
+
483
+ def auto_pop(self, exc: t.Optional[BaseException]) -> None:
484
+ if self.request.environ.get("flask._preserve_context") or (
485
+ exc is not None and self.app.preserve_context_on_exception
486
+ ):
487
+ self.preserved = True
488
+ self._preserved_exc = exc # type: ignore
489
+ else:
490
+ self.pop(exc)
491
+
492
+ def __enter__(self) -> "RequestContext":
493
+ self.push()
494
+ return self
495
+
496
+ def __exit__(
497
+ self,
498
+ exc_type: t.Optional[type],
499
+ exc_value: t.Optional[BaseException],
500
+ tb: t.Optional[TracebackType],
501
+ ) -> None:
502
+ # do not pop the request stack if we are in debug mode and an
503
+ # exception happened. This will allow the debugger to still
504
+ # access the request object in the interactive shell. Furthermore
505
+ # the context can be force kept alive for the test client.
506
+ # See flask.testing for how this works.
507
+ self.auto_pop(exc_value)
508
+
509
+ def __repr__(self) -> str:
510
+ return (
511
+ f"<{type(self).__name__} {self.request.url!r}"
512
+ f" [{self.request.method}] of {self.app.name}>"
513
+ )
testbed/pallets__flask/src/flask/debughelpers.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import typing as t
3
+ from warnings import warn
4
+
5
+ from .app import Flask
6
+ from .blueprints import Blueprint
7
+ from .globals import _request_ctx_stack
8
+
9
+
10
+ class UnexpectedUnicodeError(AssertionError, UnicodeError):
11
+ """Raised in places where we want some better error reporting for
12
+ unexpected unicode or binary data.
13
+ """
14
+
15
+
16
+ class DebugFilesKeyError(KeyError, AssertionError):
17
+ """Raised from request.files during debugging. The idea is that it can
18
+ provide a better error message than just a generic KeyError/BadRequest.
19
+ """
20
+
21
+ def __init__(self, request, key):
22
+ form_matches = request.form.getlist(key)
23
+ buf = [
24
+ f"You tried to access the file {key!r} in the request.files"
25
+ " dictionary but it does not exist. The mimetype for the"
26
+ f" request is {request.mimetype!r} instead of"
27
+ " 'multipart/form-data' which means that no file contents"
28
+ " were transmitted. To fix this error you should provide"
29
+ ' enctype="multipart/form-data" in your form.'
30
+ ]
31
+ if form_matches:
32
+ names = ", ".join(repr(x) for x in form_matches)
33
+ buf.append(
34
+ "\n\nThe browser instead transmitted some file names. "
35
+ f"This was submitted: {names}"
36
+ )
37
+ self.msg = "".join(buf)
38
+
39
+ def __str__(self):
40
+ return self.msg
41
+
42
+
43
+ class FormDataRoutingRedirect(AssertionError):
44
+ """This exception is raised in debug mode if a routing redirect
45
+ would cause the browser to drop the method or body. This happens
46
+ when method is not GET, HEAD or OPTIONS and the status code is not
47
+ 307 or 308.
48
+ """
49
+
50
+ def __init__(self, request):
51
+ exc = request.routing_exception
52
+ buf = [
53
+ f"A request was sent to '{request.url}', but routing issued"
54
+ f" a redirect to the canonical URL '{exc.new_url}'."
55
+ ]
56
+
57
+ if f"{request.base_url}/" == exc.new_url.partition("?")[0]:
58
+ buf.append(
59
+ " The URL was defined with a trailing slash. Flask"
60
+ " will redirect to the URL with a trailing slash if it"
61
+ " was accessed without one."
62
+ )
63
+
64
+ buf.append(
65
+ " Send requests to the canonical URL, or use 307 or 308 for"
66
+ " routing redirects. Otherwise, browsers will drop form"
67
+ " data.\n\n"
68
+ "This exception is only raised in debug mode."
69
+ )
70
+ super().__init__("".join(buf))
71
+
72
+
73
+ def attach_enctype_error_multidict(request):
74
+ """Patch ``request.files.__getitem__`` to raise a descriptive error
75
+ about ``enctype=multipart/form-data``.
76
+
77
+ :param request: The request to patch.
78
+ :meta private:
79
+ """
80
+ oldcls = request.files.__class__
81
+
82
+ class newcls(oldcls):
83
+ def __getitem__(self, key):
84
+ try:
85
+ return super().__getitem__(key)
86
+ except KeyError as e:
87
+ if key not in request.form:
88
+ raise
89
+
90
+ raise DebugFilesKeyError(request, key).with_traceback(
91
+ e.__traceback__
92
+ ) from None
93
+
94
+ newcls.__name__ = oldcls.__name__
95
+ newcls.__module__ = oldcls.__module__
96
+ request.files.__class__ = newcls
97
+
98
+
99
+ def _dump_loader_info(loader) -> t.Generator:
100
+ yield f"class: {type(loader).__module__}.{type(loader).__name__}"
101
+ for key, value in sorted(loader.__dict__.items()):
102
+ if key.startswith("_"):
103
+ continue
104
+ if isinstance(value, (tuple, list)):
105
+ if not all(isinstance(x, str) for x in value):
106
+ continue
107
+ yield f"{key}:"
108
+ for item in value:
109
+ yield f" - {item}"
110
+ continue
111
+ elif not isinstance(value, (str, int, float, bool)):
112
+ continue
113
+ yield f"{key}: {value!r}"
114
+
115
+
116
+ def explain_template_loading_attempts(app: Flask, template, attempts) -> None:
117
+ """This should help developers understand what failed"""
118
+ info = [f"Locating template {template!r}:"]
119
+ total_found = 0
120
+ blueprint = None
121
+ reqctx = _request_ctx_stack.top
122
+ if reqctx is not None and reqctx.request.blueprint is not None:
123
+ blueprint = reqctx.request.blueprint
124
+
125
+ for idx, (loader, srcobj, triple) in enumerate(attempts):
126
+ if isinstance(srcobj, Flask):
127
+ src_info = f"application {srcobj.import_name!r}"
128
+ elif isinstance(srcobj, Blueprint):
129
+ src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"
130
+ else:
131
+ src_info = repr(srcobj)
132
+
133
+ info.append(f"{idx + 1:5}: trying loader of {src_info}")
134
+
135
+ for line in _dump_loader_info(loader):
136
+ info.append(f" {line}")
137
+
138
+ if triple is None:
139
+ detail = "no match"
140
+ else:
141
+ detail = f"found ({triple[1] or '<string>'!r})"
142
+ total_found += 1
143
+ info.append(f" -> {detail}")
144
+
145
+ seems_fishy = False
146
+ if total_found == 0:
147
+ info.append("Error: the template could not be found.")
148
+ seems_fishy = True
149
+ elif total_found > 1:
150
+ info.append("Warning: multiple loaders returned a match for the template.")
151
+ seems_fishy = True
152
+
153
+ if blueprint is not None and seems_fishy:
154
+ info.append(
155
+ " The template was looked up from an endpoint that belongs"
156
+ f" to the blueprint {blueprint!r}."
157
+ )
158
+ info.append(" Maybe you did not place a template in the right folder?")
159
+ info.append(" See https://flask.palletsprojects.com/blueprints/#templates")
160
+
161
+ app.logger.info("\n".join(info))
162
+
163
+
164
+ def explain_ignored_app_run() -> None:
165
+ if os.environ.get("WERKZEUG_RUN_MAIN") != "true":
166
+ warn(
167
+ Warning(
168
+ "Silently ignoring app.run() because the application is"
169
+ " run from the flask command line executable. Consider"
170
+ ' putting app.run() behind an if __name__ == "__main__"'
171
+ " guard to silence this warning."
172
+ ),
173
+ stacklevel=3,
174
+ )
testbed/pallets__flask/src/flask/globals.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing as t
2
+ from functools import partial
3
+
4
+ from werkzeug.local import LocalProxy
5
+ from werkzeug.local import LocalStack
6
+
7
+ if t.TYPE_CHECKING:
8
+ from .app import Flask
9
+ from .ctx import _AppCtxGlobals
10
+ from .sessions import SessionMixin
11
+ from .wrappers import Request
12
+
13
+ _request_ctx_err_msg = """\
14
+ Working outside of request context.
15
+
16
+ This typically means that you attempted to use functionality that needed
17
+ an active HTTP request. Consult the documentation on testing for
18
+ information about how to avoid this problem.\
19
+ """
20
+ _app_ctx_err_msg = """\
21
+ Working outside of application context.
22
+
23
+ This typically means that you attempted to use functionality that needed
24
+ to interface with the current application object in some way. To solve
25
+ this, set up an application context with app.app_context(). See the
26
+ documentation for more information.\
27
+ """
28
+
29
+
30
+ def _lookup_req_object(name):
31
+ top = _request_ctx_stack.top
32
+ if top is None:
33
+ raise RuntimeError(_request_ctx_err_msg)
34
+ return getattr(top, name)
35
+
36
+
37
+ def _lookup_app_object(name):
38
+ top = _app_ctx_stack.top
39
+ if top is None:
40
+ raise RuntimeError(_app_ctx_err_msg)
41
+ return getattr(top, name)
42
+
43
+
44
+ def _find_app():
45
+ top = _app_ctx_stack.top
46
+ if top is None:
47
+ raise RuntimeError(_app_ctx_err_msg)
48
+ return top.app
49
+
50
+
51
+ # context locals
52
+ _request_ctx_stack = LocalStack()
53
+ _app_ctx_stack = LocalStack()
54
+ current_app: "Flask" = LocalProxy(_find_app) # type: ignore
55
+ request: "Request" = LocalProxy(partial(_lookup_req_object, "request")) # type: ignore
56
+ session: "SessionMixin" = LocalProxy( # type: ignore
57
+ partial(_lookup_req_object, "session")
58
+ )
59
+ g: "_AppCtxGlobals" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignore
testbed/pallets__flask/src/flask/helpers.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pkgutil
3
+ import socket
4
+ import sys
5
+ import typing as t
6
+ import warnings
7
+ from datetime import datetime
8
+ from functools import lru_cache
9
+ from functools import update_wrapper
10
+ from threading import RLock
11
+
12
+ import werkzeug.utils
13
+ from werkzeug.routing import BuildError
14
+ from werkzeug.urls import url_quote
15
+
16
+ from .globals import _app_ctx_stack
17
+ from .globals import _request_ctx_stack
18
+ from .globals import current_app
19
+ from .globals import request
20
+ from .globals import session
21
+ from .signals import message_flashed
22
+
23
+ if t.TYPE_CHECKING:
24
+ from .wrappers import Response
25
+
26
+
27
+ def get_env() -> str:
28
+ """Get the environment the app is running in, indicated by the
29
+ :envvar:`FLASK_ENV` environment variable. The default is
30
+ ``'production'``.
31
+ """
32
+ return os.environ.get("FLASK_ENV") or "production"
33
+
34
+
35
+ def get_debug_flag() -> bool:
36
+ """Get whether debug mode should be enabled for the app, indicated
37
+ by the :envvar:`FLASK_DEBUG` environment variable. The default is
38
+ ``True`` if :func:`.get_env` returns ``'development'``, or ``False``
39
+ otherwise.
40
+ """
41
+ val = os.environ.get("FLASK_DEBUG")
42
+
43
+ if not val:
44
+ return get_env() == "development"
45
+
46
+ return val.lower() not in ("0", "false", "no")
47
+
48
+
49
+ def get_load_dotenv(default: bool = True) -> bool:
50
+ """Get whether the user has disabled loading dotenv files by setting
51
+ :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the
52
+ files.
53
+
54
+ :param default: What to return if the env var isn't set.
55
+ """
56
+ val = os.environ.get("FLASK_SKIP_DOTENV")
57
+
58
+ if not val:
59
+ return default
60
+
61
+ return val.lower() in ("0", "false", "no")
62
+
63
+
64
+ def stream_with_context(
65
+ generator_or_function: t.Union[
66
+ t.Iterator[t.AnyStr], t.Callable[..., t.Iterator[t.AnyStr]]
67
+ ]
68
+ ) -> t.Iterator[t.AnyStr]:
69
+ """Request contexts disappear when the response is started on the server.
70
+ This is done for efficiency reasons and to make it less likely to encounter
71
+ memory leaks with badly written WSGI middlewares. The downside is that if
72
+ you are using streamed responses, the generator cannot access request bound
73
+ information any more.
74
+
75
+ This function however can help you keep the context around for longer::
76
+
77
+ from flask import stream_with_context, request, Response
78
+
79
+ @app.route('/stream')
80
+ def streamed_response():
81
+ @stream_with_context
82
+ def generate():
83
+ yield 'Hello '
84
+ yield request.args['name']
85
+ yield '!'
86
+ return Response(generate())
87
+
88
+ Alternatively it can also be used around a specific generator::
89
+
90
+ from flask import stream_with_context, request, Response
91
+
92
+ @app.route('/stream')
93
+ def streamed_response():
94
+ def generate():
95
+ yield 'Hello '
96
+ yield request.args['name']
97
+ yield '!'
98
+ return Response(stream_with_context(generate()))
99
+
100
+ .. versionadded:: 0.9
101
+ """
102
+ try:
103
+ gen = iter(generator_or_function) # type: ignore
104
+ except TypeError:
105
+
106
+ def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:
107
+ gen = generator_or_function(*args, **kwargs) # type: ignore
108
+ return stream_with_context(gen)
109
+
110
+ return update_wrapper(decorator, generator_or_function) # type: ignore
111
+
112
+ def generator() -> t.Generator:
113
+ ctx = _request_ctx_stack.top
114
+ if ctx is None:
115
+ raise RuntimeError(
116
+ "Attempted to stream with context but "
117
+ "there was no context in the first place to keep around."
118
+ )
119
+ with ctx:
120
+ # Dummy sentinel. Has to be inside the context block or we're
121
+ # not actually keeping the context around.
122
+ yield None
123
+
124
+ # The try/finally is here so that if someone passes a WSGI level
125
+ # iterator in we're still running the cleanup logic. Generators
126
+ # don't need that because they are closed on their destruction
127
+ # automatically.
128
+ try:
129
+ yield from gen
130
+ finally:
131
+ if hasattr(gen, "close"):
132
+ gen.close() # type: ignore
133
+
134
+ # The trick is to start the generator. Then the code execution runs until
135
+ # the first dummy None is yielded at which point the context was already
136
+ # pushed. This item is discarded. Then when the iteration continues the
137
+ # real generator is executed.
138
+ wrapped_g = generator()
139
+ next(wrapped_g)
140
+ return wrapped_g
141
+
142
+
143
+ def make_response(*args: t.Any) -> "Response":
144
+ """Sometimes it is necessary to set additional headers in a view. Because
145
+ views do not have to return response objects but can return a value that
146
+ is converted into a response object by Flask itself, it becomes tricky to
147
+ add headers to it. This function can be called instead of using a return
148
+ and you will get a response object which you can use to attach headers.
149
+
150
+ If view looked like this and you want to add a new header::
151
+
152
+ def index():
153
+ return render_template('index.html', foo=42)
154
+
155
+ You can now do something like this::
156
+
157
+ def index():
158
+ response = make_response(render_template('index.html', foo=42))
159
+ response.headers['X-Parachutes'] = 'parachutes are cool'
160
+ return response
161
+
162
+ This function accepts the very same arguments you can return from a
163
+ view function. This for example creates a response with a 404 error
164
+ code::
165
+
166
+ response = make_response(render_template('not_found.html'), 404)
167
+
168
+ The other use case of this function is to force the return value of a
169
+ view function into a response which is helpful with view
170
+ decorators::
171
+
172
+ response = make_response(view_function())
173
+ response.headers['X-Parachutes'] = 'parachutes are cool'
174
+
175
+ Internally this function does the following things:
176
+
177
+ - if no arguments are passed, it creates a new response argument
178
+ - if one argument is passed, :meth:`flask.Flask.make_response`
179
+ is invoked with it.
180
+ - if more than one argument is passed, the arguments are passed
181
+ to the :meth:`flask.Flask.make_response` function as tuple.
182
+
183
+ .. versionadded:: 0.6
184
+ """
185
+ if not args:
186
+ return current_app.response_class()
187
+ if len(args) == 1:
188
+ args = args[0]
189
+ return current_app.make_response(args) # type: ignore
190
+
191
+
192
+ def url_for(endpoint: str, **values: t.Any) -> str:
193
+ """Generates a URL to the given endpoint with the method provided.
194
+
195
+ Variable arguments that are unknown to the target endpoint are appended
196
+ to the generated URL as query arguments. If the value of a query argument
197
+ is ``None``, the whole pair is skipped. In case blueprints are active
198
+ you can shortcut references to the same blueprint by prefixing the
199
+ local endpoint with a dot (``.``).
200
+
201
+ This will reference the index function local to the current blueprint::
202
+
203
+ url_for('.index')
204
+
205
+ See :ref:`url-building`.
206
+
207
+ Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when
208
+ generating URLs outside of a request context.
209
+
210
+ To integrate applications, :class:`Flask` has a hook to intercept URL build
211
+ errors through :attr:`Flask.url_build_error_handlers`. The `url_for`
212
+ function results in a :exc:`~werkzeug.routing.BuildError` when the current
213
+ app does not have a URL for the given endpoint and values. When it does, the
214
+ :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
215
+ it is not ``None``, which can return a string to use as the result of
216
+ `url_for` (instead of `url_for`'s default to raise the
217
+ :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
218
+ An example::
219
+
220
+ def external_url_handler(error, endpoint, values):
221
+ "Looks up an external URL when `url_for` cannot build a URL."
222
+ # This is an example of hooking the build_error_handler.
223
+ # Here, lookup_url is some utility function you've built
224
+ # which looks up the endpoint in some external URL registry.
225
+ url = lookup_url(endpoint, **values)
226
+ if url is None:
227
+ # External lookup did not have a URL.
228
+ # Re-raise the BuildError, in context of original traceback.
229
+ exc_type, exc_value, tb = sys.exc_info()
230
+ if exc_value is error:
231
+ raise exc_type(exc_value).with_traceback(tb)
232
+ else:
233
+ raise error
234
+ # url_for will use this result, instead of raising BuildError.
235
+ return url
236
+
237
+ app.url_build_error_handlers.append(external_url_handler)
238
+
239
+ Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
240
+ `endpoint` and `values` are the arguments passed into `url_for`. Note
241
+ that this is for building URLs outside the current application, and not for
242
+ handling 404 NotFound errors.
243
+
244
+ .. versionadded:: 0.10
245
+ The `_scheme` parameter was added.
246
+
247
+ .. versionadded:: 0.9
248
+ The `_anchor` and `_method` parameters were added.
249
+
250
+ .. versionadded:: 0.9
251
+ Calls :meth:`Flask.handle_build_error` on
252
+ :exc:`~werkzeug.routing.BuildError`.
253
+
254
+ :param endpoint: the endpoint of the URL (name of the function)
255
+ :param values: the variable arguments of the URL rule
256
+ :param _external: if set to ``True``, an absolute URL is generated. Server
257
+ address can be changed via ``SERVER_NAME`` configuration variable which
258
+ falls back to the `Host` header, then to the IP and port of the request.
259
+ :param _scheme: a string specifying the desired URL scheme. The `_external`
260
+ parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
261
+ behavior uses the same scheme as the current request, or
262
+ :data:`PREFERRED_URL_SCHEME` if no request context is available.
263
+ This also can be set to an empty string to build protocol-relative
264
+ URLs.
265
+ :param _anchor: if provided this is added as anchor to the URL.
266
+ :param _method: if provided this explicitly specifies an HTTP method.
267
+ """
268
+ appctx = _app_ctx_stack.top
269
+ reqctx = _request_ctx_stack.top
270
+
271
+ if appctx is None:
272
+ raise RuntimeError(
273
+ "Attempted to generate a URL without the application context being"
274
+ " pushed. This has to be executed when application context is"
275
+ " available."
276
+ )
277
+
278
+ # If request specific information is available we have some extra
279
+ # features that support "relative" URLs.
280
+ if reqctx is not None:
281
+ url_adapter = reqctx.url_adapter
282
+ blueprint_name = request.blueprint
283
+
284
+ if endpoint[:1] == ".":
285
+ if blueprint_name is not None:
286
+ endpoint = f"{blueprint_name}{endpoint}"
287
+ else:
288
+ endpoint = endpoint[1:]
289
+
290
+ external = values.pop("_external", False)
291
+
292
+ # Otherwise go with the url adapter from the appctx and make
293
+ # the URLs external by default.
294
+ else:
295
+ url_adapter = appctx.url_adapter
296
+
297
+ if url_adapter is None:
298
+ raise RuntimeError(
299
+ "Application was not able to create a URL adapter for request"
300
+ " independent URL generation. You might be able to fix this by"
301
+ " setting the SERVER_NAME config variable."
302
+ )
303
+
304
+ external = values.pop("_external", True)
305
+
306
+ anchor = values.pop("_anchor", None)
307
+ method = values.pop("_method", None)
308
+ scheme = values.pop("_scheme", None)
309
+ appctx.app.inject_url_defaults(endpoint, values)
310
+
311
+ # This is not the best way to deal with this but currently the
312
+ # underlying Werkzeug router does not support overriding the scheme on
313
+ # a per build call basis.
314
+ old_scheme = None
315
+ if scheme is not None:
316
+ if not external:
317
+ raise ValueError("When specifying _scheme, _external must be True")
318
+ old_scheme = url_adapter.url_scheme
319
+ url_adapter.url_scheme = scheme
320
+
321
+ try:
322
+ try:
323
+ rv = url_adapter.build(
324
+ endpoint, values, method=method, force_external=external
325
+ )
326
+ finally:
327
+ if old_scheme is not None:
328
+ url_adapter.url_scheme = old_scheme
329
+ except BuildError as error:
330
+ # We need to inject the values again so that the app callback can
331
+ # deal with that sort of stuff.
332
+ values["_external"] = external
333
+ values["_anchor"] = anchor
334
+ values["_method"] = method
335
+ values["_scheme"] = scheme
336
+ return appctx.app.handle_url_build_error(error, endpoint, values)
337
+
338
+ if anchor is not None:
339
+ rv += f"#{url_quote(anchor)}"
340
+ return rv
341
+
342
+
343
+ def get_template_attribute(template_name: str, attribute: str) -> t.Any:
344
+ """Loads a macro (or variable) a template exports. This can be used to
345
+ invoke a macro from within Python code. If you for example have a
346
+ template named :file:`_cider.html` with the following contents:
347
+
348
+ .. sourcecode:: html+jinja
349
+
350
+ {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
351
+
352
+ You can access this from Python code like this::
353
+
354
+ hello = get_template_attribute('_cider.html', 'hello')
355
+ return hello('World')
356
+
357
+ .. versionadded:: 0.2
358
+
359
+ :param template_name: the name of the template
360
+ :param attribute: the name of the variable of macro to access
361
+ """
362
+ return getattr(current_app.jinja_env.get_template(template_name).module, attribute)
363
+
364
+
365
+ def flash(message: str, category: str = "message") -> None:
366
+ """Flashes a message to the next request. In order to remove the
367
+ flashed message from the session and to display it to the user,
368
+ the template has to call :func:`get_flashed_messages`.
369
+
370
+ .. versionchanged:: 0.3
371
+ `category` parameter added.
372
+
373
+ :param message: the message to be flashed.
374
+ :param category: the category for the message. The following values
375
+ are recommended: ``'message'`` for any kind of message,
376
+ ``'error'`` for errors, ``'info'`` for information
377
+ messages and ``'warning'`` for warnings. However any
378
+ kind of string can be used as category.
379
+ """
380
+ # Original implementation:
381
+ #
382
+ # session.setdefault('_flashes', []).append((category, message))
383
+ #
384
+ # This assumed that changes made to mutable structures in the session are
385
+ # always in sync with the session object, which is not true for session
386
+ # implementations that use external storage for keeping their keys/values.
387
+ flashes = session.get("_flashes", [])
388
+ flashes.append((category, message))
389
+ session["_flashes"] = flashes
390
+ message_flashed.send(
391
+ current_app._get_current_object(), # type: ignore
392
+ message=message,
393
+ category=category,
394
+ )
395
+
396
+
397
+ def get_flashed_messages(
398
+ with_categories: bool = False, category_filter: t.Iterable[str] = ()
399
+ ) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]:
400
+ """Pulls all flashed messages from the session and returns them.
401
+ Further calls in the same request to the function will return
402
+ the same messages. By default just the messages are returned,
403
+ but when `with_categories` is set to ``True``, the return value will
404
+ be a list of tuples in the form ``(category, message)`` instead.
405
+
406
+ Filter the flashed messages to one or more categories by providing those
407
+ categories in `category_filter`. This allows rendering categories in
408
+ separate html blocks. The `with_categories` and `category_filter`
409
+ arguments are distinct:
410
+
411
+ * `with_categories` controls whether categories are returned with message
412
+ text (``True`` gives a tuple, where ``False`` gives just the message text).
413
+ * `category_filter` filters the messages down to only those matching the
414
+ provided categories.
415
+
416
+ See :doc:`/patterns/flashing` for examples.
417
+
418
+ .. versionchanged:: 0.3
419
+ `with_categories` parameter added.
420
+
421
+ .. versionchanged:: 0.9
422
+ `category_filter` parameter added.
423
+
424
+ :param with_categories: set to ``True`` to also receive categories.
425
+ :param category_filter: filter of categories to limit return values. Only
426
+ categories in the list will be returned.
427
+ """
428
+ flashes = _request_ctx_stack.top.flashes
429
+ if flashes is None:
430
+ _request_ctx_stack.top.flashes = flashes = (
431
+ session.pop("_flashes") if "_flashes" in session else []
432
+ )
433
+ if category_filter:
434
+ flashes = list(filter(lambda f: f[0] in category_filter, flashes))
435
+ if not with_categories:
436
+ return [x[1] for x in flashes]
437
+ return flashes
438
+
439
+
440
+ def _prepare_send_file_kwargs(
441
+ download_name: t.Optional[str] = None,
442
+ attachment_filename: t.Optional[str] = None,
443
+ etag: t.Optional[t.Union[bool, str]] = None,
444
+ add_etags: t.Optional[t.Union[bool]] = None,
445
+ max_age: t.Optional[
446
+ t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
447
+ ] = None,
448
+ cache_timeout: t.Optional[int] = None,
449
+ **kwargs: t.Any,
450
+ ) -> t.Dict[str, t.Any]:
451
+ if attachment_filename is not None:
452
+ warnings.warn(
453
+ "The 'attachment_filename' parameter has been renamed to"
454
+ " 'download_name'. The old name will be removed in Flask"
455
+ " 2.2.",
456
+ DeprecationWarning,
457
+ stacklevel=3,
458
+ )
459
+ download_name = attachment_filename
460
+
461
+ if cache_timeout is not None:
462
+ warnings.warn(
463
+ "The 'cache_timeout' parameter has been renamed to"
464
+ " 'max_age'. The old name will be removed in Flask 2.2.",
465
+ DeprecationWarning,
466
+ stacklevel=3,
467
+ )
468
+ max_age = cache_timeout
469
+
470
+ if add_etags is not None:
471
+ warnings.warn(
472
+ "The 'add_etags' parameter has been renamed to 'etag'. The"
473
+ " old name will be removed in Flask 2.2.",
474
+ DeprecationWarning,
475
+ stacklevel=3,
476
+ )
477
+ etag = add_etags
478
+
479
+ if max_age is None:
480
+ max_age = current_app.get_send_file_max_age
481
+
482
+ kwargs.update(
483
+ environ=request.environ,
484
+ download_name=download_name,
485
+ etag=etag,
486
+ max_age=max_age,
487
+ use_x_sendfile=current_app.use_x_sendfile,
488
+ response_class=current_app.response_class,
489
+ _root_path=current_app.root_path, # type: ignore
490
+ )
491
+ return kwargs
492
+
493
+
494
+ def send_file(
495
+ path_or_file: t.Union[os.PathLike, str, t.BinaryIO],
496
+ mimetype: t.Optional[str] = None,
497
+ as_attachment: bool = False,
498
+ download_name: t.Optional[str] = None,
499
+ attachment_filename: t.Optional[str] = None,
500
+ conditional: bool = True,
501
+ etag: t.Union[bool, str] = True,
502
+ add_etags: t.Optional[bool] = None,
503
+ last_modified: t.Optional[t.Union[datetime, int, float]] = None,
504
+ max_age: t.Optional[
505
+ t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
506
+ ] = None,
507
+ cache_timeout: t.Optional[int] = None,
508
+ ):
509
+ """Send the contents of a file to the client.
510
+
511
+ The first argument can be a file path or a file-like object. Paths
512
+ are preferred in most cases because Werkzeug can manage the file and
513
+ get extra information from the path. Passing a file-like object
514
+ requires that the file is opened in binary mode, and is mostly
515
+ useful when building a file in memory with :class:`io.BytesIO`.
516
+
517
+ Never pass file paths provided by a user. The path is assumed to be
518
+ trusted, so a user could craft a path to access a file you didn't
519
+ intend. Use :func:`send_from_directory` to safely serve
520
+ user-requested paths from within a directory.
521
+
522
+ If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
523
+ used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
524
+ if the HTTP server supports ``X-Sendfile``, configuring Flask with
525
+ ``USE_X_SENDFILE = True`` will tell the server to send the given
526
+ path, which is much more efficient than reading it in Python.
527
+
528
+ :param path_or_file: The path to the file to send, relative to the
529
+ current working directory if a relative path is given.
530
+ Alternatively, a file-like object opened in binary mode. Make
531
+ sure the file pointer is seeked to the start of the data.
532
+ :param mimetype: The MIME type to send for the file. If not
533
+ provided, it will try to detect it from the file name.
534
+ :param as_attachment: Indicate to a browser that it should offer to
535
+ save the file instead of displaying it.
536
+ :param download_name: The default name browsers will use when saving
537
+ the file. Defaults to the passed file name.
538
+ :param conditional: Enable conditional and range responses based on
539
+ request headers. Requires passing a file path and ``environ``.
540
+ :param etag: Calculate an ETag for the file, which requires passing
541
+ a file path. Can also be a string to use instead.
542
+ :param last_modified: The last modified time to send for the file,
543
+ in seconds. If not provided, it will try to detect it from the
544
+ file path.
545
+ :param max_age: How long the client should cache the file, in
546
+ seconds. If set, ``Cache-Control`` will be ``public``, otherwise
547
+ it will be ``no-cache`` to prefer conditional caching.
548
+
549
+ .. versionchanged:: 2.0
550
+ ``download_name`` replaces the ``attachment_filename``
551
+ parameter. If ``as_attachment=False``, it is passed with
552
+ ``Content-Disposition: inline`` instead.
553
+
554
+ .. versionchanged:: 2.0
555
+ ``max_age`` replaces the ``cache_timeout`` parameter.
556
+ ``conditional`` is enabled and ``max_age`` is not set by
557
+ default.
558
+
559
+ .. versionchanged:: 2.0
560
+ ``etag`` replaces the ``add_etags`` parameter. It can be a
561
+ string to use instead of generating one.
562
+
563
+ .. versionchanged:: 2.0
564
+ Passing a file-like object that inherits from
565
+ :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather
566
+ than sending an empty file.
567
+
568
+ .. versionadded:: 2.0
569
+ Moved the implementation to Werkzeug. This is now a wrapper to
570
+ pass some Flask-specific arguments.
571
+
572
+ .. versionchanged:: 1.1
573
+ ``filename`` may be a :class:`~os.PathLike` object.
574
+
575
+ .. versionchanged:: 1.1
576
+ Passing a :class:`~io.BytesIO` object supports range requests.
577
+
578
+ .. versionchanged:: 1.0.3
579
+ Filenames are encoded with ASCII instead of Latin-1 for broader
580
+ compatibility with WSGI servers.
581
+
582
+ .. versionchanged:: 1.0
583
+ UTF-8 filenames as specified in :rfc:`2231` are supported.
584
+
585
+ .. versionchanged:: 0.12
586
+ The filename is no longer automatically inferred from file
587
+ objects. If you want to use automatic MIME and etag support,
588
+ pass a filename via ``filename_or_fp`` or
589
+ ``attachment_filename``.
590
+
591
+ .. versionchanged:: 0.12
592
+ ``attachment_filename`` is preferred over ``filename`` for MIME
593
+ detection.
594
+
595
+ .. versionchanged:: 0.9
596
+ ``cache_timeout`` defaults to
597
+ :meth:`Flask.get_send_file_max_age`.
598
+
599
+ .. versionchanged:: 0.7
600
+ MIME guessing and etag support for file-like objects was
601
+ deprecated because it was unreliable. Pass a filename if you are
602
+ able to, otherwise attach an etag yourself.
603
+
604
+ .. versionchanged:: 0.5
605
+ The ``add_etags``, ``cache_timeout`` and ``conditional``
606
+ parameters were added. The default behavior is to add etags.
607
+
608
+ .. versionadded:: 0.2
609
+ """
610
+ return werkzeug.utils.send_file(
611
+ **_prepare_send_file_kwargs(
612
+ path_or_file=path_or_file,
613
+ environ=request.environ,
614
+ mimetype=mimetype,
615
+ as_attachment=as_attachment,
616
+ download_name=download_name,
617
+ attachment_filename=attachment_filename,
618
+ conditional=conditional,
619
+ etag=etag,
620
+ add_etags=add_etags,
621
+ last_modified=last_modified,
622
+ max_age=max_age,
623
+ cache_timeout=cache_timeout,
624
+ )
625
+ )
626
+
627
+
628
+ def send_from_directory(
629
+ directory: t.Union[os.PathLike, str],
630
+ path: t.Union[os.PathLike, str],
631
+ filename: t.Optional[str] = None,
632
+ **kwargs: t.Any,
633
+ ) -> "Response":
634
+ """Send a file from within a directory using :func:`send_file`.
635
+
636
+ .. code-block:: python
637
+
638
+ @app.route("/uploads/<path:name>")
639
+ def download_file(name):
640
+ return send_from_directory(
641
+ app.config['UPLOAD_FOLDER'], name, as_attachment=True
642
+ )
643
+
644
+ This is a secure way to serve files from a folder, such as static
645
+ files or uploads. Uses :func:`~werkzeug.security.safe_join` to
646
+ ensure the path coming from the client is not maliciously crafted to
647
+ point outside the specified directory.
648
+
649
+ If the final path does not point to an existing regular file,
650
+ raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.
651
+
652
+ :param directory: The directory that ``path`` must be located under.
653
+ :param path: The path to the file to send, relative to
654
+ ``directory``.
655
+ :param kwargs: Arguments to pass to :func:`send_file`.
656
+
657
+ .. versionchanged:: 2.0
658
+ ``path`` replaces the ``filename`` parameter.
659
+
660
+ .. versionadded:: 2.0
661
+ Moved the implementation to Werkzeug. This is now a wrapper to
662
+ pass some Flask-specific arguments.
663
+
664
+ .. versionadded:: 0.5
665
+ """
666
+ if filename is not None:
667
+ warnings.warn(
668
+ "The 'filename' parameter has been renamed to 'path'. The"
669
+ " old name will be removed in Flask 2.2.",
670
+ DeprecationWarning,
671
+ stacklevel=2,
672
+ )
673
+ path = filename
674
+
675
+ return werkzeug.utils.send_from_directory( # type: ignore
676
+ directory, path, **_prepare_send_file_kwargs(**kwargs)
677
+ )
678
+
679
+
680
+ def get_root_path(import_name: str) -> str:
681
+ """Find the root path of a package, or the path that contains a
682
+ module. If it cannot be found, returns the current working
683
+ directory.
684
+
685
+ Not to be confused with the value returned by :func:`find_package`.
686
+
687
+ :meta private:
688
+ """
689
+ # Module already imported and has a file attribute. Use that first.
690
+ mod = sys.modules.get(import_name)
691
+
692
+ if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None:
693
+ return os.path.dirname(os.path.abspath(mod.__file__))
694
+
695
+ # Next attempt: check the loader.
696
+ loader = pkgutil.get_loader(import_name)
697
+
698
+ # Loader does not exist or we're referring to an unloaded main
699
+ # module or a main module without path (interactive sessions), go
700
+ # with the current working directory.
701
+ if loader is None or import_name == "__main__":
702
+ return os.getcwd()
703
+
704
+ if hasattr(loader, "get_filename"):
705
+ filepath = loader.get_filename(import_name) # type: ignore
706
+ else:
707
+ # Fall back to imports.
708
+ __import__(import_name)
709
+ mod = sys.modules[import_name]
710
+ filepath = getattr(mod, "__file__", None)
711
+
712
+ # If we don't have a file path it might be because it is a
713
+ # namespace package. In this case pick the root path from the
714
+ # first module that is contained in the package.
715
+ if filepath is None:
716
+ raise RuntimeError(
717
+ "No root path can be found for the provided module"
718
+ f" {import_name!r}. This can happen because the module"
719
+ " came from an import hook that does not provide file"
720
+ " name information or because it's a namespace package."
721
+ " In this case the root path needs to be explicitly"
722
+ " provided."
723
+ )
724
+
725
+ # filepath is import_name.py for a module, or __init__.py for a package.
726
+ return os.path.dirname(os.path.abspath(filepath))
727
+
728
+
729
+ class locked_cached_property(werkzeug.utils.cached_property):
730
+ """A :func:`property` that is only evaluated once. Like
731
+ :class:`werkzeug.utils.cached_property` except access uses a lock
732
+ for thread safety.
733
+
734
+ .. versionchanged:: 2.0
735
+ Inherits from Werkzeug's ``cached_property`` (and ``property``).
736
+ """
737
+
738
+ def __init__(
739
+ self,
740
+ fget: t.Callable[[t.Any], t.Any],
741
+ name: t.Optional[str] = None,
742
+ doc: t.Optional[str] = None,
743
+ ) -> None:
744
+ super().__init__(fget, name=name, doc=doc)
745
+ self.lock = RLock()
746
+
747
+ def __get__(self, obj: object, type: type = None) -> t.Any: # type: ignore
748
+ if obj is None:
749
+ return self
750
+
751
+ with self.lock:
752
+ return super().__get__(obj, type=type)
753
+
754
+ def __set__(self, obj: object, value: t.Any) -> None:
755
+ with self.lock:
756
+ super().__set__(obj, value)
757
+
758
+ def __delete__(self, obj: object) -> None:
759
+ with self.lock:
760
+ super().__delete__(obj)
761
+
762
+
763
+ def is_ip(value: str) -> bool:
764
+ """Determine if the given string is an IP address.
765
+
766
+ :param value: value to check
767
+ :type value: str
768
+
769
+ :return: True if string is an IP address
770
+ :rtype: bool
771
+ """
772
+ for family in (socket.AF_INET, socket.AF_INET6):
773
+ try:
774
+ socket.inet_pton(family, value)
775
+ except OSError:
776
+ pass
777
+ else:
778
+ return True
779
+
780
+ return False
781
+
782
+
783
+ @lru_cache(maxsize=None)
784
+ def _split_blueprint_path(name: str) -> t.List[str]:
785
+ out: t.List[str] = [name]
786
+
787
+ if "." in name:
788
+ out.extend(_split_blueprint_path(name.rpartition(".")[0]))
789
+
790
+ return out
testbed/pallets__flask/src/flask/json/__init__.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import decimal
3
+ import json as _json
4
+ import typing as t
5
+ import uuid
6
+ from datetime import date
7
+
8
+ from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps
9
+ from werkzeug.http import http_date
10
+
11
+ from ..globals import current_app
12
+ from ..globals import request
13
+
14
+ if t.TYPE_CHECKING:
15
+ from ..app import Flask
16
+ from ..wrappers import Response
17
+
18
+
19
+ class JSONEncoder(_json.JSONEncoder):
20
+ """The default JSON encoder. Handles extra types compared to the
21
+ built-in :class:`json.JSONEncoder`.
22
+
23
+ - :class:`datetime.datetime` and :class:`datetime.date` are
24
+ serialized to :rfc:`822` strings. This is the same as the HTTP
25
+ date format.
26
+ - :class:`uuid.UUID` is serialized to a string.
27
+ - :class:`dataclasses.dataclass` is passed to
28
+ :func:`dataclasses.asdict`.
29
+ - :class:`~markupsafe.Markup` (or any object with a ``__html__``
30
+ method) will call the ``__html__`` method to get a string.
31
+
32
+ Assign a subclass of this to :attr:`flask.Flask.json_encoder` or
33
+ :attr:`flask.Blueprint.json_encoder` to override the default.
34
+ """
35
+
36
+ def default(self, o: t.Any) -> t.Any:
37
+ """Convert ``o`` to a JSON serializable type. See
38
+ :meth:`json.JSONEncoder.default`. Python does not support
39
+ overriding how basic types like ``str`` or ``list`` are
40
+ serialized, they are handled before this method.
41
+ """
42
+ if isinstance(o, date):
43
+ return http_date(o)
44
+ if isinstance(o, (decimal.Decimal, uuid.UUID)):
45
+ return str(o)
46
+ if dataclasses and dataclasses.is_dataclass(o):
47
+ return dataclasses.asdict(o)
48
+ if hasattr(o, "__html__"):
49
+ return str(o.__html__())
50
+ return super().default(o)
51
+
52
+
53
+ class JSONDecoder(_json.JSONDecoder):
54
+ """The default JSON decoder.
55
+
56
+ This does not change any behavior from the built-in
57
+ :class:`json.JSONDecoder`.
58
+
59
+ Assign a subclass of this to :attr:`flask.Flask.json_decoder` or
60
+ :attr:`flask.Blueprint.json_decoder` to override the default.
61
+ """
62
+
63
+
64
+ def _dump_arg_defaults(
65
+ kwargs: t.Dict[str, t.Any], app: t.Optional["Flask"] = None
66
+ ) -> None:
67
+ """Inject default arguments for dump functions."""
68
+ if app is None:
69
+ app = current_app
70
+
71
+ if app:
72
+ cls = app.json_encoder
73
+ bp = app.blueprints.get(request.blueprint) if request else None # type: ignore
74
+ if bp is not None and bp.json_encoder is not None:
75
+ cls = bp.json_encoder
76
+
77
+ # Only set a custom encoder if it has custom behavior. This is
78
+ # faster on PyPy.
79
+ if cls is not _json.JSONEncoder:
80
+ kwargs.setdefault("cls", cls)
81
+
82
+ kwargs.setdefault("cls", cls)
83
+ kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])
84
+ kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])
85
+ else:
86
+ kwargs.setdefault("sort_keys", True)
87
+ kwargs.setdefault("cls", JSONEncoder)
88
+
89
+
90
+ def _load_arg_defaults(
91
+ kwargs: t.Dict[str, t.Any], app: t.Optional["Flask"] = None
92
+ ) -> None:
93
+ """Inject default arguments for load functions."""
94
+ if app is None:
95
+ app = current_app
96
+
97
+ if app:
98
+ cls = app.json_decoder
99
+ bp = app.blueprints.get(request.blueprint) if request else None # type: ignore
100
+ if bp is not None and bp.json_decoder is not None:
101
+ cls = bp.json_decoder
102
+
103
+ # Only set a custom decoder if it has custom behavior. This is
104
+ # faster on PyPy.
105
+ if cls not in {JSONDecoder, _json.JSONDecoder}:
106
+ kwargs.setdefault("cls", cls)
107
+
108
+
109
+ def dumps(obj: t.Any, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> str:
110
+ """Serialize an object to a string of JSON.
111
+
112
+ Takes the same arguments as the built-in :func:`json.dumps`, with
113
+ some defaults from application configuration.
114
+
115
+ :param obj: Object to serialize to JSON.
116
+ :param app: Use this app's config instead of the active app context
117
+ or defaults.
118
+ :param kwargs: Extra arguments passed to :func:`json.dumps`.
119
+
120
+ .. versionchanged:: 2.0.2
121
+ :class:`decimal.Decimal` is supported by converting to a string.
122
+
123
+ .. versionchanged:: 2.0
124
+ ``encoding`` is deprecated and will be removed in Flask 2.1.
125
+
126
+ .. versionchanged:: 1.0.3
127
+ ``app`` can be passed directly, rather than requiring an app
128
+ context for configuration.
129
+ """
130
+ _dump_arg_defaults(kwargs, app=app)
131
+ return _json.dumps(obj, **kwargs)
132
+
133
+
134
+ def dump(
135
+ obj: t.Any, fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any
136
+ ) -> None:
137
+ """Serialize an object to JSON written to a file object.
138
+
139
+ Takes the same arguments as the built-in :func:`json.dump`, with
140
+ some defaults from application configuration.
141
+
142
+ :param obj: Object to serialize to JSON.
143
+ :param fp: File object to write JSON to.
144
+ :param app: Use this app's config instead of the active app context
145
+ or defaults.
146
+ :param kwargs: Extra arguments passed to :func:`json.dump`.
147
+
148
+ .. versionchanged:: 2.0
149
+ Writing to a binary file, and the ``encoding`` argument, is
150
+ deprecated and will be removed in Flask 2.1.
151
+ """
152
+ _dump_arg_defaults(kwargs, app=app)
153
+ _json.dump(obj, fp, **kwargs)
154
+
155
+
156
+ def loads(s: str, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:
157
+ """Deserialize an object from a string of JSON.
158
+
159
+ Takes the same arguments as the built-in :func:`json.loads`, with
160
+ some defaults from application configuration.
161
+
162
+ :param s: JSON string to deserialize.
163
+ :param app: Use this app's config instead of the active app context
164
+ or defaults.
165
+ :param kwargs: Extra arguments passed to :func:`json.loads`.
166
+
167
+ .. versionchanged:: 2.0
168
+ ``encoding`` is deprecated and will be removed in Flask 2.1. The
169
+ data must be a string or UTF-8 bytes.
170
+
171
+ .. versionchanged:: 1.0.3
172
+ ``app`` can be passed directly, rather than requiring an app
173
+ context for configuration.
174
+ """
175
+ _load_arg_defaults(kwargs, app=app)
176
+ return _json.loads(s, **kwargs)
177
+
178
+
179
+ def load(fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:
180
+ """Deserialize an object from JSON read from a file object.
181
+
182
+ Takes the same arguments as the built-in :func:`json.load`, with
183
+ some defaults from application configuration.
184
+
185
+ :param fp: File object to read JSON from.
186
+ :param app: Use this app's config instead of the active app context
187
+ or defaults.
188
+ :param kwargs: Extra arguments passed to :func:`json.load`.
189
+
190
+ .. versionchanged:: 2.0
191
+ ``encoding`` is deprecated and will be removed in Flask 2.1. The
192
+ file must be text mode, or binary mode with UTF-8 bytes.
193
+ """
194
+ _load_arg_defaults(kwargs, app=app)
195
+ return _json.load(fp, **kwargs)
196
+
197
+
198
+ def htmlsafe_dumps(obj: t.Any, **kwargs: t.Any) -> str:
199
+ """Serialize an object to a string of JSON with :func:`dumps`, then
200
+ replace HTML-unsafe characters with Unicode escapes and mark the
201
+ result safe with :class:`~markupsafe.Markup`.
202
+
203
+ This is available in templates as the ``|tojson`` filter.
204
+
205
+ The returned string is safe to render in HTML documents and
206
+ ``<script>`` tags. The exception is in HTML attributes that are
207
+ double quoted; either use single quotes or the ``|forceescape``
208
+ filter.
209
+
210
+ .. versionchanged:: 2.0
211
+ Uses :func:`jinja2.utils.htmlsafe_json_dumps`. The returned
212
+ value is marked safe by wrapping in :class:`~markupsafe.Markup`.
213
+
214
+ .. versionchanged:: 0.10
215
+ Single quotes are escaped, making this safe to use in HTML,
216
+ ``<script>`` tags, and single-quoted attributes without further
217
+ escaping.
218
+ """
219
+ return _jinja_htmlsafe_dumps(obj, dumps=dumps, **kwargs)
220
+
221
+
222
+ def htmlsafe_dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:
223
+ """Serialize an object to JSON written to a file object, replacing
224
+ HTML-unsafe characters with Unicode escapes. See
225
+ :func:`htmlsafe_dumps` and :func:`dumps`.
226
+ """
227
+ fp.write(htmlsafe_dumps(obj, **kwargs))
228
+
229
+
230
+ def jsonify(*args: t.Any, **kwargs: t.Any) -> "Response":
231
+ """Serialize data to JSON and wrap it in a :class:`~flask.Response`
232
+ with the :mimetype:`application/json` mimetype.
233
+
234
+ Uses :func:`dumps` to serialize the data, but ``args`` and
235
+ ``kwargs`` are treated as data rather than arguments to
236
+ :func:`json.dumps`.
237
+
238
+ 1. Single argument: Treated as a single value.
239
+ 2. Multiple arguments: Treated as a list of values.
240
+ ``jsonify(1, 2, 3)`` is the same as ``jsonify([1, 2, 3])``.
241
+ 3. Keyword arguments: Treated as a dict of values.
242
+ ``jsonify(data=data, errors=errors)`` is the same as
243
+ ``jsonify({"data": data, "errors": errors})``.
244
+ 4. Passing both arguments and keyword arguments is not allowed as
245
+ it's not clear what should happen.
246
+
247
+ .. code-block:: python
248
+
249
+ from flask import jsonify
250
+
251
+ @app.route("/users/me")
252
+ def get_current_user():
253
+ return jsonify(
254
+ username=g.user.username,
255
+ email=g.user.email,
256
+ id=g.user.id,
257
+ )
258
+
259
+ Will return a JSON response like this:
260
+
261
+ .. code-block:: javascript
262
+
263
+ {
264
+ "username": "admin",
265
+ "email": "admin@localhost",
266
+ "id": 42
267
+ }
268
+
269
+ The default output omits indents and spaces after separators. In
270
+ debug mode or if :data:`JSONIFY_PRETTYPRINT_REGULAR` is ``True``,
271
+ the output will be formatted to be easier to read.
272
+
273
+ .. versionchanged:: 2.0.2
274
+ :class:`decimal.Decimal` is supported by converting to a string.
275
+
276
+ .. versionchanged:: 0.11
277
+ Added support for serializing top-level arrays. This introduces
278
+ a security risk in ancient browsers. See :ref:`security-json`.
279
+
280
+ .. versionadded:: 0.2
281
+ """
282
+ indent = None
283
+ separators = (",", ":")
284
+
285
+ if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
286
+ indent = 2
287
+ separators = (", ", ": ")
288
+
289
+ if args and kwargs:
290
+ raise TypeError("jsonify() behavior undefined when passed both args and kwargs")
291
+ elif len(args) == 1: # single args are passed directly to dumps()
292
+ data = args[0]
293
+ else:
294
+ data = args or kwargs
295
+
296
+ return current_app.response_class(
297
+ f"{dumps(data, indent=indent, separators=separators)}\n",
298
+ mimetype=current_app.config["JSONIFY_MIMETYPE"],
299
+ )
testbed/pallets__flask/src/flask/logging.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+ import typing as t
4
+
5
+ from werkzeug.local import LocalProxy
6
+
7
+ from .globals import request
8
+
9
+ if t.TYPE_CHECKING:
10
+ from .app import Flask
11
+
12
+
13
+ @LocalProxy
14
+ def wsgi_errors_stream() -> t.TextIO:
15
+ """Find the most appropriate error stream for the application. If a request
16
+ is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.
17
+
18
+ If you configure your own :class:`logging.StreamHandler`, you may want to
19
+ use this for the stream. If you are using file or dict configuration and
20
+ can't import this directly, you can refer to it as
21
+ ``ext://flask.logging.wsgi_errors_stream``.
22
+ """
23
+ return request.environ["wsgi.errors"] if request else sys.stderr
24
+
25
+
26
+ def has_level_handler(logger: logging.Logger) -> bool:
27
+ """Check if there is a handler in the logging chain that will handle the
28
+ given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.
29
+ """
30
+ level = logger.getEffectiveLevel()
31
+ current = logger
32
+
33
+ while current:
34
+ if any(handler.level <= level for handler in current.handlers):
35
+ return True
36
+
37
+ if not current.propagate:
38
+ break
39
+
40
+ current = current.parent # type: ignore
41
+
42
+ return False
43
+
44
+
45
+ #: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format
46
+ #: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.
47
+ default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore
48
+ default_handler.setFormatter(
49
+ logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
50
+ )
51
+
52
+
53
+ def create_logger(app: "Flask") -> logging.Logger:
54
+ """Get the Flask app's logger and configure it if needed.
55
+
56
+ The logger name will be the same as
57
+ :attr:`app.import_name <flask.Flask.name>`.
58
+
59
+ When :attr:`~flask.Flask.debug` is enabled, set the logger level to
60
+ :data:`logging.DEBUG` if it is not set.
61
+
62
+ If there is no handler for the logger's effective level, add a
63
+ :class:`~logging.StreamHandler` for
64
+ :func:`~flask.logging.wsgi_errors_stream` with a basic format.
65
+ """
66
+ logger = logging.getLogger(app.name)
67
+
68
+ if app.debug and not logger.level:
69
+ logger.setLevel(logging.DEBUG)
70
+
71
+ if not has_level_handler(logger):
72
+ logger.addHandler(default_handler)
73
+
74
+ return logger
testbed/pallets__flask/src/flask/py.typed ADDED
File without changes
testbed/pallets__flask/src/flask/scaffold.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import os
3
+ import pkgutil
4
+ import sys
5
+ import typing as t
6
+ from collections import defaultdict
7
+ from functools import update_wrapper
8
+ from json import JSONDecoder
9
+ from json import JSONEncoder
10
+
11
+ from jinja2 import FileSystemLoader
12
+ from werkzeug.exceptions import default_exceptions
13
+ from werkzeug.exceptions import HTTPException
14
+
15
+ from .cli import AppGroup
16
+ from .globals import current_app
17
+ from .helpers import get_root_path
18
+ from .helpers import locked_cached_property
19
+ from .helpers import send_from_directory
20
+ from .templating import _default_template_ctx_processor
21
+ from .typing import AfterRequestCallable
22
+ from .typing import AppOrBlueprintKey
23
+ from .typing import BeforeRequestCallable
24
+ from .typing import TeardownCallable
25
+ from .typing import TemplateContextProcessorCallable
26
+ from .typing import URLDefaultCallable
27
+ from .typing import URLValuePreprocessorCallable
28
+
29
+ if t.TYPE_CHECKING:
30
+ from .wrappers import Response
31
+ from .typing import ErrorHandlerCallable
32
+
33
+ # a singleton sentinel value for parameter defaults
34
+ _sentinel = object()
35
+
36
+ F = t.TypeVar("F", bound=t.Callable[..., t.Any])
37
+
38
+
39
+ def setupmethod(f: F) -> F:
40
+ """Wraps a method so that it performs a check in debug mode if the
41
+ first request was already handled.
42
+ """
43
+
44
+ def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
45
+ if self._is_setup_finished():
46
+ raise AssertionError(
47
+ "A setup function was called after the first request "
48
+ "was handled. This usually indicates a bug in the"
49
+ " application where a module was not imported and"
50
+ " decorators or other functionality was called too"
51
+ " late.\nTo fix this make sure to import all your view"
52
+ " modules, database models, and everything related at a"
53
+ " central place before the application starts serving"
54
+ " requests."
55
+ )
56
+ return f(self, *args, **kwargs)
57
+
58
+ return t.cast(F, update_wrapper(wrapper_func, f))
59
+
60
+
61
+ class Scaffold:
62
+ """Common behavior shared between :class:`~flask.Flask` and
63
+ :class:`~flask.blueprints.Blueprint`.
64
+
65
+ :param import_name: The import name of the module where this object
66
+ is defined. Usually :attr:`__name__` should be used.
67
+ :param static_folder: Path to a folder of static files to serve.
68
+ If this is set, a static route will be added.
69
+ :param static_url_path: URL prefix for the static route.
70
+ :param template_folder: Path to a folder containing template files.
71
+ for rendering. If this is set, a Jinja loader will be added.
72
+ :param root_path: The path that static, template, and resource files
73
+ are relative to. Typically not set, it is discovered based on
74
+ the ``import_name``.
75
+
76
+ .. versionadded:: 2.0
77
+ """
78
+
79
+ name: str
80
+ _static_folder: t.Optional[str] = None
81
+ _static_url_path: t.Optional[str] = None
82
+
83
+ #: JSON encoder class used by :func:`flask.json.dumps`. If a
84
+ #: blueprint sets this, it will be used instead of the app's value.
85
+ json_encoder: t.Optional[t.Type[JSONEncoder]] = None
86
+
87
+ #: JSON decoder class used by :func:`flask.json.loads`. If a
88
+ #: blueprint sets this, it will be used instead of the app's value.
89
+ json_decoder: t.Optional[t.Type[JSONDecoder]] = None
90
+
91
+ def __init__(
92
+ self,
93
+ import_name: str,
94
+ static_folder: t.Optional[t.Union[str, os.PathLike]] = None,
95
+ static_url_path: t.Optional[str] = None,
96
+ template_folder: t.Optional[str] = None,
97
+ root_path: t.Optional[str] = None,
98
+ ):
99
+ #: The name of the package or module that this object belongs
100
+ #: to. Do not change this once it is set by the constructor.
101
+ self.import_name = import_name
102
+
103
+ self.static_folder = static_folder # type: ignore
104
+ self.static_url_path = static_url_path
105
+
106
+ #: The path to the templates folder, relative to
107
+ #: :attr:`root_path`, to add to the template loader. ``None`` if
108
+ #: templates should not be added.
109
+ self.template_folder = template_folder
110
+
111
+ if root_path is None:
112
+ root_path = get_root_path(self.import_name)
113
+
114
+ #: Absolute path to the package on the filesystem. Used to look
115
+ #: up resources contained in the package.
116
+ self.root_path = root_path
117
+
118
+ #: The Click command group for registering CLI commands for this
119
+ #: object. The commands are available from the ``flask`` command
120
+ #: once the application has been discovered and blueprints have
121
+ #: been registered.
122
+ self.cli = AppGroup()
123
+
124
+ #: A dictionary mapping endpoint names to view functions.
125
+ #:
126
+ #: To register a view function, use the :meth:`route` decorator.
127
+ #:
128
+ #: This data structure is internal. It should not be modified
129
+ #: directly and its format may change at any time.
130
+ self.view_functions: t.Dict[str, t.Callable] = {}
131
+
132
+ #: A data structure of registered error handlers, in the format
133
+ #: ``{scope: {code: {class: handler}}}```. The ``scope`` key is
134
+ #: the name of a blueprint the handlers are active for, or
135
+ #: ``None`` for all requests. The ``code`` key is the HTTP
136
+ #: status code for ``HTTPException``, or ``None`` for
137
+ #: other exceptions. The innermost dictionary maps exception
138
+ #: classes to handler functions.
139
+ #:
140
+ #: To register an error handler, use the :meth:`errorhandler`
141
+ #: decorator.
142
+ #:
143
+ #: This data structure is internal. It should not be modified
144
+ #: directly and its format may change at any time.
145
+ self.error_handler_spec: t.Dict[
146
+ AppOrBlueprintKey,
147
+ t.Dict[t.Optional[int], t.Dict[t.Type[Exception], "ErrorHandlerCallable"]],
148
+ ] = defaultdict(lambda: defaultdict(dict))
149
+
150
+ #: A data structure of functions to call at the beginning of
151
+ #: each request, in the format ``{scope: [functions]}``. The
152
+ #: ``scope`` key is the name of a blueprint the functions are
153
+ #: active for, or ``None`` for all requests.
154
+ #:
155
+ #: To register a function, use the :meth:`before_request`
156
+ #: decorator.
157
+ #:
158
+ #: This data structure is internal. It should not be modified
159
+ #: directly and its format may change at any time.
160
+ self.before_request_funcs: t.Dict[
161
+ AppOrBlueprintKey, t.List[BeforeRequestCallable]
162
+ ] = defaultdict(list)
163
+
164
+ #: A data structure of functions to call at the end of each
165
+ #: request, in the format ``{scope: [functions]}``. The
166
+ #: ``scope`` key is the name of a blueprint the functions are
167
+ #: active for, or ``None`` for all requests.
168
+ #:
169
+ #: To register a function, use the :meth:`after_request`
170
+ #: decorator.
171
+ #:
172
+ #: This data structure is internal. It should not be modified
173
+ #: directly and its format may change at any time.
174
+ self.after_request_funcs: t.Dict[
175
+ AppOrBlueprintKey, t.List[AfterRequestCallable]
176
+ ] = defaultdict(list)
177
+
178
+ #: A data structure of functions to call at the end of each
179
+ #: request even if an exception is raised, in the format
180
+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a
181
+ #: blueprint the functions are active for, or ``None`` for all
182
+ #: requests.
183
+ #:
184
+ #: To register a function, use the :meth:`teardown_request`
185
+ #: decorator.
186
+ #:
187
+ #: This data structure is internal. It should not be modified
188
+ #: directly and its format may change at any time.
189
+ self.teardown_request_funcs: t.Dict[
190
+ AppOrBlueprintKey, t.List[TeardownCallable]
191
+ ] = defaultdict(list)
192
+
193
+ #: A data structure of functions to call to pass extra context
194
+ #: values when rendering templates, in the format
195
+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a
196
+ #: blueprint the functions are active for, or ``None`` for all
197
+ #: requests.
198
+ #:
199
+ #: To register a function, use the :meth:`context_processor`
200
+ #: decorator.
201
+ #:
202
+ #: This data structure is internal. It should not be modified
203
+ #: directly and its format may change at any time.
204
+ self.template_context_processors: t.Dict[
205
+ AppOrBlueprintKey, t.List[TemplateContextProcessorCallable]
206
+ ] = defaultdict(list, {None: [_default_template_ctx_processor]})
207
+
208
+ #: A data structure of functions to call to modify the keyword
209
+ #: arguments passed to the view function, in the format
210
+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a
211
+ #: blueprint the functions are active for, or ``None`` for all
212
+ #: requests.
213
+ #:
214
+ #: To register a function, use the
215
+ #: :meth:`url_value_preprocessor` decorator.
216
+ #:
217
+ #: This data structure is internal. It should not be modified
218
+ #: directly and its format may change at any time.
219
+ self.url_value_preprocessors: t.Dict[
220
+ AppOrBlueprintKey,
221
+ t.List[URLValuePreprocessorCallable],
222
+ ] = defaultdict(list)
223
+
224
+ #: A data structure of functions to call to modify the keyword
225
+ #: arguments when generating URLs, in the format
226
+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a
227
+ #: blueprint the functions are active for, or ``None`` for all
228
+ #: requests.
229
+ #:
230
+ #: To register a function, use the :meth:`url_defaults`
231
+ #: decorator.
232
+ #:
233
+ #: This data structure is internal. It should not be modified
234
+ #: directly and its format may change at any time.
235
+ self.url_default_functions: t.Dict[
236
+ AppOrBlueprintKey, t.List[URLDefaultCallable]
237
+ ] = defaultdict(list)
238
+
239
+ def __repr__(self) -> str:
240
+ return f"<{type(self).__name__} {self.name!r}>"
241
+
242
+ def _is_setup_finished(self) -> bool:
243
+ raise NotImplementedError
244
+
245
+ @property
246
+ def static_folder(self) -> t.Optional[str]:
247
+ """The absolute path to the configured static folder. ``None``
248
+ if no static folder is set.
249
+ """
250
+ if self._static_folder is not None:
251
+ return os.path.join(self.root_path, self._static_folder)
252
+ else:
253
+ return None
254
+
255
+ @static_folder.setter
256
+ def static_folder(self, value: t.Optional[t.Union[str, os.PathLike]]) -> None:
257
+ if value is not None:
258
+ value = os.fspath(value).rstrip(r"\/")
259
+
260
+ self._static_folder = value
261
+
262
+ @property
263
+ def has_static_folder(self) -> bool:
264
+ """``True`` if :attr:`static_folder` is set.
265
+
266
+ .. versionadded:: 0.5
267
+ """
268
+ return self.static_folder is not None
269
+
270
+ @property
271
+ def static_url_path(self) -> t.Optional[str]:
272
+ """The URL prefix that the static route will be accessible from.
273
+
274
+ If it was not configured during init, it is derived from
275
+ :attr:`static_folder`.
276
+ """
277
+ if self._static_url_path is not None:
278
+ return self._static_url_path
279
+
280
+ if self.static_folder is not None:
281
+ basename = os.path.basename(self.static_folder)
282
+ return f"/{basename}".rstrip("/")
283
+
284
+ return None
285
+
286
+ @static_url_path.setter
287
+ def static_url_path(self, value: t.Optional[str]) -> None:
288
+ if value is not None:
289
+ value = value.rstrip("/")
290
+
291
+ self._static_url_path = value
292
+
293
+ def get_send_file_max_age(self, filename: t.Optional[str]) -> t.Optional[int]:
294
+ """Used by :func:`send_file` to determine the ``max_age`` cache
295
+ value for a given file path if it wasn't passed.
296
+
297
+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
298
+ the configuration of :data:`~flask.current_app`. This defaults
299
+ to ``None``, which tells the browser to use conditional requests
300
+ instead of a timed cache, which is usually preferable.
301
+
302
+ .. versionchanged:: 2.0
303
+ The default configuration is ``None`` instead of 12 hours.
304
+
305
+ .. versionadded:: 0.9
306
+ """
307
+ value = current_app.send_file_max_age_default
308
+
309
+ if value is None:
310
+ return None
311
+
312
+ return int(value.total_seconds())
313
+
314
+ def send_static_file(self, filename: str) -> "Response":
315
+ """The view function used to serve files from
316
+ :attr:`static_folder`. A route is automatically registered for
317
+ this view at :attr:`static_url_path` if :attr:`static_folder` is
318
+ set.
319
+
320
+ .. versionadded:: 0.5
321
+ """
322
+ if not self.has_static_folder:
323
+ raise RuntimeError("'static_folder' must be set to serve static_files.")
324
+
325
+ # send_file only knows to call get_send_file_max_age on the app,
326
+ # call it here so it works for blueprints too.
327
+ max_age = self.get_send_file_max_age(filename)
328
+ return send_from_directory(
329
+ t.cast(str, self.static_folder), filename, max_age=max_age
330
+ )
331
+
332
+ @locked_cached_property
333
+ def jinja_loader(self) -> t.Optional[FileSystemLoader]:
334
+ """The Jinja loader for this object's templates. By default this
335
+ is a class :class:`jinja2.loaders.FileSystemLoader` to
336
+ :attr:`template_folder` if it is set.
337
+
338
+ .. versionadded:: 0.5
339
+ """
340
+ if self.template_folder is not None:
341
+ return FileSystemLoader(os.path.join(self.root_path, self.template_folder))
342
+ else:
343
+ return None
344
+
345
+ def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
346
+ """Open a resource file relative to :attr:`root_path` for
347
+ reading.
348
+
349
+ For example, if the file ``schema.sql`` is next to the file
350
+ ``app.py`` where the ``Flask`` app is defined, it can be opened
351
+ with:
352
+
353
+ .. code-block:: python
354
+
355
+ with app.open_resource("schema.sql") as f:
356
+ conn.executescript(f.read())
357
+
358
+ :param resource: Path to the resource relative to
359
+ :attr:`root_path`.
360
+ :param mode: Open the file in this mode. Only reading is
361
+ supported, valid values are "r" (or "rt") and "rb".
362
+ """
363
+ if mode not in {"r", "rt", "rb"}:
364
+ raise ValueError("Resources can only be opened for reading.")
365
+
366
+ return open(os.path.join(self.root_path, resource), mode)
367
+
368
+ def _method_route(
369
+ self,
370
+ method: str,
371
+ rule: str,
372
+ options: dict,
373
+ ) -> t.Callable[[F], F]:
374
+ if "methods" in options:
375
+ raise TypeError("Use the 'route' decorator to use the 'methods' argument.")
376
+
377
+ return self.route(rule, methods=[method], **options)
378
+
379
+ def get(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
380
+ """Shortcut for :meth:`route` with ``methods=["GET"]``.
381
+
382
+ .. versionadded:: 2.0
383
+ """
384
+ return self._method_route("GET", rule, options)
385
+
386
+ def post(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
387
+ """Shortcut for :meth:`route` with ``methods=["POST"]``.
388
+
389
+ .. versionadded:: 2.0
390
+ """
391
+ return self._method_route("POST", rule, options)
392
+
393
+ def put(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
394
+ """Shortcut for :meth:`route` with ``methods=["PUT"]``.
395
+
396
+ .. versionadded:: 2.0
397
+ """
398
+ return self._method_route("PUT", rule, options)
399
+
400
+ def delete(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
401
+ """Shortcut for :meth:`route` with ``methods=["DELETE"]``.
402
+
403
+ .. versionadded:: 2.0
404
+ """
405
+ return self._method_route("DELETE", rule, options)
406
+
407
+ def patch(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
408
+ """Shortcut for :meth:`route` with ``methods=["PATCH"]``.
409
+
410
+ .. versionadded:: 2.0
411
+ """
412
+ return self._method_route("PATCH", rule, options)
413
+
414
+ def route(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
415
+ """Decorate a view function to register it with the given URL
416
+ rule and options. Calls :meth:`add_url_rule`, which has more
417
+ details about the implementation.
418
+
419
+ .. code-block:: python
420
+
421
+ @app.route("/")
422
+ def index():
423
+ return "Hello, World!"
424
+
425
+ See :ref:`url-route-registrations`.
426
+
427
+ The endpoint name for the route defaults to the name of the view
428
+ function if the ``endpoint`` parameter isn't passed.
429
+
430
+ The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
431
+ ``OPTIONS`` are added automatically.
432
+
433
+ :param rule: The URL rule string.
434
+ :param options: Extra options passed to the
435
+ :class:`~werkzeug.routing.Rule` object.
436
+ """
437
+
438
+ def decorator(f: F) -> F:
439
+ endpoint = options.pop("endpoint", None)
440
+ self.add_url_rule(rule, endpoint, f, **options)
441
+ return f
442
+
443
+ return decorator
444
+
445
+ @setupmethod
446
+ def add_url_rule(
447
+ self,
448
+ rule: str,
449
+ endpoint: t.Optional[str] = None,
450
+ view_func: t.Optional[t.Callable] = None,
451
+ provide_automatic_options: t.Optional[bool] = None,
452
+ **options: t.Any,
453
+ ) -> None:
454
+ """Register a rule for routing incoming requests and building
455
+ URLs. The :meth:`route` decorator is a shortcut to call this
456
+ with the ``view_func`` argument. These are equivalent:
457
+
458
+ .. code-block:: python
459
+
460
+ @app.route("/")
461
+ def index():
462
+ ...
463
+
464
+ .. code-block:: python
465
+
466
+ def index():
467
+ ...
468
+
469
+ app.add_url_rule("/", view_func=index)
470
+
471
+ See :ref:`url-route-registrations`.
472
+
473
+ The endpoint name for the route defaults to the name of the view
474
+ function if the ``endpoint`` parameter isn't passed. An error
475
+ will be raised if a function has already been registered for the
476
+ endpoint.
477
+
478
+ The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is
479
+ always added automatically, and ``OPTIONS`` is added
480
+ automatically by default.
481
+
482
+ ``view_func`` does not necessarily need to be passed, but if the
483
+ rule should participate in routing an endpoint name must be
484
+ associated with a view function at some point with the
485
+ :meth:`endpoint` decorator.
486
+
487
+ .. code-block:: python
488
+
489
+ app.add_url_rule("/", endpoint="index")
490
+
491
+ @app.endpoint("index")
492
+ def index():
493
+ ...
494
+
495
+ If ``view_func`` has a ``required_methods`` attribute, those
496
+ methods are added to the passed and automatic methods. If it
497
+ has a ``provide_automatic_methods`` attribute, it is used as the
498
+ default if the parameter is not passed.
499
+
500
+ :param rule: The URL rule string.
501
+ :param endpoint: The endpoint name to associate with the rule
502
+ and view function. Used when routing and building URLs.
503
+ Defaults to ``view_func.__name__``.
504
+ :param view_func: The view function to associate with the
505
+ endpoint name.
506
+ :param provide_automatic_options: Add the ``OPTIONS`` method and
507
+ respond to ``OPTIONS`` requests automatically.
508
+ :param options: Extra options passed to the
509
+ :class:`~werkzeug.routing.Rule` object.
510
+ """
511
+ raise NotImplementedError
512
+
513
+ def endpoint(self, endpoint: str) -> t.Callable:
514
+ """Decorate a view function to register it for the given
515
+ endpoint. Used if a rule is added without a ``view_func`` with
516
+ :meth:`add_url_rule`.
517
+
518
+ .. code-block:: python
519
+
520
+ app.add_url_rule("/ex", endpoint="example")
521
+
522
+ @app.endpoint("example")
523
+ def example():
524
+ ...
525
+
526
+ :param endpoint: The endpoint name to associate with the view
527
+ function.
528
+ """
529
+
530
+ def decorator(f):
531
+ self.view_functions[endpoint] = f
532
+ return f
533
+
534
+ return decorator
535
+
536
+ @setupmethod
537
+ def before_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:
538
+ """Register a function to run before each request.
539
+
540
+ For example, this can be used to open a database connection, or
541
+ to load the logged in user from the session.
542
+
543
+ .. code-block:: python
544
+
545
+ @app.before_request
546
+ def load_user():
547
+ if "user_id" in session:
548
+ g.user = db.session.get(session["user_id"])
549
+
550
+ The function will be called without any arguments. If it returns
551
+ a non-``None`` value, the value is handled as if it was the
552
+ return value from the view, and further request handling is
553
+ stopped.
554
+ """
555
+ self.before_request_funcs.setdefault(None, []).append(f)
556
+ return f
557
+
558
+ @setupmethod
559
+ def after_request(self, f: AfterRequestCallable) -> AfterRequestCallable:
560
+ """Register a function to run after each request to this object.
561
+
562
+ The function is called with the response object, and must return
563
+ a response object. This allows the functions to modify or
564
+ replace the response before it is sent.
565
+
566
+ If a function raises an exception, any remaining
567
+ ``after_request`` functions will not be called. Therefore, this
568
+ should not be used for actions that must execute, such as to
569
+ close resources. Use :meth:`teardown_request` for that.
570
+ """
571
+ self.after_request_funcs.setdefault(None, []).append(f)
572
+ return f
573
+
574
+ @setupmethod
575
+ def teardown_request(self, f: TeardownCallable) -> TeardownCallable:
576
+ """Register a function to be run at the end of each request,
577
+ regardless of whether there was an exception or not. These functions
578
+ are executed when the request context is popped, even if not an
579
+ actual request was performed.
580
+
581
+ Example::
582
+
583
+ ctx = app.test_request_context()
584
+ ctx.push()
585
+ ...
586
+ ctx.pop()
587
+
588
+ When ``ctx.pop()`` is executed in the above example, the teardown
589
+ functions are called just before the request context moves from the
590
+ stack of active contexts. This becomes relevant if you are using
591
+ such constructs in tests.
592
+
593
+ Teardown functions must avoid raising exceptions. If
594
+ they execute code that might fail they
595
+ will have to surround the execution of that code with try/except
596
+ statements and log any errors.
597
+
598
+ When a teardown function was called because of an exception it will
599
+ be passed an error object.
600
+
601
+ The return values of teardown functions are ignored.
602
+
603
+ .. admonition:: Debug Note
604
+
605
+ In debug mode Flask will not tear down a request on an exception
606
+ immediately. Instead it will keep it alive so that the interactive
607
+ debugger can still access it. This behavior can be controlled
608
+ by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
609
+ """
610
+ self.teardown_request_funcs.setdefault(None, []).append(f)
611
+ return f
612
+
613
+ @setupmethod
614
+ def context_processor(
615
+ self, f: TemplateContextProcessorCallable
616
+ ) -> TemplateContextProcessorCallable:
617
+ """Registers a template context processor function."""
618
+ self.template_context_processors[None].append(f)
619
+ return f
620
+
621
+ @setupmethod
622
+ def url_value_preprocessor(
623
+ self, f: URLValuePreprocessorCallable
624
+ ) -> URLValuePreprocessorCallable:
625
+ """Register a URL value preprocessor function for all view
626
+ functions in the application. These functions will be called before the
627
+ :meth:`before_request` functions.
628
+
629
+ The function can modify the values captured from the matched url before
630
+ they are passed to the view. For example, this can be used to pop a
631
+ common language code value and place it in ``g`` rather than pass it to
632
+ every view.
633
+
634
+ The function is passed the endpoint name and values dict. The return
635
+ value is ignored.
636
+ """
637
+ self.url_value_preprocessors[None].append(f)
638
+ return f
639
+
640
+ @setupmethod
641
+ def url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:
642
+ """Callback function for URL defaults for all view functions of the
643
+ application. It's called with the endpoint and values and should
644
+ update the values passed in place.
645
+ """
646
+ self.url_default_functions[None].append(f)
647
+ return f
648
+
649
+ @setupmethod
650
+ def errorhandler(
651
+ self, code_or_exception: t.Union[t.Type[Exception], int]
652
+ ) -> t.Callable[["ErrorHandlerCallable"], "ErrorHandlerCallable"]:
653
+ """Register a function to handle errors by code or exception class.
654
+
655
+ A decorator that is used to register a function given an
656
+ error code. Example::
657
+
658
+ @app.errorhandler(404)
659
+ def page_not_found(error):
660
+ return 'This page does not exist', 404
661
+
662
+ You can also register handlers for arbitrary exceptions::
663
+
664
+ @app.errorhandler(DatabaseError)
665
+ def special_exception_handler(error):
666
+ return 'Database connection failed', 500
667
+
668
+ .. versionadded:: 0.7
669
+ Use :meth:`register_error_handler` instead of modifying
670
+ :attr:`error_handler_spec` directly, for application wide error
671
+ handlers.
672
+
673
+ .. versionadded:: 0.7
674
+ One can now additionally also register custom exception types
675
+ that do not necessarily have to be a subclass of the
676
+ :class:`~werkzeug.exceptions.HTTPException` class.
677
+
678
+ :param code_or_exception: the code as integer for the handler, or
679
+ an arbitrary exception
680
+ """
681
+
682
+ def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":
683
+ self.register_error_handler(code_or_exception, f)
684
+ return f
685
+
686
+ return decorator
687
+
688
+ @setupmethod
689
+ def register_error_handler(
690
+ self,
691
+ code_or_exception: t.Union[t.Type[Exception], int],
692
+ f: "ErrorHandlerCallable",
693
+ ) -> None:
694
+ """Alternative error attach function to the :meth:`errorhandler`
695
+ decorator that is more straightforward to use for non decorator
696
+ usage.
697
+
698
+ .. versionadded:: 0.7
699
+ """
700
+ if isinstance(code_or_exception, HTTPException): # old broken behavior
701
+ raise ValueError(
702
+ "Tried to register a handler for an exception instance"
703
+ f" {code_or_exception!r}. Handlers can only be"
704
+ " registered for exception classes or HTTP error codes."
705
+ )
706
+
707
+ try:
708
+ exc_class, code = self._get_exc_class_and_code(code_or_exception)
709
+ except KeyError:
710
+ raise KeyError(
711
+ f"'{code_or_exception}' is not a recognized HTTP error"
712
+ " code. Use a subclass of HTTPException with that code"
713
+ " instead."
714
+ ) from None
715
+
716
+ self.error_handler_spec[None][code][exc_class] = f
717
+
718
+ @staticmethod
719
+ def _get_exc_class_and_code(
720
+ exc_class_or_code: t.Union[t.Type[Exception], int]
721
+ ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:
722
+ """Get the exception class being handled. For HTTP status codes
723
+ or ``HTTPException`` subclasses, return both the exception and
724
+ status code.
725
+
726
+ :param exc_class_or_code: Any exception class, or an HTTP status
727
+ code as an integer.
728
+ """
729
+ exc_class: t.Type[Exception]
730
+ if isinstance(exc_class_or_code, int):
731
+ exc_class = default_exceptions[exc_class_or_code]
732
+ else:
733
+ exc_class = exc_class_or_code
734
+
735
+ assert issubclass(
736
+ exc_class, Exception
737
+ ), "Custom exceptions must be subclasses of Exception."
738
+
739
+ if issubclass(exc_class, HTTPException):
740
+ return exc_class, exc_class.code
741
+ else:
742
+ return exc_class, None
743
+
744
+
745
+ def _endpoint_from_view_func(view_func: t.Callable) -> str:
746
+ """Internal helper that returns the default endpoint for a given
747
+ function. This always is the function name.
748
+ """
749
+ assert view_func is not None, "expected view func if endpoint is not provided."
750
+ return view_func.__name__
751
+
752
+
753
+ def _matching_loader_thinks_module_is_package(loader, mod_name):
754
+ """Attempt to figure out if the given name is a package or a module.
755
+
756
+ :param: loader: The loader that handled the name.
757
+ :param mod_name: The name of the package or module.
758
+ """
759
+ # Use loader.is_package if it's available.
760
+ if hasattr(loader, "is_package"):
761
+ return loader.is_package(mod_name)
762
+
763
+ cls = type(loader)
764
+
765
+ # NamespaceLoader doesn't implement is_package, but all names it
766
+ # loads must be packages.
767
+ if cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":
768
+ return True
769
+
770
+ # Otherwise we need to fail with an error that explains what went
771
+ # wrong.
772
+ raise AttributeError(
773
+ f"'{cls.__name__}.is_package()' must be implemented for PEP 302"
774
+ f" import hooks."
775
+ )
776
+
777
+
778
+ def _find_package_path(root_mod_name):
779
+ """Find the path that contains the package or module."""
780
+ try:
781
+ spec = importlib.util.find_spec(root_mod_name)
782
+
783
+ if spec is None:
784
+ raise ValueError("not found")
785
+ # ImportError: the machinery told us it does not exist
786
+ # ValueError:
787
+ # - the module name was invalid
788
+ # - the module name is __main__
789
+ # - *we* raised `ValueError` due to `spec` being `None`
790
+ except (ImportError, ValueError):
791
+ pass # handled below
792
+ else:
793
+ # namespace package
794
+ if spec.origin in {"namespace", None}:
795
+ return os.path.dirname(next(iter(spec.submodule_search_locations)))
796
+ # a package (with __init__.py)
797
+ elif spec.submodule_search_locations:
798
+ return os.path.dirname(os.path.dirname(spec.origin))
799
+ # just a normal module
800
+ else:
801
+ return os.path.dirname(spec.origin)
802
+
803
+ # we were unable to find the `package_path` using PEP 451 loaders
804
+ loader = pkgutil.get_loader(root_mod_name)
805
+
806
+ if loader is None or root_mod_name == "__main__":
807
+ # import name is not found, or interactive/main module
808
+ return os.getcwd()
809
+
810
+ if hasattr(loader, "get_filename"):
811
+ filename = loader.get_filename(root_mod_name)
812
+ elif hasattr(loader, "archive"):
813
+ # zipimporter's loader.archive points to the .egg or .zip file.
814
+ filename = loader.archive
815
+ else:
816
+ # At least one loader is missing both get_filename and archive:
817
+ # Google App Engine's HardenedModulesHook, use __file__.
818
+ filename = importlib.import_module(root_mod_name).__file__
819
+
820
+ package_path = os.path.abspath(os.path.dirname(filename))
821
+
822
+ # If the imported name is a package, filename is currently pointing
823
+ # to the root of the package, need to get the current directory.
824
+ if _matching_loader_thinks_module_is_package(loader, root_mod_name):
825
+ package_path = os.path.dirname(package_path)
826
+
827
+ return package_path
828
+
829
+
830
+ def find_package(import_name: str):
831
+ """Find the prefix that a package is installed under, and the path
832
+ that it would be imported from.
833
+
834
+ The prefix is the directory containing the standard directory
835
+ hierarchy (lib, bin, etc.). If the package is not installed to the
836
+ system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),
837
+ ``None`` is returned.
838
+
839
+ The path is the entry in :attr:`sys.path` that contains the package
840
+ for import. If the package is not installed, it's assumed that the
841
+ package was imported from the current working directory.
842
+ """
843
+ root_mod_name, _, _ = import_name.partition(".")
844
+ package_path = _find_package_path(root_mod_name)
845
+ py_prefix = os.path.abspath(sys.prefix)
846
+
847
+ # installed to the system
848
+ if package_path.startswith(py_prefix):
849
+ return py_prefix, package_path
850
+
851
+ site_parent, site_folder = os.path.split(package_path)
852
+
853
+ # installed to a virtualenv
854
+ if site_folder.lower() == "site-packages":
855
+ parent, folder = os.path.split(site_parent)
856
+
857
+ # Windows (prefix/lib/site-packages)
858
+ if folder.lower() == "lib":
859
+ return parent, package_path
860
+
861
+ # Unix (prefix/lib/pythonX.Y/site-packages)
862
+ if os.path.basename(parent).lower() == "lib":
863
+ return os.path.dirname(parent), package_path
864
+
865
+ # something else (prefix/site-packages)
866
+ return site_parent, package_path
867
+
868
+ # not installed
869
+ return None, package_path
testbed/pallets__flask/src/flask/sessions.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import typing as t
3
+ import warnings
4
+ from collections.abc import MutableMapping
5
+ from datetime import datetime
6
+
7
+ from itsdangerous import BadSignature
8
+ from itsdangerous import URLSafeTimedSerializer
9
+ from werkzeug.datastructures import CallbackDict
10
+
11
+ from .helpers import is_ip
12
+ from .json.tag import TaggedJSONSerializer
13
+
14
+ if t.TYPE_CHECKING:
15
+ import typing_extensions as te
16
+ from .app import Flask
17
+ from .wrappers import Request, Response
18
+
19
+
20
+ class SessionMixin(MutableMapping):
21
+ """Expands a basic dictionary with session attributes."""
22
+
23
+ @property
24
+ def permanent(self) -> bool:
25
+ """This reflects the ``'_permanent'`` key in the dict."""
26
+ return self.get("_permanent", False)
27
+
28
+ @permanent.setter
29
+ def permanent(self, value: bool) -> None:
30
+ self["_permanent"] = bool(value)
31
+
32
+ #: Some implementations can detect whether a session is newly
33
+ #: created, but that is not guaranteed. Use with caution. The mixin
34
+ # default is hard-coded ``False``.
35
+ new = False
36
+
37
+ #: Some implementations can detect changes to the session and set
38
+ #: this when that happens. The mixin default is hard coded to
39
+ #: ``True``.
40
+ modified = True
41
+
42
+ #: Some implementations can detect when session data is read or
43
+ #: written and set this when that happens. The mixin default is hard
44
+ #: coded to ``True``.
45
+ accessed = True
46
+
47
+
48
+ class SecureCookieSession(CallbackDict, SessionMixin):
49
+ """Base class for sessions based on signed cookies.
50
+
51
+ This session backend will set the :attr:`modified` and
52
+ :attr:`accessed` attributes. It cannot reliably track whether a
53
+ session is new (vs. empty), so :attr:`new` remains hard coded to
54
+ ``False``.
55
+ """
56
+
57
+ #: When data is changed, this is set to ``True``. Only the session
58
+ #: dictionary itself is tracked; if the session contains mutable
59
+ #: data (for example a nested dict) then this must be set to
60
+ #: ``True`` manually when modifying that data. The session cookie
61
+ #: will only be written to the response if this is ``True``.
62
+ modified = False
63
+
64
+ #: When data is read or written, this is set to ``True``. Used by
65
+ # :class:`.SecureCookieSessionInterface` to add a ``Vary: Cookie``
66
+ #: header, which allows caching proxies to cache different pages for
67
+ #: different users.
68
+ accessed = False
69
+
70
+ def __init__(self, initial: t.Any = None) -> None:
71
+ def on_update(self) -> None:
72
+ self.modified = True
73
+ self.accessed = True
74
+
75
+ super().__init__(initial, on_update)
76
+
77
+ def __getitem__(self, key: str) -> t.Any:
78
+ self.accessed = True
79
+ return super().__getitem__(key)
80
+
81
+ def get(self, key: str, default: t.Any = None) -> t.Any:
82
+ self.accessed = True
83
+ return super().get(key, default)
84
+
85
+ def setdefault(self, key: str, default: t.Any = None) -> t.Any:
86
+ self.accessed = True
87
+ return super().setdefault(key, default)
88
+
89
+
90
+ class NullSession(SecureCookieSession):
91
+ """Class used to generate nicer error messages if sessions are not
92
+ available. Will still allow read-only access to the empty session
93
+ but fail on setting.
94
+ """
95
+
96
+ def _fail(self, *args: t.Any, **kwargs: t.Any) -> "te.NoReturn":
97
+ raise RuntimeError(
98
+ "The session is unavailable because no secret "
99
+ "key was set. Set the secret_key on the "
100
+ "application to something unique and secret."
101
+ )
102
+
103
+ __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail # type: ignore # noqa: B950
104
+ del _fail
105
+
106
+
107
+ class SessionInterface:
108
+ """The basic interface you have to implement in order to replace the
109
+ default session interface which uses werkzeug's securecookie
110
+ implementation. The only methods you have to implement are
111
+ :meth:`open_session` and :meth:`save_session`, the others have
112
+ useful defaults which you don't need to change.
113
+
114
+ The session object returned by the :meth:`open_session` method has to
115
+ provide a dictionary like interface plus the properties and methods
116
+ from the :class:`SessionMixin`. We recommend just subclassing a dict
117
+ and adding that mixin::
118
+
119
+ class Session(dict, SessionMixin):
120
+ pass
121
+
122
+ If :meth:`open_session` returns ``None`` Flask will call into
123
+ :meth:`make_null_session` to create a session that acts as replacement
124
+ if the session support cannot work because some requirement is not
125
+ fulfilled. The default :class:`NullSession` class that is created
126
+ will complain that the secret key was not set.
127
+
128
+ To replace the session interface on an application all you have to do
129
+ is to assign :attr:`flask.Flask.session_interface`::
130
+
131
+ app = Flask(__name__)
132
+ app.session_interface = MySessionInterface()
133
+
134
+ Multiple requests with the same session may be sent and handled
135
+ concurrently. When implementing a new session interface, consider
136
+ whether reads or writes to the backing store must be synchronized.
137
+ There is no guarantee on the order in which the session for each
138
+ request is opened or saved, it will occur in the order that requests
139
+ begin and end processing.
140
+
141
+ .. versionadded:: 0.8
142
+ """
143
+
144
+ #: :meth:`make_null_session` will look here for the class that should
145
+ #: be created when a null session is requested. Likewise the
146
+ #: :meth:`is_null_session` method will perform a typecheck against
147
+ #: this type.
148
+ null_session_class = NullSession
149
+
150
+ #: A flag that indicates if the session interface is pickle based.
151
+ #: This can be used by Flask extensions to make a decision in regards
152
+ #: to how to deal with the session object.
153
+ #:
154
+ #: .. versionadded:: 0.10
155
+ pickle_based = False
156
+
157
+ def make_null_session(self, app: "Flask") -> NullSession:
158
+ """Creates a null session which acts as a replacement object if the
159
+ real session support could not be loaded due to a configuration
160
+ error. This mainly aids the user experience because the job of the
161
+ null session is to still support lookup without complaining but
162
+ modifications are answered with a helpful error message of what
163
+ failed.
164
+
165
+ This creates an instance of :attr:`null_session_class` by default.
166
+ """
167
+ return self.null_session_class()
168
+
169
+ def is_null_session(self, obj: object) -> bool:
170
+ """Checks if a given object is a null session. Null sessions are
171
+ not asked to be saved.
172
+
173
+ This checks if the object is an instance of :attr:`null_session_class`
174
+ by default.
175
+ """
176
+ return isinstance(obj, self.null_session_class)
177
+
178
+ def get_cookie_name(self, app: "Flask") -> str:
179
+ """Returns the name of the session cookie.
180
+
181
+ Uses ``app.session_cookie_name`` which is set to ``SESSION_COOKIE_NAME``
182
+ """
183
+ return app.session_cookie_name
184
+
185
+ def get_cookie_domain(self, app: "Flask") -> t.Optional[str]:
186
+ """Returns the domain that should be set for the session cookie.
187
+
188
+ Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise
189
+ falls back to detecting the domain based on ``SERVER_NAME``.
190
+
191
+ Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is
192
+ updated to avoid re-running the logic.
193
+ """
194
+
195
+ rv = app.config["SESSION_COOKIE_DOMAIN"]
196
+
197
+ # set explicitly, or cached from SERVER_NAME detection
198
+ # if False, return None
199
+ if rv is not None:
200
+ return rv if rv else None
201
+
202
+ rv = app.config["SERVER_NAME"]
203
+
204
+ # server name not set, cache False to return none next time
205
+ if not rv:
206
+ app.config["SESSION_COOKIE_DOMAIN"] = False
207
+ return None
208
+
209
+ # chop off the port which is usually not supported by browsers
210
+ # remove any leading '.' since we'll add that later
211
+ rv = rv.rsplit(":", 1)[0].lstrip(".")
212
+
213
+ if "." not in rv:
214
+ # Chrome doesn't allow names without a '.'. This should only
215
+ # come up with localhost. Hack around this by not setting
216
+ # the name, and show a warning.
217
+ warnings.warn(
218
+ f"{rv!r} is not a valid cookie domain, it must contain"
219
+ " a '.'. Add an entry to your hosts file, for example"
220
+ f" '{rv}.localdomain', and use that instead."
221
+ )
222
+ app.config["SESSION_COOKIE_DOMAIN"] = False
223
+ return None
224
+
225
+ ip = is_ip(rv)
226
+
227
+ if ip:
228
+ warnings.warn(
229
+ "The session cookie domain is an IP address. This may not work"
230
+ " as intended in some browsers. Add an entry to your hosts"
231
+ ' file, for example "localhost.localdomain", and use that'
232
+ " instead."
233
+ )
234
+
235
+ # if this is not an ip and app is mounted at the root, allow subdomain
236
+ # matching by adding a '.' prefix
237
+ if self.get_cookie_path(app) == "/" and not ip:
238
+ rv = f".{rv}"
239
+
240
+ app.config["SESSION_COOKIE_DOMAIN"] = rv
241
+ return rv
242
+
243
+ def get_cookie_path(self, app: "Flask") -> str:
244
+ """Returns the path for which the cookie should be valid. The
245
+ default implementation uses the value from the ``SESSION_COOKIE_PATH``
246
+ config var if it's set, and falls back to ``APPLICATION_ROOT`` or
247
+ uses ``/`` if it's ``None``.
248
+ """
249
+ return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]
250
+
251
+ def get_cookie_httponly(self, app: "Flask") -> bool:
252
+ """Returns True if the session cookie should be httponly. This
253
+ currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``
254
+ config var.
255
+ """
256
+ return app.config["SESSION_COOKIE_HTTPONLY"]
257
+
258
+ def get_cookie_secure(self, app: "Flask") -> bool:
259
+ """Returns True if the cookie should be secure. This currently
260
+ just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
261
+ """
262
+ return app.config["SESSION_COOKIE_SECURE"]
263
+
264
+ def get_cookie_samesite(self, app: "Flask") -> str:
265
+ """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the
266
+ ``SameSite`` attribute. This currently just returns the value of
267
+ the :data:`SESSION_COOKIE_SAMESITE` setting.
268
+ """
269
+ return app.config["SESSION_COOKIE_SAMESITE"]
270
+
271
+ def get_expiration_time(
272
+ self, app: "Flask", session: SessionMixin
273
+ ) -> t.Optional[datetime]:
274
+ """A helper method that returns an expiration date for the session
275
+ or ``None`` if the session is linked to the browser session. The
276
+ default implementation returns now + the permanent session
277
+ lifetime configured on the application.
278
+ """
279
+ if session.permanent:
280
+ return datetime.utcnow() + app.permanent_session_lifetime
281
+ return None
282
+
283
+ def should_set_cookie(self, app: "Flask", session: SessionMixin) -> bool:
284
+ """Used by session backends to determine if a ``Set-Cookie`` header
285
+ should be set for this session cookie for this response. If the session
286
+ has been modified, the cookie is set. If the session is permanent and
287
+ the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is
288
+ always set.
289
+
290
+ This check is usually skipped if the session was deleted.
291
+
292
+ .. versionadded:: 0.11
293
+ """
294
+
295
+ return session.modified or (
296
+ session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]
297
+ )
298
+
299
+ def open_session(
300
+ self, app: "Flask", request: "Request"
301
+ ) -> t.Optional[SessionMixin]:
302
+ """This is called at the beginning of each request, after
303
+ pushing the request context, before matching the URL.
304
+
305
+ This must return an object which implements a dictionary-like
306
+ interface as well as the :class:`SessionMixin` interface.
307
+
308
+ This will return ``None`` to indicate that loading failed in
309
+ some way that is not immediately an error. The request
310
+ context will fall back to using :meth:`make_null_session`
311
+ in this case.
312
+ """
313
+ raise NotImplementedError()
314
+
315
+ def save_session(
316
+ self, app: "Flask", session: SessionMixin, response: "Response"
317
+ ) -> None:
318
+ """This is called at the end of each request, after generating
319
+ a response, before removing the request context. It is skipped
320
+ if :meth:`is_null_session` returns ``True``.
321
+ """
322
+ raise NotImplementedError()
323
+
324
+
325
+ session_json_serializer = TaggedJSONSerializer()
326
+
327
+
328
+ class SecureCookieSessionInterface(SessionInterface):
329
+ """The default session interface that stores sessions in signed cookies
330
+ through the :mod:`itsdangerous` module.
331
+ """
332
+
333
+ #: the salt that should be applied on top of the secret key for the
334
+ #: signing of cookie based sessions.
335
+ salt = "cookie-session"
336
+ #: the hash function to use for the signature. The default is sha1
337
+ digest_method = staticmethod(hashlib.sha1)
338
+ #: the name of the itsdangerous supported key derivation. The default
339
+ #: is hmac.
340
+ key_derivation = "hmac"
341
+ #: A python serializer for the payload. The default is a compact
342
+ #: JSON derived serializer with support for some extra Python types
343
+ #: such as datetime objects or tuples.
344
+ serializer = session_json_serializer
345
+ session_class = SecureCookieSession
346
+
347
+ def get_signing_serializer(
348
+ self, app: "Flask"
349
+ ) -> t.Optional[URLSafeTimedSerializer]:
350
+ if not app.secret_key:
351
+ return None
352
+ signer_kwargs = dict(
353
+ key_derivation=self.key_derivation, digest_method=self.digest_method
354
+ )
355
+ return URLSafeTimedSerializer(
356
+ app.secret_key,
357
+ salt=self.salt,
358
+ serializer=self.serializer,
359
+ signer_kwargs=signer_kwargs,
360
+ )
361
+
362
+ def open_session(
363
+ self, app: "Flask", request: "Request"
364
+ ) -> t.Optional[SecureCookieSession]:
365
+ s = self.get_signing_serializer(app)
366
+ if s is None:
367
+ return None
368
+ val = request.cookies.get(self.get_cookie_name(app))
369
+ if not val:
370
+ return self.session_class()
371
+ max_age = int(app.permanent_session_lifetime.total_seconds())
372
+ try:
373
+ data = s.loads(val, max_age=max_age)
374
+ return self.session_class(data)
375
+ except BadSignature:
376
+ return self.session_class()
377
+
378
+ def save_session(
379
+ self, app: "Flask", session: SessionMixin, response: "Response"
380
+ ) -> None:
381
+ name = self.get_cookie_name(app)
382
+ domain = self.get_cookie_domain(app)
383
+ path = self.get_cookie_path(app)
384
+ secure = self.get_cookie_secure(app)
385
+ samesite = self.get_cookie_samesite(app)
386
+ httponly = self.get_cookie_httponly(app)
387
+
388
+ # If the session is modified to be empty, remove the cookie.
389
+ # If the session is empty, return without setting the cookie.
390
+ if not session:
391
+ if session.modified:
392
+ response.delete_cookie(
393
+ name,
394
+ domain=domain,
395
+ path=path,
396
+ secure=secure,
397
+ samesite=samesite,
398
+ httponly=httponly,
399
+ )
400
+
401
+ return
402
+
403
+ # Add a "Vary: Cookie" header if the session was accessed at all.
404
+ if session.accessed:
405
+ response.vary.add("Cookie")
406
+
407
+ if not self.should_set_cookie(app, session):
408
+ return
409
+
410
+ expires = self.get_expiration_time(app, session)
411
+ val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore
412
+ response.set_cookie(
413
+ name,
414
+ val, # type: ignore
415
+ expires=expires,
416
+ httponly=httponly,
417
+ domain=domain,
418
+ path=path,
419
+ secure=secure,
420
+ samesite=samesite,
421
+ )
testbed/pallets__flask/src/flask/signals.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing as t
2
+
3
+ try:
4
+ from blinker import Namespace
5
+
6
+ signals_available = True
7
+ except ImportError:
8
+ signals_available = False
9
+
10
+ class Namespace: # type: ignore
11
+ def signal(self, name: str, doc: t.Optional[str] = None) -> "_FakeSignal":
12
+ return _FakeSignal(name, doc)
13
+
14
+ class _FakeSignal:
15
+ """If blinker is unavailable, create a fake class with the same
16
+ interface that allows sending of signals but will fail with an
17
+ error on anything else. Instead of doing anything on send, it
18
+ will just ignore the arguments and do nothing instead.
19
+ """
20
+
21
+ def __init__(self, name: str, doc: t.Optional[str] = None) -> None:
22
+ self.name = name
23
+ self.__doc__ = doc
24
+
25
+ def send(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
26
+ pass
27
+
28
+ def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
29
+ raise RuntimeError(
30
+ "Signalling support is unavailable because the blinker"
31
+ " library is not installed."
32
+ ) from None
33
+
34
+ connect = connect_via = connected_to = temporarily_connected_to = _fail
35
+ disconnect = _fail
36
+ has_receivers_for = receivers_for = _fail
37
+ del _fail
38
+
39
+
40
+ # The namespace for code signals. If you are not Flask code, do
41
+ # not put signals in here. Create your own namespace instead.
42
+ _signals = Namespace()
43
+
44
+
45
+ # Core signals. For usage examples grep the source code or consult
46
+ # the API documentation in docs/api.rst as well as docs/signals.rst
47
+ template_rendered = _signals.signal("template-rendered")
48
+ before_render_template = _signals.signal("before-render-template")
49
+ request_started = _signals.signal("request-started")
50
+ request_finished = _signals.signal("request-finished")
51
+ request_tearing_down = _signals.signal("request-tearing-down")
52
+ got_request_exception = _signals.signal("got-request-exception")
53
+ appcontext_tearing_down = _signals.signal("appcontext-tearing-down")
54
+ appcontext_pushed = _signals.signal("appcontext-pushed")
55
+ appcontext_popped = _signals.signal("appcontext-popped")
56
+ message_flashed = _signals.signal("message-flashed")