Ejemplo n.º 1
0
def create_app(config_object=DefaultConfig):

    app = Flask(__name__)

    # Add teardown_request to the app, here we ensure the db session is removed after the
    # request has been completed in any way.
    # db.session.remove will call rollback explicitly if needed
    @app.teardown_request
    def shutdown_session(exception):
        if not exception:
            db.session.commit()

        db.session.remove()

    app.config.from_object(config_object)
    app.config.from_pyfile('../config.cfg', silent=True)
    app.config.from_pyfile('../conf_wsapi.cfg', silent=True)
    app.config['JSON_SORT_KEYS'] = False

    # Configure SQLALCHEMY_DATABASE_URI for MySQL
    _uri = "mysql+pymysql://%s:%s@%s:%s/%s" % (
        app.config['DB_USER'], app.config['DB_PASS'], app.config['DB_HOST'],
        app.config['DB_PORT'], app.config['DB_NAME'])
    app.config['SQLALCHEMY_DATABASE_URI'] = _uri

    # Configure logging location and log file name
    log_file = app.config['LOGGING_LOCATION'] + "/mpwsapi.log"
    if not os.path.exists(app.config['LOGGING_LOCATION']):
        os.makedirs(app.config['LOGGING_LOCATION'])
        subprocess.call(['chmod', '2775', app.config['LOGGING_LOCATION']])

    # This config option will convert all date objects to string
    app.config['RESTFUL_JSON'] = {'default': json_serial}

    # Set default log level
    _log_level = logging.INFO

    # If app is set to debug set logging to debug
    if app.config['DEBUG']:
        app.config['LOGGING_LEVEL'] = 'debug'

    if app.config['LOGGING_LEVEL'].lower() == 'info':
        _log_level = logging.INFO
    elif app.config['LOGGING_LEVEL'].lower() == 'debug':
        _log_level = logging.DEBUG
    elif app.config['LOGGING_LEVEL'].lower() == 'warning':
        _log_level = logging.WARNING
    elif app.config['LOGGING_LEVEL'].lower() == 'error':
        _log_level = logging.ERROR
    elif app.config['LOGGING_LEVEL'].lower() == 'critical':
        _log_level = logging.CRITICAL
    else:
        _log_level = logging.INFO

    # Set and Enable Logging
    handler = logging.handlers.TimedRotatingFileHandler(log_file,
                                                        when='midnight',
                                                        interval=1,
                                                        backupCount=30)
    handler.setLevel(_log_level)  # This is needed for log rotation
    # Set log file formatting
    formatter = logging.Formatter(app.config['LOGGING_FORMAT'])
    handler.setFormatter(formatter)
    # Add handler and set app log level
    app.logger.addHandler(handler)
    app.logger.setLevel(_log_level)

    read_siteconfig_server_data(app)
    register_extensions(app)
    register_blueprints(app)
    cache.init_app(app, config={'CACHE_TYPE': 'simple'})
    return app
Ejemplo n.º 2
0
def create_app(config_object=DefaultConfig):

	app = Flask(__name__)

	# Add teardown_request to the app, here we ensure the db session is removed after the
	# request has been completed in any way.
	# db.session.remove will call rollback explicitly if needed
	@app.teardown_request
	def shutdown_session(exception):
		if not exception:
			db.session.commit()

		db.session.remove()

	app.config.from_object(config_object)
	app.config.from_pyfile('../config.cfg', silent=True)
	app.config.from_pyfile('../conf_wsapi.cfg', silent=True)
	app.config['JSON_SORT_KEYS'] = False

	# Configure SQLALCHEMY_DATABASE_URI for MySQL
	_uri = "mysql+pymysql://%s:%s@%s:%s/%s" % (app.config['DB_USER'], app.config['DB_PASS'], app.config['DB_HOST'], app.config['DB_PORT'], app.config['DB_NAME'])
	app.config['SQLALCHEMY_DATABASE_URI'] = _uri

	# Configure logging location and log file name
	log_file = app.config['LOGGING_LOCATION'] + "/mpwsapi.log"
	if not os.path.exists(app.config['LOGGING_LOCATION']):
		os.makedirs(app.config['LOGGING_LOCATION'])
		subprocess.call(['chmod', '2775', app.config['LOGGING_LOCATION']])

	# This config option will convert all date objects to string
	app.config['RESTFUL_JSON'] = {'default': json_serial}

	# Set default log level
	_log_level = logging.INFO

	# If app is set to debug set logging to debug
	if app.config['DEBUG']:
		app.config['LOGGING_LEVEL'] = 'debug'

	if app.config['LOGGING_LEVEL'].lower() == 'info':
		_log_level = logging.INFO
	elif app.config['LOGGING_LEVEL'].lower() == 'debug':
		_log_level = logging.DEBUG
	elif app.config['LOGGING_LEVEL'].lower() == 'warning':
		_log_level = logging.WARNING
	elif app.config['LOGGING_LEVEL'].lower() == 'error':
		_log_level = logging.ERROR
	elif app.config['LOGGING_LEVEL'].lower() == 'critical':
		_log_level = logging.CRITICAL
	else:
		_log_level = logging.INFO

	# Set and Enable Logging
	handler = logging.handlers.TimedRotatingFileHandler(log_file, when='midnight', interval=1, backupCount=30)
	handler.setLevel(_log_level) # This is needed for log rotation
	# Set log file formatting
	formatter = logging.Formatter(app.config['LOGGING_FORMAT'])
	handler.setFormatter(formatter)
	# Add handler and set app log level
	app.logger.addHandler(handler)
	app.logger.setLevel(_log_level)

	read_siteconfig_server_data(app)
	register_extensions(app)
	register_blueprints(app)
	cache.init_app(app, config={'CACHE_TYPE': 'simple'})
	return app
