Skip to content
Myr

Merge pull request #2490 from davidism/cli-review

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

Rewrite CLI errors and docs

authored by David Lord · committed by GitHub · parents 8020d5e, 9bc329c · Browse files · 5 files+369 added−293 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+369 added−293 removed

  • tests:+10 added−2 removed
  • other:+359 added−291 removed

5 files+369 added−293 removed

modified:docs/cli.rst+263 added-215 removed
1.. currentmodule:: flask23.. _cli:45Command Line Interface6======================76.. versionadded:: 0.118Installing Flask installs the ``flask`` script, a `Click`_ command line9interface, in your virtualenv. Executed from the terminal, this script gives10access to built-in, extension, and application-defined commands. The ``--help``11option will give more information about any commands and options.128.. currentmodule:: flask13.. _Click: http://click.pocoo.org/1410One of the nice new features in Flask 0.11 is the built-in integration of11the `click <http://click.pocoo.org/>`_ command line interface. This12enables a wide range of new features for the Flask ecosystem and your own13applications.1515Basic Usage16-----------16Application Discovery17---------------------1818After installation of Flask you will now find a :command:`flask` script19installed into your virtualenv. If you don't want to install Flask or you20have a special use-case you can also use ``python -m flask`` to accomplish21exactly the same.19The ``flask`` command is installed by Flask, not your application; it must be20told where to find your application in order to use it. The ``FLASK_APP``21environment variable is used to specify how to load the application.2223The way this script works is by providing access to all the commands on24your 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.23Unix Bash (Linux, Mac, etc.)::2428For 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.25 $ export FLASK_APP=hello26 $ flask run2732You 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.28Windows CMD::2937In 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.30 > set FLASK_APP=hello31 > flask run3242Given a :file:`hello.py` file with the application in it named ``app``43this is how it can be run.33Windows PowerShell::3445Environment variables (On Windows use ``set`` instead of ``export``)::35 > $env:FLASK_APP = "hello"36 > flask run3747 export FLASK_APP=hello48 flask run38While ``FLASK_APP`` supports a variety of options for specifying your39application, most use cases should be simple. Here are the typical values:4050Or with a filename::41(nothing)42 The file :file:`wsgi.py` is imported, automatically detecting an app43 (``app``). This provides an easy way to create an app from a factory with44 extra arguments.4552 export FLASK_APP=/path/to/hello.py53 flask run46``FLASK_APP=hello``47 The name is imported, automatically detecting an app (``app``) or factory48 (``create_app``).4955Virtualenv Integration56----------------------50----5158If you are constantly working with a virtualenv you can also put the59``export FLASK_APP`` into your ``activate`` script by adding it to the60bottom of the file. That way every time you activate your virtualenv you61automatically also activate the correct application name.52``FLASK_APP`` has three parts: an optional path that sets the current working53directory, a Python file or dotted import path, and an optional variable54name of the instance or factory. If the name is a factory, it can optionally55be followed by arguments in parentheses. The following values demonstrate these56parts:5763Edit the activate script for the shell you use. For example:58``FLASK_APP=src/hello``59 Sets the current working directory to ``src`` then imports ``hello``.6065Unix Bash: ``venv/bin/activate``::61``FLASK_APP=hello.web``62 Imports the path ``hello.web``.6367 FLASK_APP=hello68 export FLASK_APP64``FLASK_APP=hello:app2``65 Uses the ``app2`` Flask instance in ``hello``.6670Windows CMD.exe: ``venv\Scripts\activate.bat``::67``FLASK_APP="hello:create_app('dev')"``68 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``69 as the argument.7072 set "FLASK_APP=hello"73 :END71If ``FLASK_APP`` is not set, the command will look for a file called72:file:`wsgi.py` or :file:`app.py` and try to detect an application instance or73factory.7475Debug Flag76----------75Within the given import, the command looks for an application instance named76``app`` or ``application``, then any application instance. If no instance is77found, the command looks for a factory function named ``create_app`` or78``make_app`` that returns an instance.7978The :command:`flask` script can also be instructed to enable the debug79mode of the application automatically by exporting ``FLASK_DEBUG``. If80set to ``1`` debug is enabled or ``0`` disables it::80When calling an application factory, if the factory takes an argument named81``info``, then the :class:`~cli.ScriptInfo` instance is passed as a keyword82argument. If parentheses follow the factory name, their contents are parsed83as Python literals and passes as arguments to the function. This means that84strings must still be in quotes.8582 export FLASK_DEBUG=18684Running a Shell85---------------87Run the Development Server88--------------------------8987To run an interactive Python shell you can use the ``shell`` command::90The :func:`run <cli.run_command>` command will start the development server. It91replaces the :meth:`Flask.run` method in most cases. ::9289 flask shell93 $ flask run94 * Serving Flask app "hello"95 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)9691This will start up an interactive Python shell, setup the correct92application context and setup the local variables in the shell. This is93done by invoking the :meth:`Flask.make_shell_context` method of the94application. By default you have access to your ``app`` and :data:`g`.97.. warning:: Do not use this command to run your application in production.98 Only use the development server during development. The development server99 is provided for convenience, but is not designed to be particularly secure,100 stable, or efficient. See :ref:`deployment` for how to run in production.10196Custom Commands97---------------10299If you want to add more commands to the shell script you can do this100easily. For instance if you want a shell command to initialize the database you101can do this::103Open a Shell104------------105103 import click104 from flask import Flask106To explore the data in your application, you can start an interactive Python107shell with the :func:`shell <cli.shell_command>` command. An application108context will be active, and the app instance will be imported. ::109106 app = Flask(__name__)110 $ flask shell111 Python 3.6.2 (default, Jul 20 2017, 03:52:27)112 [GCC 7.1.1 20170630] on linux113 App: example114 Instance: /home/user/Projects/hello/instance115 >>>116108 @app.cli.command()109 def initdb():110 """Initialize the database."""111 click.echo('Init the db')117Use :meth:`~Flask.shell_context_processor` to add other automatic imports.118113The command will then show up on the command line::119115 $ flask initdb116 Init the db120Debug Mode121----------122118Application Context119-------------------123Set the :envvar:`FLASK_DEBUG` environment variable to override the124application's :attr:`~Flask.debug` flag. The value ``1`` enables it, ``0``125disables it. Forcing the debug flag on also enables the debugger and reloader126when running the development server. ::127121Most commands operate on the application so it makes a lot of sense if122they have the application context setup. Because of this, if you register123a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the124callback will automatically be wrapped through :func:`cli.with_appcontext`125which informs the cli system to ensure that an application context is set126up. This behavior is not available if a command is added later with127:func:`~click.Group.add_command` or through other means.128 $ FLASK_DEBUG=1 flask run129 * Serving Flask app "hello"130 * Forcing debug mode on131 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)132 * Restarting with inotify reloader133 * Debugger is active!134 * Debugger PIN: 223-456-919135129It can also be disabled by passing ``with_appcontext=False`` to the130decorator::136132 @app.cli.command(with_appcontext=False)133 def example():134 pass135136137.. _dotenv:138139Loading Environment Variables From ``.env`` Files140-------------------------------------------------139Environment Variables From dotenv140---------------------------------141142Rather than setting ``FLASK_APP`` each time you open a new terminal, you can143use Flask's dotenv support to set environment variables automatically.144142If `python-dotenv`_ is installed, running the :command:`flask` command will set145If `python-dotenv`_ is installed, running the ``flask`` command will set146environment variables defined in the files :file:`.env` and :file:`.flaskenv`.147This can be used to avoid having to set ``FLASK_APP`` manually every time you148open a new terminal, and to set configuration using environment variables149similar to how some deployment services work.
2 unmodified lines
152which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be153used for public variables, such as ``FLASK_APP``, while :file:`.env` should not154be committed to your repository so that it can set private variables.155153Directories are scanned upwards from the directory you call :command:`flask`156Directories are scanned upwards from the directory you call ``flask``157from to locate the files. The current working directory will be set to the158location of the file, with the assumption that that is the top level project159directory.160158The files are only loaded by the :command:`flask` command or calling159:meth:`~flask.Flask.run`. If you would like to load these files when running in160production, you should call :func:`~flask.cli.load_dotenv` manually.161The files are only loaded by the ``flask`` command or calling162:meth:`~Flask.run`. If you would like to load these files when running in163production, you should call :func:`~cli.load_dotenv` manually.164165.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme166167165Factory Functions166-----------------168Environment Variables From virtualenv169-------------------------------------170168In case you are using factory functions to create your application (see169:ref:`app-factories`) you will discover that the :command:`flask` command170cannot work with them directly. Flask won't be able to figure out how to171instantiate your application properly by itself. Because of this reason172the recommendation is to create a separate file that instantiates173applications. This is not the only way to make this work. Another is the174:ref:`custom-scripts` support.171If you do not want to install dotenv support, you can still set environment172variables by adding them to the end of the virtualenv's :file:`activate`173script. Activating the virtualenv will set the variables.174176For instance if you have a factory function that creates an application177from a filename you could make a separate file that creates such an178application from an environment variable.175Unix Bash, :file:`venv/bin/activate`::176180This could be a file named :file:`autoapp.py` with these contents::177 export FLASK_APP=hello178182 import os183 from yourapplication import create_app184 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])179Windows CMD, :file:`venv\Scripts\activate.bat`::180186Once this has happened you can make the :command:`flask` command automatically187pick it up::181 set FLASK_APP=hello182189 export YOURAPPLICATION_CONFIG=/path/to/config.cfg190 export FLASK_APP=/path/to/autoapp.py183It is preferred to use dotenv support over this, since :file:`.flaskenv` can be184committed to the repository so that it works automatically wherever the project185is checked out.186192From this point onwards :command:`flask` will find your application.187194.. _custom-scripts:188Custom Commands189---------------190196Custom Scripts197--------------191The ``flask`` command is implemented using `Click`_. See that project's192documentation for full information about writing commands.193199While the most common way is to use the :command:`flask` command, you can200also make your own "driver scripts". Since Flask uses click for the201scripts there is no reason you cannot hook these scripts into any click202application. There is one big caveat and that is, that commands203registered to :attr:`Flask.cli` will expect to be (indirectly at least)204launched from a :class:`flask.cli.FlaskGroup` click group. This is205necessary so that the commands know which Flask application they have to206work with.194This example adds the command ``create_user`` that takes the argument195``name``. ::196208To understand why you might want custom scripts you need to understand how209click finds and executes the Flask application. If you use the210:command:`flask` script you specify the application to work with on the211command line or environment variable as an import name. This is simple212but it has some limitations. Primarily it does not work with application213factory functions (see :ref:`app-factories`).197 import click198 from flask import Flask199215With a custom script you don't have this problem as you can fully216customize how the application will be created. This is very useful if you217write reusable applications that you want to ship to users and they should218be presented with a custom management script.200 app = Flask(__name__)201220To explain all of this, here is an example :file:`manage.py` script that221manages a hypothetical wiki application. We will go through the details222afterwards::202 @app.cli.command()203 @click.argument('name')204 def create_user(name):205 ...206224 import os207::208209 flask create_user admin210211This example adds the same command, but as ``user create``, a command in a212group. This is useful if you want to organize multiple related commands. ::213214 import click215 from flask import Flask226 from flask.cli import FlaskGroup216 from flask.cli import AppGroup217228 def create_wiki_app(info):229 from yourwiki import create_app230 return create_app(231 config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))218 app = Flask(__name__)219 user_cli = AppGroup('user')220233 @click.group(cls=FlaskGroup, create_app=create_wiki_app)234 def cli():235 """This is a management script for the wiki application."""221 @user_cli.command('create')222 @click.argument('name')223 def create_user(name):224 ...225237 if __name__ == '__main__':238 cli()226 app.cli.add_command(user_cli)227240That's a lot of code for not much, so let's go through all parts step by241step.228::2292431. First we import the ``click`` library as well as the click extensions244 from the ``flask.cli`` package. Primarily we are here interested245 in the :class:`~flask.cli.FlaskGroup` click group.2462. The next thing we do is defining a function that is invoked with the247 script info object (:class:`~flask.cli.ScriptInfo`) from Flask and its248 purpose is to fully import and create the application. This can249 either directly import an application object or create it (see250 :ref:`app-factories`). In this case we load the config from an251 environment variable.2523. Next step is to create a :class:`FlaskGroup`. In this case we just253 make an empty function with a help doc string that just does nothing254 and then pass the ``create_wiki_app`` function as a factory function.230 flask user create demo231256 Whenever click now needs to operate on a Flask application it will257 call that function with the script info and ask for it to be created.2584. All is rounded up by invoking the script.232260CLI Plugins261-----------233Application Context234~~~~~~~~~~~~~~~~~~~235263Flask extensions can always patch the :attr:`Flask.cli` instance with more264commands if they want. However there is a second way to add CLI plugins265to Flask which is through ``setuptools``. If you make a Python package that266should export a Flask command line plugin you can ship a :file:`setup.py` file267that declares an entrypoint that points to a click command:236Commands added using the Flask app's :attr:`~Flask.cli`237:meth:`~cli.AppGroup.command` decorator will be executed with an application238context pushed, so your command and extensions have access to the app and its239configuration. If you create a command using the Click :func:`~click.command`240decorator instead of the Flask decorator, you can use241:func:`~cli.with_appcontext` to get the same behavior. ::242269Example :file:`setup.py`::243 import click244 from flask.cli import with_appcontext245246 @click.command247 @with_appcontext248 def do_work():249 ...250251 app.cli.add_command(do_work)252253If you're sure a command doesn't need the context, you can disable it::254255 @app.cli.command(with_appcontext=False)256 def do_work():257 ...258259260Plugins261-------262263Flask will automatically load commands specified in the ``flask.commands``264`entry point`_. This is useful for extensions that want to add commands when265they are installed. Entry points are specified in :file:`setup.py` ::266267 from setuptools import setup268269 setup(270 name='flask-my-extension',275 ...276 entry_points='''277 [flask.commands]278 my-command=mypackage.commands:cli279 ''',271 ...,272 entry_points={273 'flask.commands': [274 'my-command=flask_my_extension.commands:cli'275 ],276 },277 )278282Inside :file:`mypackage/commands.py` you can then export a Click object::279280.. _entry point: https://packaging.python.org/tutorials/distributing-packages/#entry-points281282Inside :file:`flask_my_extension/commands.py` you can then export a Click283object::284285 import click286287 @click.command()288 def cli():288 """This is an example command."""289 ...290290Once that package is installed in the same virtualenv as Flask itself you291can run ``flask my-command`` to invoke your command. This is useful to292provide extra functionality that Flask itself cannot ship.291Once that package is installed in the same virtualenv as your Flask project,292you can run ``flask my-command`` to invoke the command.293294295.. _custom-scripts:296297Custom Scripts298--------------299300When you are using the app factory pattern, it may be more convenient to define301your own Click script. Instead of using ``FLASK_APP`` and letting Flask load302your application, you can create your own Click object and export it as a303`console script`_ entry point.304305Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::306307 import click308 from flask import Flask309 from flask.cli import FlaskGroup310311 def create_app():312 app = Flask('wiki')313 # other setup314 return app315316 @click.group(cls=FlaskGroup, create_app=create_app)317 def cli():318 """Management script for the Wiki application."""319320Define the entry point in :file:`setup.py`::321322 from setuptools import setup323324 setup(325 name='flask-my-extension',326 ...,327 entry_points={328 'console_scripts': [329 'wiki=wiki:cli'330 ],331 },332 )333334Install the application in the virtualenv in editable mode and the custom335script is available. Note that you don't need to set ``FLASK_APP``. ::336337 $ pip install -e .338 $ wiki run339340.. _console script: https://packaging.python.org/tutorials/distributing-packages/#console-scripts341342343PyCharm Integration344-------------------345297The new Flask CLI features aren’t yet fully integrated into the PyCharm IDE,298so we have to do a few tweaks to get them working smoothly.346The new Flask CLI features aren't yet fully integrated into the PyCharm IDE,347so we have to do a few tweaks to get them working smoothly. These instructions348should be similar for any other IDE you might want to use.349300In your PyCharm application, with your project open, click on *Run*301from the menu bar and go to *Edit Configurations*. You’ll be greeted by a302screen similar to this:350In PyCharm, with your project open, click on *Run* from the menu bar and go to351*Edit Configurations*. You'll be greeted by a screen similar to this:352353.. image:: _static/pycharm-runconfig.png354 :align: center355 :class: screenshot356 :alt: screenshot of pycharm's run configuration settings357309There’s quite a few options to change, but don’t worry— once we’ve done it310for one command, we can easily copy the entire configuration and make a311single tweak to give us access to other flask cli commands, including312any custom ones you may implement yourself.358There's quite a few options to change, but once we've done it for one command,359we can easily copy the entire configuration and make a single tweak to give us360access to other commands, including any custom ones you may implement yourself.361314For the *Script* input (**A**), we want to navigate to the virtual environment315we’re using for our project and within that folder we want to pick the ``flask``316file which will reside in the ``bin`` folder, or in the ``Scripts`` folder if317you're on Windows.362For the *Script* input (**A**), navigate to your project's virtual environment.363Within that folder, pick the ``flask`` executable which will reside in the364``bin`` folder, or in the ``Scripts`` on Windows.365319The *Script Parameter* field (**B**) is set to the cli command you wish to320execute, in this example we use ``run`` which will run our development server.366The *Script Parameter* field (**B**) is set to the CLI command you to execute.367In this example we use ``run``, which will run the development server.368322We need to add an environment variable (**C**) to identify our application.323Click on the browse button and add an entry with ``FLASK_APP`` on the324left and the name of the python file, or package on the right325(``app.py`` for example).369You can skip this next step if you're using :ref:`dotenv`. We need to add an370environment variable (**C**) to identify our application. Click on the browse371button and add an entry with ``FLASK_APP`` on the left and the name of the372Python file or package on the right (``app.py`` for example).373374Next we need to set the working directory (**D**) to be the same folder where328our application file or package resides.375our application file or package resides. PyCharm changed it to the directory376with the ``flask`` executable when we selected it earlier, which is incorrect.377378Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a331good descriptive name, such as “Run Flask Server” and click *Apply*.379good descriptive name, such as "Run Flask Server", and click *Apply*.380333Now that we have on run configuration which implements ``flask run`` from within334PyCharm, we can simply copy that configuration and alter the script argument335to run a different cli command, e.g. ``flask shell``.381Now that we have a configuration which runs ``flask run`` from within PyCharm,382we can simply copy that configuration and alter the *Script* argument383to run a different CLI command, e.g. ``flask shell``.
modified:docs/installation.rst+3 added
41 unmodified lines
42 Python's ``json`` module. It is preferred for JSON operations if it is43 installed.44* `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask``45 commands.46* `Watchdog`_ provides a faster, more efficient reloader for the development47 server.4849.. _Blinker: https://pythonhosted.org/blinker/50.. _SimpleJSON: https://simplejson.readthedocs.io/51.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme52.. _watchdog: https://pythonhosted.org/watchdog/5354Virtual environments55--------------------56
125 unmodified lines
modified:flask/cli.py+93 added-76 removed
44 unmodified lines
4546 # Search for the most common names first.47 for attr_name in ('app', 'application'):48 app = getattr(module, attr_name, None)4950 if isinstance(app, Flask):51 return app5253 # Otherwise find the only object that is a Flask instance.
4 unmodified lines
58 if len(matches) == 1:59 return matches[0]60 elif len(matches) > 1:61 raise NoAppException(61 'Auto-detected multiple Flask applications in module "{module}".'62 ' Use "FLASK_APP={module}:name" to specify the correct'63 ' one.'.format(module=module.__name__)62 'Detected multiple Flask applications in module "{module}". Use '63 '"FLASK_APP={module}:name" to specify the correct '64 'one.'.format(module=module.__name__)65 )6667 # Search for app factory functions.68 for attr_name in ('create_app', 'make_app'):69 app_factory = getattr(module, attr_name, None)7071 if inspect.isfunction(app_factory):72 try:72 app = call_factory(app_factory, script_info)73 app = call_factory(script_info, app_factory)7475 if isinstance(app, Flask):76 return app77 except TypeError:78 raise NoAppException(77 'Auto-detected "{function}()" in module "{module}", but '78 'could not call it without specifying arguments.'.format(79 function=attr_name, module=module.__name__79 'Detected factory "{factory}" in module "{module}", but '80 'could not call it without arguments. Use '81 '"FLASK_APP=\'{module}:{factory}(args)\'" to specify '82 'arguments.'.format(83 factory=attr_name, module=module.__name__84 )85 )8687 raise NoAppException(84 'Failed to find application in module "{module}". Are you sure '85 'it contains a Flask application? Maybe you wrapped it in a WSGI '86 'middleware.'.format(module=module.__name__)88 'Failed to find Flask application or factory in module "{module}". '89 'Use "FLASK_APP={module}:name to specify one.'.format(90 module=module.__name__91 )92 )939490def call_factory(app_factory, script_info, arguments=()):95def call_factory(script_info, app_factory, arguments=()):96 """Takes an app factory, a ``script_info` object and optionally a tuple97 of arguments. Checks for the existence of a script_info argument and calls98 the app_factory depending on that and the arguments provided.99 """
6 unmodified lines
106 elif arguments:107 return app_factory(*arguments)108 elif not arguments and len(arg_names) == 1 and arg_defaults is None:109 return app_factory(script_info)110111 return app_factory()112113108def find_app_by_string(string, script_info, module):109 """Checks if the given string is a variable name or a function. If it is110 a function, it checks for specified arguments and whether it takes111 a ``script_info`` argument and calls the function with the appropriate112 arguments."""113 from . import Flask114 function_regex = r'^(?P<name>\w+)(?:\((?P<args>.*)\))?$'115 match = re.match(function_regex, string)116 if match:117 name, args = match.groups()118 try:119 if args is not None:120 args = args.rstrip(' ,')121 if args:122 args = ast.literal_eval(123 "({args}, )".format(args=args))124 else:125 args = ()126 app_factory = getattr(module, name, None)127 app = call_factory(app_factory, script_info, args)128 else:129 attr = getattr(module, name, None)130 if inspect.isfunction(attr):131 app = call_factory(attr, script_info)132 else:133 app = attr114def find_app_by_string(script_info, module, app_name):115 """Checks if the given string is a variable name or a function. If it is a116 function, it checks for specified arguments and whether it takes a117 ``script_info`` argument and calls the function with the appropriate118 arguments.119 """120 from flask import Flask121 match = re.match(r'^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$', app_name)122135 if isinstance(app, Flask):136 return app137 else:138 raise NoAppException('Failed to find application in module '139 '"{name}"'.format(name=module))123 if not match:124 raise NoAppException(125 '"{name}" is not a valid variable name or function '126 'expression.'.format(name=app_name)127 )128129 name, args = match.groups()130131 try:132 attr = getattr(module, name)133 except AttributeError as e:134 raise NoAppException(e.args[0])135136 if inspect.isfunction(attr):137 if args:138 try:139 args = ast.literal_eval('({args},)'.format(args=args))140 except (ValueError, SyntaxError)as e:141 raise NoAppException(142 'Could not parse the arguments in '143 '"{app_name}".'.format(e=e, app_name=app_name)144 )145 else:146 args = ()147148 try:149 app = call_factory(script_info, attr, args)150 except TypeError as e:141 new_error = NoAppException(142 '{e}\nThe app factory "{factory}" in module "{module}" could'143 ' not be called with the specified arguments (and a'144 ' script_info argument automatically added if applicable).'145 ' Did you make sure to use the right number of arguments as'146 ' well as not using keyword arguments or'147 ' non-literals?'.format(e=e, factory=string, module=module))148 reraise(NoAppException, new_error, sys.exc_info()[2])151 raise NoAppException(152 '{e}\nThe factory "{app_name}" in module "{module}" could not '153 'be called with the specified arguments.'.format(154 e=e, app_name=app_name, module=module.__name__155 )156 )157 else:150 raise NoAppException(151 'The provided string "{string}" is not a valid variable name'152 'or function expression.'.format(string=string))158 app = attr159160 if isinstance(app, Flask):161 return app162163 raise NoAppException(164 'A valid Flask application was not obtained from '165 '"{module}:{app_name}".'.format(166 module=module.__name__, app_name=app_name167 )168 )169170171def prepare_import(path):172 """Given a filename this will try to calculate the python path, add it173 to the search path and return the actual module name that is expected.174 """
21 unmodified lines
196 return '.'.join(module_name[::-1])197198199def locate_app(script_info, module_name, app_name, raise_if_not_found=True):184 """Attempts to locate the application."""200 __traceback_hide__ = True201202 try:203 __import__(module_name)
16 unmodified lines
220221 if app_name is None:222 return find_best_app(script_info, module)223 else:209 return find_app_by_string(app_name, script_info, module)224 return find_app_by_string(script_info, module, app_name)225226227def get_version(ctx, param, value):228 if not value or ctx.resilient_parsing:
4 unmodified lines
233 'python_version': sys.version,234 }, color=ctx.color)235 ctx.exit()236222version_option = click.Option(['--version'],223 help='Show the flask version',224 expose_value=False,225 callback=get_version,226 is_flag=True, is_eager=True)237238version_option = click.Option(239 ['--version'],240 help='Show the flask version',241 expose_value=False,242 callback=get_version,243 is_flag=True,244 is_eager=True245)246247248class DispatchingApp(object):249 """Special application that dispatches to a Flask application which250 is imported by name in a background thread. If an error happens251 it is recorded and shown as part of the WSGI handling which in case
79 unmodified lines
331332 app = None333334 if self.create_app is not None:315 app = call_factory(self.create_app, self)335 app = call_factory(self, self.create_app)336 else:337 if self.app_import_path:338 path, name = (self.app_import_path.split(':', 1) + [None])[:2]339 import_name = prepare_import(path)
377 unmodified lines
717 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())718719720cli = FlaskGroup(help="""\701This shell command acts as general utility script for Flask applications.721A general utility script for Flask applications.722703It loads the application configured (through the FLASK_APP environment704variable) and then provides commands either provided by the application or705Flask itself.723Provides commands from Flask, extensions, and the application. Loads the724application defined in the FLASK_APP environment variable, or from a wsgi.py725file. Debug mode can be controlled with the FLASK_DEBUG726environment variable.727707The most useful commands are the "run" and "shell" command.708709Example usage:710728\b712 %(prefix)s%(cmd)s FLASK_APP=hello.py713 %(prefix)s%(cmd)s FLASK_DEBUG=1714 %(prefix)sflask run715""" % {716 'cmd': os.name == 'posix' and 'export' or 'set',717 'prefix': os.name == 'posix' and '$ ' or '',718})729 {prefix}{cmd} FLASK_APP=hello.py730 {prefix}{cmd} FLASK_DEBUG=1731 {prefix}flask run732""".format(733 cmd='export' if os.name == 'posix' else 'set',734 prefix='$ ' if os.name == 'posix' else '> '735))736737738def main(as_module=False):739 args = sys.argv[1:]
20 unmodified lines
modified:tests/test_apps/cliapp/factory.py+4 added
11 unmodified lines
121314def create_app3(foo, script_info):15 return Flask('_'.join(['app3', foo, script_info.data['test']]))161718def no_app():19 pass
modified:tests/test_cli.py+6 added-2 removed
198 unmodified lines
199 # trailing comma space200 ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),201 # takes script_info202 ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),203 # strip whitespace204 ('cliapp.factory', ' create_app () ', 'app'),205))206def test_locate_app(test_apps, iname, aname, result):207 info = ScriptInfo()208 info.data['test'] = 'spam'
5 unmodified lines
214 ('cliapp/app', None),215 ('cliapp.app', 'notanapp'),216 # not enough arguments217 ('cliapp.factory', 'create_app2("foo")'),218 # invalid identifier219 ('cliapp.factory', 'create_app('),220 # no app returned221 ('cliapp.factory', 'no_app'),222 # nested import error223 ('cliapp.importerrorapp', None),224 # not a Python file225 ('cliapp.message.txt', None),220 # space before arg list221 ('cliapp.factory', 'create_app ()'),226))227def test_locate_app_raises(test_apps, iname, aname):228 info = ScriptInfo()229
248 unmodified lines