Flask – Application Factory

Application factory is a pattern in flask and used most of the times when we split our code based into difference files.

In the previous blog post we slow how to simply split our code, in this post we will take it further and see what is best recommended way of doing it and why.

What is an App Factory

Instead of creating a <em>Flask</em> instance globally, you will create it inside a function. This function is known as the application factory. Any configuration, registration, and other setup the application needs will happen inside the function, then the application will be returned.

Flask will automatically detect the factory functions (<em>create_app</em> or <em>make_app</em>) If you make a factory with other function name like create_app_testing etc it will not be detected automatically


If we want to change our existing source code to app factory pattern we need to make this change


This is a very simple change, what we done is made a create_app function returned our app object.

This is what an app factory, but in our case this will not work yet as we need mongo, jwt objects to be global.

Initialize Services with App Factory

When using app factory, we have to follow a particular pattern to initialize our services, be it mongo, sql, redis etc all these libraries have a standard init_app function. Let’s see how it looks in our case


So, now we are following the init_app pattern, and this common across most flask services .

In the current case a seperate db.py file looks like an overkill, then is mostly required when we have migrations etc in the current case let’s just remove the separate file


Next, lets follow the same pattern for jwt token as well


Project Directory Structure

Mostly project structure looks like

- flaskr/
- __init__.py
- db.py
- helper.py
- api/
- __init__.py
- todo.py
- auth.py
- models/
- tests/
- var/instance/
- config.py
- run.py
- setup.py
- requirements.txt

the flaskr/ folder can be renamed to app/ as well

Let’s structure our project accordingly.

There also a concept of instance folder that you should be aware of at this stage http://flask.pocoo.org/docs/1.0/config/#instance-folders