コード例 #1
0
ファイル: __init__.py プロジェクト: Bjorn97/microblog
def create_app(config_class=ProdConfig):
    """
    Create flask app, init addons, blueprints and setup logging
    """
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    moment.init_app(app)
    bootstrap.init_app(app)

    #pylint: disable=wrong-import-position, cyclic-import
    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from app.auth import bp as auth_bp
    app.register_blueprint(auth_bp)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)
    #pylint: enable=wrong-import-position, cyclic-import

    if not app.debug and not app.testing:
        formatter = RequestFormatter(
            '[%(asctime)s %(levelname)s] %(remote_addr)s requested %(url)s\n: %(message)s [in %(module)s:%(lineno)d]'
        )
        default_handler.setFormatter(formatter)
        app.logger.setLevel(logging.INFO)

    return app
コード例 #2
0
def create_app():
    """
    This basic application will just bring up an HTTP serverself.
    Created based on flask documentation:
    https://flask.palletsprojects.com/en/1.1.x/quickstart/#a-minimal-application
    """

    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object('config.settings')
    app.config.from_pyfile('settings.py')

    app.logger.setLevel(app.config['LOG_LEVEL'])
    default_handler.setFormatter(formatter)

    app.logger.debug(app.config)
    app.register_blueprint(user)
    AuthView.register(app)
    ConfirmView.register(app)
    UsersView.register(app)

    # Initialize extentions to our app.
    db.init_app(app)
    marshmallow.init_app(app)
    jwt.init_app(app)
    mail_extension.init_app(app)

    init_jwt_callbacks(app)
    app.jinja_env.globals.update(current_user=current_user)

    return app
コード例 #3
0
 def __init__(self, 
         app = None, 
         fmt = None, 
         werkzeug = False,
         afterlog = False,
         aftermsg = 'END',
         afterlevel = INFO,
         beforelog = False,
         beforemsg = 'START',
         beforelevel = INFO,
         fmtaccesslog = FMT_ACCESS_LOG,
         enabledaccesslog = None):
     self._afterLog = afterlog
     self._afterMsg = aftermsg
     self._afterLevel = afterlevel
     self._beforeLog = beforelog
     self._beforeMsg = beforemsg
     self._beforeLevel = beforelevel
     if app is not None:
         self.init_app(app)
     if fmt is not None:
         default_handler.setFormatter(Formatter(fmt))
     if not werkzeug:
         getLogger('werkzeug').setLevel(100)
     getLogger('access.log')
     if enabledaccesslog and app.env == 'production':
         fileH = FileHandler(enabledaccesslog)
         fileH.setLevel(INFO)
         formatter = Formatter(fmtaccesslog)
         fileH.setFormatter(formatter)
         getLogger('access.log').addHandler(fileH)
     self._add_specific_log()
コード例 #4
0
def create_app(config_mode=None, config_file=None):
    app = Flask(__name__)
    app.url_map.strict_slashes = False
    cors.init_app(app)
    compress.init_app(app)

    app.config.from_object(default_settings)

    if config_mode:
        app.config.from_object(getattr(config, config_mode))
    elif config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar("APP_SETTINGS", silent=True)

    set_settings(app)

    if not app.debug:
        email_hdlr.setLevel(WARNING)
        email_hdlr.setFormatter(flask_formatter)
        app.logger.addHandler(email_hdlr)

    default_handler.setFormatter(flask_formatter)
    app.register_blueprint(housekeeping)
    check_settings(app)

    app.register_blueprint(api)
    register_rq(app)
    configure_talisman(app)
    configure_cache(app)
    app.json_encoder = CustomEncoder
    return app
コード例 #5
0
def configure_log_formatter() -> None:
    default_handler.setFormatter(
        logging.Formatter(
            "%(asctime)s %(levelname)s in [%(pathname)s:%(lineno)d]: %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
        )
    )
