Open a resource file relative to :attr:`root_path` for reading. For example, if the file ``schema.sql`` is next to the file ``app.py`` where the ``Flask`` app is defined, it can be opened with: .. code-block:: python with app.open_resource("schema.sql")
(
self, resource: str, mode: str = "rb", encoding: str | None = None
)
| 328 | ) |
| 329 | |
| 330 | def open_resource( |
| 331 | self, resource: str, mode: str = "rb", encoding: str | None = None |
| 332 | ) -> t.IO[t.AnyStr]: |
| 333 | """Open a resource file relative to :attr:`root_path` for reading. |
| 334 | |
| 335 | For example, if the file ``schema.sql`` is next to the file |
| 336 | ``app.py`` where the ``Flask`` app is defined, it can be opened |
| 337 | with: |
| 338 | |
| 339 | .. code-block:: python |
| 340 | |
| 341 | with app.open_resource("schema.sql") as f: |
| 342 | conn.executescript(f.read()) |
| 343 | |
| 344 | :param resource: Path to the resource relative to :attr:`root_path`. |
| 345 | :param mode: Open the file in this mode. Only reading is supported, |
| 346 | valid values are ``"r"`` (or ``"rt"``) and ``"rb"``. |
| 347 | :param encoding: Open the file with this encoding when opening in text |
| 348 | mode. This is ignored when opening in binary mode. |
| 349 | |
| 350 | .. versionchanged:: 3.1 |
| 351 | Added the ``encoding`` parameter. |
| 352 | """ |
| 353 | if mode not in {"r", "rt", "rb"}: |
| 354 | raise ValueError("Resources can only be opened for reading.") |
| 355 | |
| 356 | path = os.path.join(self.root_path, resource) |
| 357 | |
| 358 | if mode == "rb": |
| 359 | return open(path, mode) # pyright: ignore |
| 360 | |
| 361 | return open(path, mode, encoding=encoding) |
| 362 | |
| 363 | def open_instance_resource( |
| 364 | self, resource: str, mode: str = "rb", encoding: str | None = "utf-8" |
no outgoing calls