add encoding parameter to open_resource
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 · parent 66af0e5 · Browse files · 4 files·+79 added−51 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- co-authored-by: mark <lopkophacked@protonmail.com>
Diff stats
4 files+79 added−51 removed
- tests:+21 added−10 removed
- other:+58 added−41 removed
Provenance
- Commit
28d5a4d- Tree
ad31956- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
66af0e5
4 files changed+79 added−51 removed
modified:src/flask/app.py+36 added-20 removed
318 unmodified lines319 return send_from_directory(320 t.cast(str, self.static_folder), filename, max_age=max_age321 )322 323- def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:324- """Open a resource file relative to :attr:`root_path` for325- reading.323+ def open_resource(324+ self, resource: str, mode: str = "rb", encoding: str | None = None325+ ) -> t.IO[t.AnyStr]:326+ """Open a resource file relative to :attr:`root_path` for reading.327 328 For example, if the file ``schema.sql`` is next to the file329 ``app.py`` where the ``Flask`` app is defined, it can be opened330 with:2 unmodified lines333 334 with app.open_resource("schema.sql") as f:335 conn.executescript(f.read())336 336- :param resource: Path to the resource relative to337- :attr:`root_path`.338- :param mode: Open the file in this mode. Only reading is339- supported, valid values are "r" (or "rt") and "rb".337+ :param resource: Path to the resource relative to :attr:`root_path`.338+ :param mode: Open the file in this mode. Only reading is supported,339+ valid values are ``"r"`` (or ``"rt"``) and ``"rb"``.340+ :param encoding: Open the file with this encoding when opening in text341+ mode. This is ignored when opening in binary mode.342 341- Note this is a duplicate of the same method in the Flask342- class.343-343+ .. versionchanged:: 3.1344+ Added the ``encoding`` parameter.345 """346 if mode not in {"r", "rt", "rb"}:347 raise ValueError("Resources can only be opened for reading.")348 348- return open(os.path.join(self.root_path, resource), mode)349+ path = os.path.join(self.root_path, resource)350 350- def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:351- """Opens a resource from the application's instance folder352- (:attr:`instance_path`). Otherwise works like353- :meth:`open_resource`. Instance resources can also be opened for354- writing.351+ if mode == "rb":352+ return open(path, mode)353 356- :param resource: the name of the resource. To access resources within357- subfolders use forward slashes as separator.358- :param mode: resource file opening mode, default is 'rb'.354+ return open(path, mode, encoding=encoding)355+356+ def open_instance_resource(357+ self, resource: str, mode: str = "rb", encoding: str | None = "utf-8"358+ ) -> t.IO[t.AnyStr]:359+ """Open a resource file relative to the application's instance folder360+ :attr:`instance_path`. Unlike :meth:`open_resource`, files in the361+ instance folder can be opened for writing.362+363+ :param resource: Path to the resource relative to :attr:`instance_path`.364+ :param mode: Open the file in this mode.365+ :param encoding: Open the file with this encoding when opening in text366+ mode. This is ignored when opening in binary mode.367+368+ .. versionchanged:: 3.1369+ Added the ``encoding`` parameter.370 """360- return open(os.path.join(self.instance_path, resource), mode)371+ path = os.path.join(self.instance_path, resource)372 373+ if "b" in mode:374+ return open(path, mode)375+376+ return open(path, mode, encoding=encoding)377+378 def create_jinja_environment(self) -> Environment:379 """Create the Jinja environment based on :attr:`jinja_options`380 and the various Jinja-related methods of the app. Changing381 :attr:`jinja_options` after this will have no effect. Also adds1134 unmodified linesmodified:src/flask/blueprints.py+19 added-20 removed
99 unmodified lines100 return send_from_directory(101 t.cast(str, self.static_folder), filename, max_age=max_age102 )103 104- def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:105- """Open a resource file relative to :attr:`root_path` for106- reading.104+ def open_resource(105+ self, resource: str, mode: str = "rb", encoding: str | None = "utf-8"106+ ) -> t.IO[t.AnyStr]:107+ """Open a resource file relative to :attr:`root_path` for reading. The108+ blueprint-relative equivalent of the app's :meth:`~.Flask.open_resource`109+ method.110 108- For example, if the file ``schema.sql`` is next to the file109- ``app.py`` where the ``Flask`` app is defined, it can be opened110- with:111+ :param resource: Path to the resource relative to :attr:`root_path`.112+ :param mode: Open the file in this mode. Only reading is supported,113+ valid values are ``"r"`` (or ``"rt"``) and ``"rb"``.114+ :param encoding: Open the file with this encoding when opening in text115+ mode. This is ignored when opening in binary mode.116 112- .. code-block:: python113-114- with app.open_resource("schema.sql") as f:115- conn.executescript(f.read())116-117- :param resource: Path to the resource relative to118- :attr:`root_path`.119- :param mode: Open the file in this mode. Only reading is120- supported, valid values are "r" (or "rt") and "rb".121-122- Note this is a duplicate of the same method in the Flask123- class.124-117+ .. versionchanged:: 3.1118+ Added the ``encoding`` parameter.119 """120 if mode not in {"r", "rt", "rb"}:121 raise ValueError("Resources can only be opened for reading.")122 129- return open(os.path.join(self.root_path, resource), mode)123+ path = os.path.join(self.root_path, resource)124+125+ if mode == "rb":126+ return open(path, mode)127+128+ return open(path, mode, encoding=encoding)modified:tests/test_helpers.py+21 added-10 removed
332 unmodified lines333 assert rv.status_code == 200334 assert rv.data == b"Hello"335 assert rv.mimetype == "text/html"336 337- @pytest.mark.parametrize("mode", ("r", "rb", "rt"))338- def test_open_resource(self, mode):339- app = flask.Flask(__name__)337 341- with app.open_resource("static/index.html", mode) as f:342- assert "<h1>Hello World!</h1>" in str(f.read())338+@pytest.mark.parametrize("mode", ("r", "rb", "rt"))339+def test_open_resource(mode):340+ app = flask.Flask(__name__)341 344- @pytest.mark.parametrize("mode", ("w", "x", "a", "r+"))345- def test_open_resource_exceptions(self, mode):346- app = flask.Flask(__name__)342+ with app.open_resource("static/index.html", mode) as f:343+ assert "<h1>Hello World!</h1>" in str(f.read())344 345+346+@pytest.mark.parametrize("mode", ("w", "x", "a", "r+"))347+def test_open_resource_exceptions(mode):348+ app = flask.Flask(__name__)349+348- with pytest.raises(ValueError):349- app.open_resource("static/index.html", mode)350+ with pytest.raises(ValueError):351+ app.open_resource("static/index.html", mode)352+353+354+@pytest.mark.parametrize("encoding", ("utf-8", "utf-16-le"))355+def test_open_resource_with_encoding(tmp_path, encoding):356+ app = flask.Flask(__name__, root_path=os.fspath(tmp_path))357+ (tmp_path / "test").write_text("test", encoding=encoding)358+359+ with app.open_resource("test", mode="rt", encoding=encoding) as f:360+ assert f.read() == "test"modified:CHANGES.rst+3 added-1 removed
1 unmodified line2 -------------3 4 - Provide a configuration option to control automatic option5 responses. :pr:`5496`6+- ``Flask.open_resource``/``open_instance_resource`` and7+ ``Blueprint.open_resource`` take an ``encoding`` parameter to use when8+ opening in text mode. It defaults to ``utf-8``. :issue:`5504`9 7-10 Version 3.0.311 -------------12 13 Released 2024-04-071561 unmodified lines