コード例 #6
0
def register_logging(app):
    class RequestFormatter(logging.Formatter):
        def format(self, record):
            record.url = request.url
            record.remote_addr = request.remote_addr
            return super(RequestFormatter, self).format(record)

    request_formatter = RequestFormatter(
        '[%(asctime)s] %(remote_addr)s requested %(url)s\n'
        '%(levelname)s in %(module)s: %(message)s')
    default_handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    file_handler = RotatingFileHandler(os.path.join(basedir,
                                                    'logs/bluelog.log'),
                                       maxBytes=10 * 1024 * 1024,
                                       backupCount=10)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.DEBUG)
    default_handler.setFormatter(formatter)
    mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                               fromaddr=app.config['MAIL_USERNAME'],
                               toaddrs=['ADMIN_EMAIL'],
                               subject='Bluelog Application Error',
                               credentials=(app.config['MAIL_USERNAME'],
                                            app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(request_formatter)

    if not app.debug:
        app.logger.addHandler(mail_handler)
        app.logger.addHandler(file_handler)
        app.logger.addHandler(default_handler)
コード例 #7
0
def injectLogMessage(msgIdFieldName):
    formatter = RequestFormatter(
        msgIdFieldName,
        '%(asctime)s - %(message_id)s - %(levelname)s - %(name)s - %(message)s'
    )
    default_handler.setFormatter(formatter)
    streamHandler.setFormatter(formatter)
コード例 #8
0
def initiate_app():
    """Create a Flask app
    """
    # Instantiate logger
    formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    default_handler.setFormatter(formatter)
    root_logger.addHandler(default_handler)

    # Create app instance
    app = Flask(__name__)

    # assign value to class local variable which can't be accessed directly and it can be access using Server().get_server() throughout the app
    global server_carrier
    server_carrier = Server(app)

    # now the env variables are assible using app.config.get('ENV_VAR_NAME')
    app.config.from_object("src.config.settings")

    CORS(app, supports_credentials=True)

    # attach routes using blueprints
    # attach_routes(app)
    register_blueprints(app)

    return app
コード例 #9
0
ファイル: _log.py プロジェクト: namur007/Glitch_MLS
def setup_logger():
    nw = datetime.datetime.now()
    log_file = os.path.join(".data/logs",
                            "Log_{}{}{}".format(nw.year, nw.month, nw.day))

    root = logging.getLogger()

    class RequestFormatter(Formatter):
        def format(self, record):
            if has_request_context():
                record.url = request.url
                record.remote_addr = request.environ.get(
                    'HTTP_X_FORWARDED_FOR', request.remote_addr)
            else:
                # print("no app context")
                record.url = None
                record.remote_addr = None

            return super().format(record)

    formatter = RequestFormatter(
        '[%(asctime)s]\t%(remote_addr)s requested %(url)s\t%(levelname)s\t%(module)s\t%(message)s'
    )

    default_handler.setFormatter(formatter)
    root.addHandler(default_handler)
    root.setLevel(logging.INFO)

    f_handler = logging.FileHandler(log_file)
    f_handler.setFormatter(formatter)
    f_handler.setLevel(logging.INFO)
    root.addHandler(f_handler)
コード例 #10
0
def create_app(config):

    from .mock_api import setup_blueprint as mock_api_blueprint
    from .new_api import setup_blueprint as new_api_blueprint

    default_handler.setFormatter(formatter)

    # create application instance
    app = Flask(__name__)
    app.json_encoder = CustomJSONEncoder

    # config from object
    app.config.from_object(config)

    db.init_app(app)
    RequestID(app)

    from app.resources.authentication import identity, authenticate

    jwt = JWT(app=app,
              authentication_handler=authenticate,
              identity_handler=identity)

    # repetir isso para outros modulos
    app.register_blueprint(mock_api_blueprint())
    app.register_blueprint(new_api_blueprint())

    return app
コード例 #11
0
ファイル: test.py プロジェクト: apanly/python_learn_master
 def __init__(self):
     ## 设置Job使用debug模式
     app.config['DEBUG'] = True
     logging_format = logging.Formatter(
         '%(levelname)s %(asctime)s %(filename)s:%(funcName)s L%(lineno)s %(message)s'
     )
     default_handler.setFormatter(logging_format)
コード例 #12
0
def create_logger(app):
    formatter = Formatter('[%(asctime)s] [%(filename)s:%(lineno)d] [%(levelname)s]\t%(message)s')
    default_handler.setFormatter(formatter)

    file_handler = FileHandler(app.config["LOGGING_FILE"])
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(app.config["LOGGING_LEVEL"])
コード例 #13
0
def set_app_logger(logger, log_level, log_file, log_format, **kwargs):
    '''配置flask app的logger'''
    logger.setLevel(log_level)
    formatter = RequestFormatter(log_format)
    default_handler.setFormatter(formatter)
    file_handler = logging.FileHandler(log_file)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
コード例 #14
0
def create_app(config_name):
    app = Flask(__name__)

    # Config
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Extensions
    db.init_app(app)
    auth.init_app(app=app)

    # Middleware / Wrappers
    if app.config['APP_ENABLE_PROXY_FIX']:
        ReverseProxyPrefixFix(app)
    if app.config['APP_ENABLE_REQUEST_ID']:
        RequestID(app)
    if app.config['APP_ENABLE_SENTRY']:
        sentry_sdk.init(**app.config['SENTRY_CONFIG'])

    # Logging
    formatter = RequestFormatter(
        '[%(asctime)s] [%(levelname)s] [%(request_id)s] [%(url)s]: %(message)s'
    )
    default_handler.setFormatter(formatter)
    default_handler.setLevel(app.config['LOGGING_LEVEL'])

    # Error handlers
    app.register_error_handler(BadRequest, error_handler_generic_bad_request)
    app.register_error_handler(NotFound, error_handler_generic_not_found)
    app.register_error_handler(UnprocessableEntity,
                               error_handler_generic_unprocessable_entity)
    app.register_error_handler(InternalServerError,
                               error_handler_generic_internal_server_error)

    # CLI commands
    app.cli.add_command(seeding_cli_group)
    app.cli.add_command(importing_cli_group)

    # Routes
    app.add_url_rule('/', 'index', index_route)
    app.add_url_rule('/meta/health/canary',
                     'canary_health_check',
                     healthcheck_canary_route,
                     methods=['get', 'options'])

    # Resource blueprints
    app.register_blueprint(projects_blueprint)
    app.register_blueprint(people_blueprint)
    app.register_blueprint(grants_blueprint)
    app.register_blueprint(organisations_blueprint)
    app.register_blueprint(category_schemes_blueprint)
    app.register_blueprint(category_terms_blueprint)
    app.register_blueprint(participants_blueprint)
    app.register_blueprint(allocations_blueprint)
    app.register_blueprint(categorisations_blueprint)

    return app
コード例 #15
0
    def init_app(self, app):
        werkzeug = logging.getLogger("werkzeug")
        werkzeug.disabled = True

        formatter = logging.Formatter("[%(asctime)s.%(msecs)03d] (%(levelname)s) %(message)s","%m-%d-%Y %H:%M:%S")
        default_handler.setFormatter(formatter)
        app.logger.setLevel(app.config['LOG_LEVEL'])

        app.after_request(self.cleanup)
        got_request_exception.connect(self.bailout, app)
コード例 #16
0
def create_app():
    flask_app = Flask(__name__, static_url_path='/static')
    default_handler.setFormatter(logging.Formatter(
        '[%(asctime)s] %(levelname)s in %(filename)s '
        '[%(funcName)s:%(lineno)d]: %(message)s'
    ))
    api = Api(flask_app)
    set_routing(flask_app, api)
    kazoo_conn = KazooConn.get_instance()
    kazoo_conn.create_conn(hosts='127.0.0.1:2181')
    return flask_app
コード例 #17
0
ファイル: __main__.py プロジェクト: Muhaddatha/OSBv2
def setup_logging():
    logger.setLevel(logging.INFO)
    # app.logger.removeHandler(default_handler)
    # app.logger.getLogger
    # ch = logging.StreamHandler()
    # ch.setLevel(Config.LOG_LEVEL)
    default_handler.setFormatter(
        logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    # logger.addHandler(ch)
    logger.info("setting up logging, done.")
コード例 #18
0
def setup_logging_handler() -> RotatingFileHandler:
    formatter = RequestFormatter(
        '[%(asctime)s] %(remote_addr)s requested %(url)s %(levelname)s in %(module)s: %(message)s'
    )

    file_logging_handler = RotatingFileHandler(filename="logs/flask_app.log",
                                               maxBytes=10000,
                                               encoding="utf-8")
    file_logging_handler.setFormatter(formatter)
    file_logging_handler.setLevel(logging.WARN)
    default_handler.setFormatter(formatter)
    return file_logging_handler
コード例 #19
0
def init_logger():
    """
    Utility function to initialise the logger.

    Use this to set up logging for your server.
    This should be called just after the app object is intantiated.
    """
    formatter = RequestFormatter(
        "[%(asctime)s] %(remote_addr)s requested %(url)s\n"
        "%(levelname)s in %(module)s: %(message)s")
    default_handler.setLevel(logging.INFO)
    default_handler.setFormatter(formatter)
コード例 #20
0
ファイル: __init__.py プロジェクト: kazizehsan/oneflask
def setup_logger(app):
    formatter = Formatter(
        '[%(asctime)s] %(levelname)s in %(module)s [%(pathname)s : %(lineno)d] :::: %(message)s'
    )
    default_handler.setFormatter(formatter)
    if __name__ != "__main__":
        gunicorn_logger = logging.getLogger("gunicorn.error")
        if gunicorn_logger.level:
            # When gunicorn_logger.level is greater than 0, it
            # means app was initialized through gunicorn.
            app.logger.handlers = gunicorn_logger.handlers
            app.logger.setLevel(gunicorn_logger.level)
コード例 #21
0
def create_app(config_obj=None):
    """
    Create a Flask application object.

    :param str config_obj: the path to the configuration object to use instead of calling
        load_config
    :return: a Flask application object
    :rtype: flask.Flask
    """
    app = Flask(__name__)
    if config_obj:
        app.config.from_object(config_obj)
    else:
        load_config(app)

    # Configure logging
    default_handler.setFormatter(
        logging.Formatter(fmt=app.config["CACHITO_LOG_FORMAT"], datefmt="%Y-%m-%d %H:%M:%S")
    )
    app.logger.setLevel(app.config["CACHITO_LOG_LEVEL"])
    for logger_name in app.config["CACHITO_ADDITIONAL_LOGGERS"]:
        logger = logging.getLogger(logger_name)
        logger.setLevel(app.config["CACHITO_LOG_LEVEL"])
        # Add the Flask handler that streams to WSGI stderr
        logger.addHandler(default_handler)

    # Initialize the database
    db.init_app(app)
    # Initialize the database migrations
    migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "migrations")
    Migrate(app, db, directory=migrations_dir)
    # Initialize Flask Login
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(user_loader)
    login_manager.request_loader(load_user_from_request)

    app.register_blueprint(docs)
    app.register_blueprint(api_v1, url_prefix="/api/v1")
    app.add_url_rule("/healthcheck", view_func=healthcheck)

    for code in default_exceptions.keys():
        app.register_error_handler(code, json_error)
    app.register_error_handler(CachitoError, json_error)
    app.register_error_handler(ValidationError, json_error)
    app.register_error_handler(ContentManifestError, json_error)
    app.register_error_handler(pydantic.ValidationError, validation_error)

    init_metrics(app)

    return app
コード例 #22
0
def create_app(config_obj=None):  # pragma: no cover
    """
    Create a Flask application object.

    :param str config_obj: the path to the configuration object to use instead of calling
        load_config
    :return: a Flask application object
    :rtype: flask.Flask
    """
    app = Flask(__name__)
    if config_obj:
        app.config.from_object(config_obj)
    else:
        load_config(app)

    # Validate the config
    validate_api_config(app.config)

    # Configure logging
    default_handler.setFormatter(
        logging.Formatter(fmt=app.config['IIB_LOG_FORMAT'],
                          datefmt='%Y-%m-%d %H:%M:%S'))
    app.logger.setLevel(app.config['IIB_LOG_LEVEL'])
    for logger_name in app.config['IIB_ADDITIONAL_LOGGERS']:
        logger = logging.getLogger(logger_name)
        logger.setLevel(app.config['IIB_LOG_LEVEL'])
        # Add the Flask handler that streams to WSGI stderr
        logger.addHandler(default_handler)

    # Initialize the database
    db.init_app(app)
    # Initialize the database migrations
    migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                  'migrations')
    Migrate(app, db, directory=migrations_dir)
    # Initialize Flask Login
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(user_loader)
    login_manager.request_loader(load_user_from_request)

    app.register_blueprint(docs)
    app.register_blueprint(api_v1, url_prefix='/api/v1')
    for code in default_exceptions.keys():
        app.register_error_handler(code, json_error)
    app.register_error_handler(IIBError, json_error)
    app.register_error_handler(ValidationError, json_error)
    app.register_error_handler(kombu.exceptions.KombuError, json_error)

    return app
