Server-Side Scripting/Dictionaries/Python (Flask)

From Wikiversity
Jump to navigation Jump to search

app.py[edit | edit source]

# This program reads a user-selected text file of countries
# and Celsius temperatures. It displays the data in Celsius
# and Fahrenheit sorted in decending order by temperature.
#
# File format:
# Country,Temperature
# American Samoa,37.2° C
# Bulgaria,45.2° C
#
# References:
#   https://www.mathsisfun.com/temperature-conversion.html
#   https://en.wikibooks.org/wiki/Python_Programming
#   https://www.javatpoint.com/flask-file-uploading

import flask

app = flask.Flask(__name__)

FORM = """
<h1>Temperature Conversion</h1>
<p>Select a comma-separated file of countries and Celsius temperatures:</p>
<form method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file">
<input type="submit">
</form>
"""

@app.route('/', methods=["GET"])
def root_get():
    return FORM

@app.route('/', methods=["POST"])
def root_post():
    file = flask.request.files["file"]
    result = "<h1>Temperature Conversion</h1>"
    result += f"<h2>{file.filename}</h2>"
    result += process_file(file)
    return result

def process_file(file):
    if not file:
        return "No file selected"

    text = file.read().decode()
    lines = text.strip().split("\n")
    if "country," in lines[0].lower():
        lines.pop(0) # Remove heading line

    table = []
    for line in lines:
        try:
            record = process_line(line)
            table.append(record)
        except ValueError as exception:
            return str(exception)

    table.sort(key=lambda x:x["celsius"], reverse=True)
    result = format_table(table)
    return result

def process_line(line):
    record = {}
    array = line.split(",")
    if len(array) != 2:
        raise ValueError("Invalid file format")

    record["country"] = array[0]
    celsius = array[1]
    index = celsius.find("° C")
    if index < 0:
        raise ValueError("Invalid file format")

    try:
        celsius = float(celsius[0:index])
    except:
        raise ValueError("Invalid temperature data")

    record["celsius"] = celsius
    fahrenheit = celsius * 9 / 5 + 32
    record["fahrenheit"] = fahrenheit
    return record

def format_table(table):
    result = "<table><tr><th>Country</th>"
    result += "<th>Celsius</th>"
    result += "<th>Fahrenheit</th></tr>"

    for record in table:
        result += f"<tr><td>{record['country']}</td>" 
        result += f"<td>{record['celsius']:.1f}° C</td>"
        result += f"<td>{record['fahrenheit']:.1f}° F</td></tr>"

    result += "</table>"
    return result

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

Try It[edit | edit source]

Copy and paste the code above into the following free online development environment or use your own Python (Flask) compiler / interpreter / IDE.

See Also[edit | edit source]