Skip to content
Myr

Merge pull request #2414 from davidism/cli-load-local-package

Before adoption: this commit came in with the history the project adopted, so no landing records it.

FLASK_APP doesn't require .py extension for local packages

authored by David Lord · committed by GitHub · parents 59f7966, fb845b9 · Browse files · 8 files+158 added−151 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+158 added−151 removed

  • tests:+106 added−73 removed
  • other:+52 added−78 removed

8 files+158 added−151 removed

modified:flask/cli.py+49 added-78 removed
128 unmodified lines
129130 if isinstance(app, Flask):131 return app132 else:133 raise RuntimeError('Failed to find application in module '133 raise NoAppException('Failed to find application in module '134 '"{name}"'.format(name=module))135 except TypeError as e:136 new_error = NoAppException(137 '{e}\nThe app factory "{factory}" in module "{module}" could'
8 unmodified lines
146 'The provided string "{string}" is not a valid variable name'147 'or function expression.'.format(string=string))148149150def prepare_exec_for_file(filename):150def prepare_import(path):151 """Given a filename this will try to calculate the python path, add it152 to the search path and return the actual module name that is expected.153 """154 module = []154 path = os.path.realpath(path)155156 # Chop off file extensions or package markers157 if os.path.split(filename)[1] == '__init__.py':158 filename = os.path.dirname(filename)159 elif filename.endswith('.py'):160 filename = filename[:-3]161 else:162 raise NoAppException('The file provided (%s) does exist but is not a '163 'valid Python file. This means that it cannot '164 'be used as application. Please change the '165 'extension to .py' % filename)166 filename = os.path.realpath(filename)156 if os.path.splitext(path)[1] == '.py':157 path = os.path.splitext(path)[0]158168 dirpath = filename169 while 1:170 dirpath, extra = os.path.split(dirpath)171 module.append(extra)172 if not os.path.isfile(os.path.join(dirpath, '__init__.py')):159 if os.path.basename(path) == '__init__':160 path = os.path.dirname(path)161162 module_name = []163164 # move up until outside package structure (no __init__.py)165 while True:166 path, name = os.path.split(path)167 module_name.append(name)168169 if not os.path.exists(os.path.join(path, '__init__.py')):170 break171175 if sys.path[0] != dirpath:176 sys.path.insert(0, dirpath)172 if sys.path[0] != path:173 sys.path.insert(0, path)174178 return '.'.join(module[::-1])175 return '.'.join(module_name[::-1])176177181def locate_app(script_info, app_id, raise_if_not_found=True):178def locate_app(script_info, module_name, app_name, raise_if_not_found=True):179 """Attempts to locate the application."""180 __traceback_hide__ = True181185 if ':' in app_id:186 module, app_obj = app_id.split(':', 1)187 else:188 module = app_id189 app_obj = None190182 try:192 __import__(module)183 __import__(module_name)184 except ImportError:185 # Reraise the ImportError if it occurred within the imported module.186 # Determine this by checking whether the trace has a depth > 1.187 if sys.exc_info()[-1].tb_next:197 stack_trace = traceback.format_exc()188 raise NoAppException(199 'There was an error trying to import the app ({module}):\n'200 '{stack_trace}'.format(201 module=module, stack_trace=stack_trace202 )189 'While importing "{name}", an ImportError was raised:'190 '\n\n{tb}'.format(name=module_name, tb=traceback.format_exc())191 )192 elif raise_if_not_found:193 raise NoAppException(206 'The file/path provided ({module}) does not appear to exist.'207 ' Please verify the path is correct. If app is not on'208 ' PYTHONPATH, ensure the extension is .py.'.format(209 module=module)194 'Could not import "{name}"."'.format(name=module_name)195 )196 else:197 return198214 mod = sys.modules[module]199 module = sys.modules[module_name]200216 if app_obj is None:217 return find_best_app(script_info, mod)201 if app_name is None:202 return find_best_app(script_info, module)203 else:219 return find_app_by_string(app_obj, script_info, mod)204 return find_app_by_string(app_name, script_info, module)205206222def find_default_import_path():223 app = os.environ.get('FLASK_APP')224 if app is None:225 return226 if os.path.isfile(app):227 return prepare_exec_for_file(app)228 return app229230207def get_version(ctx, param, value):208 if not value or ctx.resilient_parsing:209 return210 message = 'Flask %(version)s\nPython %(python_version)s'
72 unmodified lines
283 onwards as click object.284 """285286 def __init__(self, app_import_path=None, create_app=None):311 if create_app is None:312 if app_import_path is None:313 app_import_path = find_default_import_path()314 self.app_import_path = app_import_path315 else:316 app_import_path = None317287 #: Optionally the import path for the Flask application.319 self.app_import_path = app_import_path288 self.app_import_path = app_import_path or os.environ.get('FLASK_APP')289 #: Optionally a function that is passed the script info to create290 #: the instance of the application.291 self.create_app = create_app292 #: A dictionary with arbitrary data that can be associated with
10 unmodified lines
303304 if self._loaded_app is not None:305 return self._loaded_app306307 app = None308309 if self.create_app is not None:339 rv = call_factory(self.create_app, self)310 app = call_factory(self.create_app, self)311 else:312 if self.app_import_path:342 rv = locate_app(self, self.app_import_path)313 path, name = (self.app_import_path.split(':', 1) + [None])[:2]314 import_name = prepare_import(path)315 app = locate_app(self, import_name, name)316 else:344 for module in ['wsgi.py', 'app.py']:345 import_path = prepare_exec_for_file(module)346 rv = locate_app(347 self, import_path, raise_if_not_found=False317 for path in ('wsgi.py', 'app.py'):318 import_name = prepare_import(path)319 app = locate_app(320 self, import_name, None, raise_if_not_found=False321 )322350 if rv:323 if app:324 break325353 if not rv:354 raise NoAppException(355 'Could not locate Flask application. You did not provide '356 'the FLASK_APP environment variable, and a wsgi.py or '357 'app.py module was not found in the current directory.\n\n'358 'For more information see '359 'http://flask.pocoo.org/docs/latest/quickstart/'360 )326 if not app:327 raise NoAppException(328 'Could not locate a Flask application. You did not provide '329 'the "FLASK_APP" environment variable, and a "wsgi.py" or '330 '"app.py" module was not found in the current directory.'331 )332333 debug = get_debug_flag()334335 if debug is not None:365 rv._reconfigure_for_run_debug(debug)336 app._reconfigure_for_run_debug(debug)337367 self._loaded_app = rv368 return rv338 self._loaded_app = app339 return app340341342pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)343
328 unmodified lines
added:tests/test_apps/cliapp/inner1/inner2/__init__.py
added:tests/test_apps/cliapp/inner1/inner2/flask.py+3 added
1from flask import Flask23app = Flask(__name__)
added:tests/test_apps/cliapp/inner1/__init__.py+3 added
1from flask import Flask23application = Flask(__name__)
modified:tests/test_apps/cliapp/factory.py+4 added-4 removed
2 unmodified lines
3from flask import Flask456def create_app():7 return Flask('create_app')7 return Flask('app')8910def create_app2(foo, bar):11 return Flask("_".join(['create_app2', foo, bar]))11 return Flask('_'.join(['app2', foo, bar]))121314def create_app3(foo, bar, script_info):15 return Flask("_".join(['create_app3', foo, bar]))14def create_app3(foo, script_info):15 return Flask('_'.join(['app3', foo, script_info.data['test']]))
added:tests/test_apps/cliapp/message.txt+1 added
1So long, and thanks for all the fish.
modified:tests/test_cli.py+95 added-69 removed
9 unmodified lines
10# This file was part of Flask-CLI and was modified under the terms its license,11# the Revised BSD License.12# Copyright (C) 2015 CERN.13#14from __future__ import absolute_import, print_function14from __future__ import absolute_import1516import os17import sys18from functools import partial1920import click21import pytest22from click.testing import CliRunner2324from flask import Flask, current_app25from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \26 find_best_app, get_version, locate_app, prepare_import, with_appcontext2724from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \25 find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \26 find_default_import_path, get_version282829@pytest.fixture30def runner():31 return CliRunner()32
91 unmodified lines
124125 pytest.raises(NoAppException, find_best_app, script_info, Module)126127128def test_prepare_exec_for_file(test_apps):129 """Expect the correct path to be set and the correct module name to be returned.128cwd = os.getcwd()129test_path = os.path.abspath(os.path.join(130 os.path.dirname(__file__), 'test_apps'131))132131 :func:`prepare_exec_for_file` has a side effect, where132 the parent directory of given file is added to `sys.path`.133134@pytest.mark.parametrize('value,path,result', (135 ('test', cwd, 'test'),136 ('test.py', cwd, 'test'),137 ('a/test', os.path.join(cwd, 'a'), 'test'),138 ('test/__init__.py', cwd, 'test'),139 ('test/__init__', cwd, 'test'),140 # nested package141 (142 os.path.join(test_path, 'cliapp', 'inner1', '__init__'),143 test_path, 'cliapp.inner1'144 ),145 (146 os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),147 test_path, 'cliapp.inner1.inner2'148 ),149 # dotted name150 ('test.a.b', cwd, 'test.a.b'),151 (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),152 # not a Python file, will be caught during import153 (154 os.path.join(test_path, 'cliapp', 'message.txt'),155 test_path, 'cliapp.message.txt'156 ),157))158def test_prepare_import(request, value, path, result):159 """Expect the correct path to be set and the correct import and app names160 to be returned.161162 :func:`prepare_exec_for_file` has a side effect where the parent directory163 of the given import is added to :data:`sys.path`. This is reset after the164 test runs.165 """134 realpath = os.path.realpath('/tmp/share/test.py')135 dirname = os.path.dirname(realpath)136 assert prepare_exec_for_file('/tmp/share/test.py') == 'test'137 assert dirname in sys.path166 original_path = sys.path[:]167139 realpath = os.path.realpath('/tmp/share/__init__.py')140 dirname = os.path.dirname(os.path.dirname(realpath))141 assert prepare_exec_for_file('/tmp/share/__init__.py') == 'share'142 assert dirname in sys.path168 def reset_path():169 sys.path[:] = original_path170144 with pytest.raises(NoAppException):145 prepare_exec_for_file('/tmp/share/test.txt')171 request.addfinalizer(reset_path)172173 assert prepare_import(value) == result174 assert sys.path[0] == path175148def test_locate_app(test_apps):149 """Test of locate_app."""150 script_info = ScriptInfo()151 assert locate_app(script_info, "cliapp.app").name == "testapp"152 assert locate_app(script_info, "cliapp.app:testapp").name == "testapp"153 assert locate_app(script_info, "cliapp.factory").name == "create_app"154 assert locate_app(155 script_info, "cliapp.factory").name == "create_app"156 assert locate_app(157 script_info, "cliapp.factory:create_app").name == "create_app"158 assert locate_app(159 script_info, "cliapp.factory:create_app()").name == "create_app"160 assert locate_app(161 script_info, "cliapp.factory:create_app2('foo', 'bar')"162 ).name == "create_app2_foo_bar"163 assert locate_app(164 script_info, "cliapp.factory:create_app2('foo', 'bar', )"165 ).name == "create_app2_foo_bar"166 assert locate_app(167 script_info, "cliapp.factory:create_app3('baz', 'qux')"168 ).name == "create_app3_baz_qux"169 assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"170 pytest.raises(171 NoAppException, locate_app, script_info, "notanpp.py")172 pytest.raises(173 NoAppException, locate_app, script_info, "cliapp/app")174 pytest.raises(175 RuntimeError, locate_app, script_info, "cliapp.app:notanapp")176 pytest.raises(177 NoAppException, locate_app,178 script_info, "cliapp.factory:create_app2('foo')")179 pytest.raises(180 NoAppException, locate_app,181 script_info, "cliapp.factory:create_app ()")182 pytest.raises(183 NoAppException, locate_app, script_info, "cliapp.importerrorapp")184 assert locate_app(185 script_info, "notanpp.py", raise_if_not_found=False186 ) is None176177@pytest.mark.parametrize('iname,aname,result', (178 ('cliapp.app', None, 'testapp'),179 ('cliapp.app', 'testapp', 'testapp'),180 ('cliapp.factory', None, 'app'),181 ('cliapp.factory', 'create_app', 'app'),182 ('cliapp.factory', 'create_app()', 'app'),183 # no script_info184 ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),185 # trailing comma space186 ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),187 # takes script_info188 ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),189))190def test_locate_app(test_apps, iname, aname, result):191 info = ScriptInfo()192 info.data['test'] = 'spam'193 assert locate_app(info, iname, aname).name == result194189def test_find_default_import_path(test_apps, monkeypatch, tmpdir):190 """Test of find_default_import_path."""191 monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)192 assert find_default_import_path() == None193 monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')194 assert find_default_import_path() == 'notanapp'195 tmpfile = tmpdir.join('testapp.py')196 tmpfile.write('')197 monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))198 expect_rv = prepare_exec_for_file(str(tmpfile))199 assert find_default_import_path() == expect_rv195196@pytest.mark.parametrize('iname,aname', (197 ('notanapp.py', None),198 ('cliapp/app', None),199 ('cliapp.app', 'notanapp'),200 # not enough arguments201 ('cliapp.factory', 'create_app2("foo")'),202 # nested import error203 ('cliapp.importerrorapp', None),204 # not a Python file205 ('cliapp.message.txt', None),206 # space before arg list207 ('cliapp.factory', 'create_app ()'),208))209def test_locate_app_raises(test_apps, iname, aname):210 info = ScriptInfo()211212 with pytest.raises(NoAppException):213 locate_app(info, iname, aname)214215216def test_locate_app_suppress_raise():217 info = ScriptInfo()218 app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)219 assert app is None220221 # only direct import error is suppressed222 with pytest.raises(NoAppException):223 locate_app(224 info, 'cliapp.importerrorapp', None, raise_if_not_found=False225 )226227228def test_get_version(test_apps, capsys):229 """Test of get_version."""230 from flask import __version__ as flask_ver231 from sys import version as py_ver
185 unmodified lines
modified:CHANGES+3 added
50 unmodified lines
51 (`#2319`_)52- FLASK_APP=myproject.app:create_app('dev') support.53- ``FLASK_APP`` can be set to an app factory, with arguments if needed, for54 example ``FLASK_APP=myproject.app:create_app('dev')``. (`#2326`_)55- ``FLASK_APP`` can point to local packages that are not installed in dev mode,56 although `pip install -e` should still be preferred. (`#2414`_)57- ``View.provide_automatic_options = True`` is set on the view function from58 ``View.as_view``, to be detected in ``app.add_url_rule``. (`#2316`_)59- Error handling will try handlers registered for ``blueprint, code``,60 ``app, code``, ``blueprint, exception``, ``app, exception``. (`#2314`_)
67 unmodified lines
128.. _#2374: https://github.com/pallets/flask/pull/2374129.. _#2373: https://github.com/pallets/flask/pull/2373130.. _#2385: https://github.com/pallets/flask/issues/2385131.. _#2412: https://github.com/pallets/flask/pull/2412132.. _#2414: https://github.com/pallets/flask/pull/2414133134Version 0.12.2135--------------136
617 unmodified lines