Skip to content
Myr

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

10 files+68 added−259 removed

modified:docs/api.rst-2 removed
216 unmodified lines
217.. autofunction:: send_file218219.. autofunction:: send_from_directory220221.. autofunction:: safe_join222221.. autofunction:: escape222223.. autoclass:: Markup224 :members: escape, unescape, striptags
549 unmodified lines
modified:src/flask/json/__init__.py+1 added-60 removed
1import dataclasses2import decimal3import io3import json as _json4import typing as t5import uuid7import warnings6from datetime import date78from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps9from werkzeug.http import http_date
111 unmodified lines
121 ``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)126130 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 )127137 if isinstance(rv, str):138 return rv.encode(encoding) # type: ignore139140 return rv141142128def 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 lines
143 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 None164165 try:166 fp.write("")167 except TypeError:168 show_warning = True169 fp = io.TextIOWrapper(fp, encoding or "utf-8") # type: ignore170171 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 )178147 _json.dump(obj, fp, **kwargs)148149150def loads(s: str, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:
15 unmodified lines
166 ``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)203204 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 )211212 if isinstance(s, bytes):213 s = s.decode(encoding)214170 return _json.loads(s, **kwargs)171172173def load(fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:
11 unmodified lines
185 ``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)235236 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 )244245 if isinstance(fp.read(0), bytes):246 fp = io.TextIOWrapper(fp, encoding) # type: ignore247189 return _json.load(fp, **kwargs)190191192def htmlsafe_dumps(obj: t.Any, **kwargs: t.Any) -> str:
101 unmodified lines
modified:src/flask/__init__.py-1 removed
21 unmodified lines
22from .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_join26from .helpers import send_file as send_file27from .helpers import send_from_directory as send_from_directory28from .helpers import stream_with_context as stream_with_context29from .helpers import url_for as url_for
16 unmodified lines
modified:src/flask/blueprints.py+6 added-16 removed
297 unmodified lines
298 self_name = options.get("name", self.name)299 name = f"{name_prefix}.{self_name}".lstrip(".")300301 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 ""304304 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 warnings310313 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 )320311 first_bp_registration = not any(bp is self for bp in app.blueprints.values())312 first_name_registration = name not in app.blueprints313314 app.blueprints[name] = self
285 unmodified lines
modified:src/flask/cli.py+13 added-57 removed
3 unmodified lines
4import platform5import re6import sys7import traceback8import warnings8from functools import update_wrapper9from operator import attrgetter10from threading import Lock11from threading import Thread
20 unmodified lines
32class NoAppException(click.UsageError):33 """Raised if an application cannot be found or loaded."""343537def find_best_app(script_info, module):36def 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 Flask
22 unmodified lines
63 app_factory = getattr(module, attr_name, None)6465 if inspect.isfunction(app_factory):66 try:68 app = call_factory(script_info, app_factory)67 app = app_factory()6869 if isinstance(app, Flask):70 return app71 except TypeError as e:
13 unmodified lines
85 " to specify one."86 )878890def 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 kwargs9899 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_info106107 if not args and len(sig.parameters) == 1:108 first_parameter = next(iter(sig.parameters.values()))109110 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)122123 return app_factory(*args, **kwargs)12412589def _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 lines
111 # https://docs.python.org/2/library/sys.html#sys.exc_info112 del tb113114152def find_app_by_string(script_info, module, app_name):115def 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 Flask
8 unmodified lines
128 ) from None129130 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 lines
165 # 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 lines
216217 return ".".join(module_name[::-1])218219256def locate_app(script_info, module_name, app_name, raise_if_not_found=True):220def locate_app(module_name, app_name, raise_if_not_found=True):221 __traceback_hide__ = True # noqa: F841222223 try:224 __import__(module_name)
11 unmodified lines
236237 module = sys.modules[module_name]238239 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)243244245def get_version(ctx, param, value):246 if not value or ctx.resilient_parsing:
112 unmodified lines
359 if self._loaded_app is not None:360 return self._loaded_app361362 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)375376 if app:377 break378
567 unmodified lines
946)947948949def 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()951952953if __name__ == "__main__":954 main()
modified:src/flask/config.py+3 added-26 removed
174 unmodified lines
175 :meth:`from_mapping` method.176177 .. code-block:: python178179 import json180 app.config.from_file("config.json", load=json.load)181182 import toml183 app.config.from_file("config.toml", load=toml.load)184185 :param filename: The path to the data file. This can be an
20 unmodified lines
206 raise207208 return self.from_mapping(obj)209207 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.210211 :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.215216 .. 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.219220 .. versionadded:: 0.11221 """222 import warnings223 from . import json224225 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)232210 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-upper
59 unmodified lines
modified:src/flask/helpers.py+4 added-50 removed
3 unmodified lines
4import sys5import typing as t6import warnings7from datetime import datetime8from datetime import timedelta8from functools import lru_cache9from functools import update_wrapper10from threading import RLock1112import werkzeug.utils14from werkzeug.exceptions import NotFound13from werkzeug.routing import BuildError14from werkzeug.urls import url_quote1516from .globals import _app_ctx_stack
434 unmodified lines
451 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_filename460461 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_timeout469470 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_etags
146 unmodified lines
624 )625 )626627630def 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.633634 :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)646647 if path is None:648 raise NotFound()649650 return path651652628def 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 lines
665 """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 = filename
85 unmodified lines
759 with self.lock:760 super().__delete__(obj)761762788def total_seconds(td: timedelta) -> int:789 """Returns the total seconds from a timedelta object.790791 :param timedelta td: the timedelta to be converted in seconds792793 :returns: number of seconds794 :rtype: int795796 .. 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.seconds807808763def is_ip(value: str) -> bool:764 """Determine if the given string is an IP address.765766 :param value: value to check
24 unmodified lines
modified:tests/test_blueprints.py+2 added-2 removed
952 unmodified lines
953 bp2 = flask.Blueprint("bp", __name__)954955 app.register_blueprint(bp)956957 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, error959960 app.register_blueprint(bp, name="again") # same bp, different name, ok961962 with pytest.raises(ValueError):
41 unmodified lines
modified:tests/test_cli.py+16 added-44 removed
47 unmodified lines
48 assert testapp.cli.name == testapp.name495051def test_find_best_app(test_apps):52 script_info = ScriptInfo()5352 class Module:53 app = Flask("appname")5457 assert find_best_app(script_info, Module) == Module.app55 assert find_best_app(Module) == Module.app5657 class Module:58 application = Flask("appname")5962 assert find_best_app(script_info, Module) == Module.application60 assert find_best_app(Module) == Module.application6162 class Module:63 myapp = Flask("appname")6467 assert find_best_app(script_info, Module) == Module.myapp65 assert find_best_app(Module) == Module.myapp6667 class Module:68 @staticmethod69 def create_app():70 return Flask("appname")7174 app = find_best_app(script_info, Module)72 app = find_best_app(Module)73 assert isinstance(app, Flask)74 assert app.name == "appname"7576 class Module:77 @staticmethod78 def create_app(**kwargs):79 return Flask("appname")8083 app = find_best_app(script_info, Module)81 app = find_best_app(Module)82 assert isinstance(app, Flask)83 assert app.name == "appname"8485 class Module:86 @staticmethod89 def create_app(foo):90 return Flask("appname")9192 with pytest.deprecated_call(match="Script info"):93 app = find_best_app(script_info, Module)9495 assert isinstance(app, Flask)96 assert app.name == "appname"9798 class Module:99 @staticmethod100 def create_app(foo=None, script_info=None):101 return Flask("appname")102103 with pytest.deprecated_call(match="script_info"):104 app = find_best_app(script_info, Module)105106 assert isinstance(app, Flask)107 assert app.name == "appname"108109 class Module:110 @staticmethod87 def make_app():88 return Flask("appname")89114 app = find_best_app(script_info, Module)90 app = find_best_app(Module)91 assert isinstance(app, Flask)92 assert app.name == "appname"9394 class Module:
2 unmodified lines
97 @staticmethod98 def create_app():99 return Flask("appname2")100125 assert find_best_app(script_info, Module) == Module.myapp101 assert find_best_app(Module) == Module.myapp102103 class Module:104 myapp = Flask("appname1")105106 @staticmethod107 def create_app():108 return Flask("appname2")109134 assert find_best_app(script_info, Module) == Module.myapp110 assert find_best_app(Module) == Module.myapp111112 class Module:113 pass114139 pytest.raises(NoAppException, find_best_app, script_info, Module)115 pytest.raises(NoAppException, find_best_app, Module)116117 class Module:118 myapp1 = Flask("appname1")119 myapp2 = Flask("appname2")120145 pytest.raises(NoAppException, find_best_app, script_info, Module)121 pytest.raises(NoAppException, find_best_app, Module)122123 class Module:124 @staticmethod125 def create_app(foo, bar):126 return Flask("appname2")127152 pytest.raises(NoAppException, find_best_app, script_info, Module)128 pytest.raises(NoAppException, find_best_app, Module)129130 class Module:131 @staticmethod132 def create_app():133 raise TypeError("bad bad factory!")134159 pytest.raises(TypeError, find_best_app, script_info, Module)135 pytest.raises(TypeError, find_best_app, Module)136137138@pytest.mark.parametrize(139 "value,path,result",
55 unmodified lines
195 ("cliapp.factory", " create_app () ", "app"),196 ),197)198def 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 == result200201202@pytest.mark.parametrize(203 "iname,aname",
13 unmodified lines
217 ("cliapp.message.txt", None),218 ),219)220def test_locate_app_raises(test_apps, iname, aname):246 info = ScriptInfo()247221 with pytest.raises(NoAppException):249 locate_app(info, iname, aname)222 locate_app(iname, aname)223224225def 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 None228229 # 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)232233234def test_get_version(test_apps, capsys):235 from flask import __version__ as flask_version
429 unmodified lines
modified:CHANGES.rst+23 added-1 removed
3 unmodified lines
4-------------56Unreleased78- 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`1112 - 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.2223- 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.2627 - ``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``.313233Version 2.0.234-------------3536Released 2021-10-04
1178 unmodified lines