使用 FastAPI、HTML、CSS 和 JSON 构建简单的博客应用程序

WBOY
发布: 2024-09-10 06:47:39
原创
1049 人浏览过

在本教程中,我们将使用 FastAPI 创建一个基本的博客应用程序作为后端,使用 HTMLCSS 作为前端,以及 JSON 文件,用于执行基本的 CRUD(创建、读取、更新、删除)操作。
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+
  • FastAPI
  • 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。以获得更丰富的用户体验。

这就是本博客的全部内容了!请继续关注更多更新并继续构建令人惊叹的应用程序! ?✨

以上是使用 FastAPI、HTML、CSS 和 JSON 构建简单的博客应用程序的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!