Skip to content
Myr

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

5 files+75 added−19 removed

modified:docs/cli.rst+8 added-4 removed
23 unmodified lines
24your Flask application's :attr:`Flask.cli` instance as well as some25built-in commands that are always there. Flask extensions can also26register more commands there if they desire so.2728For the :command:`flask` script to work, an application needs to be29discovered. This is achieved by exporting the ``FLASK_APP`` environment30variable. It can be either set to an import path or to a filename of a31Python module that contains a Flask application.28For the :command:`flask` script to work, an application needs to be discovered.29Flask looks for a module named :file:`wsgi.py` or :file:`app.py` by default,30and if it finds one it assumes the application is defined in it.3132You can instruct Flask to look for the application in a different module by33exporting the ``FLASK_APP`` environment variable. It can be either set to an34import path or to a filename of a Python module that contains a Flask35application.3637In that imported file the name of the app needs to be called ``app`` or38optionally be specified after a colon. For instance39``mymodule:application`` would tell it to use the `application` object in40the :file:`mymodule.py` file.
267 unmodified lines
modified:flask/cli.py+37 added-14 removed
170 unmodified lines
171 module.append(extra)172 if not os.path.isfile(os.path.join(dirpath, '__init__.py')):173 break174175 if sys.path[0] != dirpath:175 sys.path.insert(0, dirpath)176 sys.path.insert(0, dirpath)177178 return '.'.join(module[::-1])179180179def locate_app(script_info, app_id):181def locate_app(script_info, app_id, raise_if_not_found=True):182 """Attempts to locate the application."""183 __traceback_hide__ = True184185 if ':' in app_id:186 module, app_obj = app_id.split(':', 1)187 else:188 module = app_id
5 unmodified lines
194 # 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 return212213 mod = sys.modules[module]214215 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 lines
336337 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 )348349 if rv:350 break351352 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 )360336 rv = locate_app(self, self.app_import_path)337361 debug = get_debug_flag()362363 if debug is not None:364 rv._reconfigure_for_run_debug(debug)
335 unmodified lines
added:tests/test_apps/helloworld/hello.py+6 added
1from flask import Flask2app = Flask(__name__)34@app.route("/")5def hello():6 return "Hello World!"
added:tests/test_apps/helloworld/wsgi.py+1 added
1from hello import app
modified:tests/test_cli.py+23 added-1 removed
179 unmodified lines
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 None187188189def test_find_default_import_path(test_apps, monkeypatch, tmpdir):190 """Test of find_default_import_path."""
25 unmodified lines
216 assert flask_ver in out217 assert py_ver in out218219217def test_scriptinfo(test_apps):220def 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 lines
230 app = obj.load_app()231 assert app.name == "createapp"232 assert obj.load_app() == app233234 obj = ScriptInfo()235 pytest.raises(NoAppException, obj.load_app)236237 # 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'244245 # 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'252253254def test_with_appcontext(runner):255 """Test of with_appcontext."""256257 @click.command()
133 unmodified lines