Jump to content

Server-Side Scripting/Arrays/Python (Flask)

From Wikiversity

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 descending 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:
            array = process_line(line)
            table.append(array)
        except ValueError as exception:
            return str(exception)

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

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

    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")

    array[1] = celsius
    fahrenheit = celsius * 9 / 5 + 32
    array.append(fahrenheit)
    return array

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

    for row in table:
        result += f"<tr><td>{row[0]}</td>" 
        result += f"<td>{row[1]:.1f}° C</td>"
        result += f"<td>{row[2]:.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]