在本教程中,我們將使用FastAPI建立一個基本的部落格應用程式作為後端,使用 HTMLCSS作為前端,並使用一個JSON檔案來執行基本的 CRUD(建立、讀取、更新、刪除)操作。

FastAPI 是一個使用 Python 建立 API 的現代 Web 框架,以其簡單、速度和對非同步操作的內建支援而聞名。

下面的實作看起來像這樣:

部落格清單頁面

部落格詳細頁面

建立新部落格頁面

先決條件

在開始之前,請確保您已安裝以下軟體:

  • Python 3.7+

  • 快速API

  • Uvicorn(用於執行 FastAPI 應用程式)

要安裝 FastAPI 和 Uvicorn,您可以使用 pip:

pip install fastapi uvicorn python-multipart

專案結構

該專案的架構如下:

/blog_app
    ├── static
    │   └── style.css
    ├── templates
    │   ├── index.html
    │   ├── post.html
    │   ├── create_post.html
    ├── blog.json
    ├── main.py

第 1 步:設定 FastAPI

建立一個main.py文件,其中將包含 FastAPI 應用程式。

from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import json
import os

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")

# Load or initialize blog data
BLOG_FILE = "blog.json"

if not os.path.exists(BLOG_FILE):
    with open(BLOG_FILE, "w") as f:
        json.dump([], f)

def read_blog_data():
    with open(BLOG_FILE, "r") as f:
        return json.load(f)

def write_blog_data(data):
    with open(BLOG_FILE, "w") as f:
        json.dump(data, f)

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

@app.get("/post/{post_id}", response_class=HTMLResponse)
async def read_post(request: Request, post_id: int):
    blogs = read_blog_data()
    post = blogs[post_id] if 0 <= post_id < len(blogs) else None
    return templates.TemplateResponse("post.html", {"request": request, "post": post})

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

@app.post("/create_post")
async def create_post(title: str = Form(...), content: str = Form(...)):
    blogs = read_blog_data()
    blogs.append({"title": title, "content": content})
    write_blog_data(blogs)
    return RedirectResponse("/", status_code=303)

@app.post("/delete_post/{post_id}")
async def delete_post(post_id: int):
    blogs = read_blog_data()
    if 0 <= post_id < len(blogs):
        blogs.pop(post_id)
        write_blog_data(blogs)
    return RedirectResponse("/", status_code=303)

第 2 步:設定 HTML 和 CSS

在模板資料夾中,建立以下 HTML 檔案:

index.html

該文件將列出所有部落格文章。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog App</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <h1>Blog Posts</h1>
    <a href="/create_post">Create New Post</a>
    <div>
        {% for post in blogs %}
        <div class="post">
            <h2>{{ post.title }}</h2>
            <p>{{ post.content[:100] }}...</p>
            <a href="/post/{{ loop.index0 }}">Read more</a>
            <form method="post" action="/delete_post/{{ loop.index0 }}">
                <button type="submit">Delete</button>
            </form>
        </div>
        {% endfor %}
    </div>
</body>
</html>

post.html

該文件將顯示部落格文章的完整內容。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ post.title }}</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <h1>{{ post.title }}</h1>
    <p>{{ post.content }}</p>
    <a href="/">Back to Home</a>
</body>
</html>

create_post.html

該文件將包含用於建立新帖子的表單。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create a New Post</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <h1>Create a New Post</h1>
    <form method="post" action="/create_post">
        <label for="title">Title</label>
        <input type="text" name="title" id="title" required>
        <label for="content">Content</label>
        <textarea name="content" id="content" required></textarea>
        <button type="submit">Create</button>
    </form>
    <a href="/">Back to Home</a>
</body>
</html>

步驟 3: 使用 CSS 設計樣式

在 static 資料夾中,建立style.css檔案以加入一些基本樣式。

body {
    font-family: Arial, sans-serif;
    padding: 20px;
    background-color: #f0f0f0;
}

h1 {
    color: #333;
}

a {
    text-decoration: none;
    color: #0066cc;
}

.post {
    background-color: #fff;
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 5px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

button {
    background-color: #ff4d4d;
    border: none;
    padding: 5px 10px;
    color: white;
    border-radius: 3px;
    cursor: pointer;
}

button:hover {
    background-color: #ff1a1a;
}

input, textarea {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
}

第 4 步:執行應用程式

現在一切都已設定完畢,使用 Uvicorn 執行 FastAPI 應用程式。

uvicorn main:app --reload

在瀏覽器中造訪http://127.0.0.1:8000 ,您應該會看到部落格首頁。

作為作業,您可以使用資料庫 🗄️ 而不僅僅是 JSON 來建立全端 Web 應用程式。

透過資料庫,您可以新增更多功能 🌟、提高效能 🚀 並增強整體 UI/UX 🎨,以獲得更豐富的使用者體驗。

這就是本部落格的全部內容!請繼續關注更多更新並繼續建立令人驚嘆的應用程式! 💻✨


原文出處:https://dev.to/jagroop2001/building-a-simple-blog-app-using-fastapi-html-css-and-json-1dc


共有 0 則留言