94 lines
3.2 KiB
Python
94 lines
3.2 KiB
Python
from flask import Flask, current_app
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
from flask_login import LoginManager
|
|
from flask_migrate import Migrate
|
|
from flask_jwt_extended import JWTManager
|
|
from config import Config
|
|
import logging
|
|
from logging.handlers import RotatingFileHandler
|
|
import os
|
|
|
|
db = SQLAlchemy()
|
|
migrate = Migrate()
|
|
login_manager = LoginManager()
|
|
jwt = JWTManager()
|
|
|
|
def create_app(config_class=Config):
|
|
app = Flask(__name__)
|
|
app.config.from_object(config_class)
|
|
|
|
db.init_app(app)
|
|
migrate.init_app(app, db)
|
|
login_manager.init_app(app)
|
|
jwt.init_app(app)
|
|
|
|
# 设置日志记录器
|
|
if not app.debug:
|
|
if not os.path.exists('logs'):
|
|
os.mkdir('logs')
|
|
file_handler = RotatingFileHandler('logs/app.log', maxBytes=10240, backupCount=10, delay=True)
|
|
file_handler.setFormatter(logging.Formatter(
|
|
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
|
|
file_handler.setLevel(logging.INFO)
|
|
app.logger.addHandler(file_handler)
|
|
|
|
app.logger.setLevel(logging.INFO)
|
|
app.logger.info('Application startup')
|
|
|
|
from app import models
|
|
from app.models import RoleTemplate, Permission
|
|
|
|
def init_database():
|
|
db.create_all()
|
|
models.UserField.init_default_fields()
|
|
models.Department.init_default_departments()
|
|
models.Department.init_default_fields()
|
|
models.RoleField.init_default_fields()
|
|
models.Role.init_default_roles()
|
|
models.PermissionField.init_default_fields()
|
|
models.Permission.init_default_permissions()
|
|
|
|
def init_role_templates():
|
|
templates = [
|
|
{
|
|
'name': '管理员',
|
|
'description': '系统管理员,拥有所有权限',
|
|
'permissions': ['用户管理', '角色管理', '部门管理', '权限管理']
|
|
},
|
|
{
|
|
'name': '普通用户',
|
|
'description': '普通用户,拥有基本权限',
|
|
'permissions': ['查看个人信息', '修改个人信息']
|
|
},
|
|
]
|
|
|
|
for template in templates:
|
|
if not RoleTemplate.query.filter_by(name=template['name']).first():
|
|
permissions = [Permission.query.filter_by(name=p).first() for p in template['permissions']]
|
|
RoleTemplate.create_template(
|
|
name=template['name'],
|
|
description=template['description'],
|
|
permissions=[p for p in permissions if p]
|
|
)
|
|
|
|
with app.app_context():
|
|
init_database()
|
|
init_role_templates()
|
|
|
|
from app.auth import bp as auth_bp
|
|
app.register_blueprint(auth_bp)
|
|
|
|
from app.departments import bp as departments_bp
|
|
app.register_blueprint(departments_bp, url_prefix='/departments')
|
|
|
|
from app.roles import bp as roles_bp
|
|
app.register_blueprint(roles_bp, url_prefix='/roles')
|
|
|
|
from app.permissions import bp as permissions_bp
|
|
app.register_blueprint(permissions_bp, url_prefix='/permissions')
|
|
|
|
from app.users import bp as users_bp
|
|
app.register_blueprint(users_bp, url_prefix='/users')
|
|
|
|
return app
|