弗兰的悲惨之旅
99.73M · 2026-04-04
构建一个迷你博客,实现:
整个项目结构小巧,但逻辑完整,可扩展性高。
我们使用 Flask 推荐的基本结构:
flask_blog/
│── app.py # 主程序
│── models.py # 数据读写模块
│── static/ # 静态文件(css/js/img)
│── templates/
│ ├── base.html
│ ├── index.html
│ ├── post.html
│ ├── new_post.html
│── data/
└── posts.json # 存储文章
pip install flask
如果你想升级,可加:
pip install flask-wtf
但基础项目不强制。
这里我们使用一个简单的 JSON 文件保存文章。
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)
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)
功能点:
架构简洁但非常清晰。
所有页面的公共布局:
<!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>
{% 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 %}
{% extends "base.html" %}
{% block content %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<p><small>发布时间:{{ post.created_at }}</small></p>
{% endblock %}
{% 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 %}
你可以随意写点:
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;
}
进入目录执行:
python app.py
打开:
http://127.0.0.1:5000
你就能看到自己的迷你博客啦!
这个项目基础但可扩展性超级强,可以继续升级: