Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
47 lines (37 loc) · 1.36 KB
/
Copy pathapp.py
File metadata and controls
47 lines (37 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from flask import Flask, render_template, request
from conversion_functions import conversion_functions
from utils import format_result
app = Flask(__name__)
@app.route("/", defaults={"unit": "length"})
@app.route("/<unit>", methods=["GET", "POST"])
def converter(unit):
target_template = f"{unit}.html"
if request.method == "POST":
try:
value = float(request.form[unit])
except ValueError:
return render_template(target_template, unit=unit, error="Invalid value")
convert_from = request.form["convert-from"]
convert_to = request.form["convert-to"]
if convert_from == convert_to:
return render_template(
target_template,
unit=unit,
result=format_result(value),
value=value,
convert_from=convert_from,
convert_to=convert_to,
)
conversion_function = conversion_functions[
f"convert_{convert_from.replace('-', '_')}"
]
result = format_result(conversion_function(value, convert_to))
return render_template(
target_template,
unit=unit,
result=result,
value=value,
convert_from=convert_from,
convert_to=convert_to,
)
return render_template(target_template, unit=unit)