Merge pull request #4337 from pallets/remove-deprecated-code
Before adoption: this commit came in with the history the project adopted, so no landing records it.
remove deprecated code
authored by David Lord · committed by GitHub · parents ea93a52, 15a3e82 · Browse files · 10 files·+68 added−259 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+68 added−259 removed
- tests:+18 added−46 removed
- other:+50 added−213 removed
Provenance
- Commit
7620cb7- Tree
522a7ac- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
ea93a52- Parent 2
15a3e82
10 files changed+68 added−259 removed
modified:docs/api.rst-2 removed
216 unmodified lines217 .. autofunction:: send_file218 219 .. autofunction:: send_from_directory220 221-.. autofunction:: safe_join222-221 .. autofunction:: escape222 223 .. autoclass:: Markup224 :members: escape, unescape, striptags549 unmodified linesmodified:src/flask/json/__init__.py+1 added-60 removed
1 import dataclasses2 import decimal3-import io3 import json as _json4 import typing as t5 import uuid7-import warnings6 from datetime import date7 8 from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps9 from werkzeug.http import http_date111 unmodified lines121 ``app`` can be passed directly, rather than requiring an app122 context for configuration.123 """124 _dump_arg_defaults(kwargs, app=app)127- encoding = kwargs.pop("encoding", None)128- rv = _json.dumps(obj, **kwargs)125+ return _json.dumps(obj, **kwargs)126 130- if encoding is not None:131- warnings.warn(132- "'encoding' is deprecated and will be removed in Flask 2.1.",133- DeprecationWarning,134- stacklevel=2,135- )127 137- if isinstance(rv, str):138- return rv.encode(encoding) # type: ignore139-140- return rv141-142-128 def dump(129 obj: t.Any, fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any130 ) -> None:131 """Serialize an object to JSON written to a file object.11 unmodified lines143 Writing to a binary file, and the ``encoding`` argument, is144 deprecated and will be removed in Flask 2.1.145 """146 _dump_arg_defaults(kwargs, app=app)162- encoding = kwargs.pop("encoding", None)163- show_warning = encoding is not None164-165- try:166- fp.write("")167- except TypeError:168- show_warning = True169- fp = io.TextIOWrapper(fp, encoding or "utf-8") # type: ignore170-171- if show_warning:172- warnings.warn(173- "Writing to a binary file, and the 'encoding' argument, is"174- " deprecated and will be removed in Flask 2.1.",175- DeprecationWarning,176- stacklevel=2,177- )178-147 _json.dump(obj, fp, **kwargs)148 149 150 def loads(s: str, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:15 unmodified lines166 ``app`` can be passed directly, rather than requiring an app167 context for configuration.168 """169 _load_arg_defaults(kwargs, app=app)202- encoding = kwargs.pop("encoding", None)203-204- if encoding is not None:205- warnings.warn(206- "'encoding' is deprecated and will be removed in Flask 2.1."207- " The data must be a string or UTF-8 bytes.",208- DeprecationWarning,209- stacklevel=2,210- )211-212- if isinstance(s, bytes):213- s = s.decode(encoding)214-170 return _json.loads(s, **kwargs)171 172 173 def load(fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:11 unmodified lines185 ``encoding`` is deprecated and will be removed in Flask 2.1. The186 file must be text mode, or binary mode with UTF-8 bytes.187 """188 _load_arg_defaults(kwargs, app=app)234- encoding = kwargs.pop("encoding", None)235-236- if encoding is not None:237- warnings.warn(238- "'encoding' is deprecated and will be removed in Flask 2.1."239- " The file must be text mode, or binary mode with UTF-8"240- " bytes.",241- DeprecationWarning,242- stacklevel=2,243- )244-245- if isinstance(fp.read(0), bytes):246- fp = io.TextIOWrapper(fp, encoding) # type: ignore247-189 return _json.load(fp, **kwargs)190 191 192 def htmlsafe_dumps(obj: t.Any, **kwargs: t.Any) -> str:101 unmodified linesmodified:src/flask/__init__.py-1 removed
21 unmodified lines22 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_join26 from .helpers import send_file as send_file27 from .helpers import send_from_directory as send_from_directory28 from .helpers import stream_with_context as stream_with_context29 from .helpers import url_for as url_for16 unmodified linesmodified:src/flask/blueprints.py+6 added-16 removed
297 unmodified lines298 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 304- if app.blueprints[name] is not self:305- raise ValueError(306- f"The name '{self_name}' is already registered for"307- f" a different blueprint{existing_at}. Use 'name='"308- " to provide a unique name."309- )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- else:311- import warnings310 313- warnings.warn(314- f"The name '{self_name}' is already registered for"315- f" this blueprint{existing_at}. Use 'name=' to"316- " provide a unique name. This will become an error"317- " in Flask 2.1.",318- stacklevel=4,319- )320-311 first_bp_registration = not any(bp is self for bp in app.blueprints.values())312 first_name_registration = name not in app.blueprints313 314 app.blueprints[name] = self285 unmodified linesmodified:src/flask/cli.py+13 added-57 removed
3 unmodified lines4 import platform5 import re6 import sys7 import traceback8-import warnings8 from functools import update_wrapper9 from operator import attrgetter10 from threading import Lock11 from threading import Thread20 unmodified lines32 class NoAppException(click.UsageError):33 """Raised if an application cannot be found or loaded."""34 35 37-def find_best_app(script_info, module):36+def find_best_app(module):37 """Given a module instance this tries to find the best possible38 application in the module or raises an exception.39 """40 from . import Flask22 unmodified lines63 app_factory = getattr(module, attr_name, None)64 65 if inspect.isfunction(app_factory):66 try:68- app = call_factory(script_info, app_factory)67+ app = app_factory()68 69 if isinstance(app, Flask):70 return app71 except TypeError as e:13 unmodified lines85 " to specify one."86 )87 88 90-def call_factory(script_info, app_factory, args=None, kwargs=None):91- """Takes an app factory, a ``script_info` object and optionally a tuple92- of arguments. Checks for the existence of a script_info argument and calls93- the app_factory depending on that and the arguments provided.94- """95- sig = inspect.signature(app_factory)96- args = [] if args is None else args97- kwargs = {} if kwargs is None else kwargs98-99- if "script_info" in sig.parameters:100- warnings.warn(101- "The 'script_info' argument is deprecated and will not be"102- " passed to the app factory function in Flask 2.1.",103- DeprecationWarning,104- )105- kwargs["script_info"] = script_info106-107- if not args and len(sig.parameters) == 1:108- first_parameter = next(iter(sig.parameters.values()))109-110- if (111- first_parameter.default is inspect.Parameter.empty112- # **kwargs is reported as an empty default, ignore it113- and first_parameter.kind is not inspect.Parameter.VAR_KEYWORD114- ):115- warnings.warn(116- "Script info is deprecated and will not be passed as the"117- " single argument to the app factory function in Flask"118- " 2.1.",119- DeprecationWarning,120- )121- args.append(script_info)122-123- return app_factory(*args, **kwargs)124-125-89 def _called_with_wrong_args(f):90 """Check whether calling a function raised a ``TypeError`` because91 the call failed or because something in the factory raised the92 error.18 unmodified lines111 # https://docs.python.org/2/library/sys.html#sys.exc_info112 del tb113 114 152-def find_app_by_string(script_info, module, app_name):115+def find_app_by_string(module, app_name):116 """Check if the given string is a variable name or a function. Call117 a function to get the app instance, or return the variable directly.118 """119 from . import Flask8 unmodified lines128 ) from None129 130 if isinstance(expr, ast.Name):131 name = expr.id169- args = kwargs = None132+ args = []133+ kwargs = {}134 elif isinstance(expr, ast.Call):135 # Ensure the function name is an attribute name only.136 if not isinstance(expr.func, ast.Name):137 raise NoAppException(27 unmodified lines165 # If the attribute is a function, call it with any args and kwargs166 # to get the real application.167 if inspect.isfunction(attr):168 try:205- app = call_factory(script_info, attr, args, kwargs)169+ app = attr(*args, **kwargs)170 except TypeError as e:171 if not _called_with_wrong_args(attr):172 raise173 42 unmodified lines216 217 return ".".join(module_name[::-1])218 219 256-def locate_app(script_info, module_name, app_name, raise_if_not_found=True):220+def locate_app(module_name, app_name, raise_if_not_found=True):221 __traceback_hide__ = True # noqa: F841222 223 try:224 __import__(module_name)11 unmodified lines236 237 module = sys.modules[module_name]238 239 if app_name is None:276- return find_best_app(script_info, module)240+ return find_best_app(module)241 else:278- return find_app_by_string(script_info, module, app_name)242+ return find_app_by_string(module, app_name)243 244 245 def get_version(ctx, param, value):246 if not value or ctx.resilient_parsing:112 unmodified lines359 if self._loaded_app is not None:360 return self._loaded_app361 362 if self.create_app is not None:399- app = call_factory(self, self.create_app)363+ app = self.create_app()364 else:365 if self.app_import_path:366 path, name = (367 re.split(r":(?![\\/])", self.app_import_path, 1) + [None]368 )[:2]369 import_name = prepare_import(path)406- app = locate_app(self, import_name, name)370+ app = locate_app(import_name, name)371 else:372 for path in ("wsgi.py", "app.py"):373 import_name = prepare_import(path)410- app = locate_app(self, import_name, None, raise_if_not_found=False)374+ app = locate_app(import_name, None, raise_if_not_found=False)375 376 if app:377 break378 567 unmodified lines946 )947 948 949 def main() -> None:986- if int(click.__version__[0]) < 8:987- warnings.warn(988- "Using the `flask` cli with Click 7 is deprecated and"989- " will not be supported starting with Flask 2.1."990- " Please upgrade to Click 8 as soon as possible.",991- DeprecationWarning,992- )993- # TODO omit sys.argv once https://github.com/pallets/click/issues/536 is fixed994- cli.main(args=sys.argv[1:])950+ cli.main()951 952 953 if __name__ == "__main__":954 main()modified:src/flask/config.py+3 added-26 removed
174 unmodified lines175 :meth:`from_mapping` method.176 177 .. code-block:: python178 179+ import json180+ app.config.from_file("config.json", load=json.load)181+182 import toml183 app.config.from_file("config.toml", load=toml.load)184 185 :param filename: The path to the data file. This can be an20 unmodified lines206 raise207 208 return self.from_mapping(obj)209 207- def from_json(self, filename: str, silent: bool = False) -> bool:208- """Update the values in the config from a JSON file. The loaded209- data is passed to the :meth:`from_mapping` method.210-211- :param filename: The path to the JSON file. This can be an212- absolute path or relative to the config root path.213- :param silent: Ignore the file if it doesn't exist.214- :return: ``True`` if the file was loaded successfully.215-216- .. deprecated:: 2.0.0217- Will be removed in Flask 2.1. Use :meth:`from_file` instead.218- This was removed early in 2.0.0, was added back in 2.0.1.219-220- .. versionadded:: 0.11221- """222- import warnings223- from . import json224-225- warnings.warn(226- "'from_json' is deprecated and will be removed in Flask"227- " 2.1. Use 'from_file(path, json.load)' instead.",228- DeprecationWarning,229- stacklevel=2,230- )231- return self.from_file(filename, json.load, silent=silent)232-210 def from_mapping(211 self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any212 ) -> bool:213 """Updates the config like :meth:`update` ignoring items with non-upper59 unmodified linesmodified:src/flask/helpers.py+4 added-50 removed
3 unmodified lines4 import sys5 import typing as t6 import warnings7 from datetime import datetime8-from datetime import timedelta8 from functools import lru_cache9 from functools import update_wrapper10 from threading import RLock11 12 import werkzeug.utils14-from werkzeug.exceptions import NotFound13 from werkzeug.routing import BuildError14 from werkzeug.urls import url_quote15 16 from .globals import _app_ctx_stack434 unmodified lines451 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"457- " 2.1.",455+ " 2.2.",456 DeprecationWarning,457 stacklevel=3,458 )459 download_name = attachment_filename460 461 if cache_timeout is not None:462 warnings.warn(463 "The 'cache_timeout' parameter has been renamed to"466- " 'max_age'. The old name will be removed in Flask 2.1.",464+ " 'max_age'. The old name will be removed in Flask 2.2.",465 DeprecationWarning,466 stacklevel=3,467 )468 max_age = cache_timeout469 470 if add_etags is not None:471 warnings.warn(472 "The 'add_etags' parameter has been renamed to 'etag'. The"475- " old name will be removed in Flask 2.1.",473+ " old name will be removed in Flask 2.2.",474 DeprecationWarning,475 stacklevel=3,476 )477 etag = add_etags146 unmodified lines624 )625 )626 627 630-def safe_join(directory: str, *pathnames: str) -> str:631- """Safely join zero or more untrusted path components to a base632- directory to avoid escaping the base directory.633-634- :param directory: The trusted base directory.635- :param pathnames: The untrusted path components relative to the636- base directory.637- :return: A safe path, otherwise ``None``.638- """639- warnings.warn(640- "'flask.helpers.safe_join' is deprecated and will be removed in"641- " Flask 2.1. Use 'werkzeug.utils.safe_join' instead.",642- DeprecationWarning,643- stacklevel=2,644- )645- path = werkzeug.utils.safe_join(directory, *pathnames)646-647- if path is None:648- raise NotFound()649-650- return path651-652-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,33 unmodified lines665 """666 if filename is not None:667 warnings.warn(668 "The 'filename' parameter has been renamed to 'path'. The"694- " old name will be removed in Flask 2.1.",669+ " old name will be removed in Flask 2.2.",670 DeprecationWarning,671 stacklevel=2,672 )673 path = filename85 unmodified lines759 with self.lock:760 super().__delete__(obj)761 762 788-def total_seconds(td: timedelta) -> int:789- """Returns the total seconds from a timedelta object.790-791- :param timedelta td: the timedelta to be converted in seconds792-793- :returns: number of seconds794- :rtype: int795-796- .. deprecated:: 2.0797- Will be removed in Flask 2.1. Use798- :meth:`timedelta.total_seconds` instead.799- """800- warnings.warn(801- "'total_seconds' is deprecated and will be removed in Flask"802- " 2.1. Use 'timedelta.total_seconds' instead.",803- DeprecationWarning,804- stacklevel=2,805- )806- return td.days * 60 * 60 * 24 + td.seconds807-808-763 def is_ip(value: str) -> bool:764 """Determine if the given string is an IP address.765 766 :param value: value to check24 unmodified linesmodified:tests/test_blueprints.py+2 added-2 removed
952 unmodified lines953 bp2 = flask.Blueprint("bp", __name__)954 955 app.register_blueprint(bp)956 957- with pytest.warns(UserWarning):958- app.register_blueprint(bp) # same bp, same name, warning957+ with pytest.raises(ValueError):958+ app.register_blueprint(bp) # same bp, same name, error959 960 app.register_blueprint(bp, name="again") # same bp, different name, ok961 962 with pytest.raises(ValueError):41 unmodified linesmodified:tests/test_cli.py+16 added-44 removed
47 unmodified lines48 assert testapp.cli.name == testapp.name49 50 51 def test_find_best_app(test_apps):52- script_info = ScriptInfo()53-52 class Module:53 app = Flask("appname")54 57- assert find_best_app(script_info, Module) == Module.app55+ assert find_best_app(Module) == Module.app56 57 class Module:58 application = Flask("appname")59 62- assert find_best_app(script_info, Module) == Module.application60+ assert find_best_app(Module) == Module.application61 62 class Module:63 myapp = Flask("appname")64 67- assert find_best_app(script_info, Module) == Module.myapp65+ assert find_best_app(Module) == Module.myapp66 67 class Module:68 @staticmethod69 def create_app():70 return Flask("appname")71 74- app = find_best_app(script_info, Module)72+ app = find_best_app(Module)73 assert isinstance(app, Flask)74 assert app.name == "appname"75 76 class Module:77 @staticmethod78 def create_app(**kwargs):79 return Flask("appname")80 83- app = find_best_app(script_info, Module)81+ app = find_best_app(Module)82 assert isinstance(app, Flask)83 assert app.name == "appname"84 85 class Module:86 @staticmethod89- def create_app(foo):90- return Flask("appname")91-92- with pytest.deprecated_call(match="Script info"):93- app = find_best_app(script_info, Module)94-95- assert isinstance(app, Flask)96- assert app.name == "appname"97-98- class Module:99- @staticmethod100- def create_app(foo=None, script_info=None):101- return Flask("appname")102-103- with pytest.deprecated_call(match="script_info"):104- app = find_best_app(script_info, Module)105-106- assert isinstance(app, Flask)107- assert app.name == "appname"108-109- class Module:110- @staticmethod87 def make_app():88 return Flask("appname")89 114- app = find_best_app(script_info, Module)90+ app = find_best_app(Module)91 assert isinstance(app, Flask)92 assert app.name == "appname"93 94 class Module:2 unmodified lines97 @staticmethod98 def create_app():99 return Flask("appname2")100 125- assert find_best_app(script_info, Module) == Module.myapp101+ assert find_best_app(Module) == Module.myapp102 103 class Module:104 myapp = Flask("appname1")105 106 @staticmethod107 def create_app():108 return Flask("appname2")109 134- assert find_best_app(script_info, Module) == Module.myapp110+ assert find_best_app(Module) == Module.myapp111 112 class Module:113 pass114 139- pytest.raises(NoAppException, find_best_app, script_info, Module)115+ pytest.raises(NoAppException, find_best_app, Module)116 117 class Module:118 myapp1 = Flask("appname1")119 myapp2 = Flask("appname2")120 145- pytest.raises(NoAppException, find_best_app, script_info, Module)121+ pytest.raises(NoAppException, find_best_app, Module)122 123 class Module:124 @staticmethod125 def create_app(foo, bar):126 return Flask("appname2")127 152- pytest.raises(NoAppException, find_best_app, script_info, Module)128+ pytest.raises(NoAppException, find_best_app, Module)129 130 class Module:131 @staticmethod132 def create_app():133 raise TypeError("bad bad factory!")134 159- pytest.raises(TypeError, find_best_app, script_info, Module)135+ pytest.raises(TypeError, find_best_app, Module)136 137 138 @pytest.mark.parametrize(139 "value,path,result",55 unmodified lines195 ("cliapp.factory", " create_app () ", "app"),196 ),197 )198 def test_locate_app(test_apps, iname, aname, result):223- info = ScriptInfo()224- assert locate_app(info, iname, aname).name == result199+ assert locate_app(iname, aname).name == result200 201 202 @pytest.mark.parametrize(203 "iname,aname",13 unmodified lines217 ("cliapp.message.txt", None),218 ),219 )220 def test_locate_app_raises(test_apps, iname, aname):246- info = ScriptInfo()247-221 with pytest.raises(NoAppException):249- locate_app(info, iname, aname)222+ locate_app(iname, aname)223 224 225 def test_locate_app_suppress_raise(test_apps):253- info = ScriptInfo()254- app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)226+ app = locate_app("notanapp.py", None, raise_if_not_found=False)227 assert app is None228 229 # only direct import error is suppressed230 with pytest.raises(NoAppException):259- locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)231+ locate_app("cliapp.importerrorapp", None, raise_if_not_found=False)232 233 234 def test_get_version(test_apps, capsys):235 from flask import __version__ as flask_version429 unmodified linesmodified:CHANGES.rst+23 added-1 removed
3 unmodified lines4 -------------5 6 Unreleased7 8+- Drop support for Python 3.6. :pr:`4335`8-- Update Click dependency to >= 8.0.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 by14+ ``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. Use21+ ``name=`` when registering to specify a unique name.22 23+- Some parameters in ``send_file`` and ``send_from_directory`` were24+ renamed in 2.0. The deprecation period for the old names is extended25+ to 2.2. Be sure to test with deprecation warnings visible.26+27+ - ``attachment_filename`` is renamed to ``download_name``.28+ - ``cache_timeout`` is renamed to ``max_age``.29+ - ``add_etags`` is renamed to ``etag``.30+ - ``filename`` is renamed to ``path``.31+32+33 Version 2.0.234 -------------35 36 Released 2021-10-041178 unmodified lines