การสร้างโปรเจ็คใหม่ด้วย FastAPI และ Jinja

มาลองสร้างเว็บไชต์สำหรับแปลงชื่อ ตัวพิมพ์ เล็กเป็นพิมพ์ใหญ่กันดูครับ

  1. เปิด VSCode และสร้างโฟลเดอร์สำหรับโปรเจ็คใหม่ของคุณ แล้วเปิดโฟลเดอร์นี้ใน VSCode
  2. สร้างไฟล์ main.py ในโฟลเดอร์โปรเจ็คของคุณ ซึ่งจะเป็นไฟล์ที่เก็บโค้ดของ FastAPI
  3. เขียนโค้ด FastAPI ในไฟล์ main.py ใส่โค้ดดังนี้:
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/", response_class=HTMLResponse)
async def form_post(request: Request, input_text: str = Form(...)):
    processed_text = input_text.upper() # .upper() ใช้สำหรับแปลงข้อความพิมพ์เล็กเป็นพิมพ์ใหญ่
    return templates.TemplateResponse("result.html",
        {"request": request, "processed_text": processed_text}
    )
  1. สร้างโฟลเดอร์ชื่อ templates ในโฟลเดอร์โปรเจ็คของคุณ
  2. สร้างไฟล์ index.html ในโฟลเดอร์ templates และใส่โค้ด HTML ตัวอย่างเช่น:
<!DOCTYPE html>
<html>
<head>
    <title>FastAPI and Jinja</title>
</head>
<body>
    <h1>FastAPI and Jinja</h1>
    <form method="post">
        <label for="input_text">Enter Text:</label>
        <input type="text" name="input_text" id="input_text" required>
        <button type="submit">Submit</button>
    </form>
</body>
</html>
  1. สร้างไฟล์ result.html ในโฟลเดอร์ templates และใส่โค้ด HTML ตัวอย่างเช่น:
<!DOCTYPE html>
<html>
<head>
    <title>Result</title>
</head>
<body>
    <h1>Result</h1>
    <p>Processed Text: {{ processed_text }}</p>
    <a href="/">Back to Home</a>
</body>
</html>
  1. เปิดเทอร์มินอล (Terminal) ใน VSCode และรันแอปพลิเคชัน FastAPI ด้วยคำสั่ง:
uvicorn main:app --reload

คุณจะเห็นข้อความที่บอกว่าแอปพลิเคชันรันอยู่ที่ http://127.0.0.1:8000 ให้เปิดเว็บเบราว์เซอร์และเข้าถึง URL นี้จากนั้นกรอกข้อความ ภาษาอังกฤษ แล้วคลิกที่ปุ่ม “Submit” คุณจะเห็นข้อความแปลงเป็นพิมพ์ใหญ่