コード例 #23
0
ファイル: dispatch.py プロジェクト: apanly/python3_jobs
    def __init__(self):
        app.config['DEBUG'] = True
        '''
        这里得考虑常驻Job,那么这个文件句柄就会被一直占用。如果日志按天设置,就会有老日志文件句柄被占
        所以这里的日志请需要使用logrotate进行切割就行了, 那就在/etc/logrotate.d/jobs配置
        '''
        log_path = self.getLogPath( "dispatch.log" )
        handler = logging.FileHandler( log_path , encoding='UTF-8')
        logging_format = logging.Formatter('%(levelname)s %(asctime)s %(filename)s:%(funcName)s L%(lineno)s %(message)s')
        handler.setFormatter(logging_format)
        app.logger.addHandler( handler )

        ##默认的还是继续输出
        default_handler.setFormatter(logging_format)
コード例 #24
0
ファイル: __init__.py プロジェクト: dasani08/flask-api
def make_app():
    from app.auth import init_app as init_auth
    from app.api import bp as api_bp
    from app.command import init_command
    app = Flask(__name__)

    app.config.from_pyfile(get_config(), silent=False)
    app.config['SQLALCHEMY_DATABASE_URI'] = get_env('SQLALCHEMY_DATABASE_URI')
    app.config['JWT_ACCESS_LIFESPAN'] = {'hours': 24}
    app.config['JWT_REFRESH_LIFESPAN'] = {'days': 30}
    app.register_error_handler(
        ApiError,
        ApiError.build_error_handler(),
    )

    RequestID(app)
    app.logger.setLevel(os.environ.get('LOG_LEVEL', logging.INFO))
    app.logger.debug('starting application')
    logging.getLogger('werkzeug').disabled = True
    # add unique request id to logger
    formatter = RequestFormatter(
        '[%(asctime)s] [%(levelname)s] [%(request_id)s] %(module)s: %(message)s'
    )
    default_handler.setFormatter(formatter)

    db.init_app(app)
    cors.init_app(app, expose_headers=['x-token'])
    migrate.init_app(app, db)

    init_command(app)
    init_auth(app)
    app.register_blueprint(api_bp)

    @app.errorhandler(werkzeug.exceptions.BadRequest)
    def handle_bad_request(e):
        return 'bad request!', 400

    @app.errorhandler(PraetorianError)
    @app.errorhandler(MissingUserError)
    @app.errorhandler(AuthenticationError)
    def handle_authen_error(e):
        app.logger.warning(e.message)
        return jsonify({
            'status': 401,
            'message': 'Username or password is incorrect'
        }), 200

    return app
