Permalink
Browse files

Convert Flask.run into a noop when run from the CLI

  • Loading branch information...
1 parent 42fbbb4 commit c9b33d0e860e347f1ed46eebadbfef4f5422b6da @mitsuhiko mitsuhiko committed Jan 29, 2017
Showing with 30 additions and 0 deletions.
  1. +4 −0 CHANGES
  2. +7 −0 flask/app.py
  3. +7 −0 flask/cli.py
  4. +12 −0 flask/debughelpers.py
View
@@ -8,6 +8,10 @@ Version 0.13
Major release, unreleased
+- Make `app.run()` into a noop if a Flask application is run from the
+ development server on the command line. This avoids some behavior that
+ was confusing to debug for newcomers.
+
Version 0.12.1
--------------
View
@@ -824,6 +824,13 @@ def run(self, host=None, port=None, debug=None, **options):
:func:`werkzeug.serving.run_simple` for more
information.
"""
+ # Change this into a no-op if the server is invoked from the
+ # command line. Have a look at cli.py for more information.
+ if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':
+ from .debughelpers import explain_ignored_app_run
+ explain_ignored_app_run()
+ return
+
from werkzeug.serving import run_simple
_host = '127.0.0.1'
_port = 5000
View
@@ -412,6 +412,13 @@ def run_command(info, host, port, reload, debugger, eager_loading,
"""
from werkzeug.serving import run_simple
+ # Set a global flag that indicates that we were invoked from the
+ # command line interface provided server command. This is detected
+ # by Flask.run to make the call into a no-op. This is necessary to
+ # avoid ugly errors when the script that is loaded here also attempts
+ # to start a server.
+ os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'
+
debug = get_debug_flag()
if reload is None:
reload = bool(debug)
View
@@ -8,6 +8,9 @@
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
+import os
+from warnings import warn
+
from ._compat import implements_to_string, text_type
from .app import Flask
from .blueprints import Blueprint
@@ -153,3 +156,12 @@ def explain_template_loading_attempts(app, template, attempts):
info.append(' See http://flask.pocoo.org/docs/blueprints/#templates')
app.logger.info('\n'.join(info))
+
+
+def explain_ignored_app_run():
+ if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
+ warn(Warning('Silently ignoring app.run() because the '
+ 'application is run from the flask command line '
+ 'executable. Consider putting app.run() behind an '
+ 'if __name__ == "__main__" guard to silence this '
+ 'warning.'), stacklevel=3)

0 comments on commit c9b33d0

Please sign in to comment.