Server-Side Scripting/Strings and Files/Python (Flask)

From Wikiversity
Jump to navigation Jump to search

app.py[edit | edit source]

# This program reads a user-selected text file of Fahrenheit
# temperatures and converts the temperatures to Celsius.
#
# File format:
# 32° F
# 98.6° F
# 212° F 
#
# 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 file of Fahrenheit temperatures for conversion:</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"

    result = "<table><tr><th>Fahrenheit</th><th>Celsius</th></tr>"

    text = file.read().decode()
    lines = text.strip().split("\n")
    for line in lines:
        result += process_line(line)

    result += "</table>"
    return result

def process_line(line):
    index = line.find("° F")
    if index < 0:
        return "Invalid file format"

    try:
        fahrenheit = float(line[0:index])
    except:
        return "Invalid temperature data"

    celsius = (fahrenheit - 32) * 5 / 9
    result = f"<tr><td>{fahrenheit}</td>"
    result += f"<td>{celsius:.1f}</td></tr>"
    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]