Server-Side Scripting/Key-Value Databases/Python (Flask)

app.py

edit
# This program creates and displays a temperature database
# with options to insert, update, and delete records.
#
# Assumes Redis is installed locally. If you have Redis running
# separately (such as in a Docker container), replace localhost below
# with your Redis server's IP address.
#
# References:
#   https://en.wikibooks.org/wiki/Python_Programming
#   https://realpython.com/python-redis/

import flask
import redis as redis_lib

app = flask.Flask(__name__)

HOST = "localhost"
DATABASE = 0

FORM = """
<h1>Temperature Data Entry</h1>
<p>Enter country and temperature. Enter again to update.</p>
<p>Enter country without temperature to delete.</p>
<form method="POST">
<p><label for="country">Country:</label>
<input type="text" id="country" name="country" required></p>
<p><label for="stop">Temperature:</label>
<input type="text" id="temperature" name="temperature"></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
<hr>
"""

@app.route('/', methods=["GET"])
def root_get():
    try:
        return FORM + get_data()
    except Exception as exception:
        return exception

@app.route('/', methods=["POST"])
def root_post():
    try:
        country = flask.request.form["country"].strip()
        temperature = flask.request.form["temperature"].strip()

        if not country_exists(country):
            insert_country(country, temperature)
        elif temperature != "":
            update_country(country, temperature)
        else:
            delete_country(country)

        return FORM + get_data()
    except Exception as exception:
        return exception

def get_data():
    redis = redis_lib.Redis(host=HOST, db=DATABASE)
    result = "<table><tr><th>Country</th>"
    result += "<th>Temperature</th></tr>"
    countries = redis.keys()
    countries.sort()
    for country in countries:
        temperature = redis.get(country)
        result += f"<tr><td>{country.decode()}</td>"
        result += f"<td>{temperature.decode()}</td></tr>"
    result += "</table>"
    return result

def country_exists(country):
    redis = redis_lib.Redis(host=HOST, db=DATABASE)
    return bool(redis.exists(country))

def insert_country(country, temperature):
    redis = redis_lib.Redis(host=HOST, db=DATABASE)
    redis.set(country, temperature)

def update_country(country, temperature):
    redis = redis_lib.Redis(host=HOST, db=DATABASE)
    redis.set(country, temperature)

def delete_country(country):
    redis = redis_lib.Redis(host=HOST, db=DATABASE)
    redis.delete(country)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

Try It

edit
  1. Use Docker/Redis to run a Redis server.
  2. Use Docker/Flask and copy and paste the code above to run as the Flask application. Be sure to modify the Redis host address to match the address received by your Redis server.

See Also

edit