>  기사  >  백엔드 개발  >  FastAPI, HTML, CSS 및 JSON을 사용하여 간단한 블로그 앱 구축

FastAPI, HTML, CSS 및 JSON을 사용하여 간단한 블로그 앱 구축

WBOY
WBOY원래의
2024-09-10 06:47:391051검색

이 튜토리얼에서는 백엔드에 FastAPI를 사용하고 프런트엔드에 HTMLCSS를 사용하고 기본 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 수행하기 위한 JSON 파일입니다.
FastAPI는 Python으로 API를 구축하기 위한 최신 웹 프레임워크로, 단순성, 속도 및 비동기 작업에 대한 내장 지원

으로 잘 알려져 있습니다.

아래 구현은 다음과 같습니다.

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

전제조건

시작하기 전에 다음이 설치되어 있는지 확인하세요.

  • 파이썬 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를 사용한 스타일링

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 대신 데이터베이스 ?️를 사용하여 풀 스택 웹 앱을 만들 수 있습니다.
데이터베이스를 사용하면 더 많은 기능을 추가하고, 성능을 향상하고, 전반적인 UI/UX를 향상할 수 있습니다. 더욱 풍부한 사용자 경험을 제공합니다.

이 블로그는 여기까지입니다! 더 많은 업데이트를 기대하고 계속해서 놀라운 앱을 만들어 보세요! ?✨

위 내용은 FastAPI, HTML, CSS 및 JSON을 사용하여 간단한 블로그 앱 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.