Merge pull request #2378 from miguelgrinberg/default-flask-app
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Import app from wsgi.py or app.py if FLASK_APP is not defined
authored by David Lord · committed by GitHub · parents d625d41, 448368e · Browse files · 5 files·+75 added−19 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+75 added−19 removed
- tests:+30 added−1 removed
- other:+45 added−18 removed
Provenance
- Commit
29c055a- Tree
2c5f983- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d625d41- Parent 2
448368e
5 files changed+75 added−19 removed
modified:docs/cli.rst+8 added-4 removed
23 unmodified lines24 your Flask application's :attr:`Flask.cli` instance as well as some25 built-in commands that are always there. Flask extensions can also26 register more commands there if they desire so.27 28-For the :command:`flask` script to work, an application needs to be29-discovered. This is achieved by exporting the ``FLASK_APP`` environment30-variable. It can be either set to an import path or to a filename of a31-Python module that contains a Flask application.28+For the :command:`flask` script to work, an application needs to be discovered.29+Flask looks for a module named :file:`wsgi.py` or :file:`app.py` by default,30+and if it finds one it assumes the application is defined in it.31 32+You can instruct Flask to look for the application in a different module by33+exporting the ``FLASK_APP`` environment variable. It can be either set to an34+import path or to a filename of a Python module that contains a Flask35+application.36+37 In that imported file the name of the app needs to be called ``app`` or38 optionally be specified after a colon. For instance39 ``mymodule:application`` would tell it to use the `application` object in40 the :file:`mymodule.py` file.267 unmodified linesmodified:flask/cli.py+37 added-14 removed
170 unmodified lines171 module.append(extra)172 if not os.path.isfile(os.path.join(dirpath, '__init__.py')):173 break174 175+ if sys.path[0] != dirpath:175- sys.path.insert(0, dirpath)176+ sys.path.insert(0, dirpath)177+178 return '.'.join(module[::-1])179 180 179-def locate_app(script_info, app_id):181+def locate_app(script_info, app_id, raise_if_not_found=True):182 """Attempts to locate the application."""183 __traceback_hide__ = True184+185 if ':' in app_id:186 module, app_obj = app_id.split(':', 1)187 else:188 module = app_id5 unmodified lines194 # Reraise the ImportError if it occurred within the imported module.195 # Determine this by checking whether the trace has a depth > 1.196 if sys.exc_info()[-1].tb_next:197 stack_trace = traceback.format_exc()195- raise NoAppException('There was an error trying to import'196- ' the app (%s):\n%s' % (module, stack_trace))198+ 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+ )203+ )204+ elif raise_if_not_found:205+ raise NoAppException(206+ 'The file/path provided (%s) does not appear to exist. Please'207+ ' verify the path is correct. If app is not on PYTHONPATH,'208+ ' ensure the extension is .py.'.format(module=module)209+ )210 else:198- raise NoAppException('The file/path provided (%s) does not appear'199- ' to exist. Please verify the path is '200- 'correct. If app is not on PYTHONPATH, '201- 'ensure the extension is .py' % module)211+ return212 213 mod = sys.modules[module]214+215 if app_obj is None:216 return find_best_app(script_info, mod)217 else:218 return find_app_by_string(app_obj, script_info, mod)117 unmodified lines336 337 if self.create_app is not None:338 rv = call_factory(self.create_app, self)339 else:329- if not self.app_import_path:340+ if self.app_import_path:341+ rv = locate_app(self, self.app_import_path)342+ else:343+ for module in ['wsgi.py', 'app.py']:344+ import_path = prepare_exec_for_file(module)345+ rv = locate_app(346+ self, import_path, raise_if_not_found=False347+ )348+349+ if rv:350+ break351+352+ if not rv:353 raise NoAppException(354 'Could not locate Flask application. You did not provide '332- 'the FLASK_APP environment variable.\n\nFor more '333- 'information see '334- 'http://flask.pocoo.org/docs/latest/quickstart/')355+ 'the FLASK_APP environment variable, and a wsgi.py or '356+ 'app.py module was not found in the current directory.\n\n'357+ 'For more information see '358+ 'http://flask.pocoo.org/docs/latest/quickstart/'359+ )360 336- rv = locate_app(self, self.app_import_path)337-361 debug = get_debug_flag()362 363 if debug is not None:364 rv._reconfigure_for_run_debug(debug)335 unmodified linesadded:tests/test_apps/helloworld/hello.py+6 added
1+from flask import Flask2+app = Flask(__name__)3+4+@app.route("/")5+def hello():6+ return "Hello World!"added:tests/test_apps/helloworld/wsgi.py+1 added
1+from hello import appmodified:tests/test_cli.py+23 added-1 removed
179 unmodified lines180 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 None187 188 189 def test_find_default_import_path(test_apps, monkeypatch, tmpdir):190 """Test of find_default_import_path."""25 unmodified lines216 assert flask_ver in out217 assert py_ver in out218 219 217-def test_scriptinfo(test_apps):220+def test_scriptinfo(test_apps, monkeypatch):221 """Test of ScriptInfo."""222 obj = ScriptInfo(app_import_path="cliapp.app:testapp")223 assert obj.load_app().name == "testapp"224 assert obj.load_app().name == "testapp"5 unmodified lines230 app = obj.load_app()231 assert app.name == "createapp"232 assert obj.load_app() == app233 234+ obj = ScriptInfo()235+ pytest.raises(NoAppException, obj.load_app)236 237+ # import app from wsgi.py in current directory238+ monkeypatch.chdir(os.path.abspath(os.path.join(239+ os.path.dirname(__file__), 'test_apps', 'helloworld'240+ )))241+ obj = ScriptInfo()242+ app = obj.load_app()243+ assert app.name == 'hello'244+245+ # import app from app.py in current directory246+ monkeypatch.chdir(os.path.abspath(os.path.join(247+ os.path.dirname(__file__), 'test_apps', 'cliapp'248+ )))249+ obj = ScriptInfo()250+ app = obj.load_app()251+ assert app.name == 'testapp'252+253+254 def test_with_appcontext(runner):255 """Test of with_appcontext."""256 257 @click.command()133 unmodified lines