It is better to encourage users to utilise the app ensure_sync method
(or the newely added async_to_sync method) so that any extensions that
alter these methods take affect throughout the users code.
With the helper method users code fix parts of their code to the
asgiref async_to_sync ignoring any extension changes.
Firstly `run_sync` was a misleading name as it didn't run anything,
instead I think `async_to_sync` is much clearer as it converts a
coroutine function to a function. (Name stolen from asgiref).
Secondly trying to run the ensure_sync during registration made the
code more complex and brittle, e.g. the _flask_async_wrapper
usage. This was done to pay any setup costs during registration rather
than runtime, however this only saved a iscoroutne check. It allows
the weirdness of the Blueprint and Scaffold ensure_sync methods to be
removed.
Switching to runtime ensure_sync usage provides a method for
extensions to also support async, as now documented.
As long as popular libraries (e.g. Celery) require click 7, depending
on Click 8 in Flask makes it hard to test the latest version (and its
other dependencies) in existing applications.
Wrapped functions are not comparable, see
https://bugs.python.org/issue3564, therefore a marker is used to note
when the function has been sync wrapped to allow comparison with the
wrapped function instead.
This ensures that multiple route decorators work without raising
exceptions i.e.,
@app.route("/")
@app.route("/a")
async def index():
...
works.
This allows blueprints to be nested within blueprints via a new
Blueprint.register_blueprint method. This should provide a use case
that has been desired for the past ~10 years.
This works by setting the endpoint name to be the blueprint names,
from parent to child delimeted by "." and then iterating over the
blueprint names in reverse order in the app (from most specific to
most general). This means that the expectation of nesting a blueprint
within a nested blueprint is met.
This allows extensions to override the Flask.ensure_sync method and
have the change apply to blueprints as well. Without this change it is
possible for differing blueprints to have differing ensure_sync
approaches depending on the extension used - which would likely result
in event-loop blocking issues.
This also allows blueprints to have a custom ensure_sync, although
this is a by product rather than an expected use case.
Werkzeug offers a ContextVar replacement for Python < 3.7, however it
doesn't work across asyncio tasks, hence it makes sense to error out
rather than find there are odd bugs.
Note the docs build requires the latest (dev) Werkzeug due to this
change (to import ContextVar from werkzeug.local).
This allows for async functions to be passed to the Flask class
instance, for example as a view function,
@app.route("/")
async def index():
return "Async hello"
this comes with a cost though of poorer performance than using the
sync equivalent.
asgiref is the standard way to run async code within a sync context,
and is used in Django making it a safe and sane choice for this.
This takes a popular API whereby instead of passing the HTTP method as
an argument to route it is instead used as the method name i.e.
@app.route("/", methods=["POST"])
is now writeable as,
@app.post("/")
This is simply syntatic sugar, it doesn't do anything else, but makes
it slightly easier for users.
I've included all the methods that are relevant and aren't auto
generated i.e. not connect, head, options, and trace.
The implementations were moved to Werkzeug, Flask's functions become
wrappers around Werkzeug to pass some Flask-specific values.
cache_timeout is renamed to max_age. SEND_FILE_MAX_AGE_DEFAULT,
app.send_file_max_age_default, and app.get_send_file_max_age defaults
to None. This tells the browser to use conditional requests rather than
a 12 hour cache.
attachment_filename is renamed to download_name, and is always sent if
a name is known.
Deprecate helpers.safe_join in favor of werkzeug.utils.safe_join.
Removed most of the send_file tests, they're tested in Werkzeug.
In the file upload example, renamed the uploaded_file view to
download_file to avoid a common source of confusion.
Flask's client.open mirrors Werkzeug's for processing an existing
environ.
Always test with latest code for other Pallets projects. This will
be changed back once the new versions are released.
Flask instances with static folders were creating a reference cycle
via their "static" view function (which held a strong reference back
to the Flask instance to call its `send_static_file` method). This
prevented CPython from freeing the memory for a Flask instance
when all external references to it were released.
Now use a weakref for the back reference to avoid this.
Co-authored-by: Joshua Bronson <jab@users.noreply.github.com>
When loading the app fails for the --help command, only the error
message is shown, then the help text. The full traceback is shown for
other exceptions. Also show the message when loading fails while
getting a command, instead of only "command not found". The error
message goes to stderr to match other error behavior, and is in red
with an extra newline to make it more obvious next to the help text.
Also fixes an issue with the test_apps fixture that caused an imported
app to still be importable after the test was over and the path was
reset. Now the module cache is reset as well.
* No longer causes AttributeError: 'PosixPath' object has no
attribute 'rstrip'.
* This was broken by e6178fe489
which was released in 1.1.2.
* Add a regression test that now passes.
See #3557.
TOML is a very popular format now, and is taking hold in the Python
ecosystem via pyproject.toml (among others). This allows toml config
files via,
app.config.from_file("config.toml", toml.loads)
it also allows for any other file format whereby there is a loader
that takes a string and returns a mapping.
- pytest 5.x drops python2 compatibility and therefore only implements PEP 451
- pytest 5.x made the repr of `ExcInfo` less confusing (fixed tests depending
on the old format)
`RequestContext.match_request` is moved from `__init__` to `push`. This
causes matching to happen later, when the app context is available.
This enables URL converters that use things such as the database.
After pallets/werkzeug#1577, mismatched configured and real server
names will show a warning in addition to raising 404. This caused
tests that did this deliberately to fail.
This patch removes the pytest fixture we were using to fail on
warnings, instead using the standard `-Werror` option. This speeds
up the tests by ~3x.
Before, returning a `bool` from a route caused the error
```
[2019-05-31 10:08:42,216] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 2070, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Users/johnzeringue/Documents/ts-open/flask/env/lib/python3.7/site-packages/werkzeug/wrappers/base_response.py", line 269, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Users/johnzeringue/Documents/ts-open/flask/env/lib/python3.7/site-packages/werkzeug/wrappers/base_response.py", line 26, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/Users/johnzeringue/Documents/ts-open/flask/env/lib/python3.7/site-packages/werkzeug/test.py", line 1119, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'bool' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 2393, in wsgi_app
response = self.full_dispatch_request()
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 1906, in full_dispatch_request
return self.finalize_request(rv)
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 1921, in finalize_request
response = self.make_response(rv)
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 2078, in make_response
reraise(TypeError, new_error, sys.exc_info()[2])
File "/Users/johnzeringue/Documents/ts-open/flask/flask/_compat.py", line 39, in reraise
raise value.with_traceback(tb)
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 2070, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Users/johnzeringue/Documents/ts-open/flask/env/lib/python3.7/site-packages/werkzeug/wrappers/base_response.py", line 269, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Users/johnzeringue/Documents/ts-open/flask/env/lib/python3.7/site-packages/werkzeug/wrappers/base_response.py", line 26, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/Users/johnzeringue/Documents/ts-open/flask/env/lib/python3.7/site-packages/werkzeug/test.py", line 1119, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'bool' object is not callable
The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a bool.
```
Now, it returns the more readable
```
[2019-05-31 10:36:19,500] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 2400, in wsgi_app
response = self.full_dispatch_request()
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 1907, in full_dispatch_request
return self.finalize_request(rv)
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 1922, in finalize_request
response = self.make_response(rv)
File "/Users/johnzeringue/Documents/ts-open/flask/flask/app.py", line 2085, in make_response
" {rv.__class__.__name__}.".format(rv=rv))
TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a bool.
```
Fixes#3214
-prefix a path delimiter iff there's a path to delimit
-ensures a valid default static route rule is created on application
intialisation for the case 'static_folder=""' and implicit
'static_url_path'
This supports an increasingly common usecase whereby JSON is the
primary response (rather than a templated string). Given Flask has a
short syntax for HTML reponses, it seems fitting that it should also
do so for JSON responses. In practice it allows,
@app.route("/")
def index():
return {
"api_stuff": "values",
}
* Current behavior: If a base class inherits MethodView and child class
inherits without overwriting "methods". The "methods" defined in base
class would be ignored
* Fix: Inherit all the "methods" defined in base classes if "methods"
variable is not overwritten
If attachment filename is bytes type and contains non-ascii coded bytes,
then the following ASCII encoding process will trigger
UnicodeDecodeError exception.
Fix issue #2933.
See: https://www.python.org/dev/peps/pep-0519/
This is mostly encountered with pathlib in python 3, but this API
suggests any PathLike object can be treated like a filepath with
`__fspath__` function.
We've discovered that passing Unicode in Host actually works, except for
test client limitations on Python 2 - and the only things that don't
work are non-printable characters.
If create_url_adapter raises (which it can if werkzeug cannot bind
environment, for example on non-ASCII Host header), we handle it as
other routing exceptions rather than raising through.
ref https://github.com/pallets/werkzeug/issues/640
Flask currently supports importing app through a combination of module
path and app variable name, such as '/usr/app.py:my_app'. When the
module path contains a colon, it will conflict with this import way and
a `flask.cli.NoAppException` will be raised.
A file path on a Windows system may contain a colon followed by a slash.
So we solved this problem on Windows by ignoring the colon followed by a
slash when we split app_import_path.
Fix issue #2961.
This is mainly intended for custom CLIs that may load a config file
which already sets the debug flag and does not make use of the `FLASK_*`
env vars at all.
Change the default value of ``index`` to ``None`` in ``register()`` so
that it is possible to insert a new tag as the penultimate item in the
order list.
rename new subdomain test, parametrize
test allowing subdomains as well as ips
add subdomain_matching param to docs
add some references to docs
add version changed to create_url_adapter