Organize Flask Code Professionally

Gerry Sabar
6 min readJul 18, 2019

--

The common tutorial for running Flask microframework is as follow:

1. create directory & virtual environment then run the virtual environment
2. installing flask over pip (as well as other libraries)
3. export FLASK_APP parameter i.e. “export FLASK_APP=app.py”
4. Put all your code in one file for example app.py
5. execute flask run command in terminal

Although for any newcomer seem convenient but in professional working condition we tend to do the adjustment to make the code cleaner & neat since we’re dealing with many other issues as well such as Docker, deployment, etc. Therefore in this article we’ll try to restructure a work from this article for study case:

https://medium.com/@gerrysabar/basic-crud-with-flask-1-0-2-swagger-sqlalchemy-d26ae303e99d

First of all, to help you in case in the middle of learning this article you’ve got ambiguity or confusion, our final structure will be like this for reference:

As for me I named my project as blueprint (you can rename it with something else). venv directory is created when you create your own flask local environment. You also can ignore migrations directory since it’s generated when you create migration from flask.

Using requirements.txt to install library

Any beginner friendly tutorial will let’s you to install any flask library using pip command. If you’re working alone it won’t be a problem but there’s a big chance you’ll work with more than one programmer and your code is hosted in repository such as Github or Gitlab. Installing each library whenever you pull the code isn’t a good idea even it’s getting worse if your app is getting bigger and has to install more than 10 libraries for example. Therefore one good practice is using requirements.txt file. Let’s create a file named requirements.txt in project root directory and add code as follow:

Libraries we added above are all libraries we have implemented from this article but at previous article we just simply used pip command. Now we can install all those libraries above inside your active virtual environment with this command (make sure you activate your local python environment first):

$ pip install -r requirements.txt

The good thing is you just need to add/remove libraries as well as change the version from requirements.txt then execute the command again if you need to modify libraries on your project. This is much convenient compared with installing pip individually. That’s why requirements.txt is becoming the common practice in real app development. We also crreate a file named config.py in root directory so later at migration section you’ll use it

Implementing shell executable file in Flask

In Linux / Mac environment we can create .sh file to execute certain command which is equivalent to .bat file in Windows environment. It’s not convenient to run multiple export command and execute flask run command to run our flask microframework. However, the good thing is we can put them all in .sh file so when only need to execute one command instead of execute multiple commands to run our flask microframework. To do this, let’s create a file named “activate.sh” in root project directory:

Now you just need to type:

$ . activate.sh

or

$ source activate.sh

to run your flask application instead of using export (or set in windows) command. Furthermore you can add comment inside .sh file as well as adding more commands inside the file then need to execute by one command in terminal which is much convenient when you’re working with many other programmers to help them set up their own local environment before working.

Next, let’s add an empty file inside our root project directory & whenever create any new directory named __init__.py and also please create this file inside any new directory you created. Why? According to python documentation:

“The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.”

A simple example for this case is let’s say you’ve got another folder named “api” and inside api you’ve got module Log and you need to import this module to api.py, then inside folder name you need to add __init__.py file as well as a file that is contained module Log otherwise you can’t load module Log to api.py. Let’s implement to our project now by copying code from api.py to __init__.py and remove api.py then modify the code at line 1 & 2 our activate.sh become line 1 & 2 at code below:

The benefit from doing this is you don’t need to restart your app in terminal whenever you modify the code unlike previous code from this article.

Application Factories Approach

This part may tricky & confusing for any newcomer. I’ll try learn by doing approach and you can conclude by yourself. However, this article will be a good reference if you want to understand the concept first. Let’s create a file named app_factory.py in root project directory:

Next, let’s create a directory named app in our root directory and as mentioned before, don’t forget to add __init__.py as well with code:

Let’s implement web module first. Create a directory named web inside app directory & add __init__.py with code:

next inside web directory let’s add views.py:

Last for web module we need a template to render login.html. Let’s add a directory named templates in root project directory and add a file login.html

Sweet, we just added a simple login html page to be accessed at localhost:5000.

Adding API With Swagger

It’s common a web page provides REST API and flask provides cool features to support it. Let’s added it in our project as well. Create a directory named api inside app directory then create __init__.py for our api part

Then we add views.py inside api directory

Cool! now if you execute activate.sh we and access localhost:5000 we can see a page as follow

And you can access swagger documentation page at localhost:5000/api/docs

Adding Model And Migration To Flask

Great! We have structured flask app professionally. One last thing, how do we handle migration and model? Let’s develop one single-file for model named models.py inside app directory. Later you can develop your own way to structure it when it’s getting bigger since you already understand the project structure

since in config.py we create a connection to mysql with database named blueprint, don’t forget to create a database named blueprint with proper user & password connection. Now how to run the migration? It’s pretty easy, you just need go to the terminal and execute this command for linux environment (after activate your app local environment):

$ export FLASK_APP=app_factory.py

$ flask db init

$ flask db migrate

$ flask db upgrade

You can create another shell file just like activate.sh if you like to do so for migration as well. If you check our mysql you can see there is a table named log. Before we proceed to implement it in our API please add about one or two records first to log table. Then in app/api/views.py let’s modify a bit at line 3 and method get at class LogList to fetch all records from log. Previously I have added two records at log table and when we try swagger we can see the result like this

Congrats! We just develop a skeleton for professional flask app. Please keep in mind that this is not the perfect approach but the idea is how to organize your flask app be able to be maintained easily. As time goes by, technology always improve so do with programming technique but we have the main idea on how to separate each file/module to be maintainable. If you want to have more detail on how to deal with basic CRUD on swagger with SQLAlchemy you can go to my article here. You also can see the fully working code in this github.

--

--

No responses yet