Application Setup
A Flask application is an instance of the Flask
class.Everything about the application, such as configuration and URLs, willbe registered with this class.
The most straightforward way to create a Flask application is to createa global Flask
instance directly at the top of your code, likehow the “Hello, World!” example did on the previous page. While this issimple and useful in some cases, it can cause some tricky issues as theproject grows.
Instead of creating a Flask
instance globally, you will createit inside a function. This function is known as the applicationfactory. Any configuration, registration, and other setup theapplication needs will happen inside the function, then the applicationwill be returned.
The Application Factory
It’s time to start coding! Create the flaskr
directory and add theinit.py
file. The init.py
serves double duty: it willcontain the application factory, and it tells Python that the flaskr
directory should be treated as a package.
- $ mkdir flaskr
- import os
- from flask import Flask
- def create_app(test_config=None):
- # create and configure the app
- app = Flask(__name__, instance_relative_config=True)
- app.config.from_mapping(
- SECRET_KEY='dev',
- DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
- )
- if test_config is None:
- # load the instance config, if it exists, when not testing
- app.config.from_pyfile('config.py', silent=True)
- else:
- # load the test config if passed in
- app.config.from_mapping(test_config)
- # ensure the instance folder exists
- try:
- os.makedirs(app.instance_path)
- except OSError:
- pass
- # a simple page that says hello
- @app.route('/hello')
- def hello():
- return 'Hello, World!'
- return app
create_app
is the application factory function. You’ll add to itlater in the tutorial, but it already does a lot.
app = Flask(name, instance_relative_config=True)
creates theFlask
instance.name
is the name of the current Python module. The appneeds to know where it’s located to set up some paths, andname
is a convenient way to tell it that.instance_relative_config=True
tells the app thatconfiguration files are relative to theinstance folder. The instance folderis located outside theflaskr
package and can hold localdata that shouldn’t be committed to version control, such asconfiguration secrets and the database file.
app.config.from_mapping()
setssome default configuration that the app will use:SECRET_KEY
is used by Flask and extensions to keep datasafe. It’s set to'dev'
to provide a convenient valueduring development, but it should be overridden with a randomvalue when deploying.DATABASE
is the path where the SQLite database file will besaved. It’s underapp.instance_path
, which is thepath that Flask has chosen for the instance folder. You’ll learnmore about the database in the next section.
app.config.from_pyfile()
overridesthe default configuration with values taken from theconfig.py
file in the instance folder if it exists. For example, whendeploying, this can be used to set a realSECRET_KEY
.test_config
can also be passed to the factory, and will beused instead of the instance configuration. This is so the testsyou’ll write later in the tutorial can be configuredindependently of any development values you have configured.
os.makedirs()
ensures thatapp.instance_path
exists. Flaskdoesn’t create the instance folder automatically, but it needs to becreated because your project will create the SQLite database filethere.@app.route()
creates a simple route so you cansee the application working before getting into the rest of thetutorial. It creates a connection between the URL/hello
and afunction that returns a response, the string'Hello, World!'
inthis case.
Run The Application
Now you can run your application using the flask
command. From theterminal, tell Flask where to find your application, then run it indevelopment mode. Remember, you should still be in the top-levelflask-tutorial
directory, not the flaskr
package.
Development mode shows an interactive debugger whenever a page raises anexception, and restarts the server whenever you make changes to thecode. You can leave it running and just reload the browser page as youfollow the tutorial.
For Linux and Mac:
- $ export FLASK_APP=flaskr
- $ export FLASK_ENV=development
- $ flask run
For Windows cmd, use set
instead of export
:
- > set FLASK_APP=flaskr
- > set FLASK_ENV=development
- > flask run
For Windows PowerShell, use $env:
instead of export
:
- > $env:FLASK_APP = "flaskr"
- > $env:FLASK_ENV = "development"
- > flask run
You’ll see output similar to this:
- * Serving Flask app "flaskr"
- * Environment: development
- * Debug mode: on
- * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
- * Restarting with stat
- * Debugger is active!
- * Debugger PIN: 855-212-761
Visit http://127.0.0.1:5000/hello in a browser and you should see the“Hello, World!” message. Congratulations, you’re now running your Flaskweb application!
Continue to Define and Access the Database.