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
0:01
let's review this idea of factoring our view methods
0:04
into separate files with Flask Blueprints.
0:07
So there's two parts here
0:09
first we work on the file that contains the view methods
0:12
that we're breaking a little bit of our web app out into.
0:16
So here's let look at views/packages.py
0:19
okay we're going to import flask, but instead of saying
0:21
flask.app we say flask.blueprint
0:24
give it a friendly name
0:25
we give it an import name and a template folder.
0:28
That creates a blueprint and just like before
0:30
we say blueprint.route and from there on
0:33
it's pretty much exactly the same
0:34
just use the word blueprint instead of app.
0:37
But don't forget, we also have to now go back and register
0:39
these after the blueprints have been created.
0:41
So in our main start-up code
0:43
in our example, which is app.py
0:45
we're going to import that module
0:49
that contains the extra functions.
0:51
I'm going to create the app just as normal
0:52
and then we're going to register the blueprint
0:54
so app.register_blueprints and give it the blueprint
0:57
from that other module.
1:00
We can do this with as many pieces of we want to
1:02
break it up into and then we just say app.run.
1:05
I really love this pattern.
1:07
It drives me crazy when applications are crammed
1:10
all into one file.
1:11
This helps you organize your codes
1:13
you can quickly find the view methods
1:14
the templates
1:15
all the stuff that is related to one part of your website
1:18
so I highly encourage you to use this.