Doing it all as an app
While blueprints are good for organising the code things will start to get messy as the app grows. We can use python modules to create a more organised structure.
Directoryflaskapp/
Directorystatic/
- style.css
Directorytemplates/
- index.html
- base.html
__init__.py
- blog.py
- db.py
Creating the app
Create a new folder called flaskapp
and add a __init__.py
file to it. This file will be the entry point for the app.
-
The
create_app
function creates a new Flask appThis function is automatically called by Flask when the app is run. It accepts an optional
test_config
parameter which can be used to pass in configuration values. -
Config is set
The app is configured with a
SECRET_KEY
and aDATABASE
path. TheSECRET_KEY
is used by Flask and extensions to keep data safe. TheDATABASE
is the path where the SQLite database file will be stored. -
A method to load external configuration
The
config.py
file in the instance folder can be used to set configuration values. This is useful for setting values that should not be in version control. -
The
instance
folder is createdThe
instance
folder is created if it does not exist. This folder is used to store files that should not be in version control.with contextlib.suppress(OSError):
is used to suppress the error if the folder already exists. This is similar to atry
andexcept
block. -
A ping route is added
A simple route is added to check if the app is running. When the
/ping
route is accessed, the app will returnpong!
.
Running the app
To run our app we can run:
Adding the blog blueprint
Create a new file called blog.py
and add the following code to it.
This blueprint will be used to handle all the blog related routes.
Registering the blueprint
Update the __init__.py
file to register the blueprint.
Setting up the database
Following from how we set up the blog blueprint, we can create a new file called db.py
and add the following code to it.
-
The
Base
class is created as a base for the databases -
The
db
object is createdThe
db
object is created using theSQLAlchemy
class. Themodel_class
parameter is set to theBase
class to use it as the base for all models. -
The
Post
model is createdThe
Post
model is created with anid
,title
, andcontent
column. Theid
column is the primary key. Thetitle
andcontent
columns are set to be not nullable. -
The
init_app
function is createdThe
init_app
function is created to initialise the database. Thedb
object is initialised with the app. The database is created with thecreate_all
method.
In the __init__.py
file, import the db
module and call the init_app
function.
With the database set up, we can now add a route to add a post to the database.