Jump to content

Server-Side Scripting/Iteration/Python (FastAPI)

From Wikiversity

routers/lesson4.py

[edit | edit source]
# Demonstrates conditions, while loops and for loops using
# Celsius and Fahrenheit temperature conversion tables.
#
# References:
#   https://www.mathsisfun.com/temperature-conversion.html
#   https://fastapi.tiangolo.com/tutorial/query-params/
#   https://fastapi.tiangolo.com/tutorial/request-forms/

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

router = APIRouter(prefix="/lesson4")
templates = Jinja2Templates(directory="templates")

@router.get("/", response_class=HTMLResponse)
async def get_lesson4(request: Request):
    return templates.TemplateResponse(
        "lesson4.html", 
        {   
            "request": request,
            "table": ""
        }
    )

@router.post("/", response_class=HTMLResponse)
async def post_lesson4(request: Request):
    form = dict(await request.form())
    try:
        start = int(form["start"])
        stop = int(form["stop"])
        increment = int(form["increment"])
        submit = form["submit"]

        if submit == "Celsius":
            result = process_celsius(start, stop, increment)
        elif submit == "Fahrenheit":
            result = process_fahrenheit(start, stop, increment)
        else:
            result = "Unknown submit value: " + submit
    except Exception as exception:
        result = str(exception)

    return templates.TemplateResponse(
        "lesson4.html", 
        {   
            "request": request,
            "table": result
        }
    )

def process_celsius(start, stop, increment):
    result = "<table><tr><th>Celsius</th><th>Fahrenheit</th></tr>"
    celsius = start
    while celsius <= stop:
        fahrenheit = celsius * 9 / 5 + 32
        result += f"<tr><td>{celsius}</td>"
        result += f"<td>{fahrenheit:0.1f}</td></tr>"
        celsius += increment
    result += "</table>"
    return result

def process_fahrenheit(start, stop, increment):
    result = "<table><tr><th>Fahrenheit</th><th>Celsius</th></tr>"
    for fahrenheit in range(start, stop + increment, increment):
        celsius = (fahrenheit - 32) * 5 / 9
        result += f"<tr><td>{fahrenheit}</td>"
        result += f"<td>{celsius:0.1f}</td></tr>"
    result += "</table>"
    return result

templates/lesson4.html

[edit | edit source]
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Lesson 4</title>
    <link rel="stylesheet" href="{{url_for('static', path='/styles.css')}}">
    <style>
        p {
            min-height: 1em;
        }
    </style>
</head>

<body>
    <h1>Temperature Conversion</h1>
    <form method="POST">
        <p><label for="start">Start:</label>
            <input type="text" id="start" name="start" value="0">
        </p>
        <p><label for="stop">Stop:</label>
            <input type="text" id="stop" name="stop" value="100">
        </p>
        <p><label for="increment:">Increment</label>
            <input type="text" id="increment" name="increment" value="10">
        </p>
        <p><input type="submit" name="submit" value="Celsius">
            <input type="submit" name="submit" value="Fahrenheit">
        </p>
    </form>
    {{table|safe}}
</body>

</html>

Try It

[edit | edit source]

See Server-Side Scripting/Routes and Templates/Python (FastAPI) to create a test environment.

See Also

[edit | edit source]