FastAPI、HTML、CSS、JSON を使用したシンプルなブログ アプリの構築

WBOY
リリース: 2024-09-10 06:47:39
オリジナル
1049 人が閲覧しました

このチュートリアルでは、バックエンドに FastAPI、フロントエンドに HTMLCSS、そして を使用して基本的なブログ アプリを作成します。基本的な CRUD (作成、読み取り、更新、削除) 操作を実行するための JSON ファイル。
FastAPI は、Python で API を構築するための最新の Web フレームワークであり、そのシンプルさ、速度、および非同期操作の組み込みサポートで知られています。

以下の実装は次のようになります:

Building a Simple Blog App Using FastAPI, HTML, CSS, and JSON

Building a Simple Blog App Using FastAPI, HTML, CSS, and JSON

Building a Simple Blog App Using FastAPI, HTML, CSS, and JSON

前提条件

始める前に、以下がインストールされていることを確認してください:

  • 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 のセットアップ

FastAPI アプリケーションを含む main.py ファイルを作成します。

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 を使用したスタイル設定

静的フォルダーに 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 を強化したりできます。より豊かなユーザーエクスペリエンスを実現します。

このブログは以上です。さらなるアップデートに注目して、素晴らしいアプリを構築し続けてください! ?✨

以上がFastAPI、HTML、CSS、JSON を使用したシンプルなブログ アプリの構築の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!