Skip to content
Myr

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

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

authored by David Lord · committed by David Lord · parents d575de5, f3551c8 · Browse files · 14 files+202 added−163 removed
This commit

State

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

Diff stats

14 files+202 added−163 removed

  • tests:+48 added−79 removed
  • other:+154 added−84 removed

14 files+202 added−163 removed

modified:docs/deploying/index.rst+1 added
14 unmodified lines
15--------------1617- `Deploying Flask on Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_18- `Deploying Flask on Google App Engine <https://cloud.google.com/appengine/docs/standard/python3/runtime>`_19- `Deploying Flask on Google Cloud Run <https://cloud.google.com/run/docs/quickstarts/build-and-deploy/python>`_20- `Deploying Flask on AWS Elastic Beanstalk <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html>`_21- `Deploying on Azure (IIS) <https://docs.microsoft.com/en-us/azure/app-service/containers/how-to-configure-python>`_22- `Deploying on PythonAnywhere <https://help.pythonanywhere.com/pages/Flask/>`_23
12 unmodified lines
modified:src/flask/__init__.py+41 added-41 removed
1from markupsafe import escape2from markupsafe import Markup3from werkzeug.exceptions import abort4from werkzeug.utils import redirect3from werkzeug.exceptions import abort as abort4from werkzeug.utils import redirect as redirect56from . import json7from .app import Flask8from .app import Request9from .app import Response10from .blueprints import Blueprint11from .config import Config12from .ctx import after_this_request13from .ctx import copy_current_request_context14from .ctx import has_app_context15from .ctx import has_request_context16from .globals import _app_ctx_stack17from .globals import _request_ctx_stack18from .globals import current_app19from .globals import g20from .globals import request21from .globals import session22from .helpers import flash23from .helpers import get_flashed_messages24from .helpers import get_template_attribute25from .helpers import make_response26from .helpers import safe_join27from .helpers import send_file28from .helpers import send_from_directory29from .helpers import stream_with_context30from .helpers import url_for31from .json import jsonify32from .signals import appcontext_popped33from .signals import appcontext_pushed34from .signals import appcontext_tearing_down35from .signals import before_render_template36from .signals import got_request_exception37from .signals import message_flashed38from .signals import request_finished39from .signals import request_started40from .signals import request_tearing_down41from .signals import signals_available42from .signals import template_rendered43from .templating import render_template44from .templating import render_template_string6from . import json as json7from .app import Flask as Flask8from .app import Request as Request9from .app import Response as Response10from .blueprints import Blueprint as Blueprint11from .config import Config as Config12from .ctx import after_this_request as after_this_request13from .ctx import copy_current_request_context as copy_current_request_context14from .ctx import has_app_context as has_app_context15from .ctx import has_request_context as has_request_context16from .globals import _app_ctx_stack as _app_ctx_stack17from .globals import _request_ctx_stack as _request_ctx_stack18from .globals import current_app as current_app19from .globals import g as g20from .globals import request as request21from .globals import session as session22from .helpers import flash as flash23from .helpers import get_flashed_messages as get_flashed_messages24from .helpers import get_template_attribute as get_template_attribute25from .helpers import make_response as make_response26from .helpers import safe_join as safe_join27from .helpers import send_file as send_file28from .helpers import send_from_directory as send_from_directory29from .helpers import stream_with_context as stream_with_context30from .helpers import url_for as url_for31from .json import jsonify as jsonify32from .signals import appcontext_popped as appcontext_popped33from .signals import appcontext_pushed as appcontext_pushed34from .signals import appcontext_tearing_down as appcontext_tearing_down35from .signals import before_render_template as before_render_template36from .signals import got_request_exception as got_request_exception37from .signals import message_flashed as message_flashed38from .signals import request_finished as request_finished39from .signals import request_started as request_started40from .signals import request_tearing_down as request_tearing_down41from .signals import signals_available as signals_available42from .signals import template_rendered as template_rendered43from .templating import render_template as render_template44from .templating import render_template_string as render_template_string4546__version__ = "2.1.0.dev0"
modified:src/flask/app.py+2 added-1 removed
70 unmodified lines
71from .wrappers import Request72from .wrappers import Response7374if t.TYPE_CHECKING:75 import typing_extensions as te76 from .blueprints import Blueprint77 from .testing import FlaskClient78 from .testing import FlaskCliRunner79
1361 unmodified lines
1441 self.logger.error(1442 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1443 )14441444 def raise_routing_exception(self, request: Request) -> t.NoReturn:1445 def raise_routing_exception(self, request: Request) -> "te.NoReturn":1446 """Exceptions that are recording during routing are reraised with1447 this method. During debug we are not reraising redirect requests1448 for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising1449 a different error instead to help debug situations.
627 unmodified lines
modified:src/flask/blueprints.py+20 added-12 removed
186 unmodified lines
187 static_url_path=static_url_path,188 template_folder=template_folder,189 root_path=root_path,190 )191192 if "." in name:193 raise ValueError("'name' may not contain a dot '.' character.")194195 self.name = name196 self.url_prefix = url_prefix197 self.subdomain = subdomain198 self.deferred_functions: t.List[DeferredSetupFunction] = []
60 unmodified lines
259 def register(self, app: "Flask", options: dict) -> None:260 """Called by :meth:`Flask.register_blueprint` to register all261 views and callbacks registered on the blueprint with the262 application. Creates a :class:`.BlueprintSetupState` and calls259 each :meth:`record` callbackwith it.263 each :meth:`record` callback with it.264265 :param app: The application this blueprint is being registered266 with.267 :param options: Keyword arguments forwarded from
75 unmodified lines
343 self.cli.name = cli_resolved_group344 app.cli.add_command(self.cli)345346 for blueprint, bp_options in self._blueprints:343 url_prefix = options.get("url_prefix", "")344 if "url_prefix" in bp_options:345 url_prefix = (346 url_prefix.rstrip("/") + "/" + bp_options["url_prefix"].lstrip("/")347 bp_options = bp_options.copy()348 bp_url_prefix = bp_options.get("url_prefix")349350 if bp_url_prefix is None:351 bp_url_prefix = blueprint.url_prefix352353 if state.url_prefix is not None and bp_url_prefix is not None:354 bp_options["url_prefix"] = (355 state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/")356 )357349 bp_options["url_prefix"] = url_prefix358 bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."359 blueprint.register(app, bp_options)360361 def add_url_rule(
5 unmodified lines
367 ) -> None:368 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for369 the :func:`url_for` function is prefixed with the name of the blueprint.370 """363 if endpoint:364 assert "." not in endpoint, "Blueprint endpoints should not contain dots"365 if view_func and hasattr(view_func, "__name__"):366 assert (367 "." not in view_func.__name__368 ), "Blueprint view function name should not contain dots"371 if endpoint and "." in endpoint:372 raise ValueError("'endpoint' may not contain a dot '.' character.")373374 if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__:375 raise ValueError("'view_func' name may not contain a dot '.' character.")376377 self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))378379 def app_template_filter(self, name: t.Optional[str] = None) -> t.Callable:380 """Register a custom template filter, available application wide. Like
170 unmodified lines
modified:src/flask/ctx.py+20 added-2 removed
39 unmodified lines
4041 .. versionadded:: 0.1042 """4344 # Define attr methods to let mypy know this is a namespace object45 # that has arbitrary attributes.4647 def __getattr__(self, name: str) -> t.Any:48 try:49 return self.__dict__[name]50 except KeyError:51 raise AttributeError(name) from None5253 def __setattr__(self, name: str, value: t.Any) -> None:54 self.__dict__[name] = value5556 def __delattr__(self, name: str) -> None:57 try:58 del self.__dict__[name]59 except KeyError:60 raise AttributeError(name) from None6162 def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any:63 """Get an attribute by name, or a default value. Like64 :meth:`dict.get`.65
29 unmodified lines
95 .. versionadded:: 0.1196 """97 return self.__dict__.setdefault(name, default)9881 def __contains__(self, item: t.Any) -> bool:99 def __contains__(self, item: str) -> bool:100 return item in self.__dict__10184 def __iter__(self) -> t.Iterator:102 def __iter__(self) -> t.Iterator[str]:103 return iter(self.__dict__)104105 def __repr__(self) -> str:106 top = _app_ctx_stack.top
372 unmodified lines
modified:src/flask/globals.py+5 added-3 removed
4 unmodified lines
5from werkzeug.local import LocalStack67if t.TYPE_CHECKING:8 from .app import Flask9 from .ctx import AppContext9 from .ctx import _AppCtxGlobals10 from .sessions import SessionMixin11 from .wrappers import Request1213_request_ctx_err_msg = """\
38 unmodified lines
52_request_ctx_stack = LocalStack()53_app_ctx_stack = LocalStack()54current_app: "Flask" = LocalProxy(_find_app) # type: ignore55request: "Request" = LocalProxy(partial(_lookup_req_object, "request")) # type: ignore56session: "SessionMixin" = LocalProxy(partial(_lookup_req_object, "session")) # type: ignore # noqa: B95057g: "AppContext" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignore56session: "SessionMixin" = LocalProxy( # type: ignore57 partial(_lookup_req_object, "session")58)59g: "_AppCtxGlobals" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignore
modified:src/flask/helpers.py+43 added-21 removed
2 unmodified lines
3import socket4import sys5import typing as t6import warnings7from datetime import datetime8from datetime import timedelta9from functools import update_wrapper10from threading import RLock11
424 unmodified lines
436 return flashes437438439def _prepare_send_file_kwargs(439 download_name=None,440 attachment_filename=None,441 etag=None,442 add_etags=None,443 max_age=None,444 cache_timeout=None,445 **kwargs,446):440 download_name: t.Optional[str] = None,441 attachment_filename: t.Optional[str] = None,442 etag: t.Optional[t.Union[bool, str]] = None,443 add_etags: t.Optional[t.Union[bool]] = None,444 max_age: t.Optional[445 t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]446 ] = None,447 cache_timeout: t.Optional[int] = None,448 **kwargs: t.Any,449) -> t.Dict[str, t.Any]:450 if attachment_filename is not None:451 warnings.warn(452 "The 'attachment_filename' parameter has been renamed to"453 " 'download_name'. The old name will be removed in Flask"
30 unmodified lines
484 etag=etag,485 max_age=max_age,486 use_x_sendfile=current_app.use_x_sendfile,487 response_class=current_app.response_class,485 _root_path=current_app.root_path,488 _root_path=current_app.root_path, # type: ignore489 )490 return kwargs491492493def send_file(491 path_or_file,492 mimetype=None,493 as_attachment=False,494 download_name=None,495 attachment_filename=None,496 conditional=True,497 etag=True,498 add_etags=None,499 last_modified=None,500 max_age=None,501 cache_timeout=None,494 path_or_file: t.Union[os.PathLike, str, t.BinaryIO],495 mimetype: t.Optional[str] = None,496 as_attachment: bool = False,497 download_name: t.Optional[str] = None,498 attachment_filename: t.Optional[str] = None,499 conditional: bool = True,500 etag: t.Union[bool, str] = True,501 add_etags: t.Optional[bool] = None,502 last_modified: t.Optional[t.Union[datetime, int, float]] = None,503 max_age: t.Optional[504 t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]505 ] = None,506 cache_timeout: t.Optional[int] = None,507):508 """Send the contents of a file to the client.509510 The first argument can be a file path or a file-like object. Paths
135 unmodified lines
646647 return path648649645def send_from_directory(directory: str, path: str, **kwargs: t.Any) -> "Response":650def send_from_directory(651 directory: t.Union[os.PathLike, str],652 path: t.Union[os.PathLike, str],653 filename: t.Optional[str] = None,654 **kwargs: t.Any,655) -> "Response":656 """Send a file from within a directory using :func:`send_file`.657658 .. code-block:: python659
15 unmodified lines
675 :param path: The path to the file to send, relative to676 ``directory``.677 :param kwargs: Arguments to pass to :func:`send_file`.678679 .. versionchanged:: 2.0680 ``path`` replaces the ``filename`` parameter.681682 .. versionadded:: 2.0683 Moved the implementation to Werkzeug. This is now a wrapper to684 pass some Flask-specific arguments.685686 .. versionadded:: 0.5687 """688 if filename is not None:689 warnings.warn(690 "The 'filename' parameter has been renamed to 'path'. The"691 " old name will be removed in Flask 2.1.",692 DeprecationWarning,693 stacklevel=2,694 )695 path = filename696697 return werkzeug.utils.send_from_directory( # type: ignore698 directory, path, **_prepare_send_file_kwargs(**kwargs)699 )700
123 unmodified lines
modified:src/flask/scaffold.py+1 added-1 removed
286 unmodified lines
287 value = value.rstrip("/")288289 self._static_url_path = value290291 def get_send_file_max_age(self, filename: str) -> t.Optional[int]:291 def get_send_file_max_age(self, filename: t.Optional[str]) -> t.Optional[int]:292 """Used by :func:`send_file` to determine the ``max_age`` cache293 value for a given file path if it wasn't passed.294295 By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
567 unmodified lines
modified:src/flask/sessions.py+2 added-1 removed
10 unmodified lines
11from .helpers import is_ip12from .json.tag import TaggedJSONSerializer1314if t.TYPE_CHECKING:15 import typing_extensions as te16 from .app import Flask17 from .wrappers import Request, Response1819
72 unmodified lines
92 available. Will still allow read-only access to the empty session93 but fail on setting.94 """9595 def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn: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."
304 unmodified lines
modified:src/flask/wrappers.py+2 added-1 removed
6 unmodified lines
7from . import json8from .globals import current_app910if t.TYPE_CHECKING:11 import typing_extensions as te12 from werkzeug.routing import Rule131415class Request(RequestBase):
75 unmodified lines
91 from .debughelpers import attach_enctype_error_multidict9293 attach_enctype_error_multidict(self)9494 def on_json_loading_failed(self, e: Exception) -> t.NoReturn:95 def on_json_loading_failed(self, e: Exception) -> "te.NoReturn":96 if current_app and current_app.debug:97 raise BadRequest(f"Failed to decode JSON object: {e}")9899 raise BadRequest()
36 unmodified lines
modified:tests/test_basic.py+3 added-3 removed
1629 unmodified lines
1630 assert client.get("/foo").data == b"/en/about"163116321633def test_inject_blueprint_url_defaults(app):1634 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")1634 bp = flask.Blueprint("foo", __name__, template_folder="template")16351636 @bp.url_defaults1637 def bp_defaults(endpoint, values):1638 values["page"] = "login"
4 unmodified lines
16431644 app.register_blueprint(bp)16451646 values = dict()1647 app.inject_url_defaults("foo.bar.baz.view", values)1647 app.inject_url_defaults("foo.view", values)1648 expected = dict(page="login")1649 assert values == expected16501651 with app.test_request_context("/somepage"):1652 url = flask.url_for("foo.bar.baz.view")1652 url = flask.url_for("foo.view")1653 expected = "/login"1654 assert url == expected16551656
373 unmodified lines
modified:tests/test_blueprints.py+45 added-76 removed
1import functools21import pytest2from jinja2 import TemplateNotFound3from werkzeug.http import parse_cache_control_header4
245 unmodified lines
250 templates = sorted(app.jinja_env.list_templates())251 assert templates == ["admin/index.html", "frontend/index.html"]252253256def test_dotted_names(app, client):257 frontend = flask.Blueprint("myapp.frontend", __name__)258 backend = flask.Blueprint("myapp.backend", __name__)254def test_dotted_name_not_allowed(app, client):255 with pytest.raises(ValueError):256 flask.Blueprint("app.ui", __name__)257260 @frontend.route("/fe")261 def frontend_index():262 return flask.url_for("myapp.backend.backend_index")258264 @frontend.route("/fe2")265 def frontend_page2():266 return flask.url_for(".frontend_index")267268 @backend.route("/be")269 def backend_index():270 return flask.url_for("myapp.frontend.frontend_index")271272 app.register_blueprint(frontend)273 app.register_blueprint(backend)274275 assert client.get("/fe").data.strip() == b"/be"276 assert client.get("/fe2").data.strip() == b"/fe"277 assert client.get("/be").data.strip() == b"/fe"278279259def test_dotted_names_from_app(app, client):260 test = flask.Blueprint("test", __name__)261262 @app.route("/")
58 unmodified lines
321322def test_route_decorator_custom_endpoint_with_dots(app, client):323 bp = flask.Blueprint("bp", __name__)324346 @bp.route("/foo")347 def foo():348 return flask.request.endpoint325 with pytest.raises(ValueError):326 bp.route("/", endpoint="a.b")(lambda: "")327350 try:328 with pytest.raises(ValueError):329 bp.add_url_rule("/", endpoint="a.b")330352 @bp.route("/bar", endpoint="bar.bar")353 def foo_bar():354 return flask.request.endpoint331 def view():332 return ""333356 except AssertionError:357 pass358 else:359 raise AssertionError("expected AssertionError not raised")334 view.__name__ = "a.b"335361 try:336 with pytest.raises(ValueError):337 bp.add_url_rule("/", view_func=view)338363 @bp.route("/bar/123", endpoint="bar.123")364 def foo_bar_foo():365 return flask.request.endpoint339367 except AssertionError:368 pass369 else:370 raise AssertionError("expected AssertionError not raised")371372 def foo_foo_foo():373 pass374375 pytest.raises(376 AssertionError,377 lambda: bp.add_url_rule("/bar/123", endpoint="bar.123", view_func=foo_foo_foo),378 )379380 pytest.raises(381 AssertionError, bp.route("/bar/123", endpoint="bar.123"), lambda: None382 )383384 foo_foo_foo.__name__ = "bar.123"385386 pytest.raises(387 AssertionError, lambda: bp.add_url_rule("/bar/123", view_func=foo_foo_foo)388 )389390 bp.add_url_rule(391 "/bar/456", endpoint="foofoofoo", view_func=functools.partial(foo_foo_foo)392 )393394 app.register_blueprint(bp, url_prefix="/py")395396 assert client.get("/py/foo").data == b"bp.foo"397 # The rule's didn't actually made it through398 rv = client.get("/py/bar")399 assert rv.status_code == 404400 rv = client.get("/py/bar/123")401 assert rv.status_code == 404402403340def test_endpoint_decorator(app, client):341 from werkzeug.routing import Rule342343 app.url_map.add(Rule("/foo", endpoint="bar"))
490 unmodified lines
834 assert client.get("/parent/child/grandchild/").data == b"Grandchild yes"835 assert client.get("/parent/no").data == b"Parent no"836 assert client.get("/parent/child/no").data == b"Parent no"837 assert client.get("/parent/child/grandchild/no").data == b"Grandchild no"838839840def test_nested_blueprint_url_prefix(app, client):841 parent = flask.Blueprint("parent", __name__, url_prefix="/parent")842 child = flask.Blueprint("child", __name__, url_prefix="/child")843 grandchild = flask.Blueprint("grandchild", __name__, url_prefix="/grandchild")844 apple = flask.Blueprint("apple", __name__, url_prefix="/apple")845846 @parent.route("/")847 def parent_index():848 return "Parent"849850 @child.route("/")851 def child_index():852 return "Child"853854 @grandchild.route("/")855 def grandchild_index():856 return "Grandchild"857858 @apple.route("/")859 def apple_index():860 return "Apple"861862 child.register_blueprint(grandchild)863 child.register_blueprint(apple, url_prefix="/orange") # test overwrite864 parent.register_blueprint(child)865 app.register_blueprint(parent)866867 assert client.get("/parent/").data == b"Parent"868 assert client.get("/parent/child/").data == b"Child"869 assert client.get("/parent/child/grandchild/").data == b"Grandchild"870 assert client.get("/parent/child/orange/").data == b"Apple"
modified:CHANGES.rst+16 added
11 unmodified lines
12-------------1314Unreleased1516- Re-add the ``filename`` parameter in ``send_from_directory``. The17 ``filename`` parameter has been renamed to ``path``, the old name18 is deprecated. :pr:`4019`19- Mark top-level names as exported so type checking understands20 imports in user projects. :issue:`4024`21- Fix type annotation for ``g`` and inform mypy that it is a namespace22 object that has arbitrary attributes. :issue:`4020`23- Fix some types that weren't available in Python 3.6.0. :issue:`4040`24- Improve typing for ``send_file``, ``send_from_directory``, and25 ``get_send_file_max_age``. :issue:`4044`, :pr:`4026`26- Show an error when a blueprint name contains a dot. The ``.`` has27 special meaning, it is used to separate (nested) blueprint names and28 the endpoint name. :issue:`4041`29- Combine URL prefixes when nesting blueprints that were created with30 a ``url_prefix`` value. :issue:`4037`313233Version 2.0.034-------------3536Released 2021-05-11
1094 unmodified lines
modified:CONTRIBUTING.rst+1 added-1 removed
127 unmodified lines
128.. _latest version of git: https://git-scm.com/downloads129.. _username: https://docs.github.com/en/github/using-git/setting-your-username-in-git130.. _email: https://docs.github.com/en/github/setting-up-and-managing-your-github-user-account/setting-your-commit-email-address131.. _GitHub account: https://github.com/join132.. _Fork: https://github.com/pallets/jinja/fork132.. _Fork: https://github.com/pallets/flask/fork133.. _Clone: https://docs.github.com/en/github/getting-started-with-github/fork-a-repo#step-2-create-a-local-clone-of-your-fork134135136Start coding
85 unmodified lines