import os
from flask import Flask
defcreate_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 isNone:# 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 existstry:
os.makedirs(app.instance_path)except OSError:pass# a simple page that says hello
@app.route('/hello')defhello():return'Hello, World!'from.import db
db.init_app(app)from.import auth
app.register_blueprint(auth.bp)from.import blog
app.register_blueprint(blog.bp)
app.add_url_rule('/', endpoint='index')return app
import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
definit_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)definit_db():
db = get_db()with current_app.open_resource('schema.sql')as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
@with_appcontext
definit_db_command():"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')defget_db():if'db'notin g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
defclose_db(e=None):
db = g.pop('db',None)if db isnotNone:
db