Ejemplo n.º 3
0
def create_app(config_object=DefaultConfig):

    app = Flask(__name__)

    # Add teardown_request to the app, here we ensure the db session is removed after the
    # request has been completed in any way.
    # db.session.remove will call rollback explicitly if needed
    @app.teardown_request
    def shutdown_session(exception):
        if not exception:
            db.session.commit()

        db.session.remove()

    @app.teardown_appcontext
    def teardown_appcontext(response_or_exc):
        db.session.remove()

    app.config.from_object(config_object)
    app.config.from_pyfile('../config.cfg', silent=True)
    app.config.from_pyfile('../conf_wsapi.cfg', silent=True)
    app.config['JSON_SORT_KEYS'] = False

    # Configure SQLALCHEMY_DATABASE_URI for MySQL
    _uri = "%s://%s:%s@%s:%s/%s" % (
        app.config['DB_CONNECTOR'], app.config['DB_USER'],
        app.config['DB_PASS'], app.config['DB_HOST'], app.config['DB_PORT'],
        app.config['DB_NAME'])
    app.config['SQLALCHEMY_DATABASE_URI'] = _uri
    app.config['DB_URI_STRING'] = "%s://%s@%s:%s/%s" % (
        app.config['DB_CONNECTOR'], app.config['DB_USER'],
        app.config['DB_HOST'], app.config['DB_PORT'], app.config['DB_NAME'])

    # Configure logging location and log file name
    log_file = app.config['LOGGING_LOCATION'] + "/mpwsapi.log"
    if not os.path.exists(app.config['LOGGING_LOCATION']):
        os.makedirs(app.config['LOGGING_LOCATION'])
        subprocess.call(['chmod', '2775', app.config['LOGGING_LOCATION']])

    # This config option will convert all date objects to string
    app.config['RESTFUL_JSON'] = {'default': json_serial}

    # Set default log level
    _log_level = logging.INFO

    # If app is set to debug set logging to debug
    if app.config['DEBUG']:
        app.config['LOGGING_LEVEL'] = 'debug'

    if app.config['LOGGING_LEVEL'].lower() == 'info':
        _log_level = logging.INFO
    elif app.config['LOGGING_LEVEL'].lower() == 'debug':
        _log_level = logging.DEBUG
    elif app.config['LOGGING_LEVEL'].lower() == 'warning':
        _log_level = logging.WARNING
    elif app.config['LOGGING_LEVEL'].lower() == 'error':
        _log_level = logging.ERROR
    elif app.config['LOGGING_LEVEL'].lower() == 'critical':
        _log_level = logging.CRITICAL
    else:
        _log_level = logging.INFO

    # Set and Enable Logging
    # handler = logging.handlers.TimedRotatingFileHandler(log_file, when='midnight', interval=1, backupCount=30)
    handler = logging.handlers.RotatingFileHandler(log_file,
                                                   maxBytes=10485760,
                                                   backupCount=30)
    handler.setLevel(_log_level)  # This is needed for log rotation
    # Set log file formatting
    formatter = logging.Formatter(app.config['LOGGING_FORMAT'])
    handler.setFormatter(formatter)
    # Add handler and set app log level
    app.logger.addHandler(handler)
    app.logger.setLevel(_log_level)

    read_siteconfig_server_data(app)
    register_extensions(app)
    register_blueprints(app)
    cache.init_app(app, config={'CACHE_TYPE': 'simple'})

    @app.before_request
    def only_supported_agents():
        req = request.environ
        pathInfo = req['PATH_INFO']
        if '/v1/auth/' in pathInfo or '/v1/token/' in pathInfo or '/agent/config/' in pathInfo or '/agent/update/' in pathInfo or '/agent/upload/' in pathInfo:
            app.logger.info("Bypass before_request for " + pathInfo)
        else:
            _req_agent = req['HTTP_X_AGENT_ID']
            _req_agent_ver = '0'
            if 'HTTP_X_AGENT_VER' in req:
                _req_agent_ver = req['HTTP_X_AGENT_VER']

            # Agent Ver is Less than Min Agent Ver
            if app.config['VERIFY_MIN_AGENT_VER']:
                if LooseVersion(_req_agent_ver) < LooseVersion(
                        app.config['MIN_AGENT_VER']):
                    abort(409)
                    #return {'errorno': 409, 'errormsg': 'Agent Version not accepted.', 'result': {}}, 409

    return app