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 部署
相关推荐
怕浪猫6 小时前
2028编程圈很火的10个Skills
算法·面试·github
行百里er7 小时前
Redis 完结篇——Redis 热点问题在 Spring Boot 项目中实战
redis·后端
Smoothcloud润云7 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook7 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴7 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
高频因子挖掘机8 小时前
只取最近 60 个交易日,却每次拉全历史:量化脚本变慢的原因与改法
后端·github·api
诺伦8 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索
oooost8 小时前
pytorch学习笔记1
python·学习方法
数字融合8 小时前
透明化视频孪生虚实映射一体化融合技术
人工智能·python·数码相机
孟健8 小时前
从5000亿Token到83%字节匹配:AI逆向工程与重构的工程闭环实践
后端·架构·ai编程