flask is a compact python web framework that combines simplicity and speed of
development with a design that can scale when complexity grows.
flask documentation, however, is a little too eager to show off this
simplicity, and all the basic examples introduce practices that won't work when
your application grows from tiny to small.
In its most basic form, a
flask application lives inside a single file, a file
that looks like this:
app = Flask(__name__) db = SQLAlchemy(app) class Thing(db.Model): id = db.Column(db.Integer, primary_key = True) @app.route('/') def index(): return 'Hello World!'
Note that both views and models (via
route()) depend on the
When you attempt to move them into their own, separate files, you'll discover
that there's a circular dependency in both cases:
views will need to import
app to use
app will want to import
views to set up those
routes. The same will happen with
db objects needing each
Breaking the cycle
db mutual dependency is easily solved by postponing the initialization
# models.py db = SQLAlchemy() # no `app` paramater # app.py from models import db db.init_app(app) # delayed initialization
Easy enough, no hacks involved. Same goes for the
# views.py blueprint = Blueprint('views', __name__) @blueprint.route('/') def index(): return 'Hello World!' # app.py from views import blueprint app.register_blueprint(blueprint)
flask documentation should be very clear about the right design pattern
for these cases. It's not. The amount of work required to do it right is so
minimal that I don't really see why this is not mentioned early on.
As I said above, I think
flask is too proud of its simplicity. Too proud to
show you even the slightest level of complexity as you learn the framework.