Server-Side Scripting/Document Databases/Python (Flask)

From Wikiversity
Jump to navigation Jump to search

app.py[edit | edit source]

# This program creates and displays a temperature database
# with options to insert, update, and delete records.
#
# Assumes MongoDB is installed locally. If you have MongoDB running
# separately (such as in a Docker container), replace localhost below
# with your MongoDB server's IP address.
#
# References:
#   https://en.wikibooks.org/wiki/Python_Programming
#   https://docs.mongodb.com/manual/tutorial/
#   https://www.w3schools.com/python/python_mongodb_getstarted.asp

import flask
import pymongo

app = flask.Flask(__name__)

HOST = "mongodb://localhost"
DATABASE = "temperature"
COLLECTION = "countries"

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():
    mongo = pymongo.MongoClient(HOST)
    database = mongo[DATABASE]
    collection = database[COLLECTION]
    result = "<table><tr><th>ID</th>"
    result += "<th>Country</th>"
    result += "<th>Temperature</th></tr>"
    for document in collection.find():
        result += f"<tr><td>{document['_id']}</td>"
        result += f"<td>{document['country']}</td>"
        result += f"<td>{document['temperature']}</td></tr>"
    result += "</table>"
    return result

def country_exists(country):
    mongo = pymongo.MongoClient(HOST)
    database = mongo[DATABASE]
    collection = database[COLLECTION]
    filter = {
        "country": country
    }
    return bool(collection.count(filter))

def insert_country(country, temperature):
    mongo = pymongo.MongoClient(HOST)
    database = mongo[DATABASE]
    collection = database[COLLECTION]
    document = {
        "country": country,
        "temperature": temperature
    }
    collection.insert_one(document)

def update_country(country, temperature):
    mongo = pymongo.MongoClient(HOST)
    database = mongo[DATABASE]
    collection = database[COLLECTION]
    filter = {
        "country": country
    }
    update = {
        "$set": { "temperature": temperature }
    }
    collection.update_one(filter, update)

def delete_country(country):
    mongo = pymongo.MongoClient(HOST)
    database = mongo[DATABASE]
    collection = database[COLLECTION]
    filter = {
        "country": country
    }
    collection.delete_one(filter)

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

Try It[edit | edit source]

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

See Also[edit | edit source]