示例#1
0
文件: wsgi.py 项目: chrisboyd/lokole
def _configure_flask(app: Flask):
    app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = config.APPINSIGHTS_KEY
    app.config['APPINSIGHTS_ENDPOINT_URI'] = config.APPINSIGHTS_HOST
    app.config['APPINSIGHTS_DISABLE_TRACE_LOGGING'] = True
    app.config['APPINSIGHTS_DISABLE_REQUEST_LOGGING'] = True
    AppInsights(app)

    CORS(app)
示例#2
0
def build_app(apis, host=_host, port=_port, ui=_ui):
    app = App(__name__, host=host, port=port, server='flask', options={'swagger_ui': ui})

    for api in apis:
        app.add_api(api)

    app.app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = config.APPINSIGHTS_KEY
    app.app.config['APPINSIGHTS_ENDPOINT_URI'] = config.APPINSIGHTS_HOST
    app.app.config['APPINSIGHTS_DISABLE_TRACE_LOGGING'] = True
    AppInsights(app.app)

    return app
示例#3
0
def create_app():
    app = Flask(__name__)

    env_config = Config.APP_ENV
    app.config.from_object(config[env_config])
   
   # initialize login manager
    login_manager.login_message = 'First you must sign in.'
    login_manager.login_message_category = 'danger'
    login_manager.init_app(app)

    with app.app_context():
        db.init_app(app)
        create_tables()

    # enable CSRF protection
    csrf.init_app(app)

    # enable Cross-Origin Resource Sharing
    CORS(app)
    
    #socketIO.init_app(app, cors_allowed_origins='*')

    app.config['UPLOAD_FOLDER'] = os.path.join(app.instance_path, 'storage')

    initialize_admin_api_blueprint(app)
    initialize_companies_api_blueprint(app)
    initialize_cv_platform_api_blueprint(app)
    initialize_website_api_blueprint(app)
    initialize_student_api_blueprint(app)

    # add health-check route
    @app.route('/health', methods=['GET'])
    def health():
        return jsonify(message="I am alive!")

    # set up index route
    @app.route('/', methods=['GET'])
    def index():
        return redirect(url_for('companies_api.get_company_login_form'))

    # enable azure insights integration
    appinsights = AppInsights(app)
    @app.after_request
    def after_request(response):
        appinsights.flush()
        return response

    app.app_context().push()
    return app
示例#4
0
    def init_app(self, app):
        INTEGRATIONS = ['httplib', 'sqlalchemy', 'requests']

        export_LocalForwarder = trace_exporter.TraceExporter(
            # FIXME - Move to config
            service_name=os.getenv('SERVICE_NAME', 'python-service'),
            endpoint=os.getenv('OCAGENT_TRACE_EXPORTER_ENDPOINT'),
            transport=BackgroundThreadTransport)

        tracer = tracer_module.Tracer(exporter=export_LocalForwarder,
                                      propagator=TraceContextPropagator())
        config_integration.trace_integrations(INTEGRATIONS, tracer=tracer)

        # Hookup OpenCensus to Flask
        FlaskMiddleware(app=app, exporter=export_LocalForwarder)

        # Also hookup AppInsights for logging
        AppInsights(app)
示例#5
0
    def run_flask_server(self, port, host):
        """Run the flask server."""
        app = Flask(__name__)

        if self.service_config[
                'appinsights_key'] is not None and self.service_config[
                    'service_name'] is not None:
            app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = self.service_config[
                'appinsights_key']
            # log requests, traces and exceptions to the Application Insights service
            appinsights = AppInsights(app)
            appinsights.context.cloud.role = self.service_config[
                'service_name']

        # pylint: disable=unused-variable
        @app.route('/')
        def index():
            return self.mlflow_config[
                'model_name'] + ' Model Runner Service is up.'

        @app.route('/predict', methods=['POST'])
        def get_prediction():
            request_body = request.get_json()
            latest_run = self.search_model(request_body['modelParameters'])
            if latest_run is None:
                response = json.dumps(
                    self.build_prediction_response(
                        "error", 'No successfully finished runs were found',
                        []))
            else:
                self.download_model(latest_run['info']['run_uuid'])
                model_result = self.load_and_predict(
                    latest_run['info']['run_uuid'],
                    request_body['predictionParameters'])
                response = json.dumps(
                    self.build_prediction_response("success", None,
                                                   model_result.tolist()))
            return response

        app.run(port=port, host=host)
