Flask 框架入门:快速搭建个人博客网站
Flask 是一个轻量级 Python Web 框架,适合快速开发小型应用。下面分步指导搭建基础博客网站:
1. 环境准备
安装必要依赖:
pip install flask flask-sqlalchemy flask-wtf
2. 项目结构
创建基础目录:
/blog
├── app.py # 主程序
├── templates/ # HTML模板
├── static/ # CSS/JS文件
└── models.py # 数据模型
3. 数据模型(models.py)
使用 SQLite 存储博客文章:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
content = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.now)
4. 主程序(app.py)
初始化应用和路由:
from flask import Flask, render_template, request, redirect
from models import db, Post
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db.init_app(app)
@app.route('/')
def index():
posts = Post.query.all()
return render_template('index.html', posts=posts)
@app.route('/create', methods=['GET', 'POST'])
def create_post():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
new_post = Post(title=title, content=content)
db.session.add(new_post)
db.session.commit()
return redirect('/')
return render_template('create.html')
5. 模板文件
templates/index.html(首页):
<!DOCTYPE html>
<html>
<head>
<title>我的博客</title>
</head>
<body>
<h1>最新文章</h1>
{% for post in posts %}
<div>
<h2>{{ post.title }}</h2>
<p>{{ post.content[:100] }}...</p>
<small>{{ post.created_at }}</small>
</div>
{% endfor %}
<a href="/create">写新文章</a>
</body>
</html>
templates/create.html(创建页):
<form method="POST">
<input type="text" name="title" placeholder="标题" required>
<textarea name="content" placeholder="内容" required></textarea>
<button type="submit">发布</button>
</form>
6. 启动应用
在终端运行:
export FLASK_APP=app.py
flask run
访问 http://localhost:5000 即可查看博客
7. 功能扩展建议
- 用户认证:添加
flask-login实现登录 - 样式美化:在
static/添加 CSS 文件 - 分页功能:使用
paginate = Post.query.paginate(page=1, per_page=5) - 部署上线:推荐使用 Heroku 或 PythonAnywhere
提示:开发时启用调试模式:
if __name__ == '__main__': app.run(debug=True)
通过这个基础框架,您可以在 30 分钟内搭建可运行的博客原型,后续可根据需求逐步扩展功能。

4388

被折叠的 条评论
为什么被折叠?



