Flask-Admin管理员插件示范
安装:pip3 install flask-admin
from flask import Flask, session, abort
from peewee import CharField, SqliteDatabase, Model
from playhouse.flask_utils import FlaskDB #peewee工具
from flask_admin import Admin
from flask_admin.contrib.peewee import ModelView
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
database = SqliteDatabase('cs.db')
peewee_db = FlaskDB(app,database) #绑定
# 创建一个简单的数据库模型
class User(peewee_db.Model):
username = CharField(unique=True, max_length=80, null=False)
email = CharField(unique=True, max_length=120, null=False)
def __repr__(self):
return self.username
# 创建一个简单的数据库模型
class Blog(peewee_db.Model):
biaoti = CharField(unique=True, max_length=80, null=False)
neirong = CharField(unique=True, max_length=120, null=False)
def __repr__(self):
return self.biaoti
db = peewee_db.database
# 初始化Flask-Admin
admin = Admin(app, name='用户中心',url='/muxiaoliang')
class Admin_UserView(ModelView):
column_searchable_list = ['username', 'email']
#开启User的两个字段的搜搜
def is_accessible(self):
user_id = session.get('id')
return user_id == 5000
def inaccessible_callback(self, name, **kwargs):
return abort(404)
class Admin_BlogView(ModelView):
column_searchable_list = ['biaoti'] #开启标题的搜索
def is_accessible(self):
user_id = session.get('id') #这里判断session的id是不是5000,如果是则返回True,前提是已经指定了session
return user_id == 5000
def inaccessible_callback(self, name, **kwargs):
return abort(404)
# 添加User数据模型的管理视图
admin.add_view(Admin_UserView(User))
# 添加Blog数据模型的管理视图
admin.add_view(Admin_BlogView(Blog))
if __name__ == '__main__':
#创建数据库表
db.create_tables([User,Blog])
#运行应用
app.run(debug=True)