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 部署
相关推荐
uzong11 小时前
一个好的面试官,应该让候选人感到被尊重
面试
阳光是sunny13 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
灯澜忆梦13 小时前
GO_并发编程---定时器
开发语言·后端·golang
阳光是sunny13 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
皮皮林55113 小时前
开源实力派,给本地 AI 装上深度调研能力,一张 3090 跑到 95.7 分!
后端
努力的小雨14 小时前
把 Windows 桌面图标做成一个会自己运转的小世界
后端
触底反弹14 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
武子康14 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端
大模型码小白15 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
麻雀飞吧15 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python