Application Setup

    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 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.

    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 flaskrdirectory should be treated as a package.

    flaskr/init.py

    1. import os
    2.  
    3. from flask import Flask
    4.  
    5.  
    6. def create_app(test_config=None):
    7. # create and configure the app
    8. app = Flask(__name__, instance_relative_config=True)
    9. app.config.from_mapping(
    10. SECRET_KEY='dev',
    11. DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    12. )
    13.  
    14. if test_config is None:
    15. # load the instance config, if it exists, when not testing
    16. else:
    17. # load the test config if passed in
    18. app.config.from_mapping(test_config)
    19.  
    20. # ensure the instance folder exists
    21. try:
    22. os.makedirs(app.instance_path)
    23. except OSError:
    24. pass
    25.  
    26. # a simple page that says hello
    27. @app.route('/hello')
    28. def hello():
    29. return 'Hello, World!'
    30.  
    31. 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 the instance.

      • instance_relative_config=True tells the app thatconfiguration files are relative to theinstance folder. The instance folderis located outside the flaskr package and can hold localdata that shouldn’t be committed to version control, such asconfiguration secrets and the database file.

    • 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 under, 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 the config.pyfile in the instance folder if it exists. For example, whendeploying, this can be used to set a real SECRET_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.
    • 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.

    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:

    For Windows cmd, use set instead of export:

    1. > set FLASK_APP=flaskr
    2. > set FLASK_ENV=development
    3. > flask run

    For Windows PowerShell, use $env: instead of export:

    You’ll see output similar to this:

    1. * Serving Flask app "flaskr"
    2. * Environment: development
    3. * Debug mode: on
    4. * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    5. * Restarting with stat
    6. * Debugger is active!

    Continue to Define and Access the Database.