pallets/flask

allow setting encoding in open_resource()

liffiton opened this issue · 0 comments

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())