コード例 #25
0
def create_app():
    # 创建flask对象, 设置静态文件路径
    flask_app = Flask(__name__, static_url_path='/static')
    # 设置日志输出格式
    default_handler.setFormatter(
        logging.Formatter('[%(asctime)s] %(levelname)s in %(filename)s '
                          '[%(funcName)s:%(lineno)d]: %(message)s'))
    # 加载restful 模块
    api = Api(flask_app)
    # 初始化路由
    set_routing(flask_app, api)
    # 初始化zookeeper连接对象
    kazoo_conn = KazooConn.get_instance()
    # 创建zookeeper连接
    kazoo_conn.create_conn(hosts='127.0.0.1:2181')
    return flask_app
コード例 #26
0
def create_app() -> Flask:
    app: Flask = Flask("demo")
    app.config["PROJECT_PATH"] = str(pathlib.Path(__file__).parent.absolute())

    # 配置日志
    format_string: str = (
        "[%(asctime)s][%(levelname)s][%(filename)s:%(lineno)d:%(funcName)s:%(request_id)s]"
        " %(message)s")
    default_handler.setFormatter(logging.Formatter(format_string))
    default_handler.addFilter(RequestIDLogFilter())

    # 加载中间件
    AccessMiddleware(app)

    # 路由函数有异常时,统一处理
    app.errorhandler(Exception)(api_exception)
    return app
