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 部署
相关推荐
程序员爱钓鱼2 小时前
Python编程实战:综合项目 —— 迷你爬虫项目
后端·python·面试
white-persist2 小时前
二进制movl及CTF逆向GDB解析:Python(env)环境下dbg从原理到实战
linux·服务器·开发语言·python·网络安全·信息可视化·系统安全
Michelle80232 小时前
24大数据 while循环
大数据·python
Dream it possible!2 小时前
LeetCode 面试经典 150_二叉树_二叉树中的最大路径和(77_124_C++_困难)(DFS)
c++·leetcode·面试·二叉树
翔云 OCR API2 小时前
NFC护照鉴伪查验流程解析-ICAO9303护照真伪查验接口技术方案
开发语言·人工智能·python·计算机视觉·ocr
Qiuner2 小时前
Spring Boot 进阶:application.properties 与 application.yml 的全方位对比与最佳实践
java·spring boot·后端
艾莉丝努力练剑2 小时前
【自动化测试实战篇】Web自动化测试实战:从用例编写到报告生成
前端·人工智能·爬虫·python·pycharm·自动化·测试
chushiyunen2 小时前
django第一个项目blog
python·django