flask
1. Application Factory
configuration, registration, and setups
return the application
### 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 appinstance_relative_config=True = config files @ instance/
instance_path needs to be created manually
2. DB
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.
Last updated
Was this helpful?