示例#6
0
from logging import getLogger

from applicationinsights.flask.ext import AppInsights
from flask import Flask
from flask_caching import Cache
from flask_cors import CORS

app = Flask(__name__)

if __name__ != '__main__':
    gunicorn_logger = getLogger('gunicorn.error')
    app.logger.handlers = gunicorn_logger.handlers
    app.logger.setLevel(gunicorn_logger.level)

cors = CORS(app)
appinsights = AppInsights(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

import gutenberg_http.views  # noqa
    def run_flask_server(self, port, host):
        """Run the flask server."""
        app = Flask(__name__)

        if self.appinsights_key is not None and self.service_name is not None:
            app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = self.appinsights_key
            # log requests, traces and exceptions to the Application Insights service
            appinsights = AppInsights(app)
            appinsights.context.cloud.role = self.service_name

        # pylint: disable=unused-variable
        @app.route('/')
        def index():
            return 'Prediction Service is up.'

        # pylint: disable=unused-variable
        @app.route('/predict', methods=['POST'])
        def get_prediction():
            body = request.get_json()
            model_parameters = body['modelParameters']
            run_id = body.get('runId')
            model_type_name = body.get('modelType')
            if run_id is not None:
                # if run_id is not None it means we have a job that we haven't got it's results/artifacts
                # check for status of that job
                training_response = self.check_training_status(run_id)
                # if it haven't completed yet return it's current status
                if training_response.status != JobStatus.COMPLETED.value:
                    response = json.dumps(
                        #pylint: disable-msg=E1121
                        self.build_prediction_response(run_id, training_response.status,
                                                       training_response.status_message,
                                                       []))
                else:
                    model_response = self.get_prediction(body, model_type_name)
                    if model_response['status'] == 'error':
                        #pylint: disable-msg=E1121
                        response = json.dumps(self.build_prediction_response(run_id, JobStatus.ERROR.value,
                                                                             model_response['statusMessage'],
                                                                             []))
                    else:
                        response = json.dumps(
                            self.build_prediction_response(run_id, JobStatus.COMPLETED.value,
                                                           None,
                                                           model_response['result']))
            else:
                # if the run is None
                # two options are possible: first train a new model
                # second - maybe we already trained that model
                model_response = self.get_prediction(body, model_type_name)
                if model_response['status'] == 'error':
                    training_response = self.train_new_model(
                        body['modelType'], model_parameters)
                    response = json.dumps(
                        #pylint: disable-msg=E1121
                        self.build_prediction_response(training_response.run_id, training_response.status,
                                                       training_response.status_message,
                                                       []))
                else:
                    response = json.dumps(
                        self.build_prediction_response(run_id, JobStatus.COMPLETED.value,
                                                       None,
                                                       model_response['result']))

            return response

        app.run(port=port, host=host)
示例#8
0
    raise KeyError('TAPKEY_CLIENT_SECRET not found.')
if 'TAPKEY_TOKEN_ENDPOINT' not in os.environ:
    raise KeyError('TAPKEY_TOKEN_ENDPOINT not found.')
if 'TAPKEY_AUTHORIZATION_ENDPOINT' not in os.environ:
    raise KeyError('TAPKEY_AUTHORIZATION_ENDPOINT not found.')
if 'TAPKEY_BASE_URI' not in os.environ:
    raise KeyError('TAPKEY_BASE_URI not found.')

# Set the secret key to some random bytes
app.secret_key = bytearray(os.environ.get('APP_SECRET_KEY'), encoding="utf-8")

# Application Insights (required on Azure only)
if 'APPINSIGHTS_INSTRUMENTATIONKEY' in os.environ:
    app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = os.environ.get(
        'APPINSIGHTS_INSTRUMENTATIONKEY')
    AppInsights(app)


def fetch_tapkey_token():
    return session.get('auth')


oauth = OAuth(app)
oauth.register(
    'tapkey',
    client_id=os.environ.get('TAPKEY_CLIENT_ID'),
    client_secret=os.environ.get('TAPKEY_CLIENT_SECRET'),
    access_token_url=os.environ.get('TAPKEY_TOKEN_ENDPOINT'),
    access_token_params=None,
    authorize_url=os.environ.get('TAPKEY_AUTHORIZATION_ENDPOINT'),
    api_base_url=f"{os.environ.get('TAPKEY_BASE_URI')}/api/v1/",