Let’s build a command-line utility for quickly generating a Flask boilerplate structure.
This is a collaboration piece between Depado and the folks at Real Python.
Modeled after the Flask-Skeleton project, this tool will automate a number of repetitive tasks so that you can quickly get a Flask project up and running with the structure, extensions, and configurations that you prefer, step by step:
- Set up the basic structure
- Add a custom config file
- Utilize Bower to manage front-end dependencies
- Create a virtualenv
- Initialize Git
Once done, you’ll have a powerful scaffolding script that you can (and should) customize to meet your own development needs.
Quickstart
To start, we need a basic Flask application. For simplicity, we’ll use the Real Python boilerplate Flask structure, so just clone it down to set the base structure:
1 2 3 4 5 6 7 8 |
|
Yes, this article utilizes Python 3.4; however, the final script is compatible with both Python 2 and 3.
1st Task – The Structure
Save a new Python file as flask_skeleton.py in the root directory. This file will be used to power the entire scaffolding utility. Open it up in you favorite text editor and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
Here, we’re using argparse to obtain an appname
for the new project and then copying the skeleton directory (via shutil), which contains the project boilerplate, to quickly recreate the project structure.
The shutil.copytree()
method (source) is used to recursively copy a source directory to a destination directory (as long as the destination directory does not already exist).
Test it out:
1
|
|
This should make a copy of the Real Python boilerplate Flask structure (source) to a new directory called “new_project” (destination). Did it work? If so, remove the new project since there’s still much work to be done:
1
|
|
Handling Multiple Skeletons
What if you need an app with a MongoDB database or a payments blueprint? All apps have specific needs and you obviously can’t create a skeleton for them all, but perhaps you need a NoSQL database about fifty percent of the time. You can add a new skeleton to the root to accomplish this. Then when you run the scaffold command, simply specify the name of the directory containing the skeleton app you wish to make a copy of.
2nd Task – Configuration
Need the script up to this point? Grab it from the first tag. Or if you cloned the repo, you can grab the tag like so –
git checkout tags/first_tag
.
We now need to generate a custom config.py file for each skeleton. This script is going to do just that for us; let the code do the repetitive work! First, add a file called config.jinja2 in the templates folder:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
At the start of the scaffold script, flask_skeleton.py
, just before the main()
function, we need to initialize Jinja2
in order to render the config correctly.
1 2 3 |
|
Make sure to add the import as well:
1
|
|
Install:
1 2 |
|
Looking back at the template, config.jinja2, we have one variable that needs to be defined – {{ secret_key }}
.To do this, we can use the codecs module.
To the imports of flask_skeleton.py
add:
1
|
|
Add the following code to the bottom of the main()
function:
1 2 3 4 5 6 7 8 |
|
What if you manage several skeletons and need several configuration templates? Simple: You just have to check which skeleton is passed as an argument and use the appropriate config template. Keep in mind that
os.path.join(fullpath, 'project', 'config.py')
must represent the path where your configuration should be stored in your skeleton. If this is different for each skeleton, then you should specify the folder in which the config file is stored in as an additional argparse argument.
Ready to test?
1
|
|
Make sure the config.py file is present in the “new_project/project” folder and then remove the new project: rm -rf new_project
3rd Task – Bower
Need the updated script? Grab it here.
That’s right: We’ll be using bower to download and manage static libraries. To add bower support to the scaffold script, start with adding another argument:
1
|
|
And to handle the running of bower, add the following code right below the config section of the scaffold script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Don’t forget to add the subprocess module to the import section of flask_skeleton.py – import subprocess
.
Did you notice the which()
method (source)? This essentially uses the unix/linux which tool in order to indicate where an executable is installed in the filesystem. So, in the above code, we’re checking to see if bower
is installed. If you’re curious to know how this works, test it out in the Python 3 interpreter:
1 2 3 |
|
Unfortunately, this method, which()
, is new to Python 3.3, so, if you’re using Python 2, then you need to install a separate package – shutilwhich:
1 2 |
|
Update the imports:
1 2 3 4 |
|
Finally, turn you attention to the following lines of code:
1 2 3 4 5 6 7 8 9 |
|
Start by looking at the official subprocess documentation. Put simply, it’s used for invoking external shell commands. In the above code we are simply capturing the output from stdout and stderr.
If you’re curious to see what the output is, uncomment the print statement, # print(output)
, and then run your code…
Before testing, this code assumes that in your skeleton folder(s), you have a “project” folder that contains a “static” folder. Classical Flask application. On the command line, you can now install multiple dependencies like so:
1
|
|
4th Task – virtualenv
Again, grab the updated script, if necessary.
Since the virtual environment is one of the most important parts of any Flask (err, Python) application, creating the virtualenv using the scaffold script will be really useful. As usual, start by adding the argument:
1
|
|
And then add the following code below the bower section:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
This snippet assumes that there is a requirements.txt file in your “skeleton” folder in the root directory. If so, it will create a virtualenv and then install the dependencies.
5th task – Git Init
Updated script.
Notice a pattern yet? Add the argument:
1
|
|
Then add the code under the task for the virtualenv:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Now within the templates folder add a .gitignore file, and then add the files and folders that you’d like to ignore. Grab the example from Github, if needed. Test again.
Sum and confirm
Updated script.
Finally, let’s add a nice summary before the application is created and then ask for user confirmation before executing the script.
Summary
Add a file called brief.jinja2 to the “templates” folder:
1 2 3 4 5 6 7 8 9 10 |
|
Now we just need to catch every user-supplied argument and then render the template. First, add the import – import platform
– to the import section and then the following code just below the “variables” section in the flask_skeleton.py script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Test this out:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Nice!
Refactor
Now we need to refactor the script a bit to check for errors first. I suggest grabbing the code from the refactor tag and then comparing the diff between that script and the previous tag’s script since there are a number of small updates.
Make sure you use the updated script from the refactor tag before moving on.
Confirm
Now let’s add the user confirmation functionality by updating if __name__ == '__main__':
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
This should be fairly straightforward.
Run!
If you use Linux or Mac you can make this script easier to run. Simply add the following alias to either .bashrc or .zshrc, customizing it to match your directory structure:
1
|
|
NOTE: If you have both Python 2.7 and Python 3.4 installed you will have to specify the version you want to use – either
python
orpython3
.
Remove the new project (if necessary) – rm -rf new_project
– and then test out the script one last time to confirm:
1
|
|
Conclusion
What do you think? Did we miss anything? What other arguments would you add to argparse
in order to customize your scaffold script even further? Comment below!
Grab the final code from the repo.
Author’s Note
I (Depado) would like to thank Antonin Lenfant for his support toward the project and for the changes made to the article. He is a former coworker and a Python enthusiast. I’d also like to thank Michael Herman, from Real Python, who spotted my project on Github and asked me to write this article.
Creating this tool has been an interesting challenge. I discovered how pleasant it was to work with a template system for an application that is not a web application.
Edits made by Derrick Kearney. Thanks again, Derrick!