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

http://flask.pocoo.org/docs/1.0/patterns/appfactories/

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

https://github.com/pythexcel/tutorial/commit/72ab4a2bc048fa51403fae81603d18e9bd322946

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

https://github.com/pythexcel/tutorial/commit/3cdcb1e4233bc7702dbdd533c13a0f988fa1f60d

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

https://github.com/pythexcel/tutorial/commit/c642bd02e7ed4c0a1fc1e837bb1f597eb4686f8c

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

https://github.com/pythexcel/tutorial/commit/e4161e1040c6a4eca0b4b9d0d3f04344083d1481

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

https://github.com/pythexcel/tutorial/commit/35644d5f03366f836b64e427f2747d94b6f47430

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype