Browse Source

route app.run through the cli whenever possible

pull/2781/head
Miguel Grinberg 7 years ago
parent
commit
bd2e34c28d
  1. 24
      flask/app.py
  2. 44
      flask/cli.py

24
flask/app.py

@ -899,12 +899,28 @@ class Flask(_PackageBoundObject):
The default port is now picked from the ``SERVER_NAME`` The default port is now picked from the ``SERVER_NAME``
variable. variable.
""" """
# determine if this method is being invoked in the standard way (from
# the global scope of the __main__ module) by checking the length of
# the call stack
from inspect import stack
called_from_main = len(stack()) == 2
# Change this into a no-op if the server is invoked from the # Change this into a no-op if the server is invoked from the
# command line. Have a look at cli.py for more information. # command line. Have a look at cli.py for more information.
if os.environ.get('FLASK_RUN_FROM_CLI') == 'true': if called_from_main:
from .debughelpers import explain_ignored_app_run if os.environ.get('FLASK_RUN_FROM_CLI') == 'true':
explain_ignored_app_run() if os.environ.get('FLASK_RUN_FROM_APP_RUN') != 'true':
return from .debughelpers import explain_ignored_app_run
explain_ignored_app_run()
return
if load_dotenv and not options:
# Since this is a call with no custom settings besides host,
# port and debug, we can attempt to route it through the cli
# runner, and only fall back to the implementation in this
# function if that does not work
if cli.run_from_app_run(self, host, port, debug):
return
if get_load_dotenv(load_dotenv): if get_load_dotenv(load_dotenv):
cli.load_dotenv() cli.load_dotenv()

44
flask/cli.py

@ -874,6 +874,50 @@ debug mode.
)) ))
def run_from_app_run(app, host=None, port=None, debug=None):
if 'FLASK_APP' not in os.environ:
# attempt to determine the value of FLASK_APP through introspection
import inspect
app_name = None
for name, value in inspect.getmembers(sys.modules['__main__']):
if value == app:
app_name = name
break
if app_name is None:
return False
os.environ['FLASK_APP'] = '{}:{}'.format(sys.argv[0], app_name)
if 'FLASK_ENV' not in os.environ:
os.environ['FLASK_ENV'] = 'development' if debug else 'production'
# look for the flask executable in the same location where python is
executable = os.path.join(os.path.dirname(sys.executable), 'flask')
if not os.path.exists(executable):
# flask was not found in the expected location, let's assume that it
# is in the path
executable = 'flask'
# generate the cli arguments
if len(sys.argv) == 1:
# if no arguments were given in the command, default to "run",
# and add custom host and port if needed
args = ['run']
if host:
args += ['-h', host]
if port:
args += ['-p', port]
else:
# pass all the original arguments directly into the cli
args = sys.argv[1:]
sys.argv = [executable] + args
os.environ['FLASK_RUN_FROM_APP_RUN'] = 'true'
main()
return True
def main(as_module=False): def main(as_module=False):
args = sys.argv[1:] args = sys.argv[1:]

Loading…
Cancel
Save