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 部署
相关推荐
国强_dev9 小时前
Python 的“非直接原因”报错
开发语言·python
副露のmagic9 小时前
更弱智的算法学习 day24
python·学习·算法
颜酱9 小时前
前端必备动态规划的10道经典题目
前端·后端·算法
Chan169 小时前
【 Java八股文面试 | JavaSE篇 】
java·jvm·spring boot·面试·java-ee·八股
廖圣平9 小时前
从零开始,福袋直播间脚本研究【三】《多进程执行selenium》
python·selenium·测试工具
散峰而望9 小时前
【Coze - AI Agent 开发平台】-- 你真的了解 Coze 吗
开发语言·人工智能·python·aigc·ai编程·ai写作
辞砚技术录9 小时前
MySQL面试题——索引2nd
数据库·mysql·面试
半夏知半秋10 小时前
rust学习-闭包
开发语言·笔记·后端·学习·rust
yangSnowy10 小时前
用python抓取网页数据的基础方法
开发语言·python
gcfer10 小时前
Python基础语法记录
python