Server-Side Scripting/Arrays/Python (FastAPI)

From Wikiversity
Jump to navigation Jump to search

routers/[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,MaximumTemperature
# Bulgaria,45.2 °C
# Canada,45 °C
# References:

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

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

@router.get("/", response_class=HTMLResponse)
async def get_lesson6(request: Request):
    return templates.TemplateResponse(
            "request": request,
            "table": ""
    )"/", response_class=HTMLResponse)
async def post_lesson6(request: Request, file: UploadFile = File(...)):
        result = await process_file(file)
    except Exception as exception:
        result = exception

    return templates.TemplateResponse(
            "request": request,
            "table": result

async def process_file(file):
    if not file:
        return "No file selected"

    text = await
    text = text.decode()
    lines = text.strip().split("\n")
    if "country," in lines[0].lower():
        lines.pop(0) # Remove heading line

    table = []
    for line in lines:
            array = process_line(line)
        except ValueError as exception:
            return str(exception)

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

    result = f"<h2>{file.filename}</h2>"
    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")

        celsius = float(celsius[0:index])
        raise ValueError("Invalid temperature data")

    array[1] = celsius
    fahrenheit = celsius * 9 / 5 + 32
    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

templates/lesson6.html[edit | edit source]

<!DOCTYPE html>
<html lang="en">

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

    <h1>Temperature Conversion</h1>
    <p>Select a file of Celsius temperatures for conversion:</p>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" id="file" name="file">
        <input type="submit">


Try It[edit | edit source]

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

See Also[edit | edit source]