Cooking with Flask...

Cooking up some code with Flask to demonstrate Apache load-balancing.

CC picture of flask, Carolina Biological Supply Company

The following is a little web environment I built to test out load balancing between Flask web apps. I need to clean up the VM hosting this and didn't want to lose the activity, so here it is in a nutshell for all to enjoy and replicate as needed. I'm not going into a lot of setup details as by the time you read this (possibly even now as I write it) the precise steps would have changed. Always consult your latest documentation.

The recipe is as follows:

Steps (high-level)

  • Install Apache
  • Install Balance module
  • Configure httpd configs for Balance (see example below)
  • Install Python3
  • Install Flask
  • Code you web apps
  • Fire your web apps and see if it works!

Below are a couple of snippets from my HTTPD config file showing how the Balancer is configured and this case with two nodes:

Note: I'm replacing angle brackets with regular brackets to because of how the code is rendering in my blog engine. Copy-pasters beware!

[VirtualHost *:80]
        DocumentRoot /var/www/html
        [Proxy balancer://mycluster]
        #       Require ip
        # call hello app
        ProxyPass /hello
        ProxyPassReverse /hello
        # call howdy app
        ProxyPass /howdy
        ProxyPassReverse /howdy
        # balance main over both
        ProxyPass / balancer://mycluster/
        ProxyPassReverse / balancer://mycluster/

Below is one of the Flask apps...a very simple 'hello world' like app, nothing fancy, but lets me know what app I'm looking at when I'm testing the balancer

$ cat 
from flask import Flask
app = Flask(__name__)

def home():
    return 'Hello world!'
$ cat 
from flask import Flask
app = Flask(__name__)

def home():
    return 'Howdy world!'

Below is the script I wrote to fire all my Flask apps together...nifty when you have a bunch or want to start them via Cron.

$ cat
# clean up existing apps
killall flask;
echo "Proceeding with webapp start!";

# python app1
flask run --port=8090 >/dev/null 2>&1 &
ps -elf | grep "8090";

# python app2
flask run --port=8091 >/dev/null 2>&1 &
ps -elf | grep "8091"

Subscribe to Warybyte

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.