flask书写后台管理程序
时间: 2023-07-09 18:21:21 浏览: 121
使用Flask可以快速、灵活地搭建一个后台管理系统,下面是一个简单的示例:
1. 安装Flask和相关扩展库
```python
pip install Flask
pip install Flask-WTF
pip install Flask-Login
pip install Flask-Migrate
```
2. 创建Flask应用程序
```python
from flask import Flask
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
from app import views, models
```
3. 创建模型类
```python
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
password_hash = db.Column(db.String(128))
def __repr__(self):
return '<User {}>'.format(self.username)
```
4. 创建视图函数
```python
from flask import render_template
from flask_login import login_required
@app.route('/')
@login_required
def index():
return render_template('index.html')
```
5. 创建模板文件
```html
{% extends "base.html" %}
{% block content %}
<h1>欢迎来到后台管理系统</h1>
{% endblock %}
```
6. 创建表单类
```python
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo
class LoginForm(FlaskForm):
username = StringField('用户名', validators=[DataRequired()])
password = PasswordField('密码', validators=[DataRequired()])
submit = SubmitField('登录')
```
7. 创建登录视图函数
```python
from flask import render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, current_user, login_required
from app import app, db, login_manager
from app.forms import LoginForm
from app.models import User
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('用户名或密码错误')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
return redirect(url_for('index'))
return render_template('login.html', title='登录', form=form)
```
8. 创建登出视图函数
```python
from flask_login import logout_user
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
```
9. 创建配置文件
```python
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
```
以上是一个简单的Flask后台管理系统的示例,您可以根据自己的需求进行修改和扩展。
阅读全文