Skip to main content

Building Modular Web Apps with Blueprints

I was recently hacking about with the express framework in node.js. One thing I really like about it is that the request and response objects are passed into the callback of the route functions. Another thing which I thought was really awesome was the Router object. Specifically it allows you to isolate parts of your application which I like because it makes maintaining the application much easier. This got me thinking "I wonder if a similar concept exists within the Flask framework in Python?". 

Enter Flask Blueprints. Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. I thought as a exploratory exercise I would put together a simple application using blueprints within flask. So let's build a web application which lets you post comments and displays those comments on a web page. Okay okay, this is perfectly stupid but our purpose is to learn a little about blueprints.

A Simple Application

For this application we will have a single html page which let's a user add a comment and displays the last 10 comments posted. We will use blueprints to split out the code for the API and the page routes. Below is a screenshot of how the application is structured.


 
Application Folder Structure


Let's spend some time going through each of the files and understanding what each one is doing.

Database Helper Functions

We will be persisting the comments posted from the main page in a sqlite database named data.db. The database consists of a single table named comments which contains a description and a time stamp. The tables.sql file contains the create statement while sql_run.py removes the database and then recreates it and the table. The latter two files are just there for convenience since I won't be using an ORM for this application.

Templates and Static

The main page of the application is called index.html which inherits from base.html. 


base.html


index.html
The application will user bootstrap and JQuery for the client side presentation and DOM manipulation. The Javascript functions used in the application can be found inside the index.js file. The latter consists of a few functions which perform the following tasks:


  1. POST a comment to the application API. This function is bound to the click event of the button input.
  2. GET the last ten comments from the application API. This function is invoked on page load and on the successful posting of a comment to the application API.
  3. Display the results of the GET request above in a unrdered list.  

The Server Code

I split the application into a few files. I decided to include the functions and classes needed by the application in the utils.py file. Given this we can just import what we need in each of the other modules within the application.


utils.py

The flask application object is created within the server.py file. This split may seem unnecessary but I could see value in this approach if the application was to grow larger and the flask application required more configuration. 
 
server.py


Next up let's look at the application API and page blueprints. I have included the code for the two blueprints in mod_pages.py and mode_api.py. The mod_pages module handles requests to the root node and renders the index.html template.


mod_pages.py
Here we import the Blueprint class and render template function from the utils module. Similarly to how the flask instance is instantiated we create an instance of a Blueprint object on line three. Routing is then handled in the same way one would if they were using an instance of the Flask class i.e. decorators.

 The mod_api module contains the code for the GET and POST requests alluded to above. 



mod_api.py
In the code above we import the necessary functions and classes and instantiate an instance of the Blueprint class just as we have previously. The module consists of three routes. A route called pulse which returns a JSON object indicating that the server is up and running. The second route handles the GET requests to fetch the previous ten comments posted from the front end. The function tries to establish a connection to the database and selects the last ten records inserted. This data is then returned to the client using the jsonify function.


mod_api.py






















The third function in the module handles the POST requests from the client. First we get the request body using the get json function on the request object. Next up we get the description from the payload, insert a record into the database, fetch the last ten records inserted and return the data to the client.


Now all that is left to do is register the blueprints and run the application. This code lives within the app.py module. 


app.py

For this we import the flask application instance from the server module and the two blueprints we created earlier in the mod_api and mod_pages modules.  We register the two blueprints using the register blueprint function and in the case of the API we include a URL prefix. All that is left now is to run the application.

Et Voila, blueprints for modular flask applications.









Popular posts from this blog

Plotting My Google Location History

I have been using Android phones since about 2010 and for the most part of it I have had location history enabled. If you enjoy data like I do then you may agree that this service is pretty awesome because Google let's you download a copy of the data it collects from you using Google Takeout. I recently downloaded a copy of the places I have visited and got to analyzing.

My data set for the period consists of approximately 985 000 records starting from 2012-02-19. I wanted to try the out the folium plotting library which combines the data analysis strength of Python and the mapping prowess of Leaflets.js however rendering all the records on a single map proved problematic on my machine. Therefore in order to reduce the data set I used k means to assign each point to 1 of 100 clusters. After reducing the data set I then proceeded to use mean longitude and latitude per cluster as a proxy for my location history. This reduced data renders instantly and it is interactive which is pret…

Something interesting on the side

So I have had this blog for a few years and until now I have yet to post a single article (I have never really found time or been that interested in writing a blog). Anyway I have decided that if I am to maintain a blog, or at least make a once off post, I will try keep it aligned to what I am passionate about; Data, open source and travel for now. So without further adieu I present, something interesting on the side.

While browsing /r/algotrading I came across an interesting article about identifying mean reverting spreads in US listed equities using Python. The article itself is not very detailed, but I enjoyed it none the less. My discovery of the article coincided with the start of the JSE Challenge and I thought it may be an interesting side project to build a small system/series of scripts which I could use to identify trading opportunities and then trade on them in the game. It at the very least would be good refresher in pandas and a nice way to practice writing in python.