pip install flask
3.安装数据库支持(这里我们用 SQLite):
pip install flask_sqlalchemy
项目结构
/my_blog
/templates
- index.html
- post.html
/static
- /css
- style.css
app.py
步骤 1:创建 app.py
文件
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# 数据库模型
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
def __repr__(self):
return f'<Post {self.title}>'
# 首页:显示所有文章
@app.route('/')
def index():
posts = Post.query.all()
return render_template('index.html', posts=posts)
# 文章页面:显示单篇文章
@app.route('/post/<int:post_id>')
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('post.html', post=post)
# 创建文章
@app.route('/create', methods=['GET', 'POST'])
def create():
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(url_for('index'))
return render_template('create.html')
# 启动应用
if __name__ == "__main__":
db.create_all() # 创建数据库
app.run(debug=True)
步骤 2:创建 HTML 模板
在 templates
目录中,创建以下 HTML 文件。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>我的博客</title>
</head>
<body>
<h1>欢迎来到我的博客</h1>
<a href="{{ url_for('create') }}">创建新文章</a>
<ul>
{% for post in posts %}
<li>
<a href="{{ url_for('post', post_id=post.id) }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
</body>
</html>
post.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ post.title }}</title>
</head>
<body>
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
<a href="{{ url_for('index') }}">返回首页</a>
</body>
</html>
create.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>创建文章</title>
</head>
<body>
<h1>创建新文章</h1>
<form action="{{ url_for('create') }}" method="POST">
<label for="title">标题:</label>
<input type="text" name="title" required><br>
<label for="content">内容:</label><br>
<textarea name="content" rows="4" required></textarea><br>
<button type="submit">提交</button>
</form>
</body>
</html>
步骤 3:运行项目
app.py
文件:python app.py
http://127.0.0.1:5000/
,你会看到博客的首页,可以创建新文章并查看。