Packaging Your Flask Application
A while ago, I was working on a hobby project for my Badminton Club, The Smashing Fellows. The club meets twice a week, Tuesday and Friday. On Tuesday, we play using a system called the “Hussel” system which just means that the players are semi-randomly shuffled to create doubles matches amongst each other. The randomization allows for people to get to know each other while keeping also keeping things a bit competitive in terms of playing level. An archaic application written in Microsoft Access being used for this at the club started unravelling at the seams a few months ago. I volunteered to make a new application. The club didn’t want the application to be able to run on Windows. I went down the Windows application development rabbit hole and ended deciding to not have anything to do with that. Since, I was already familiar with the use of Python, I ended up deciding to create a web application using Flask. The unique nature of this request didn’t allow for deployment online with user information. Therefore, I ended up packaging the application into a wheel for easier deployment to run as a web server on the local machine. Usually, flask applications don’t need to be packaged. They can be deployed as is. So, for people who might be in a similar situation, I am documenting the steps that I followed. I won’t go into the details of how to create a package your python code or how to create a flask application. There are several tutorials for that. Here is how you combine.
Step 1: Add your static files into the package
Add the static files that you plan to use into your package via the pyproject.toml
file. This is usually done via the following lines:
[tool.setuptools.package-data]
"templates" = ["*.j2"]
"static" = ["*.css", "*.js"]
Here, I show an example which uses Jinja2 templates and some CSS and javascript files. This allows for the files you need for your application to run be accessible within the package and also adds it into wheel.
Step 2: Reference your files in the code
Usually flask searches for the static
and templates
folder in the root directory from where you run the app
. But since we have now moved this into the package directory, we would need to let flask where to find this. For this, we can provide the location of these folder when instantiating the Flask
class with the arguments static_folder
and templates_folder
as shown below:
from flask import Flask
from importlib.resources import path
app = Flask("<app_name>",
static_folder=path("<package_name>", "static"),
template_folder=path("<package_name>", "templates"))
Make sure to use the importlib
package to locate where your package is installed. This allows for the path to be dynamically updated based on where the user installs your package. Now when you run your flask application you should be able to see the static files you need. In case you are interested in seeing the full code base, you can find it here.