pallets / flask

The Python micro framework for building web applications.
https://flask.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
67.87k stars 16.2k forks source link

allow setting encoding in open_resource() #5504

Closed liffiton closed 3 months ago

liffiton commented 4 months ago

This is a duplicate of #1740 — that may have been closed for lack of a clear rationale, however, and I'd like to suggest it again with the following reasoning.

The documentation currently gives this example for using open_resource():

with app.open_resource("schema.sql") as f:
    conn.executescript(f.read())

On Windows, however, this can fail to open a file encoded in UTF-8, which most are these days, and safer code looks like this:

with app.open_resource("schema.sql", mode="rb") as f:
   conn.executescript(f.read().decode("utf-8"))  # type: ignore [attr-defined]

(The type comment is needed to prevent mypy from complaining about f.read() possibly being a string with no .decode() method, as it can't tell that the file was opened in 'rb' mode.)

It would be cleaner and more flexible to be able to write:

with app.open_resource("schema.sql", encoding="utf-8") as f:
   conn.executescript(f.read())