コード例 #27
0
ファイル: app.py プロジェクト: pmauduit/OneTjs
def configure_logging(app):
    """Configure file(info) and email(error) logging."""

    log_format = app.config.get(
        "LOGGING_FORMAT",
        "%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
    )
    date_format = "%Y-%m-%dT%H:%M:%SZ"
    log_levels = {
        "CRITICAL": logging.CRITICAL,
        "ERROR": logging.ERROR,
        "WARNING": logging.WARNING,
        "INFO": logging.INFO,
        "DEBUG": logging.DEBUG,
        "NOTSET": logging.NOTSET,
    }

    log_formatter = logging.Formatter(log_format, date_format)
    log_level = log_levels.get(app.config["LOGGING_LEVEL"], log_levels["INFO"])

    if "LOGGING_LOCATION" in app.config:

        log_file_name = app.config["LOGGING_LOCATION"]
        parent_dir = os.path.abspath(os.path.join(log_file_name, os.pardir))

        if not os.path.exists(parent_dir):
            os.makedirs(parent_dir)

        log_handler = RotatingFileHandler(filename=log_file_name,
                                          maxBytes=10000,
                                          backupCount=5)
        log_handler.setLevel(log_level)
        log_handler.setFormatter(log_formatter)
        app.logger.addHandler(log_handler)

        app.logger.debug("Logging initialized...")
        app.logger.debug("... log file location: {}".format(
            app.config.get("LOGGING_LOCATION")))
    else:
        default_handler.setLevel(log_level)
        default_handler.setFormatter(log_formatter)
        log_handler = logging.basicConfig(stream=sys.stdout)
        app.logger.debug("Logging initialized...")
        app.logger.debug("... default flask logging handler")
