Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Routing and URLs
Lecture: Concept: Refactoring view methods with Flask blueprints
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Before we get to the rest of our routing let's review this idea of factoring our view methods into separate files with Flask Blueprints.
0:08
So there's two parts here first we work on the file that contains the view methods that we're breaking a little bit of our web app out into.
0:17
So here's let look at views/packages.py okay we're going to import flask, but instead of saying flask.app we say flask.blueprint
0:25
give it a friendly name we give it an import name and a template folder. That creates a blueprint and just like before
0:31
we say blueprint.route and from there on it's pretty much exactly the same just use the word blueprint instead of app.
0:38
But don't forget, we also have to now go back and register these after the blueprints have been created. So in our main start-up code
0:44
in our example, which is app.py we're going to import that module that contains the extra functions. I'm going to create the app just as normal
0:53
and then we're going to register the blueprint so app.register_blueprints and give it the blueprint from that other module.
1:01
We can do this with as many pieces of we want to break it up into and then we just say app.run. I really love this pattern.
1:08
It drives me crazy when applications are crammed all into one file. This helps you organize your codes you can quickly find the view methods
1:15
the templates all the stuff that is related to one part of your website so I highly encourage you to use this.