In order to make the next chapters easier for the reader, we will look at how to use the Flask CLI (using version 0.11 onward). The CLI allows programmers to create commands that act within the application context of Flask—that is, the state in Flask that allows the modification of the Flask object. The Flask CLI comes with some default commands to run the server and a Python shell in the application context.
Let's take a look at the Flask CLI and how to initialize it. First, we must tell it how to discover our application using the following code:
$ export FLASK_APP=main.py
Then, we will use the Flask CLI to run our application using the following code:
$ flask run
Now, let's enter the shell on the application context and see how to get all the defined URL routes, using the following code:
$ flask shell
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
App: main [debug]
Instance: /chapter_1/instance
>>> app.url_map
Map([<Rule '/' (OPTIONS, GET, HEAD) -> home>,
<Rule '/static/<filename>' (OPTIONS, GET, HEAD) -> static>])
As you can see, we already have two routes defined: the / where we display the "Hello World" sentence and the static default route created by Flask. Some other useful information shows where Flask thinks our templates and static folders are, as shown in the following code:
>>> app.static_folder
/chapter_1/static'
>>> app.template_folder
'templates'
Flask CLI, uses the click library from the creator of Flask itself. It was designed to be easily extensible so that the Flask extensions can extend it and implement new commands that are available when you use them. We should indeed extend it—it makes it more useful to extend it ourselves. This is the right way to create management commands for our applications. Think about commands that you can use to migrate database schemas, create users, prune data, and so on.