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
Пример #2
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
Пример #3
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
Пример #4
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
Пример #5
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)
Пример #6
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
Пример #7
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
Пример #8
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
Пример #9
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
Пример #10
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
Пример #11
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
Пример #12
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
Пример #13
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)
Пример #14
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
Пример #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 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
Пример #16
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
Пример #17
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
Пример #18
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
    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
Пример #20
0
def create_app(confname='default'):
    app = Flask(__name__)
    app.logger.info("hackafake-backend server start")
    app.logger.debug("hackafake-backend server: Debug information here")
    app.config.from_object(configs[confname])

    db.init_app(app)

    JWTManager(app)
    CORS(app)
    FlaskJSON(app)

    from .apis import api
    api.init_app(app)

    return app
Пример #21
0
def create_app(config_override=None):

    app = Flask(__name__)
    app.json_encoder = JSONEncoder
    app.config.from_object(config)
    app.config.from_object(config_override)

    FlaskJSON(app)

    _api_version_prefix = '/api/{}'.format(app.config['API_VERSION']
                                           or 'v1.0').rstrip('/')
    api = Api(app, prefix=_api_version_prefix, catch_all_404s=True)

    db.init_app(app)

    redis_client.init_app(app)

    # TODO register more resources here ...

    api.add_resource(DateScheduleList,
                     '/schedules/<string:date>/<string:plan_or_real>',
                     endpoint='schedule.all.list')
    api.add_resource(
        ScheduleList,
        '/schedules/<string:date>/<string:line_no>/<string:plan_or_real>',
        endpoint='schedule.line.list')
    api.add_resource(
        Schedule,
        '/schedules/<string:date>/<string:line_no>/<string:plan_or_real>/<string:trip>',
        endpoint='schedule.line.trip')

    api.add_resource(LineConfigList,
                     '/configs/lines',
                     endpoint='configs.lines')
    api.add_resource(LineConfig,
                     '/configs/lines/<string:line_no>',
                     endpoint='configs.line')

    api.add_resource(
        SectionTripCounterResource,
        '/sections/<string:line_no>/<string:date>/<string:direction>',
        endpoint='sections.line')

    init_app_index(app, api)

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

    app.add_url_rule('/hairq',
                     view_func=GraphQLView.as_view('hairq',
                                                   schema=schema,
                                                   graphiql=True))

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

    return app
Пример #23
0
    def __init__(self, app):
        self.cors = CORS(app)
        self.talisman = Talisman(app)
        self.jwt = JWTManager(app)
        self.email_sender = EmailSender(app)
        self.email_verifier = EmailVerifier(app)
        self.json = FlaskJSON(app)
        self.img_manager = ImageManager(app)
        self.password_checker = PasswordEnforcer()
        self.scout_apm = ScoutApm(app)
        self.compressor = Compress(app)

        self.pymongo_db = pymongo.MongoClient(os.getenv('MONGO_URI'))[app.config['DATABASE_NAME']]

        self.mongo = mongo
        self.mongo.connect(host=os.getenv('MONGO_URI'))

        self.club_recommender = ClubRecommender(self.pymongo_db, f'ml-models/club-model-{CurrentConfig.MODE}.pkl')
        self.club_recommender.train_or_load_model(force_train=True)
Пример #24
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
Пример #25
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    FlaskJSON(app)

    # app.config['JSON_AS_ASCII'] = False
    app.config['SECRET_KEY'] = 'thisisasecretkey'

    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    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.from_mapping(test_config)

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

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return '<h1 style="padding: 15px;">Hello, World!<h1>'

    from . import db
    db.init_app(app)

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

    from . import query
    app.register_blueprint(query.bp)
    app.add_url_rule('/', endpoint='index')

    return app
Пример #26
0
def create_app():
    """App factory"""
    app = Flask(__name__)
    app.register_blueprint(page)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///links.db'

    @app.cli.command("create-database")
    def create_database():  # pylint: disable=unused-variable
        db.create_all(app=app)

    @app.cli.command("purge-database")
    def purge_database():  # pylint: disable=unused-variable
        for entry in Link.query.all():
            db.session.delete(entry)
        db.session.commit()
        print(len(Link.query.all()))

    db.init_app(app)
    FlaskJSON(app)
    return app
Пример #27
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)
Пример #28
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    FlaskJSON(app)
    app.secret_key = 'C3eROP6syUheoFpW66Om5IJu2EvUfOhR'
    app.register_blueprint(auth.bp)
    app.register_blueprint(home.bp)
    app.register_blueprint(category.bp)
    app.register_blueprint(item.bp)
    app.add_url_rule('/', endpoint='index')

    try:
        init_db()
    except:
        pass

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

    return app
Пример #29
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
Пример #30
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()

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

        @app.route('/tts-classify', methods=['POST'])
        @as_json
        def tts_classify():
            req_data = request.form if request.form else request.json
            req_data['req_id'] = uuid.uuid1()
            req_id = req_data['req_id']
            texts = req_data['texts']  # text list
            req_num = len(texts)
            req_time = time.time()
            req_data['req_time'] = req_time
            self.logger.debug("request %s" % (texts[0]))
            self.ready_to_classify_que.put(req_data)
            while req_id not in self.classify_res:
                continue

            if req_id in self.classify_res:
                return self.classify_res[req_id]
            else:
                return None

        # CORS(app, origins=self.args.cors)
        FlaskJSON(app)
        Compress().init_app(app)
        return app