Setting up a Flask Blueprint

I recently worked on a Python project that uses the Flask Framework which is excellent. I had the need to set up an Admin Back-end. This was going to be a very simple site so I decided to keep it in the main project and just put the Admin module in its own directory. I needed Flask to handle the routing for this and the simple answer was the use of the Blueprint feature. Blueprint is an object that allows a set of operations that can be registered on an application. The Blueprint helps modularize your application.

This is a simple example of a login page for the Admin site. I used a templates directory for my html files and a content directory for my static content like scripts, css and images.

Admin Site

Inside the admin _init_.py file I setup my Blueprint and routes for this module. Since Flask was already being used in the project I passed in the app that was initialized in the project _init_.py file.

For the static content, the static_url_path and the static_folder need to be defined in the Blueprint as shown above. In order to access this content in your template you will need to use the url_for function. This example retrieves the css file which is located inside of a css directory under the content folder. You can easily do the same thing for an image or JavaScript file that you need to retrieve.

I also had to specify the location of the templates folder to get the routing to work properly. With the templates directory specified you simply need to use @blueprint instead of @app. Obviously you substitute blueprint with whatever you named your Blueprint object. With the blueprint specified as the route handler, the templates folder you specified will be used.

It’s that easy to start setting up modules in your project using Flask.

Here’s a screencast I created to help setup an initial Blueprint: