Пример #1
0
def create_app_test():
    app = Flask(__name__,
                template_folder='../Views/templates',
                static_url_path='',
                static_folder='../Views/static')
    json = FlaskJSON()
    cors = CORS(resources={r"/api/*": {
        "origins": "*"
    }},
                allow_headers=[
                    "Content-Type", "Accept", "X-Request-With",
                    "access-control-allow-origin",
                    "Access-Control-Allow-Credentials"
                ],
                supports_credentials=True)
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
    app.config['MONGODB_SETTINGS'] = {
        'db': os.environ.get('MONGO_TEST_NAME'),
        'host': os.environ.get('MONGO_TEST_URI')
    }
    app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
    mongo.init_app(app)
    # app.config['SESSION_COOKIE_HTTPONLY'] = True
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=60)
    json.init_app(app)
    cors.init_app(app)
    app.register_blueprint(main)
    app.register_blueprint(diagnosis_controller)
    app.register_blueprint(patients_controller)
    app.register_blueprint(visualisation_controller)
    return app
Пример #2
0
def test_decorators():
    app = Flask(__name__)
    ext = FlaskJSON()

    @ext.error_handler
    def err_handler_func():
        pass

    @ext.invalid_json_error
    def decoder_func():
        pass

    @ext.encoder
    def encoder_func():
        pass

    assert_equals(ext._error_handler_func, err_handler_func)
    assert_equals(ext._decoder_error_func, decoder_func)

    # If FlaskJSON is not initialized with the app then only
    # '_encoder_class' will be set.
    assert_is_not_none(ext._encoder_class)
    assert_is_not(app.json_encoder, ext._encoder_class)

    # And after initialization we set our json encoder.
    ext.init_app(app)
    assert_is(app.json_encoder, ext._encoder_class)
Пример #3
0
def test_decorators():
    app = Flask(__name__)
    ext = FlaskJSON()

    @ext.error_handler
    def err_handler_func():
        pass

    @ext.invalid_json_error
    def decoder_func():
        pass

    @ext.encoder
    def encoder_func():
        pass

    assert ext._error_handler_func == err_handler_func
    assert ext._decoder_error_func == decoder_func

    # If FlaskJSON is not initialized with the app then only
    # '_encoder_class' will be set.
    assert ext._encoder_class is not None
    assert app.json_encoder is not ext._encoder_class

    # And after initialization we set our json encoder.
    ext.init_app(app)
    assert app.json_encoder is ext._encoder_class
Пример #4
0
def test_decorators():
    app = Flask('testapp')
    ext = FlaskJSON()

    @ext.error_handler
    def err_handler_func():
        pass

    @ext.invalid_json_error
    def decoder_func():
        pass

    @ext.encoder
    def encoder_func():
        pass

    assert ext._error_handler_func == err_handler_func
    assert ext._decoder_error_func == decoder_func

    # If FlaskJSON is not initialized with the app then only
    # '_encoder_class' will be set.
    assert ext._encoder_class is not None
    assert app.json_encoder is not ext._encoder_class

    # And after initialization we set our json encoder.
    ext.init_app(app)
    assert app.json_encoder is ext._encoder_class
Пример #5
0
    def create_flask_app():
        app = Flask(__name__)
        app.config['JSON_AS_ASCII'] = False

        @as_json
        @app.route("/", methods=['POST'])
        def post():
            try:
                data = request.form if request.form else request.json
                if request.method == "POST":
                    message = Updater(**dict(data))
                    print('му тут')
                    stage.next(message)
                    print('а теперь тут')
                    return "ok"
            except Exception as e:
                print(e)
                abort(404)

        @app.route("/health_status", methods=['GET'])
        def health():
            return "status ok"

        FlaskJSON(app)
        return app
Пример #6
0
def create_app(test_config=None):
    """Create and configure an instance of the Flask application."""
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        # a default secret that should be overridden by instance config
        SECRET_KEY='dev',
        JSON_ADD_STATUS=False,
        THREADED=True,
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.update(test_config)

    # initialize Flask JSON
    FlaskJSON(app)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # apply the blueprints to the app
    from api import root
    app.register_blueprint(root.BP)

    return app
Пример #7
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py', silent=True)
    app.jinja_env.globals['get_resource_as_string'] = get_resource_as_string
    if app.config.get('DEBUG'):
        from flask_cors import CORS
        CORS(app)  # enable for development (allow localhost)
    FlaskJSON(app)
    Logging(app)
    Marshmallow(app)
    db = MongoEngine(app)
    swagger = Swagger(app, template=app.config.get('TEMPLATE'))
    collections = get_collections(db)

    for collection in collections:
        module_path = '.'.join(['mpcontribs', 'api', collection, 'views'])
        try:
            module = import_module(module_path)
        except ModuleNotFoundError:
            logger.warning('API module {} not found!'.format(module_path))
            continue
        try:
            blueprint = getattr(module, collection)
            app.register_blueprint(blueprint, url_prefix='/' + collection)
        except AttributeError as ex:
            logger.warning('Failed to register blueprint {}: {}'.format(
                module_path, collection, ex))

    return app
Пример #8
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    FlaskJSON(app)
    try:
        env = os.environ['FLASK_ENV']
    except KeyError:
        env = 'development'
    try:
        app.config.from_object('config.{}Config'.format(env.capitalize()))
    except ImportError:
        pass

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    try:
        if not os._exists:
            os.makedirs(app.instance_path)
    except OSError:
        pass

    db.init_app(app)
    app.register_blueprint(auth.bp)
    # app.register_blueprint(blog.bp)
    app.register_blueprint(graph.bp)
    app.add_url_rule('/', endpoint='index')

    @app.route('/hello')
    @as_json
    def hello():
        return dict(name='Arun', age=31)

    return app
def theapp(app):
    # Enable feature
    app.config['JSON_JSONIFY_HTTP_ERRORS'] = True
    # set raise to result in 500 error
    app.config["PROPAGATE_EXCEPTIONS"] = False
    FlaskJSON(app)
    return app
Пример #10
0
    def create_flask_app(self):
        try:
            from flask import Flask, request
            from flask_compress import Compress
            from flask_cors import CORS
            from flask_json import FlaskJSON, as_json, JsonError
        except ImportError:
            raise ImportError('Flask or its dependencies are not fully installed, '
                              'they are required for serving HTTP requests.')

        app = Flask(__name__)
        app.config.update(DEBUG=False)
        #print("configged")

        @app.route('/methodCore', methods=['POST', 'GET'])
        @as_json
        def encode_query():
            data = request.form if request.form else request.json
            if type(data)==str:
                data=json.loads(data)
            logger.info("******in service:{}, new request from {}******\nquery data--->{}".format(
                self.args.ServiceName, request.remote_addr, json.dumps(data)[:50]+"... ...")
                )
            try:
                return self.processCore(data)
            except Exception as e:
                logger.error('error when handling HTTP request', exc_info=True)
                raise JsonError(description=str(e), type=str(type(e).__name__))

        #print("wrappering")
        CORS(app, origins=self.args.cors)
        FlaskJSON(app)
        Compress().init_app(app)
        return app
    def create_flask_app(self):
        self.logger.info("Started Sentiment Server...")

        self.logger.info("Prepare Flask app...")
        app = Flask(__name__)

        @app.route("/sentiment", methods=["GET", "POST"])
        @as_json
        def sentiment():
            try:
                if request.method == "POST":
                    data = request.form if request.form else request.json
                    query = data["query"]
                else:
                    query = request.args.get("query")

                self.logger.info(
                    "Received {} `sentiment` request from {}".format(
                        request.method, request.remote_addr))

                positive_proba = float(self.model([query])[0])
                return {'positive_proba': positive_proba}

            except Exception as e:
                self.logger.error('error when handling HTTP request',
                                  exc_info=True)
                raise JsonError(description=str(e), type=str(type(e).__name__))

        FlaskJSON(app)
        return app
Пример #12
0
def create_app(config_name):
    app = Flask(__name__)
    CORS(app)
    FlaskJSON(app)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    mail.init_app(app)

    app.add_url_rule(
        '/mrm',
        view_func=GraphQLView.as_view(
            'mrm',
            schema=schema,
            graphiql=True   # for having the GraphiQL interface
        )
    )
    app.add_url_rule(
        '/_healthcheck',
        view_func=GraphQLView.as_view(
            '_healthcheck',
            schema=healthcheck_schema,
            graphiql=True   # for healthchecks
        )
    )

    @app.route("/analytics", methods=['POST'])
    @Auth.user_roles('Admin', 'REST')
    def analytics_report():
        return AnalyticsRequest.validate_request(AnalyticsRequest)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()

    return app
Пример #13
0
def create_app():
    app = Flask(__name__, static_url_path='/static')
    FlaskJSON(app)
    create_config(app)
    create_assets(app)
    create_routes(app)
    return app
Пример #14
0
 def _register_json(self):
     """
     Method that registers a new json object, and a new app if the latter
     does not exist.
     :return: None
     """
     app = self.get_app()
     self.__class__.json = FlaskJSON(app)
Пример #15
0
    def create_flask_app(self):
        try:
            from flask import Flask, request
            from flask_compress import Compress
            from flask_cors import CORS
            from flask_json import FlaskJSON, as_json, JsonError
            from myClient import ConcurrentBertClient
            # from bert_base.client import ConcurrentBertClient
        except ImportError:
            raise ImportError(
                'BertClient or Flask or its dependencies are not fully installed, '
                'they are required for serving HTTP requests.'
                'Please use "pip install -U bert-serving-server[http]" to install it.'
            )

        # support up to 10 concurrent HTTP requests
        bc = ConcurrentBertClient(max_concurrency=self.args.http_max_connect,
                                  port=self.args.port,
                                  port_out=self.args.port_out,
                                  output_fmt='list',
                                  mode=self.args.mode)
        app = Flask(__name__)
        logger = set_logger(colored('PROXY', 'red'))

        @app.route('/status/server', methods=['GET'])
        @as_json
        def get_server_status():
            return bc.server_status

        @app.route('/status/client', methods=['GET'])
        @as_json
        def get_client_status():
            return bc.status

        @app.route('/encode', methods=['POST'])
        @as_json
        def encode_query():
            data = request.form if request.form else request.json
            try:
                logger.info('new request from %s' % request.remote_addr)
                print(data)
                return {
                    'id':
                    data['id'],
                    'result':
                    bc.encode(data['texts'],
                              is_tokenized=bool(data['is_tokenized'])
                              if 'is_tokenized' in data else False)
                }

            except Exception as e:
                logger.error('error when handling HTTP request', exc_info=True)
                raise JsonError(description=str(e), type=str(type(e).__name__))

        CORS(app, origins=self.args.cors)
        FlaskJSON(app)
        Compress().init_app(app)
        return app
Пример #16
0
def create_app():
    app = Flask(__name__)
    FlaskJSON(app)
    app.db = FakeDB()
    app.config['SECRET_KEY'] = 'secret_ket'

    from main_endpoints import main_bp
    app.register_blueprint(main_bp)

    return app
Пример #17
0
def create_app(testing_config=None):
    """Create and configure an instance of the Flask application."""
    app = Flask(__name__, instance_relative_config=True)

    if testing_config is not None:              # pragma: no cover
        app_config = config.TestingConfig(app)
    elif app.config["ENV"] == "production":     # pragma: no cover
        app_config = config.ProductionConfig(app)
    else:                                       # pragma: no cover
        app_config = config.DevelopmentConfig(app)

    app.config.from_object(app_config)

    Session(app)

    FlaskJSON(app)
    CORS(app, origins=app.config["CORS_ALLOWED_ORIGINS"],
         supports_credentials=True,
         )

    socketio = SocketIO(
        app,
        manage_session=False,
        engineio_logger=app.config["SOCKETIO_LOGGER"],
        cors_allowed_origins=app.config["CORS_ALLOWED_ORIGINS"],
        cors_credentials=True)

    if testing_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # load the test config
        app.config.update(testing_config)


    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # init database here when app's config is ready
    database.db.init_app(app)
    database.migrate.init_app(app, database.db)

    # init and register authentication helpers
    auth.init_app(app)

    # api handlers
    api.register_all(app)

    # websockets handlers
    ws.register_all(socketio)

    return app
Пример #18
0
def create_app():
    start = time.time()

    main_run = is_main_run()

    # create and configure the app
    app = Flask(__name__)
    app.config.from_object(os.environ.get(
        'APP_SETTINGS', "facial_beauty_predictor.server.config.Config"))

    if main_run:
        logging.info("Creating app with config:\n" +
                     '\n'.join("    {}: {}".format(k, v)
                               for k, v in app.config.items()))

    if main_run:
        app.errorhandler(Exception)(_on_exception)

        # if app.config["LOG_METRICS"]:
        #     metrics.init_app(app)
        #     request_check.init_app(app)

        fetch_files(app)
        app.config["PERCENTILE_QUEUES"] = {}
        img_paths_queue = init_worker(app)
        app.config["IMG_PATHS_QUEUE"] = img_paths_queue

        json = FlaskJSON()
        json.init_app(app)

        init_app(app)

        if not app.config["DEBUG"]:
            sentry_sdk.init(
                dsn="https://[email protected]/1785265",
                integrations=[FlaskIntegration()],
            )

        logging.info("App initialization done. Took {0:.1f}s".format(
            time.time() - start))

    return app
Пример #19
0
def test_decorators_initialized():
    app = Flask('testapp')
    ext = FlaskJSON(app)

    @ext.invalid_json_error
    def decoder_func():
        pass

    # If we apply decorator on initialized extension then it sets
    # encoder class immediately.
    assert app.json_encoder is ext._encoder_class
Пример #20
0
def test_init_deferred():
    app = Flask('testapp')

    # Check if we correctly handle this.
    # Well actually it's to increase test coverage.
    del app.extensions

    ext = FlaskJSON()
    ext.init_app(app)

    assert app.config.get('JSON_ADD_STATUS') == True
    assert app.config.get('JSON_DATE_FORMAT') is None
    assert app.config.get('JSON_TIME_FORMAT') is None
    assert app.config.get('JSON_DATETIME_FORMAT') is None
    assert app.config.get('JSON_DECODE_ERROR_MESSAGE') == 'Not a JSON.'
    assert app.request_class is JsonRequest
    # No testing response class on production.
    assert app.response_class is not JsonTestResponse
    assert app.json_encoder is JSONEncoderEx
    assert app.extensions['json'] == ext
Пример #21
0
def test_init_deferred():
    app = Flask(__name__)

    # Check if we correctly handle this.
    # Well actually it's to increase test coverage.
    del app.extensions

    ext = FlaskJSON()
    ext.init_app(app)

    assert_equals(app.config.get('JSON_ADD_STATUS'), True)
    assert_is_none(app.config.get('JSON_DATE_FORMAT'))
    assert_is_none(app.config.get('JSON_TIME_FORMAT'))
    assert_is_none(app.config.get('JSON_DATETIME_FORMAT'))
    assert_equals(app.config.get('JSON_DECODE_ERROR_MESSAGE'), 'Not a JSON.')
    assert_is(app.request_class, JsonRequest)
    # No testing response class on production.
    assert_is_not(app.response_class, JsonTestResponse)
    assert_is(app.json_encoder, JSONEncoderEx)
    assert_equals(app.extensions['json'], ext)
Пример #22
0
def test_init_deferred():
    app = Flask(__name__)

    # Check if we correctly handle this.
    # Well actually it's to increase test coverage.
    del app.extensions

    ext = FlaskJSON()
    ext.init_app(app)

    assert app.config.get('JSON_ADD_STATUS') == True
    assert app.config.get('JSON_DATE_FORMAT') is None
    assert app.config.get('JSON_TIME_FORMAT') is None
    assert app.config.get('JSON_DATETIME_FORMAT') is None
    assert app.config.get('JSON_DECODE_ERROR_MESSAGE') == 'Not a JSON.'
    assert app.request_class is JsonRequest
    # No testing response class on production.
    assert app.response_class is not JsonTestResponse
    assert app.json_encoder is JSONEncoderEx
    assert app.extensions['json'] == ext
Пример #23
0
def our_app():
    app = Flask(__name__)
    app.test_value = 0
    FlaskJSON(app)

    @app.route('/increment')
    def increment():
        app.test_value += 1
        return json_response(value=app.test_value)

    return app