コード例 #28
0
def create_app(config_name):
    app = Flask(__name__)

    # Config
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Middleware / Wrappers
    if app.config['APP_ENABLE_SENTRY']:
        sentry_sdk.init(**app.config['SENTRY_CONFIG'])
    if app.config['APP_ENABLE_CORS']:
        CORS(app, **app.config['CORS_CONFIG'])
    if app.config['APP_ENABLE_REQUEST_ID']:
        RequestID(app)

    # Logging
    class RequestFormatter(logging.Formatter):
        def format(self, record):
            record.url = 'NA'
            record.request_id = 'NA'

            if has_request_context():
                record.url = request.url
                if app.config['APP_ENABLE_REQUEST_ID']:
                    record.request_id = request.environ.get("HTTP_X_REQUEST_ID")

            return super().format(record)
    formatter = RequestFormatter(
        '[%(asctime)s] [%(levelname)s] [%(request_id)s] [%(url)s] %(module)s: %(message)s'
    )
    default_handler.setFormatter(formatter)
    default_handler.setLevel(app.config['LOGGING_LEVEL'])

    # Error handlers
    app.register_error_handler(400, error_handler_generic_bad_request)
    app.register_error_handler(404, error_handler_generic_not_found)
    app.register_error_handler(413, error_handler_request_entity_too_large)
    app.register_error_handler(500, error_handler_generic_internal_server_error)

    # App
    app.register_blueprint(meta_blueprint)
    app.register_blueprint(main_blueprint)

    return app
