Simple Linux Panel
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mdserver-web/web/admin/__init__.py

193 lines
5.1 KiB

7 months ago
# coding:utf-8
# ---------------------------------------------------------------------------------
# MW-Linux面板
# ---------------------------------------------------------------------------------
# copyright (c) 2018-∞(https://github.com/midoks/mdserver-web) All rights reserved.
# ---------------------------------------------------------------------------------
# Author: midoks <midoks@163.com>
# ---------------------------------------------------------------------------------
7 months ago
import os
7 months ago
import sys
7 months ago
import time
7 months ago
import uuid
import logging
from datetime import timedelta
7 months ago
from flask import Flask
from flask_socketio import SocketIO, emit, send
from flask import Flask, abort, request, current_app, session, url_for
7 months ago
from flask import Blueprint, render_template
from flask import render_template_string
7 months ago
from flask_migrate import Migrate
from werkzeug.local import LocalProxy
from admin.model import db as sys_db
7 months ago
from admin import setup
7 months ago
import core.mw as mw
6 months ago
import config
7 months ago
import utils.config as utils_config
7 months ago
7 months ago
root_dir = mw.getRunDir()
7 months ago
socketio = SocketIO(manage_session=False, async_mode='threading',
logger=False, engineio_logger=False, debug=False,
ping_interval=25, ping_timeout=120)
7 months ago
app = Flask(__name__, template_folder='templates/default')
7 months ago
7 months ago
# app.debug = True
7 months ago
# 静态文件配置
7 months ago
from whitenoise import WhiteNoise
app.wsgi_app = WhiteNoise(app.wsgi_app, root="../web/static/", prefix="static/", max_age=604800)
7 months ago
7 months ago
# session配置
app.secret_key = uuid.UUID(int=uuid.getnode()).hex[-12:]
# app.config['sessions'] = dict()
app.config['SESSION_PERMANENT'] = True
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_KEY_PREFIX'] = 'MW_:'
app.config['SESSION_COOKIE_NAME'] = "MW_VER_1"
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=31)
7 months ago
# db的配置
6 months ago
app.config['SQLALCHEMY_DATABASE_URI'] = mw.getSqitePrefix()+config.SQLITE_PATH # 使用 SQLite 数据库
7 months ago
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
7 months ago
7 months ago
7 months ago
# 初始化db
sys_db.init_app(app)
Migrate(app, sys_db)
7 months ago
7 months ago
# 检查数据库是否存在。如果没有就创建它。
setup_db_required = False
6 months ago
if not os.path.isfile(config.SQLITE_PATH):
7 months ago
setup_db_required = True
# with app.app_context():
# sys_db.create_all()
7 months ago
with app.app_context():
7 months ago
if setup_db_required:
sys_db.create_all()
7 months ago
7 months ago
# 初始化用户信息
with app.app_context():
7 months ago
if setup_db_required:
setup.init_admin_user()
setup.init_option()
7 months ago
7 months ago
# 加载模块
from .submodules import get_submodules
for module in get_submodules():
app.logger.info('Registering blueprint module: %s' % module)
if app.blueprints.get(module.name) is None:
app.register_blueprint(module)
7 months ago
7 months ago
@app.before_request
def requestCheck():
7 months ago
# print("hh")
pass
7 months ago
@app.after_request
def requestAfter(response):
6 months ago
response.headers['soft'] = config.APP_NAME
response.headers['mw-version'] = config.APP_VERSION
return response
@app.errorhandler(404)
def page_unauthorized(error):
return render_template_string('404 not found', error_info=error), 404
7 months ago
# 设置模板全局变量
@app.context_processor
def inject_global_variables():
6 months ago
ver = config.APP_VERSION;
7 months ago
if mw.isDebugMode():
ver = ver + str(time.time())
7 months ago
data = utils_config.getGlobalVar()
6 months ago
g_config = {
7 months ago
'version': ver,
7 months ago
'title' : '面板',
'ip' : '127.0.0.1'
7 months ago
}
6 months ago
return dict(config=g_config, data=data)
7 months ago
# from flasgger import Swagger
7 months ago
# api = Api(app, version='1.0', title='API', description='API 文档')
7 months ago
# Swagger(app)
# @app.route('/colors/<palette>/')
# def colors(palette):
# """
# 根据调色板名称返回颜色列表
# ---
# parameters:
# - name: palette
# in: path
# type: string
# enum: ['all', 'rgb', 'cmyk']
# required: true
# default: all
# definitions:
# Palette:
# type: object
# properties:
# palette_name:
# type: array
# items:
# $ref: '#/definitions/Color'
# Color:
# type: string
# responses:
# 200:
# description: 返回的颜色列表,可按调色板过滤
# schema:
# $ref: '#/definitions/Palette'
# examples:
# rgb: ['red', 'green', 'blue']
# """
# all_colors = {
# 'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
# 'rgb': ['red', 'green', 'blue']
# }
# if palette == 'all':
# result = all_colorselse
# result = {palette: all_colors.get(palette)}
# return jsonify(result)
7 months ago
7 months ago
# Log the startup
app.logger.info('########################################################')
6 months ago
app.logger.info('Starting %s v%s...', config.APP_NAME, config.APP_VERSION)
7 months ago
app.logger.info('########################################################')
app.logger.debug("Python syspath: %s", sys.path)
7 months ago
# OK
socketio.init_app(app, cors_allowed_origins="*")
7 months ago
# def create_app(app_name = None):
#
# if not app_name:
# app_name = config.APP_NAME
7 months ago
7 months ago
# # Check if app is created for CLI operations or Web
# cli_mode = False
# if app_name.endswith('-cli'):
# cli_mode = True
# return app