Create and configure an instance of the Flask application.
(test_config=None)
| 4 | |
| 5 | |
| 6 | def create_app(test_config=None): |
| 7 | """Create and configure an instance of the Flask application.""" |
| 8 | app = Flask(__name__, instance_relative_config=True) |
| 9 | app.config.from_mapping( |
| 10 | # a default secret that should be overridden by instance config |
| 11 | SECRET_KEY="dev", |
| 12 | # store the database in the instance folder |
| 13 | DATABASE=os.path.join(app.instance_path, "flaskr.sqlite"), |
| 14 | ) |
| 15 | |
| 16 | if test_config is None: |
| 17 | # load the instance config, if it exists, when not testing |
| 18 | app.config.from_pyfile("config.py", silent=True) |
| 19 | else: |
| 20 | # load the test config if passed in |
| 21 | app.config.update(test_config) |
| 22 | |
| 23 | # ensure the instance folder exists |
| 24 | os.makedirs(app.instance_path, exist_ok=True) |
| 25 | |
| 26 | @app.route("/hello") |
| 27 | def hello(): |
| 28 | return "Hello, World!" |
| 29 | |
| 30 | # register the database commands |
| 31 | from . import db |
| 32 | |
| 33 | db.init_app(app) |
| 34 | |
| 35 | # apply the blueprints to the app |
| 36 | from . import auth |
| 37 | from . import blog |
| 38 | |
| 39 | app.register_blueprint(auth.bp) |
| 40 | app.register_blueprint(blog.bp) |
| 41 | |
| 42 | # make url_for('index') == url_for('blog.index') |
| 43 | # in another app, you might define a separate main index here with |
| 44 | # app.route, while giving the blog blueprint a url_prefix, but for |
| 45 | # the tutorial the blog will be the main index |
| 46 | app.add_url_rule("/", endpoint="index") |
| 47 | |
| 48 | return app |