__init__.py 3.6 KB
import decimal
from re import template

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.StructurePrint import StructurePrint
from app.util.component.PGUtil import PGUtil
import os
from app.modules.monitor.schedule import start_schedule
import requests

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_TEMPLATE = {
        # "openapi": "3.0.0",
        # "components": {
        #     "securitySchemes": {
        #         "bearerAuth": {
        #             "type": "http",
        #             "scheme": "bearer",
        #             "bearerFormat": "JWT"
        #         },
        #     }
        # },
        "securityDefinitions": {
            "APIKeyHeader": {
                "type": "apiKey",
                "in": "header",
                "name": "Authorization"
            }
        },

        "security": [{
            "APIKeyHeader": []
        }
        ]
    }

    swagger_config = Swagger.DEFAULT_CONFIG
    swagger_config.update(configure.swagger_configure)

    Swagger(app, config=swagger_config,
            template=SWAGGER_TEMPLATE)

    # 创建数据库
    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 ["app.modules"]:
        for api in find_class(scan, BlueprintApi):
            app.register_blueprint(api.bp)

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

    start_schedule()
    return app