Jump to content

Server-Side Scripting/Requests/Python (FastAPI)

From Wikiversity

routers/lesson3.py

[edit | edit source]
# Converts a Fahrenheit temperature to Celsius using a GET request and
# converts a Celsius temperature to Fahrenheit using a POST request.
#
# 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="/lesson3")
templates = Jinja2Templates(directory="templates")

@router.get("/", response_class=HTMLResponse)
async def get_lesson3(request: Request):
    parameters = dict(request.query_params)
    try:
        fahrenheit = float(parameters["fahrenheit"])
        celsius = (fahrenheit - 32) * 5 / 9
        result = f"{fahrenheit:0.1f}° Fahrenheit is {celsius:0.1f}° Celsius"
    except:
        result = ""

    return templates.TemplateResponse(
        "lesson3.html", 
        {   
            "request": request,
            "fahrenheit": result
        }
    )

@router.post("/", response_class=HTMLResponse)
async def post_lesson3(request: Request):
    form = dict(await request.form())
    try:
        celsius = float(form["celsius"])
        fahrenheit = celsius * 9 / 5 + 32
        result = f"{celsius:0.1f}° Celsius is {fahrenheit:0.1f}° Fahrenheit"
    except:
        result = ""

    return templates.TemplateResponse(
        "lesson3.html", 
        {   
            "request": request,
            "celsius": result
        }
    )

templates/lesson3.html

[edit | edit source]
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Lesson 3</title>
    <link rel="stylesheet" href="{{url_for('static', path='/styles.css')}}">
    <style>
        p {
            min-height: 1em;
        }
    </style>
</head>
  <body>
    <form method="GET">
        <p>
            <label for="fahrenheit">Enter Fahrenheit temperature:</label>
            <input type="text" id="fahrenheit" name="fahrenheit">
            <input type="submit" value="Submit">
        </p>
        <p>
            <output>{{fahrenheit}}</output>
        </p>
    </form>
    <form method="POST">
        <p>
            <label for="celsius">Enter Celsius temperature:</label>
            <input type="text" id="celsius" name="celsius">
            <input type="submit" value="Submit">
        </p>
        <p>
            <output>{{celsius}}</output>
        </p>
    </form>
</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]