コード例 #29
0
 def init_app(cls, app: Flask) -> None:
     """初始化flask应用对象"""
     log_level = getenv('LOG_LEVEL') or 'INFO'
     app.logger.setLevel(log_level)
     default_handler.setLevel(log_level)
     default_handler.setFormatter(
         Formatter(
             '[%(asctime)s] %(pathname)s:%(lineno)d [%(levelname)s] %(message)s'
         ))
     app.before_request(before_app_request)
     app.teardown_request(teardown_app_request)
     app.json_encoder = CustomJSONEncoder
     sub, url = cls.BP_SUB_DOMAIN, cls.BP_URL_PREFIX
     app.register_blueprint(bp_admin_api,
                            subdomain=sub.get('admin'),
                            url_prefix=url.get('admin_api'))
     app.register_blueprint(bp_admin_ext,
                            subdomain=sub.get('admin'),
                            url_prefix=url.get('admin_ext'))
コード例 #30
0
def create_app(config_obj=None):  # pragma: no cover
    """
    Create a Flask application object.

    :param str config_obj: the path to the configuration object to use instead of calling
        load_config
    :return: a Flask application object
    :rtype: flask.Flask
    """
    app = Flask("plant_wn")
    if config_obj:
        app.config.from_object(config_obj)
    else:
        load_config(app)
        # Validate the config
        validate_api_config(app.config)

    # Configure logging
    default_handler.setFormatter(
        logging.Formatter(fmt=app.config["PLANT_WN_LOG_FORMAT"],
                          datefmt="%Y-%m-%d %H:%M:%S"))
    app.logger.setLevel(app.config["PLANT_WN_LOG_LEVEL"])
    for logger_name in app.config["PLANT_WN_ADDITIONAL_LOGGERS"]:
        logger = logging.getLogger(logger_name)
        logger.setLevel(app.config["PLANT_WN_LOG_LEVEL"])
        # Add the Flask handler that streams to WSGI stderr
        logger.addHandler(default_handler)

    # Initialize the database
    db.init_app(app)
    # Initialize the database migrations
    migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                  "migrations")
    Migrate(app, db, directory=migrations_dir)
    # Initialize JSON web token support
    JWTManager(app)

    app.register_blueprint(api_v1, url_prefix="/api/v1")
    for code in default_exceptions.keys():
        app.register_error_handler(code, json_error)
    app.register_error_handler(AppError, json_error)

    return app
コード例 #31
0
ファイル: thumbservice.py プロジェクト: LCOGT/thumbservice
from fits_align.ident import make_transforms
from fits_align.align import affineremap

from common import settings, get_temp_filename_prefix


app = Flask(__name__, static_folder='static')
CORS(app)

class RequestFormatter(logging.Formatter):
    def format(self, record):
        record.url = request.url
        return super().format(record)

formatter = RequestFormatter('[%(asctime)s] %(levelname)s in %(module)s for %(url)s: %(message)s')
default_handler.setFormatter(formatter)


class ThumbnailAppException(Exception):
    status_code = 500

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        result = dict(self.payload or ())
        result['message'] = self.message