__init__.py 4.3 KB
import decimal

from flask import Flask as _Flask
from flask.json import JSONEncoder as _JSONEncoder
from flask_cors import CORS

from sqlalchemy.sql.expression import true
import configure
from app.util import BlueprintApi
from app.util import find_class
from app.models import db
from app.modules.auth.oauth2 import config_oauth, myCodeIDToken
from flasgger import Swagger
import logging
from app.util.component.StructuredPrint import StructurePrint
from app.util.component.PGUtil import PGUtil
import os
from app.modules.monitor.schedule import start_schedule
import datetime





class JSONEncoder(_JSONEncoder):
    """
    因为decimal不能序列化,增加Flask对decimal类的解析
    """

    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(JSONEncoder, self).default(o)


class Flask(_Flask):
    json_encoder = JSONEncoder


GLOBAL_DIC = {}


def create_app():
    """
    flask应用创建函数
    :return:app,flask实例
    """

    # 上下文全局变量字典
    global GLOBAL_DIC

    # app基本设置
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = configure.SQLALCHEMY_DATABASE_URI
    app.config['echo'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['JSON_AS_ASCII'] = False
    app.config['SECRET_KEY'] = configure.SECRET_KEY
    app.config['OAUTH2_JWT_ENABLED'] = True

    app.config['OAUTH2_JWT_ISS'] = 'http://localhost:5000'
    app.config['OAUTH2_JWT_KEY'] = 'secret-key'
    app.config['OAUTH2_JWT_ALG'] = 'HS256'
    # app.config['SQLALCHEMY_ECHO'] = True
    
    # allows cookies and credentials to be submitted across domains
    app.config['CORS_SUPPORTS_CREDENTIALS'] = true
    app.config['CORS_ORIGINS ']="*"

    # 跨域设置
    CORS(app)

    # swagger设置
    swagger_config = Swagger.DEFAULT_CONFIG
    swagger_config.update(configure.swagger_configure)
    Swagger(app, config=swagger_config)

    # 创建数据库
    db.init_app(app)
    db.create_all(app=app)

    # 日志

    logging.basicConfig(level=configure.log_level)
    log_file = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "logs", "log.txt")
    handler = logging.FileHandler(log_file, encoding='UTF-8')   # 设置日志字符集和存储路径名字
    logging_format = logging.Formatter('[%(levelname)s] %(asctime)s %(message)s')
    handler.setFormatter(logging_format)

    app.logger.addHandler(handler)

    # 配置使用鉴权组件,不写无法认证授权
    config_oauth(app)

    # 注册blueprint,查找BlueprintApi的子类
    for scan in configure.scan_module:
        for api in find_class(scan, BlueprintApi):
            app.register_blueprint(api.bp)

    # 不检测https
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'


    @app.before_first_request
    def init_data():
        pass

    # start_schedule()
    return app

def create_schedule():
    monitor = Flask(__name__)
    monitor.config['SQLALCHEMY_DATABASE_URI'] = configure.SQLALCHEMY_DATABASE_URI
    monitor.config['echo'] = True
    monitor.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    monitor.config['JSON_AS_ASCII'] = False
    monitor.config['SECRET_KEY'] = configure.SECRET_KEY

    # allows cookies and credentials to be submitted across domains
    monitor.config['CORS_SUPPORTS_CREDENTIALS'] = true
    monitor.config['CORS_ORIGINS ']="*"
    
    # swagger设置
    swagger_config = Swagger.DEFAULT_CONFIG
    swagger_config.update(configure.swagger_configure)
    Swagger(monitor, config=swagger_config)
    
    # 创建数据库
    db.init_app(monitor)
    db.create_all(app=monitor)

    # 跨域设置
    CORS(monitor)

    # 日志
    logging.basicConfig(level=configure.log_level)
    log_file = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "logs", "monitor_log.txt")
    handler = logging.FileHandler(log_file, encoding='UTF-8')   # 设置日志字符集和存储路径名字
    logging_format = logging.Formatter('[%(levelname)s] %(asctime)s %(message)s')
    handler.setFormatter(logging_format)
    monitor.logger.addHandler(handler)

    # 不检测https
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    start_schedule()
    return monitor