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
Provenance
- Commit
4240ace- Tree
a9d948b- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
d575de5- Parent 2
f3551c8
14 files changed+202 added−163 removed
modified:docs/deploying/index.rst+1 added
14 unmodified lines15 --------------16 17 - `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 linesmodified:src/flask/__init__.py+41 added-41 removed
1 from markupsafe import escape2 from markupsafe import Markup3-from werkzeug.exceptions import abort4-from werkzeug.utils import redirect3+from werkzeug.exceptions import abort as abort4+from werkzeug.utils import redirect as redirect5 6-from . import json7-from .app import Flask8-from .app import Request9-from .app import Response10-from .blueprints import Blueprint11-from .config import Config12-from .ctx import after_this_request13-from .ctx import copy_current_request_context14-from .ctx import has_app_context15-from .ctx import has_request_context16-from .globals import _app_ctx_stack17-from .globals import _request_ctx_stack18-from .globals import current_app19-from .globals import g20-from .globals import request21-from .globals import session22-from .helpers import flash23-from .helpers import get_flashed_messages24-from .helpers import get_template_attribute25-from .helpers import make_response26-from .helpers import safe_join27-from .helpers import send_file28-from .helpers import send_from_directory29-from .helpers import stream_with_context30-from .helpers import url_for31-from .json import jsonify32-from .signals import appcontext_popped33-from .signals import appcontext_pushed34-from .signals import appcontext_tearing_down35-from .signals import before_render_template36-from .signals import got_request_exception37-from .signals import message_flashed38-from .signals import request_finished39-from .signals import request_started40-from .signals import request_tearing_down41-from .signals import signals_available42-from .signals import template_rendered43-from .templating import render_template44-from .templating import render_template_string6+from . import json as json7+from .app import Flask as Flask8+from .app import Request as Request9+from .app import Response as Response10+from .blueprints import Blueprint as Blueprint11+from .config import Config as Config12+from .ctx import after_this_request as after_this_request13+from .ctx import copy_current_request_context as copy_current_request_context14+from .ctx import has_app_context as has_app_context15+from .ctx import has_request_context as has_request_context16+from .globals import _app_ctx_stack as _app_ctx_stack17+from .globals import _request_ctx_stack as _request_ctx_stack18+from .globals import current_app as current_app19+from .globals import g as g20+from .globals import request as request21+from .globals import session as session22+from .helpers import flash as flash23+from .helpers import get_flashed_messages as get_flashed_messages24+from .helpers import get_template_attribute as get_template_attribute25+from .helpers import make_response as make_response26+from .helpers import safe_join as safe_join27+from .helpers import send_file as send_file28+from .helpers import send_from_directory as send_from_directory29+from .helpers import stream_with_context as stream_with_context30+from .helpers import url_for as url_for31+from .json import jsonify as jsonify32+from .signals import appcontext_popped as appcontext_popped33+from .signals import appcontext_pushed as appcontext_pushed34+from .signals import appcontext_tearing_down as appcontext_tearing_down35+from .signals import before_render_template as before_render_template36+from .signals import got_request_exception as got_request_exception37+from .signals import message_flashed as message_flashed38+from .signals import request_finished as request_finished39+from .signals import request_started as request_started40+from .signals import request_tearing_down as request_tearing_down41+from .signals import signals_available as signals_available42+from .signals import template_rendered as template_rendered43+from .templating import render_template as render_template44+from .templating import render_template_string as render_template_string45 46 __version__ = "2.1.0.dev0"modified:src/flask/app.py+2 added-1 removed
70 unmodified lines71 from .wrappers import Request72 from .wrappers import Response73 74 if t.TYPE_CHECKING:75+ import typing_extensions as te76 from .blueprints import Blueprint77 from .testing import FlaskClient78 from .testing import FlaskCliRunner79 1361 unmodified lines1441 self.logger.error(1442 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1443 )1444 1444- 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 linesmodified:src/flask/blueprints.py+20 added-12 removed
186 unmodified lines187 static_url_path=static_url_path,188 template_folder=template_folder,189 root_path=root_path,190 )191+192+ if "." in name:193+ raise ValueError("'name' may not contain a dot '.' character.")194+195 self.name = name196 self.url_prefix = url_prefix197 self.subdomain = subdomain198 self.deferred_functions: t.List[DeferredSetupFunction] = []60 unmodified lines259 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.264 265 :param app: The application this blueprint is being registered266 with.267 :param options: Keyword arguments forwarded from75 unmodified lines343 self.cli.name = cli_resolved_group344 app.cli.add_command(self.cli)345 346 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")349+350+ if bp_url_prefix is None:351+ bp_url_prefix = blueprint.url_prefix352+353+ 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 )357 349- bp_options["url_prefix"] = url_prefix358 bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."359 blueprint.register(app, bp_options)360 361 def add_url_rule(5 unmodified lines367 ) -> 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.")373+374+ 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.")376+377 self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))378 379 def app_template_filter(self, name: t.Optional[str] = None) -> t.Callable:380 """Register a custom template filter, available application wide. Like170 unmodified linesmodified:src/flask/ctx.py+20 added-2 removed
39 unmodified lines40 41 .. versionadded:: 0.1042 """43 44+ # Define attr methods to let mypy know this is a namespace object45+ # 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 None52+53+ def __setattr__(self, name: str, value: t.Any) -> None:54+ self.__dict__[name] = value55+56+ def __delattr__(self, name: str) -> None:57+ try:58+ del self.__dict__[name]59+ except KeyError:60+ raise AttributeError(name) from None61+62 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 lines95 .. versionadded:: 0.1196 """97 return self.__dict__.setdefault(name, default)98 81- def __contains__(self, item: t.Any) -> bool:99+ def __contains__(self, item: str) -> bool:100 return item in self.__dict__101 84- def __iter__(self) -> t.Iterator:102+ def __iter__(self) -> t.Iterator[str]:103 return iter(self.__dict__)104 105 def __repr__(self) -> str:106 top = _app_ctx_stack.top372 unmodified linesmodified:src/flask/globals.py+5 added-3 removed
4 unmodified lines5 from werkzeug.local import LocalStack6 7 if t.TYPE_CHECKING:8 from .app import Flask9- from .ctx import AppContext9+ from .ctx import _AppCtxGlobals10 from .sessions import SessionMixin11 from .wrappers import Request12 13 _request_ctx_err_msg = """\38 unmodified lines52 _request_ctx_stack = LocalStack()53 _app_ctx_stack = LocalStack()54 current_app: "Flask" = LocalProxy(_find_app) # type: ignore55 request: "Request" = LocalProxy(partial(_lookup_req_object, "request")) # type: ignore56-session: "SessionMixin" = LocalProxy(partial(_lookup_req_object, "session")) # type: ignore # noqa: B95057-g: "AppContext" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignore56+session: "SessionMixin" = LocalProxy( # type: ignore57+ partial(_lookup_req_object, "session")58+)59+g: "_AppCtxGlobals" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignoremodified:src/flask/helpers.py+43 added-21 removed
2 unmodified lines3 import socket4 import sys5 import typing as t6 import warnings7+from datetime import datetime8 from datetime import timedelta9 from functools import update_wrapper10 from threading import RLock11 424 unmodified lines436 return flashes437 438 439 def _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 lines484 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 kwargs491 492 493 def 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.509 510 The first argument can be a file path or a file-like object. Paths135 unmodified lines646 647 return path648 649 645-def send_from_directory(directory: str, path: str, **kwargs: t.Any) -> "Response":650+def 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`.657 658 .. code-block:: python659 15 unmodified lines675 :param path: The path to the file to send, relative to676 ``directory``.677 :param kwargs: Arguments to pass to :func:`send_file`.678 679+ .. versionchanged:: 2.0680+ ``path`` replaces the ``filename`` parameter.681+682 .. versionadded:: 2.0683 Moved the implementation to Werkzeug. This is now a wrapper to684 pass some Flask-specific arguments.685 686 .. 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 = filename696+697 return werkzeug.utils.send_from_directory( # type: ignore698 directory, path, **_prepare_send_file_kwargs(**kwargs)699 )700 123 unmodified linesmodified:src/flask/scaffold.py+1 added-1 removed
286 unmodified lines287 value = value.rstrip("/")288 289 self._static_url_path = value290 291- 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.294 295 By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from567 unmodified linesmodified:src/flask/sessions.py+2 added-1 removed
10 unmodified lines11 from .helpers import is_ip12 from .json.tag import TaggedJSONSerializer13 14 if t.TYPE_CHECKING:15+ import typing_extensions as te16 from .app import Flask17 from .wrappers import Request, Response18 19 72 unmodified lines92 available. Will still allow read-only access to the empty session93 but fail on setting.94 """95 95- 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 linesmodified:src/flask/wrappers.py+2 added-1 removed
6 unmodified lines7 from . import json8 from .globals import current_app9 10 if t.TYPE_CHECKING:11+ import typing_extensions as te12 from werkzeug.routing import Rule13 14 15 class Request(RequestBase):75 unmodified lines91 from .debughelpers import attach_enctype_error_multidict92 93 attach_enctype_error_multidict(self)94 94- 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}")98 99 raise BadRequest()36 unmodified linesmodified:tests/test_basic.py+3 added-3 removed
1629 unmodified lines1630 assert client.get("/foo").data == b"/en/about"1631 1632 1633 def 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")1635 1636 @bp.url_defaults1637 def bp_defaults(endpoint, values):1638 values["page"] = "login"4 unmodified lines1643 1644 app.register_blueprint(bp)1645 1646 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 == expected1650 1651 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 == expected1655 1656 373 unmodified linesmodified:tests/test_blueprints.py+45 added-76 removed
1-import functools2-1 import pytest2 from jinja2 import TemplateNotFound3 from werkzeug.http import parse_cache_control_header4 245 unmodified lines250 templates = sorted(app.jinja_env.list_templates())251 assert templates == ["admin/index.html", "frontend/index.html"]252 253 256-def test_dotted_names(app, client):257- frontend = flask.Blueprint("myapp.frontend", __name__)258- backend = flask.Blueprint("myapp.backend", __name__)254+def test_dotted_name_not_allowed(app, client):255+ with pytest.raises(ValueError):256+ flask.Blueprint("app.ui", __name__)257 260- @frontend.route("/fe")261- def frontend_index():262- return flask.url_for("myapp.backend.backend_index")258 264- @frontend.route("/fe2")265- def frontend_page2():266- return flask.url_for(".frontend_index")267-268- @backend.route("/be")269- def backend_index():270- return flask.url_for("myapp.frontend.frontend_index")271-272- app.register_blueprint(frontend)273- app.register_blueprint(backend)274-275- 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"278-279-259 def test_dotted_names_from_app(app, client):260 test = flask.Blueprint("test", __name__)261 262 @app.route("/")58 unmodified lines321 322 def test_route_decorator_custom_endpoint_with_dots(app, client):323 bp = flask.Blueprint("bp", __name__)324 346- @bp.route("/foo")347- def foo():348- return flask.request.endpoint325+ with pytest.raises(ValueError):326+ bp.route("/", endpoint="a.b")(lambda: "")327 350- try:328+ with pytest.raises(ValueError):329+ bp.add_url_rule("/", endpoint="a.b")330 352- @bp.route("/bar", endpoint="bar.bar")353- def foo_bar():354- return flask.request.endpoint331+ def view():332+ return ""333 356- except AssertionError:357- pass358- else:359- raise AssertionError("expected AssertionError not raised")334+ view.__name__ = "a.b"335 361- try:336+ with pytest.raises(ValueError):337+ bp.add_url_rule("/", view_func=view)338 363- @bp.route("/bar/123", endpoint="bar.123")364- def foo_bar_foo():365- return flask.request.endpoint339 367- except AssertionError:368- pass369- else:370- raise AssertionError("expected AssertionError not raised")371-372- def foo_foo_foo():373- pass374-375- pytest.raises(376- AssertionError,377- lambda: bp.add_url_rule("/bar/123", endpoint="bar.123", view_func=foo_foo_foo),378- )379-380- pytest.raises(381- AssertionError, bp.route("/bar/123", endpoint="bar.123"), lambda: None382- )383-384- foo_foo_foo.__name__ = "bar.123"385-386- pytest.raises(387- AssertionError, lambda: bp.add_url_rule("/bar/123", view_func=foo_foo_foo)388- )389-390- bp.add_url_rule(391- "/bar/456", endpoint="foofoofoo", view_func=functools.partial(foo_foo_foo)392- )393-394- app.register_blueprint(bp, url_prefix="/py")395-396- 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 == 404402-403-340 def test_endpoint_decorator(app, client):341 from werkzeug.routing import Rule342 343 app.url_map.add(Rule("/foo", endpoint="bar"))490 unmodified lines834 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"838+839+840+def 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")845+846+ @parent.route("/")847+ def parent_index():848+ return "Parent"849+850+ @child.route("/")851+ def child_index():852+ return "Child"853+854+ @grandchild.route("/")855+ def grandchild_index():856+ return "Grandchild"857+858+ @apple.route("/")859+ def apple_index():860+ return "Apple"861+862+ child.register_blueprint(grandchild)863+ child.register_blueprint(apple, url_prefix="/orange") # test overwrite864+ parent.register_blueprint(child)865+ app.register_blueprint(parent)866+867+ 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 lines12 -------------13 14 Unreleased15 16+- 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`31 32+33 Version 2.0.034 -------------35 36 Released 2021-05-111094 unmodified linesmodified:CONTRIBUTING.rst+1 added-1 removed
127 unmodified lines128 .. _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-fork134 135 136 Start coding85 unmodified lines