Пример #24
0
	def create_flask_app(self):
		from flask import Flask, request
		from flask_compress import Compress
		from flask_cors import CORS
		from flask_json import FlaskJSON, as_json, JsonError
		from medtype_serving.client import ConcurrentMedTypeClient

		logger = set_logger(colored('PROXY', 'red'))

		self.bc  = None
		app = Flask(__name__)
		app.config['SWAGGER'] = {
		  'title': 'Colors API',
		  'uiversion': 3,
		  'openapi': '3.0.2'
		}

		@app.route('/status/server', methods=['GET'])
		@as_json
		def get_server_status():
			if self.bc is None:
				self.bc = ConcurrentMedTypeClient(max_concurrency=self.args.http_max_connect, port=self.args.port, port_out=self.args.port_out)
			return self.bc.server_status

		@app.route('/status/client', methods=['GET'])
		@as_json
		def get_client_status():
			if self.bc is None:
				self.bc = ConcurrentMedTypeClient(max_concurrency=self.args.http_max_connect, port=self.args.port, port_out=self.args.port_out)
			return self.bc.status

		@app.route('/run_linker', methods=['POST', 'GET'])
		@as_json
		def encode_query():
		# support up to 10 concurrent HTTP requests
			if self.bc is None:
				self.bc = ConcurrentMedTypeClient(max_concurrency=self.args.http_max_connect, port=self.args.port, port_out=self.args.port_out)

			data = request.form if request.form else request.json
			try:
				logger.info('new request from %s' % request.remote_addr)
				if data is None or 'data' not in data:
					return {'id': 1, 'result': 'Sever accessible :)! Please go back to the demo page.'}
				else:
					return {'id': data['id'], 'result': self.bc.run_linker(data['data'])}

			except Exception as e:
				logger.error('error when handling HTTP request', exc_info=True)
				raise JsonError(description=str(e), type=str(type(e).__name__))

		CORS(app, origins=self.args.cors)
		FlaskJSON(app)
		Compress().init_app(app)
		return app
Пример #25
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    db.init_app(app)
    jwt.init_app(app)
    FlaskJSON(app)
    redis_client.init_app(app)

    from .flash_card import flash_card as flash_card_blueprint
    app.register_blueprint(flash_card_blueprint, url_prefix='/flash_card')
    # app.wsgi_app = Middleware(app.wsgi_app)
    return app
Пример #26
0
def test_init_constructor():
    app = Flask(__name__)
    ext = FlaskJSON(app)

    assert_equals(app.config.get('JSON_ADD_STATUS'), True)
    assert_is_none(app.config.get('JSON_DATE_FORMAT'))
    assert_is_none(app.config.get('JSON_TIME_FORMAT'))
    assert_is_none(app.config.get('JSON_DATETIME_FORMAT'))
    assert_equals(app.config.get('JSON_DECODE_ERROR_MESSAGE'), 'Not a JSON.')
    assert_is(app.request_class, JsonRequest)
    assert_is(app.json_encoder, JSONEncoderEx)
    assert_equals(app.extensions['json'], ext)
Пример #27
0
def test_init_constructor():
    app = Flask('testapp')
    ext = FlaskJSON(app)

    app.config.get('JSON_ADD_STATUS') == True
    assert app.config.get('JSON_DATE_FORMAT') is None
    assert app.config.get('JSON_TIME_FORMAT') is None
    assert app.config.get('JSON_DATETIME_FORMAT') is None
    assert app.config.get('JSON_DECODE_ERROR_MESSAGE') == 'Not a JSON.'
    assert app.request_class is JsonRequest
    assert app.json_encoder is JSONEncoderEx
    assert app.extensions['json'] == ext
Пример #28
0
    def create_flask_app(self):
        try:
            from flask import Flask, request
            from flask_compress import Compress
            from flask_cors import CORS
            from flask_json import FlaskJSON, as_json, JsonError
            from alpaca_client.alpaca_serving import ConcurrentAlpacaClient
        except ImportError:
            raise ImportError('client is not installed')

        # support up to 10 concurrent HTTP requests
        ac = ConcurrentAlpacaClient(max_concurrency=self.args.http_max_connect,
                                    port=self.args.port,
                                    port_out=self.args.port_out,
                                    output_fmt='list',
                                    ignore_all_checks=True)
        app = Flask(__name__)
        logger = set_logger(colored('PROXY', 'red'))

        @app.route('/status/server', methods=['GET'])
        @as_json
        def get_server_status():
            return ac.server_status

        @app.route('/status/client', methods=['GET'])
        @as_json
        def get_client_status():
            return ac.status

        @app.route('/encode', methods=['POST'])
        @as_json
        def encode_query():
            data = request.form if request.form else request.json
            try:
                logger.info('new request from %s' % request.remote_addr)
                return {
                    'id':
                    data['id'],
                    'result':
                    ac.encode(data['texts'],
                              is_tokenized=bool(data['is_tokenized'])
                              if 'is_tokenized' in data else False)
                }

            except Exception as e:
                logger.error('error when handling HTTP request', exc_info=True)
                raise JsonError(description=str(e), type=str(type(e).__name__))

        CORS(app, origins=self.args.cors)
        FlaskJSON(app)
        Compress().init_app(app)
        return app
