python flask 博客系统
时间: 2023-11-20 17:59:06 浏览: 33
Python Flask是一个轻量级的Web应用框架,它可以用来开发博客系统。下面是一个简单的Python Flask博客系统的例子:
```python
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/blog'
db = SQLAlchemy(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
content = db.Column(db.Text)
@app.route('/')
def index():
posts = Post.query.all()
return render_template('index.html', posts=posts)
@app.route('/post/<int:id>')
def post(id):
post = Post.query.get(id)
return render_template('post.html', post=post)
@app.route('/new', methods=['GET', 'POST'])
def new():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
post = Post(title=title, content=content)
db.session.add(post)
db.session.commit()
return redirect(url_for('index'))
return render_template('new.html')
if __name__ == '__main__':
app.run(debug=True)
```
这个例子使用了Flask和SQLAlchemy来创建一个简单的博客系统。它包括三个页面:主页、文章页面和新文章页面。主页显示所有文章的标题和摘要,文章页面显示单个文章的标题和内容,新文章页面允许用户创建新文章。