Building a simple Flask app
Posted on: 2023-09-28
Doing simple data parsing and showing results on a web page is a common request that web developers, data analysts and others tackle on a regular basis. I've had to do my fair share of such tasks as well, and here I'll show you the way I prefer to do it. A lot of people would use an IPython interface, or a larger data analytics framework, but I tend to prefer small, custom tailored solutions that use far less resources than most people seem to use.
In this post I will show you how to build a simple web app that can run with just a few megabytes of resources, and provide an HTML table showing the content of a text file over an encrypted connection.
The text file in question will be saved in records.txt and contain a number of space separated log entries:
2012-01-13 John Opened new ticket #761.
2012-01-13 Sally Assigned ticket #761.
2012-01-15 Sally Solved the issue. It was a bad capacitor.
2012-01-15 Sally Closed ticket #761.
Before we can make our Flask app, we'll install the necessary Python modules:
pip install Flask pandas certbot
If you don't want to use HTTPS you don't have to install the last module, but if you do want encryption then just run the certbot
command on the command line.
Now that we have our modules, let's write the code:
#!/usr/bin/python3
# Flask app to show data in a simple table
from flask import Flask
import pandas as pd
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
with open("records.txt", "r") as fd:
raw = fd.read()
data = []
for line in raw.split('\n'):
data.append({
'Date': line.split()[0],
'Name': line.split()[1],
'Message': ' '.join(line.split()[2:])
})
output = pd.DataFrame(data)
return output
if __name__ == '__main__':
app.run(
host='0.0.0.0',
port=443,
ssl_context=(
'/etc/letsencrypt/live/app.example.com/fullchain.pem',
'/etc/letsencrypt/live/app.example.com/privkey.pem'
),
threaded=True
)
On the first 3 lines we import the modules that we just installed. After that, we instantiate the Flask app.
Flask apps are based on routes. A single app can provide multiple routes, which would each have their own functions. Here, we only have one route which is accessed on the default endpoint / and so we only have one function. That function uses standard Python to open our text file, go through it line by line, then return the HTML code produced by the Pandas module. This module has a handy function that can convert a dataframe to HTML, so we're using it here.
Finally, we start the Flask app on port 443 using the certificates provided by LetsEncrypt. Here replace app.example.com with your hostname. After that, all you need to do is run the script and connect over the web.