Пример #29
0
def create_app(config_name):
    app = Flask(__name__)
    CORS(app)
    FlaskJSON(app)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    mail.init_app(app)

    @app.route("/", methods=['GET'])
    def index():
        return render_template('index.html')

    @app.route("/logs", methods=['GET'])
    @Auth.user_roles('Super Admin', 'REST')
    def logs():
        response = None
        log_file = 'mrm.err.log'
        try:
            open(log_file)  # trigger opening of file
            response = Response(read_log_file(log_file), mimetype='text')
        except FileNotFoundError:  # pragma: no cover
            message = 'Log file was not found'
            response = Response(message, mimetype='text', status=404)
        return response

    app.add_url_rule(
        '/mrm',
        view_func=GraphQLView.as_view(
            'mrm',
            schema=schema,
            graphiql=True   # for having the GraphiQL interface
        )
    )
    app.add_url_rule(
        '/_healthcheck',
        view_func=GraphQLView.as_view(
            '_healthcheck',
            schema=healthcheck_schema,
            graphiql=True   # for healthchecks
        )
    )

    @app.route("/analytics", methods=['POST'])
    @Auth.user_roles('Admin', 'REST')
    def analytics_report():
        return AnalyticsRequest.validate_request(AnalyticsRequest)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()

    return app
Пример #30
0
def create_app(conf_name = 'default'):
	app = Flask(__name__)
	app.config.from_object(configs[conf_name])

	FlaskJSON(app)
	db.init_app(app)
	CORS(app)

	from .main import main as main_bp
	app.register_blueprint(main_bp)
	
	from .ros import ros as ros_bp
	app.register_blueprint(ros_bp)

	return app
Пример #31
0
def create_app():
    app = Flask(__name__)
    FlaskJSON(app)
    json = FlaskJSON()
    app.config.from_object(os.environ['APP_SETTINGS'])

    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    if app.debug == True:
        try:
            from flask_debugtoolbar import DebugToolbarExtension
            toolbar = DebugToolbarExtension(app)
        except:
            pass

    import app.entity.controllers as entity
    import app.general.controllers as general

    app.register_blueprint(general.module)
    app.register_blueprint(entity.module)

    return app
    def create_flask_app(self):
        self.logger.info("Started Intent Classifier Server...")

        self.logger.info("Prepare Flask app...")
        app = Flask(__name__)

        @app.route("/predict", methods=["POST"])
        @as_json
        def predict():
            data = request.form if request.form else request.json

            try:
                model_id = int(data["model_id"])
                query = data["query"]

                self.logger.info("Received {} request from {}".format(
                    request.method, request.remote_addr))
                self.logger.info("Received model id: {}".format(model_id))

                if model_id in self.models:
                    model = self.models[model_id]
                else:
                    model = self.load_model(model_id)
                    self.models[model_id] = model

                model_answer = sorted_labels(model([query]))[0]
                output = [{
                    "answer": label,
                    "probability": probability,
                    "threshold": 0.3,
                    "accuracy_score": None
                } for label, probability in model_answer]

                self.logger.info('Received query: {}'.format(query))
                self.logger.info("Top predicted label: {}".format(
                    output[0]['answer']))
                self.logger.info("Max probability: {}".format(
                    output[0]['probability']))

                return output

            except Exception as e:
                self.logger.error('error when handling HTTP request',
                                  exc_info=True)
                raise JsonError(description=str(e), type=str(type(e).__name__))

        FlaskJSON(app)
        return app