From 789715adb9949f58b7b0272bed1a58d7cd0fad30 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Mon, 26 Dec 2016 03:50:47 +0100 Subject: [PATCH] Fix config.from_pyfile on Python 3 (#2123) * Fix config.from_pyfile on Python 3 Fix #2118 * Support Python 2.6 * Fix tests on Python 2 --- CHANGES | 3 +++ flask/config.py | 2 +- tests/test_config.py | 22 ++++++++++++++++++++-- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/CHANGES b/CHANGES index 317bd489..a0a423d1 100644 --- a/CHANGES +++ b/CHANGES @@ -8,6 +8,9 @@ Version 0.12.1 Bugfix release, unreleased +- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix + ``#2118``. + Version 0.12 ------------ diff --git a/flask/config.py b/flask/config.py index 36e8a123..697add71 100644 --- a/flask/config.py +++ b/flask/config.py @@ -126,7 +126,7 @@ class Config(dict): d = types.ModuleType('config') d.__file__ = filename try: - with open(filename) as config_file: + with open(filename, mode='rb') as config_file: exec(compile(config_file.read(), filename, 'exec'), d.__dict__) except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): diff --git a/tests/test_config.py b/tests/test_config.py index 333a5cff..5c98db98 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -7,11 +7,14 @@ :license: BSD, see LICENSE for more details. """ -import pytest -import os from datetime import timedelta +import os +import textwrap + import flask +from flask._compat import PY2 +import pytest # config keys used for the TestConfig @@ -187,3 +190,18 @@ def test_get_namespace(): assert 2 == len(bar_options) assert 'bar stuff 1' == bar_options['BAR_STUFF_1'] assert 'bar stuff 2' == bar_options['BAR_STUFF_2'] + + +@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1']) +def test_from_pyfile_weird_encoding(tmpdir, encoding): + f = tmpdir.join('my_config.py') + f.write_binary(textwrap.dedent(u''' + # -*- coding: {0} -*- + TEST_VALUE = "föö" + '''.format(encoding)).encode(encoding)) + app = flask.Flask(__name__) + app.config.from_pyfile(str(f)) + value = app.config['TEST_VALUE'] + if PY2: + value = value.decode(encoding) + assert value == u'föö'