Python编程实战:综合项目 —— Flask 迷你博客

这个项目是典型的 Web 入门实战 ------ 用 Flask 搭建一个"小而完整"的博客系统,让你掌握后端接口开发、模板渲染、数据存储、表单处理等核心技能。


一、项目目标

构建一个迷你博客,实现:

  1. 发布文章(标题 + 内容)
  2. 展示所有文章
  3. 查看单篇文章详情
  4. 文章持久化存储(本地 JSON 或 SQLite)
  5. 模板渲染(Jinja2)
  6. 简单的路由和表单处理

整个项目结构小巧,但逻辑完整,可扩展性高。


二、项目目录结构

我们使用 Flask 推荐的基本结构:

csharp 复制代码
flask_blog/
│── app.py                # 主程序
│── models.py             # 数据读写模块
│── static/               # 静态文件(css/js/img)
│── templates/
│     ├── base.html
│     ├── index.html
│     ├── post.html
│     ├── new_post.html
│── data/
      └── posts.json      # 存储文章

三、环境安装

bash 复制代码
pip install flask

如果你想升级,可加:

bash 复制代码
pip install flask-wtf

但基础项目不强制。


四、构建数据模型(models.py

这里我们使用一个简单的 JSON 文件保存文章。

python 复制代码
import json
import os
from datetime import datetime

DATA_FILE = "data/posts.json"

def load_posts():
    if not os.path.exists(DATA_FILE):
        return []
    with open(DATA_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_posts(posts):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(posts, f, ensure_ascii=False, indent=4)

def add_post(title, content):
    posts = load_posts()
    new_post = {
        "id": len(posts) + 1,
        "title": title,
        "content": content,
        "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    posts.append(new_post)
    save_posts(posts)

五、核心后端逻辑(app.py

python 复制代码
from flask import Flask, render_template, request, redirect, url_for
from models import load_posts, add_post

app = Flask(__name__)

@app.route("/")
def index():
    posts = load_posts()
    return render_template("index.html", posts=posts)

@app.route("/post/<int:post_id>")
def post_detail(post_id):
    posts = load_posts()
    post = next((p for p in posts if p["id"] == post_id), None)
    return render_template("post.html", post=post)

@app.route("/new", methods=["GET", "POST"])
def new_post():
    if request.method == "POST":
        title = request.form.get("title")
        content = request.form.get("content")
        add_post(title, content)
        return redirect(url_for("index"))
    return render_template("new_post.html")

if __name__ == "__main__":
    app.run(debug=True)

功能点:

  • GET 展示表单
  • POST 提交文章
  • 首页展示文章列表
  • /post/id 展示文章详情

架构简洁但非常清晰。


六、模板文件(templates)

1. base.html

所有页面的公共布局:

html 复制代码
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>迷你博客</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <header>
        <h1><a href="/">迷你博客</a></h1>
        <nav>
            <a href="/">首页</a>
            <a href="/new">写文章</a>
        </nav>
    </header>

    <div class="container">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

2. index.html(首页)

html 复制代码
{% extends "base.html" %}
{% block content %}
<h2>文章列表</h2>

<ul>
{% for p in posts %}
    <li>
        <a href="/post/{{ p.id }}">{{ p.title }}</a>
        <small>{{ p.created_at }}</small>
    </li>
{% endfor %}
</ul>

{% endblock %}

3. post.html(文章详情)

html 复制代码
{% extends "base.html" %}
{% block content %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<p><small>发布时间:{{ post.created_at }}</small></p>
{% endblock %}

4. new_post.html(新增文章表单)

html 复制代码
{% extends "base.html" %}
{% block content %}

<h2>写文章</h2>

<form method="post">
    <p>标题:<br>
        <input type="text" name="title" required>
    </p>
    <p>内容:<br>
        <textarea name="content" rows="10" required></textarea>
    </p>
    <button type="submit">发布</button>
</form>

{% endblock %}

七、静态样式(static/style.css)可选

你可以随意写点:

css 复制代码
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
}
header {
    background: #333;
    color: #fff;
    padding: 15px;
}
header a {
    color: #fff;
    margin-right: 10px;
    text-decoration: none;
}
.container {
    padding: 20px;
}

八、运行项目

进入目录执行:

bash 复制代码
python app.py

打开:

arduino 复制代码
http://127.0.0.1:5000

你就能看到自己的迷你博客啦!


九、项目可扩展方向

这个项目基础但可扩展性超级强,可以继续升级:

  1. 使用 SQLite 数据库(SQLAlchemy)
  2. 加上用户登录系统
  3. 博客支持 Markdown
  4. 图片上传
  5. 分页
  6. 评论系统
  7. 后台管理界面
  8. 打包为 Docker 部署
相关推荐
Mahir082 小时前
Spring 循环依赖深度解密:从问题本质到三级缓存源码级解析
java·后端·spring·缓存·面试·循环依赖·三级缓存
曲幽2 小时前
我用了FastApiAdmin后,连夜把踩过的坑都整理出来了
redis·python·postgresql·vue3·fastapi·web·sqlalchemy·admin·fastapiadmin
前端若水4 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
绝知此事4 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
涛声依旧-底层原理研究所5 小时前
残差连接与层归一化通俗易懂的详解
人工智能·python·神经网络·transformer
csdn_aspnet5 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
fantasy_arch5 小时前
pytorch人脸匹配模型
人工智能·pytorch·python
熊猫_豆豆5 小时前
广义相对论水星近日点进动完整详细数学推导
python·天体·广义相对论
web3.08889995 小时前
1688 图搜接口(item_search_img / 拍立淘) 接入方法
开发语言·python
AI算法沐枫6 小时前
深度学习python代码处理科研测序数据
数据结构·人工智能·python·深度学习·决策树·机器学习·线性回归