Skip to content
Myr

Merge remote-tracking branch 'origin/2.0.x' into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Grey Li · committed by Grey Li · parents aac6728, 49cbb77 · Browse files · 15 files+118 added−43 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+118 added−43 removed

  • tests:+34 added−1 removed
  • other:+84 added−42 removed

15 files+118 added−43 removed

modified:docs/patterns/celery.rst+1 added-1 removed
62 unmodified lines
63---------------6465Let's write a task that adds two numbers together and returns the result. We66configure Celery's broker and backend to use Redis, create a ``celery``67application using the factor from above, and then use it to define the task. ::67application using the factory from above, and then use it to define the task. ::6869 from flask import Flask7071 flask_app = Flask(__name__)
30 unmodified lines
modified:docs/async-await.rst+8 added-1 removed
5 unmodified lines
6.. versionadded:: 2.078Routes, error handlers, before request, after request, and teardown9functions can all be coroutine functions if Flask is installed with the10``async`` extra (``pip install flask[async]``). This allows views to be10``async`` extra (``pip install flask[async]``). It requires Python 3.7+11where ``contextvars.ContextVar`` is available. This allows views to be12defined with ``async def`` and use ``await``.1314.. code-block:: python15
1 unmodified line
17 async def get_data():18 data = await async_db_query(...)19 return jsonify(data)2021Pluggable class-based views also support handlers that are implemented as22coroutines. This applies to the :meth:`~flask.views.View.dispatch_request`23method in views that inherit from the :class:`flask.views.View` class, as24well as all the HTTP method handlers in views that inherit from the25:class:`flask.views.MethodView` class.2627.. admonition:: Using ``async`` on Windows on Python 3.82829 Python 3.8 has a bug related to asyncio on Windows. If you encounter30 something like ``ValueError: set_wakeup_fd only works in main thread``,
96 unmodified lines
modified:docs/installation.rst+2 added
6 unmodified lines
78We recommend using the latest version of Python. Flask supports Python93.6 and newer.1011``async`` support in Flask requires Python 3.7+ for ``contextvars.ContextVar``.121314Dependencies15------------1617These distributions will be installed automatically when installing Flask.
118 unmodified lines
modified:docs/quickstart.rst+3 added-3 removed
442 unmodified lines
443 {% else %}444 <h1>Hello, World!</h1>445 {% endif %}446447Inside templates you also have access to the :class:`~flask.request`,448:class:`~flask.session` and :class:`~flask.g` [#]_ objects449as well as the :func:`~flask.get_flashed_messages` function.447Inside templates you also have access to the :data:`~flask.Flask.config`,448:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects449as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions.450451Templates are especially useful if inheritance is used. If you want to452know how that works, see :doc:`patterns/templateinheritance`. Basically453template inheritance makes it possible to keep certain elements on each
485 unmodified lines
modified:docs/templating.rst+1 added-1 removed
35 unmodified lines
3637.. data:: config38 :noindex:3940 The current configuration object (:data:`flask.config`)40 The current configuration object (:data:`flask.Flask.config`)4142 .. versionadded:: 0.64344 .. versionchanged:: 0.10
159 unmodified lines
modified:docs/testing.rst+15 added-14 removed
46 unmodified lines
4748 import pytest4950 from flaskr import create_app51 from flaskr.db import init_db525354 @pytest.fixture55 def client():55 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 flaskr.app.config['TESTING'] = True56 db_fd, db_path = tempfile.mkstemp()57 app = create_app({'TESTING': True, 'DATABASE': db_path})5858 with flaskr.app.test_client() as client:59 with flaskr.app.app_context():60 flaskr.init_db()59 with app.test_client() as client:60 with app.app_context():61 init_db()62 yield client6364 os.close(db_fd)64 os.unlink(flaskr.app.config['DATABASE'])65 os.unlink(db_path)6667This client fixture will be called by each individual test. It gives us a68simple interface to the application, where we can trigger test requests to the69application. The client will also keep track of cookies for us.
154 unmodified lines
224temporarily. With this you can access the :class:`~flask.request`,225:class:`~flask.g` and :class:`~flask.session` objects like in view226functions. Here is a full example that demonstrates this approach::227227 import flask228 from flask import Flask, request229229 app = flask.Flask(__name__)230 app = Flask(__name__)231232 with app.test_request_context('/?name=Peter'):232 assert flask.request.path == '/'233 assert flask.request.args['name'] == 'Peter'233 assert request.path == '/'234 assert request.args['name'] == 'Peter'235236All the other objects that are context bound can be used in the same237way.238
8 unmodified lines
247the test request context leaves the ``with`` block. If you do want the248:meth:`~flask.Flask.before_request` functions to be called as well, you249need to call :meth:`~flask.Flask.preprocess_request` yourself::250250 app = flask.Flask(__name__)251 app = Flask(__name__)252253 with app.test_request_context('/?name=Peter'):254 app.preprocess_request()255 ...
4 unmodified lines
260If you want to call the :meth:`~flask.Flask.after_request` functions you261need to call into :meth:`~flask.Flask.process_response` which however262requires that you pass it a response object::263263 app = flask.Flask(__name__)264 app = Flask(__name__)265266 with app.test_request_context('/?name=Peter'):267 resp = Response('...')268 resp = app.process_response(resp)
60 unmodified lines
329context around for a little longer so that additional introspection can330happen. With Flask 0.4 this is possible by using the331:meth:`~flask.Flask.test_client` with a ``with`` block::332332 app = flask.Flask(__name__)333 app = Flask(__name__)334335 with app.test_client() as c:336 rv = c.get('/?tequila=42')337 assert request.args['tequila'] == '42'
15 unmodified lines
353keep the context around and access :data:`flask.session`::354355 with app.test_client() as c:356 rv = c.get('/')356 assert flask.session['foo'] == 42357 assert session['foo'] == 42358359This however does not make it possible to also modify the session or to360access the session before a request was fired. Starting with Flask 0.8 we361provide a so called “session transaction” which simulates the appropriate
102 unmodified lines
modified:src/flask/app.py+5 added-3 removed
59 unmodified lines
60from .templating import Environment61from .typing import AfterRequestCallable62from .typing import BeforeFirstRequestCallable63from .typing import BeforeRequestCallable64from .typing import ErrorHandlerCallable64from .typing import ResponseReturnValue65from .typing import TeardownCallable66from .typing import TemplateContextProcessorCallable67from .typing import TemplateFilterCallable
8 unmodified lines
76 import typing_extensions as te77 from .blueprints import Blueprint78 from .testing import FlaskClient79 from .testing import FlaskCliRunner80 from .typing import ErrorHandlerCallable8182if sys.version_info >= (3, 8):83 iscoroutinefunction = inspect.iscoroutinefunction84else:
1182 unmodified lines
1267 """1268 self.shell_context_processors.append(f)1269 return f12701271 def _find_error_handler(self, e: Exception) -> t.Optional[ErrorHandlerCallable]:1271 def _find_error_handler(1272 self, e: Exception1273 ) -> t.Optional["ErrorHandlerCallable[Exception]"]:1274 """Return a registered error handler for an exception in this order:1275 blueprint handler for a specific code, app handler for a specific code,1276 blueprint handler for an exception class, app handler for an exception1277 class, or ``None`` if a suitable handler is not found.1278 """1279 exc_class, code = self._get_exc_class_and_code(type(e))12801279 for c in [code, None]:1281 for c in [code, None] if code is not None else [None]:1282 for name in chain(request.blueprints, [None]):1283 handler_map = self.error_handler_spec[name][c]12841285 if not handler_map:
808 unmodified lines
modified:src/flask/blueprints.py+9 added-5 removed
6 unmodified lines
7from .scaffold import Scaffold8from .typing import AfterRequestCallable9from .typing import BeforeFirstRequestCallable10from .typing import BeforeRequestCallable11from .typing import ErrorHandlerCallable11from .typing import TeardownCallable12from .typing import TemplateContextProcessorCallable13from .typing import TemplateFilterCallable14from .typing import TemplateGlobalCallable
2 unmodified lines
17from .typing import URLValuePreprocessorCallable1819if t.TYPE_CHECKING:20 from .app import Flask21 from .typing import ErrorHandlerCallable2223DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]2425
266 unmodified lines
292 .. versionchanged:: 2.0.1293 Registering the same blueprint with the same name multiple294 times is deprecated and will become an error in Flask 2.1.295 """296 first_registration = not any(bp is self for bp in app.blueprints.values())296 name_prefix = options.get("name_prefix", "")297 self_name = options.get("name", self.name)298 name = f"{name_prefix}.{self_name}".lstrip(".")299
16 unmodified lines
316 " in Flask 2.1.",317 stacklevel=4,318 )319320 first_bp_registration = not any(bp is self for bp in app.blueprints.values())321 first_name_registration = name not in app.blueprints322323 app.blueprints[name] = self324 self._got_registered_once = True323 state = self.make_setup_state(app, options, first_registration)325 state = self.make_setup_state(app, options, first_bp_registration)326327 if self.has_static_folder:328 state.add_url_rule(329 f"{self.static_url_path}/<path:filename>",
1 unmodified line
331 endpoint="static",332 )333334 # Merge blueprint data into parent.333 if first_registration:335 if first_bp_registration or first_name_registration:336337 def extend(bp_dict, parent_dict):338 for key, values in bp_dict.items():339 key = name if key is None else f"{name}.{key}"
242 unmodified lines
582 """Like :meth:`Flask.errorhandler` but for a blueprint. This583 handler is used for all requests, even if outside of the blueprint.584 """585584 def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:586 def decorator(587 f: "ErrorHandlerCallable[Exception]",588 ) -> "ErrorHandlerCallable[Exception]":589 self.record_once(lambda s: s.app.errorhandler(code)(f))590 return f591592 return decorator
16 unmodified lines
modified:src/flask/scaffold.py+19 added-8 removed
19 unmodified lines
20from .templating import _default_template_ctx_processor21from .typing import AfterRequestCallable22from .typing import AppOrBlueprintKey23from .typing import BeforeRequestCallable24from .typing import ErrorHandlerCallable24from .typing import GenericException25from .typing import TeardownCallable26from .typing import TemplateContextProcessorCallable27from .typing import URLDefaultCallable28from .typing import URLValuePreprocessorCallable2930if t.TYPE_CHECKING:31 from .wrappers import Response32 from .typing import ErrorHandlerCallable3334# a singleton sentinel value for parameter defaults35_sentinel = object()36
107 unmodified lines
144 #: This data structure is internal. It should not be modified145 #: directly and its format may change at any time.146 self.error_handler_spec: t.Dict[147 AppOrBlueprintKey,147 t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]],148 t.Dict[149 t.Optional[int],150 t.Dict[t.Type[Exception], "ErrorHandlerCallable[Exception]"],151 ],152 ] = defaultdict(lambda: defaultdict(dict))153154 #: A data structure of functions to call at the beginning of155 #: each request, in the format ``{scope: [functions]}``. The
490 unmodified lines
646 return f647648 @setupmethod649 def errorhandler(646 self, code_or_exception: t.Union[t.Type[Exception], int]647 ) -> t.Callable[[ErrorHandlerCallable], ErrorHandlerCallable]:650 self, code_or_exception: t.Union[t.Type[GenericException], int]651 ) -> t.Callable[652 ["ErrorHandlerCallable[GenericException]"],653 "ErrorHandlerCallable[GenericException]",654 ]:655 """Register a function to handle errors by code or exception class.656657 A decorator that is used to register a function given an658 error code. Example::
21 unmodified lines
680 :param code_or_exception: the code as integer for the handler, or681 an arbitrary exception682 """683677 def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:684 def decorator(685 f: "ErrorHandlerCallable[GenericException]",686 ) -> "ErrorHandlerCallable[GenericException]":687 self.register_error_handler(code_or_exception, f)688 return f689690 return decorator691692 @setupmethod693 def register_error_handler(694 self,686 code_or_exception: t.Union[t.Type[Exception], int],687 f: ErrorHandlerCallable,695 code_or_exception: t.Union[t.Type[GenericException], int],696 f: "ErrorHandlerCallable[GenericException]",697 ) -> None:698 """Alternative error attach function to the :meth:`errorhandler`699 decorator that is more straightforward to use for non decorator700 usage.
15 unmodified lines
716 " code. Use a subclass of HTTPException with that code"717 " instead."718 )719711 self.error_handler_spec[None][code][exc_class] = f720 self.error_handler_spec[None][code][exc_class] = t.cast(721 "ErrorHandlerCallable[Exception]", f722 )723724 @staticmethod725 def _get_exc_class_and_code(726 exc_class_or_code: t.Union[t.Type[Exception], int]
149 unmodified lines
modified:src/flask/typing.py+10 added-1 removed
31 unmodified lines
32 t.Tuple[ResponseValue, StatusCode, HeadersValue],33 "WSGIApplication",34]3536GenericException = t.TypeVar("GenericException", bound=Exception, contravariant=True)3738AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39AfterRequestCallable = t.Callable[["Response"], "Response"]40BeforeFirstRequestCallable = t.Callable[[], None]41BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]40ErrorHandlerCallable = t.Callable[[Exception], ResponseReturnValue]42TeardownCallable = t.Callable[[t.Optional[BaseException]], None]43TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]44TemplateFilterCallable = t.Callable[..., t.Any]45TemplateGlobalCallable = t.Callable[..., t.Any]46TemplateTestCallable = t.Callable[..., bool]47URLDefaultCallable = t.Callable[[str, dict], None]48URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]495051if t.TYPE_CHECKING:52 import typing_extensions as te5354 class ErrorHandlerCallable(te.Protocol[GenericException]):55 def __call__(self, error: GenericException) -> ResponseReturnValue:56 ...
modified:src/flask/views.py+3 added-2 removed
1import typing as t23from .globals import current_app4from .globals import request5from .typing import ResponseReturnValue67
72 unmodified lines
80 """8182 def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:83 self = view.view_class(*class_args, **class_kwargs) # type: ignore83 return self.dispatch_request(*args, **kwargs)84 return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)8586 if cls.decorators:87 view.__name__ = name88 view.__module__ = cls.__module__
65 unmodified lines
154 if meth is None and request.method == "HEAD":155 meth = getattr(self, "get", None)156157 assert meth is not None, f"Unimplemented method {request.method!r}"157 return meth(*args, **kwargs)158 return current_app.ensure_sync(meth)(*args, **kwargs)
modified:tests/test_async.py+24 added-1 removed
4 unmodified lines
56from flask import Blueprint7from flask import Flask8from flask import request9from flask.views import MethodView10from flask.views import View1112pytest.importorskip("asgiref")1314
4 unmodified lines
19class BlueprintError(Exception):20 pass212223class AsyncView(View):24 methods = ["GET", "POST"]2526 async def dispatch_request(self):27 await asyncio.sleep(0)28 return request.method293031class AsyncMethodView(MethodView):32 async def get(self):33 await asyncio.sleep(0)34 return "GET"3536 async def post(self):37 await asyncio.sleep(0)38 return "POST"394041@pytest.fixture(name="async_app")42def _async_app():43 app = Flask(__name__)44
27 unmodified lines
72 raise BlueprintError()7374 app.register_blueprint(blueprint, url_prefix="/bp")7576 app.add_url_rule("/view", view_func=AsyncView.as_view("view"))77 app.add_url_rule("/methodview", view_func=AsyncMethodView.as_view("methodview"))7879 return app808182@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")60@pytest.mark.parametrize("path", ["/", "/home", "/bp/"])83@pytest.mark.parametrize("path", ["/", "/home", "/bp/", "/view", "/methodview"])84def test_async_route(path, async_app):85 test_client = async_app.test_client()86 response = test_client.get(path)87 assert b"GET" in response.get_data()
76 unmodified lines
modified:tests/test_blueprints.py+10 added
897 unmodified lines
898 @bp.get("/")899 def index():900 return flask.request.endpoint901902 @bp.get("/error")903 def error():904 flask.abort(403)905906 @bp.errorhandler(403)907 def forbidden(_: Exception):908 return "Error", 403909910 @bp2.get("/")911 def index2():912 return flask.request.endpoint913
4 unmodified lines
918 assert client.get("/a/").data == b"bp.index"919 assert client.get("/b/").data == b"alt.index"920 assert client.get("/a/a/").data == b"bp.sub.index2"921 assert client.get("/b/a/").data == b"alt.sub.index2"922 assert client.get("/a/error").data == b"Error"923 assert client.get("/b/error").data == b"Error"
modified:CHANGES.rst+4 added-1 removed
11 unmodified lines
12-------------1314Unreleased1516- Fix type annotation for ``teardown_request``. :issue:`4093`16- Fix type annotation for ``teardown_*`` methods. :issue:`4093`17- Fix type annotation for ``before_request`` and ``before_app_request``18 decorators. :issue:`4104`19- Fixed the issue where typing requires template global20 decorators to accept functions with no arguments. :issue:`4098`21- Support View and MethodView instances with async handlers. :issue:`4112`22- Enhance typing of ``app.errorhandler`` decorator. :issue:`4095`23- Fix registering a blueprint twice with differing names. :issue:`4124`242526Version 2.0.127-------------
1154 unmodified lines
modified:CONTRIBUTING.rst+4 added-2 removed
10 unmodified lines
11to address bugs and feature requests in Flask itself. Use one of the12following resources for questions about using Flask or issues with your13own code:1415- The ``#get-help`` channel on our Discord chat:15- The ``#questions`` channel on our Discord chat:16 https://discord.gg/pallets17- The mailing list flask@python.org for long term discussion or larger18 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`_.2223.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?tab=Frequent24.. _GitHub Discussions: https://github.com/pallets/flask/discussions252627Reporting issues28----------------
64 unmodified lines
93 default Pallets remote is "origin".9495 .. code-block:: text9695 git remote add fork https://github.com/{username}/flask97 $ git remote add fork https://github.com/{username}/flask9899- Create a virtualenv.100101 .. tabs::
128 unmodified lines