### my_project/__init__.py
import os
from flask import Flask
def create_app(test_config=None):
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:
app.config.from_pyfile('config.py', silent=True) # load the instance config, if it exists, when not testing
else:
app.config.from_mapping(test_config) # load the test config if passed in
try: # ensure the instance folder exists
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
from . import db
db.init_app(app)
return app
### flaskr/db.py
import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close(
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f: # opens a file relative to the flaskr package
db.executescript(f.read().decode('utf8'))
@click.command('init-db') # defines a command line command
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
def init_app(app):
app.teardown_appcontext(close_db) # call when cleaning up after returning the response.
app.cli.add_command(init_db_command) # adds a new command
g
a special object which is unique for each request.
store data accessed by multiple functions during the request.
connection is reused instead of creating a new connection.
current_app
a special object which is the Flask application handling the request
Blueprint
Blueprint = organize a group of related views and other code.