Ejemplo n.º 1
0
def create_app() -> Flask:
    app = Flask(__name__)
    # SimpleLogin is deployed behind NGINX
    app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)
    limiter.init_app(app)

    app.url_map.strict_slashes = False

    app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    # enable to print all queries generated by sqlalchemy
    # app.config["SQLALCHEMY_ECHO"] = True

    app.secret_key = FLASK_SECRET

    app.config["TEMPLATES_AUTO_RELOAD"] = True

    # to avoid conflict with other cookie
    app.config["SESSION_COOKIE_NAME"] = "slapp"
    if URL.startswith("https"):
        app.config["SESSION_COOKIE_SECURE"] = True
    app.config["SESSION_COOKIE_SAMESITE"] = "Lax"

    setup_error_page(app)

    init_extensions(app)
    register_blueprints(app)
    set_index_page(app)
    jinja2_filter(app)

    setup_favicon_route(app)
    setup_openid_metadata(app)

    init_admin(app)
    setup_paddle_callback(app)
    setup_do_not_track(app)

    if FLASK_PROFILER_PATH:
        LOG.d("Enable flask-profiler")
        app.config["flask_profiler"] = {
            "enabled": True,
            "storage": {"engine": "sqlite", "FILE": FLASK_PROFILER_PATH},
            "basicAuth": {
                "enabled": True,
                "username": "******",
                "password": FLASK_PROFILER_PASSWORD,
            },
            "ignore": ["^/static/.*", "/git", "/exception"],
        }
        flask_profiler.init_app(app)

    return app
Ejemplo n.º 2
0
def setup_api_app():
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)
    print ">>> run api server, use", config.__name__

    mail.init_app(app)
    db.init_app(app)
    init_celery(app)

    from api import api as main_blueprint
    app.register_blueprint(main_blueprint)
    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
    flask_profiler.init_app(app)
    return app
Ejemplo n.º 3
0
def setup_dashboard_app():
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)
    print ">>> run dashboard server, use", config.__name__

    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    init_celery(app)

    from dashboard import dashboard as admin_blueprint
    app.register_blueprint(admin_blueprint)
    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
    flask_profiler.init_app(app)
    return app
Ejemplo n.º 4
0
def init_app(app):
    app.config["flask_profiler"] = {
        "enabled": config.PROFILER['enabled'],
        "storage": {
            "engine": "sqlite"
        },
        "endpointRoot": "profiler",
        "basicAuth":{
            "enabled": bool(config.PROFILER['password']),
            "username": config.PROFILER['username'],
            "password": config.PROFILER['password']
        },
        "ignore": [
            "^/static/.*"
        ]
    }
    flask_profiler.init_app(app)
Ejemplo n.º 5
0
def create_app() -> Flask:
    app = Flask(__name__)
    app.url_map.strict_slashes = False

    app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.secret_key = FLASK_SECRET

    app.config["TEMPLATES_AUTO_RELOAD"] = True

    # to avoid conflict with other cookie
    app.config["SESSION_COOKIE_NAME"] = "slapp"

    init_extensions(app)
    register_blueprints(app)
    set_index_page(app)
    jinja2_filter(app)

    setup_error_page(app)

    setup_favicon_route(app)
    setup_openid_metadata(app)

    init_admin(app)
    setup_paddle_callback(app)
    setup_do_not_track(app)

    if FLASK_PROFILER_PATH:
        LOG.d("Enable flask-profiler")
        app.config["flask_profiler"] = {
            "enabled": True,
            "storage": {
                "engine": "sqlite",
                "FILE": FLASK_PROFILER_PATH
            },
            "basicAuth": {
                "enabled": True,
                "username": "******",
                "password": FLASK_PROFILER_PASSWORD,
            },
            "ignore": ["^/static/.*", "/git", "/exception"],
        }
        flask_profiler.init_app(app)

    return app
Ejemplo n.º 6
0
def setup_profiler(app):
    profiler = app.config['POLYSWARMD'].profiler
    if not profiler.enabled:
        return

    if profiler.db_uri is None:
        logger.error('Profiler enabled but no db configured')
        return

    app.config['flask_profiler'] = {
        'enabled': True,
        'measurement': True,
        'gui': False,
        'storage': {
            'engine': 'sqlalchemy',
            'db_url': profiler.db_uri,
        },
    }

    flask_profiler.init_app(app)
Ejemplo n.º 7
0
def create_app(config_name, updated_variables=None):
    # Config
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    if updated_variables:
        app.config.update(updated_variables)

    config[config_name].init_app(app)

    context = app.app_context()
    context.push()

    # Blueprints
    from monolith.views import blueprints
    from monolith.views.errors import handlers

    app.url_map.strict_slashes = False
    for bp in blueprints:
        app.register_blueprint(bp)
        bp.app = app

    for handler in handlers:
        app.register_error_handler(handler[0], handler[1])

    # Services
    celery.conf.update(app.config)
    es_url = app.config["ELASTICSEARCH_URL"]
    app.elasticsearch = Elasticsearch([es_url]) if es_url else None

    mail.init_app(app)
    db.init_app(app)
    db.create_all(app=app)
    redis_client.init_app(app)
    login_manager.init_app(app)
    dropzone.init_app(app)

    # Debug
    flask_profiler.init_app(app)

    return app
Ejemplo n.º 8
0
def register_profiler(app):
    config = app.config

    if not config.get("PROFILER_ENABLE"):
        return

    password = config.get("PROFILER_PASSWORD")

    config["flask_profiler"] = {
        "enabled": True,
        "storage": {
            "engine": "sqlalchemy"
        },
        "ignore": ["^/static/.*"],
    }
    if password:
        config["flask_profiler"]["basicAuth"] = {
            "enabled": True,
            "username": "******",
            "password": password,
        }
    flask_profiler.init_app(app)
Ejemplo n.º 9
0
def profile():
    """ Run profiler and debugger."""
    from flask_debugtoolbar import DebugToolbarExtension
    import flask_profiler

    app.config["flask_profiler"] = {
        "enabled": app.config["DEBUG"],
        "storage": {
            "engine": "sqlite"
        },
        "basicAuth": {
            "enabled": False
        },
        "ignore": ["^/tests/.*", "^/src"],
    }
    flask_profiler.init_app(app)
    app.config["DEBUG_TB_PROFILER_ENABLED"] = True
    app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False

    toolbar = DebugToolbarExtension()
    toolbar.init_app(app)
    print(
        " * Flask profiling running at http://127.0.0.1:4000/flask-profiler/")
Ejemplo n.º 10
0
def create_app() -> Flask:
    app = Flask(__name__)
    # SimpleLogin is deployed behind NGINX
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1)
    limiter.init_app(app)

    app.url_map.strict_slashes = False

    app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    # enable to print all queries generated by sqlalchemy
    # app.config["SQLALCHEMY_ECHO"] = True

    app.secret_key = FLASK_SECRET

    app.config["TEMPLATES_AUTO_RELOAD"] = True

    # to avoid conflict with other cookie
    app.config["SESSION_COOKIE_NAME"] = SESSION_COOKIE_NAME
    if URL.startswith("https"):
        app.config["SESSION_COOKIE_SECURE"] = True
    app.config["SESSION_COOKIE_SAMESITE"] = "Lax"

    setup_error_page(app)

    init_extensions(app)
    register_blueprints(app)
    set_index_page(app)
    jinja2_filter(app)

    setup_favicon_route(app)
    setup_openid_metadata(app)

    init_admin(app)
    setup_paddle_callback(app)
    setup_coinbase_commerce(app)
    setup_do_not_track(app)

    if FLASK_PROFILER_PATH:
        LOG.d("Enable flask-profiler")
        app.config["flask_profiler"] = {
            "enabled": True,
            "storage": {
                "engine": "sqlite",
                "FILE": FLASK_PROFILER_PATH
            },
            "basicAuth": {
                "enabled": True,
                "username": "******",
                "password": FLASK_PROFILER_PASSWORD,
            },
            "ignore": ["^/static/.*", "/git", "/exception"],
        }
        flask_profiler.init_app(app)

    # enable CORS on /api endpoints
    CORS(app, resources={r"/api/*": {"origins": "*"}})

    # set session to permanent so user stays signed in after quitting the browser
    # the cookie is valid for 7 days
    @app.before_request
    def make_session_permanent():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(days=7)

    return app
Ejemplo n.º 11
0
parser = argparse.ArgumentParser()
parser.add_argument("--profile",
                    help="Enable flask_profiler profiling",
                    action="store_true")
args = parser.parse_args()

app = create_app()

if args.profile:
    from flask_debugtoolbar import DebugToolbarExtension
    import flask_profiler
    app.config["flask_profiler"] = {
        "enabled": app.config["DEBUG"],
        "storage": {
            "engine": "sqlite"
        },
        "basicAuth": {
            "enabled": False,
        },
    }
    flask_profiler.init_app(app)
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False

    toolbar = DebugToolbarExtension()
    toolbar.init_app(app)
    print(
        " * Flask profiling running at http://127.0.0.1:4000/flask-profiler/")

app.run(debug=True, threaded=True, host="127.0.0.1", port=4000)
Ejemplo n.º 12
0
    def create_prediction_microservice(self,
                                       model_list,
                                       yml_conf=False,
                                       port=5412,
                                       host='127.0.0.1',
                                       model_info={}):
        """
        Create a prediction Flask/cherrypy microservice app
        Parameters
        ----------
        func_name : list
           location of pipeline
        model_name : str
           model name to use for this pipeline
        """
        def run_sanity_checks():
            create_storage_dir(override=False)

        STORAGE_DIR = create_storage_dir(override=False)

        #函数来自配置文件
        if yml_conf:
            function_specs, token = parse_config_data(
                parse_config_file(yml_conf))
        else:
            function_specs = model_list
        #模型信息注册
        #print function_specs
        if model_info:
            if model_info.has_key('model_desc'):
                model_desc = model_info['model_desc']
            if model_info.has_key('model_name'):
                name = model_info['model_name']
            else:
                name = generate_random_model_name()
                model_info['model_name'] = name
            version = model_info['version']
            modelpath = model_info['modelpath']
            copy_model_files_to_internal_storage(modelpath, name, version)
            model_storage_path = get_model_dir(name,
                                               version,
                                               create_if_needed=True)
            #if not does_model_exist(name, version):
            #   create_new_model(model_info)
            #else:
            #    update_model(name, version, {'activated' : True})
            #    return ('Model/version already exists.')

        #model_info['model_storage_path']=model_storage_path
        """
         保存模型元数据信息
        """
        model_function = function_specs
        save_model_to_db(name,model_function=model_function, version=version, activated=True,\
                         last_deployed=convert_dt_to_epoch(datetime.datetime.now()),model_desc=model_desc)
        logger.info(
            Fore.GREEN, 'Model Deploy',
            '\n\nYour "%s" model (version: %s) has been successfully deployed.'
            % (name, version))
        logger.info(Fore.CYAN, 'Model Function',
                    'Your deployed model function is: %s' % (function_specs))
        logger.info(Fore.CYAN, 'Usage',
                    'You can now access it at the following endpoint:')
        logger.info(
            Fore.CYAN, 'Endpoint',
            '\n\n\t\t/models/' + name + '/v' + str(version) + '/predict\n\n')
        #print '\n\nYour "%s" model (version: %s) has been successfully deployed.' % (name, version)

        #print 'You can now access it at the following endpoint:'

        #print '\n\n\t\t/models/' + name + '/v' + str(version) + '/predict\n\n'

        app = create_app(function_specs, model_info)
        app.config['flask_profiler'] = {
            "enabled": True,
            "storage": {
                "engine": "mongodb"
            },
            "basicAuth": {
                "enabled": True,
                "username": "******",
                "password": "******"
            },
            "ignore": ["^/static/.*"]
        }
        flask_profiler.init_app(app)
        # start web server
        self.run_server(app, port, host)
Ejemplo n.º 13
0
    return "product id is " + str(id)


@app.route('/product/<id>', methods=['PUT'])
def updateProduct(id):
    return "product {} is being updated".format(id)


@app.route('/products', methods=['GET'])
def listProducts():
    return "suppose I send you product list..."

# In order to active flask-profiler, you have to pass flask
# app as an argument to flask-provider.
# All the endpoints declared so far will be tracked by flask-provider.
flask_profiler.init_app(app)


# endpoint declarations after flask_profiler.init_app() will be
# hidden to flask_profider.
@app.route('/doSomething', methods=['GET'])
def doSomething():
    return "flask-provider will not measure this."


# But in case you want an endpoint to be measured by flask-provider,
# you can specify this explicitly by using profile() decorator
@app.route('/doSomething', methods=['GET'])
@flask_profiler.profile()
def doSomethingImportant():
    return "flask-provider will measure this request."
Ejemplo n.º 14
0
def create_app(profile=True):
    app = Flask(__name__)
    app.config.from_pyfile("config.py")
    if __name__ == "__main__":
        app.config.from_pyfile("config_localhost.py")
    app.config["FLASK_PROFILER"]["enabled"] = profile

    # Database
    models.db.init_app(app)
    with app.app_context():
        # models.db.drop_all()
        models.db.create_all()

    # Extras
    app.mail = Mail(app)
    UserManager(SQLAlchemyAdapter(models.db, models.User),
                app,
                register_form=AthlytixUserForm)
    CORS(app)

    # CRUD-like
    app.route('/')(home)
    app.route('/api/current_user/')(get_current_user)
    app.route('/api/current_user/client/')(clients)
    app.route('/api/current_user/client/<int:user_id>/',
              methods=["DELETE"])(delete_client)

    app.route('/api/user/', methods=["PUT"])(create_user)
    app.route('/api/user/<int:user_id>/')(get_user)
    app.route('/api/user/<int:user_id>/', methods=["POST"])(update_user)

    app.route('/api/user/<int:user_id>/goal/')(goals)
    app.route('/api/user/<int:user_id>/goal/', methods=["PUT"])(create_goal)
    app.route('/api/goal/<int:id_>/')(goal)
    app.route('/api/goal/<int:id_>/', methods=["DELETE"])(delete_goal)
    app.route('/api/goal/probability/', methods=["POST"])(goal_probabilities)

    app.route('/api/user/<int:user_id>/calorie_intake/')(intakes)
    app.route('/api/user/<int:user_id>/calorie_intake/',
              methods=["PUT"])(create_intake)
    app.route('/api/calorie_intake/',
              methods=["PUT"])(bookmarklet_create_intake)
    app.route('/api/calorie_intake/<int:id_>/')(intake)
    app.route('/api/calorie_intake/<int:id_>/',
              methods=["DELETE"])(delete_intake)

    app.route('/api/user/<int:user_id>/diet_period/')(diet_periods)
    app.route('/api/user/<int:user_id>/diet_period/',
              methods=["PUT"])(create_diet_period)
    app.route('/api/diet_period/<int:id_>/')(diet_period)
    app.route('/api/diet_period/<int:id_>/',
              methods=["DELETE"])(delete_diet_period)

    app.route('/api/user/<int:user_id>/training_period/')(training_periods)
    app.route('/api/user/<int:user_id>/training_period/',
              methods=["PUT"])(create_training_period)
    app.route('/api/training_period/<int:id_>/')(training_period)
    app.route('/api/training_period/<int:id_>/',
              methods=["DELETE"])(delete_training_period)

    app.route('/api/user/<int:user_id>/calorie_expenditure/')(expenditures)
    app.route('/api/user/<int:user_id>/calorie_expenditure/',
              methods=["PUT"])(create_expenditure)
    app.route('/api/calorie_expenditure/<int:id_>/')(expenditure)
    app.route('/api/calorie_expenditure/<int:id_>/',
              methods=["DELETE"])(delete_expenditure)

    app.route('/api/user/<int:user_id>/weight_measurement/')(
        weight_measurements)
    app.route('/api/user/<int:user_id>/weight_measurement/',
              methods=["PUT"])(create_weight_measurement)
    app.route('/api/weight_measurement/<int:id_>/')(weight_measurement)
    app.route('/api/weight_measurement/<int:id_>/',
              methods=["DELETE"])(delete_weight_measurement)

    app.route('/api/user/<int:user_id>/bodyfat_measurement/')(
        bodyfat_measurements)
    app.route('/api/user/<int:user_id>/bodyfat_measurement/',
              methods=["PUT"])(create_bodyfat_measurement)
    app.route('/api/bodyfat_measurement/<int:id_>/')(bodyfat_measurement)
    app.route('/api/bodyfat_measurement/<int:id_>/',
              methods=["DELETE"])(delete_bodyfat_measurement)

    app.route('/api/user/<int:user_id>/girth_measurement/')(girth_measurements)
    app.route('/api/user/<int:user_id>/girth_measurement/',
              methods=["PUT"])(create_girth_measurement)
    app.route('/api/girth_measurement/<int:id_>/')(girth_measurement)
    app.route('/api/girth_measurement/<int:id_>/',
              methods=["DELETE"])(delete_girth_measurement)

    app.route('/api/user/<int:user_id>/endurance_achievement/')(
        endurance_achievements)
    app.route('/api/user/<int:user_id>/endurance_achievement/',
              methods=["PUT"])(create_endurance_achievement)
    app.route('/api/endurance_achievement/<int:id_>/')(endurance_achievement)
    app.route('/api/endurance_achievement/<int:id_>/',
              methods=["DELETE"])(delete_endurance_achievement)

    app.route('/api/user/<int:user_id>/strength_achievement/')(
        strength_achievements)
    app.route('/api/user/<int:user_id>/strength_achievement/',
              methods=["PUT"])(create_strength_achievement)
    app.route('/api/strength_achievement/<int:id_>/')(strength_achievement)
    app.route('/api/strength_achievement/<int:id_>/',
              methods=["DELETE"])(delete_strength_achievement)

    app.route('/api/user/<int:user_id>/trainer_request/',
              methods=["PUT"])(create_trainer_request)
    app.route('/api/trainer_request/')(trainer_requests)
    app.route('/api/trainer_request/<int:id_>/')(trainer_request)
    app.route('/api/trainer_request/<int:id_>/',
              methods=["DELETE"])(delete_trainer_request)
    app.route('/api/trainer_request/<int:id_>/approve')(
        approve_trainer_request)

    app.route('/api/user/<int:user_id>/program/')(programs)
    app.route('/api/user/<int:user_id>/program/',
              methods=["PUT"])(create_program)
    app.route('/api/program/<int:id_>/')(program)
    app.route('/api/program/<int:id_>/', methods=["DELETE"])(delete_program)

    app.route('/api/user/<int:user_id>/all/')(get_all_user_data)

    # Client routing fixes
    app.route('/page/<path:path>')(page)
    app.route('/<path:path>')(home)

    # Error handlers
    app.errorhandler(NotAuthorizedError)(handle_not_authorized)

    app.register_blueprint(search, url_prefix='/api/search')
    app.register_blueprint(leaderboard, url_prefix='/api/leaderboard')
    app.register_blueprint(percentile, url_prefix='/api/percentile')
    app.register_blueprint(estimate, url_prefix='/api/estimate')

    flask_profiler.init_app(app)

    return app
Ejemplo n.º 15
0
def create_app(debug=False, local=False, use_profiler=True):

    #from marvin.api import theapi as api
    from marvin.api.cube import CubeView
    from marvin.api.maps import MapsView
    from marvin.api.modelcube import ModelCubeView
    from marvin.api.plate import PlateView
    from marvin.api.rss import RSSView
    from marvin.api.spaxel import SpaxelView
    from marvin.api.query import QueryView
    from marvin.api.general import GeneralRequestsView
    from marvin.web.controllers.index import index
    from marvin.web.controllers.galaxy import galaxy
    from marvin.web.controllers.search import search
    from marvin.web.controllers.plate import plate
    from marvin.web.controllers.images import images
    from marvin.web.controllers.users import users

    # ----------------------------------
    # Create App
    marvin_base = os.environ.get('MARVIN_BASE', 'marvin2')
    app = Flask(__name__, static_url_path='/{0}/static'.format(marvin_base))
    api = Blueprint("api", __name__, url_prefix='/{0}/api'.format(marvin_base))
    app.debug = debug
    jsg.JSGLUE_JS_PATH = '/{0}/jsglue.js'.format(marvin_base)
    jsglue = jsg.JSGlue(app)

    # Add Marvin Logger
    app.logger.addHandler(log)

    # Setup the profile configuration
    app.config["flask_profiler"] = {
        "enabled": True,
        "storage": {
            "engine": "sqlite",
            "FILE": os.path.join(os.environ['MARVIN_DIR'],
                                 'flask_profiler.sql')
        },
        'endpointRoot': '{0}/profiler'.format(marvin_base),
        "basicAuth": {
            "enabled": False
        }
    }

    # ----------------------------------
    # Initialize logging + Sentry + UWSGI config for Production Marvin
    if app.debug is False:

        # ----------------------------------------------------------
        # Set up getsentry.com logging - only use when in production
        dsn = os.environ.get('SENTRY_DSN', None)
        app.config['SENTRY_DSN'] = dsn
        sentry = Sentry(app, logging=True, level=logging.ERROR)

        # --------------------------------------
        # Configuration when running under uWSGI
        try:
            import uwsgi
            app.use_x_sendfile = True
        except ImportError:
            pass
    else:
        sentry = None
        config.use_sentry = False
        config.add_github_message = False

    # Change the implementation of "decimal" to a C-based version (much! faster)
    #
    # This is producing this error [ Illegal value: Decimal('3621.59598486') ]on some of the remote API tests with getSpectrum
    # Turning this off for now
    #
    # try:
    #    import cdecimal
    #    sys.modules["decimal"] = cdecimal
    # except ImportError:
    #    pass  # no available

    # Find which connection to make
    connection = getDbMachine()
    local = (connection == 'local') or local

    # ----------------------------------
    # Set some environment variables
    config._inapp = True
    os.environ['SAS_REDUX'] = 'sas/mangawork/manga/spectro/redux'
    os.environ['SAS_ANALYSIS'] = 'sas/mangawork/manga/spectro/analysis'
    os.environ['SAS_SANDBOX'] = 'sas/mangawork/manga/sandbox'
    release = os.environ.get('MARVIN_RELEASE', 'mangawork')
    os.environ[
        'SAS_PREFIX'] = 'marvin2' if release == 'mangawork' else 'dr13/marvin'
    url_prefix = '/marvin2' if local else '/{0}'.format(marvin_base)

    # ----------------------------------
    # Load the appropriate Flask configuration file for debug or production
    if app.debug:
        if local:
            server_config_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), 'configuration',
                'localhost.cfg')
        elif connection == 'utah':
            server_config_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), 'configuration',
                'utah.cfg')
        else:
            server_config_file = None
            app.logger.debug(
                "Trying to run in debug mode, but not running on a development machine that has database access."
            )
            # sys.exit(1)
    else:
        try:
            import uwsgi
            server_config_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), 'configuration',
                uwsgi.opt['flask-config-file'])
        except ImportError:
            app.logger.debug(
                "Trying to run in production mode, but not running under uWSGI. You might try running again with the '--debug' flag."
            )
            sys.exit(1)

    if server_config_file:
        app.logger.info('Loading config file: {0}'.format(server_config_file))
        app.config.from_pyfile(server_config_file)

    # ----------------------------------
    # Initialize feature flags
    feature_flags = FeatureFlag(app)
    # configFeatures(debug=app.debug)

    # Update any config parameters
    app.config["UPLOAD_FOLDER"] = os.environ.get("MARVIN_DATA_DIR", None)
    app.config["LIB_PATH"] = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), 'lib')

    # Add lib directory as a new static path
    @app.route('/{0}/lib/<path:filename>'.format(marvin_base))
    def lib(filename):
        return send_from_directory(app.config["LIB_PATH"], filename)

    # Register update global session
    @app.before_request
    def global_update():
        ''' updates the global session / config '''
        updateGlobalSession()
        # send_request()

    # ----------------
    # Error Handling
    # ----------------

    def _is_api(request):
        ''' Checks if the error comes from the api '''
        return request.blueprint == 'api' or 'api' in request.url

    @app.errorhandler(404)
    def page_not_found(error):
        name = 'Page Not Found'
        if _is_api(request):
            return make_error_json(error, name, 404)
        else:
            return make_error_page(app, name, 404, sentry=sentry)

    @app.errorhandler(500)
    def internal_server_error(error):
        name = 'Internal Server Error'
        if _is_api(request):
            return make_error_json(error, name, 500)
        else:
            return make_error_page(app, name, 500, sentry=sentry)

    @app.errorhandler(400)
    def bad_request(error):
        name = 'Bad Request'
        if _is_api(request):
            return make_error_json(error, name, 400)
        else:
            return make_error_page(app, name, 400, sentry=sentry)

    @app.errorhandler(405)
    def method_not_allowed(error):
        name = 'Method Not Allowed'
        if _is_api(request):
            return make_error_json(error, name, 405)
        else:
            return make_error_page(app, name, 405, sentry=sentry)

    @app.errorhandler(422)
    def handle_unprocessable_entity(error):
        name = 'Unprocessable Entity'
        data = getattr(error, 'data')
        if data:
            # Get validations from the ValidationError object
            messages = data['messages']
        else:
            messages = ['Invalid request']

        if _is_api(request):
            return make_error_json(error, name, 422)
        else:
            return make_error_page(app,
                                   name,
                                   422,
                                   sentry=sentry,
                                   data=messages)

    # These should be moved into the api module but they need the api blueprint to be registered on
    # I had these in the api.__init__ with the api blueprint defined there as theapi
    # which was imported here, see line 39
    # This should all be moved into the Brain and abstracted since it is
    # general useful standardized stuff (what?)

    @api.errorhandler(422)
    def handle_unprocessable_entity(err):
        # webargs attaches additional metadata to the `data` attribute
        data = getattr(err, 'data')
        if data:
            # Get validations from the ValidationError object
            messages = data['messages']
        else:
            messages = ['Invalid request']
        return jsonify({
            'validation_errors': messages,
        }), 422

    # ----------------------------------
    # Registration
    config.use_sentry = False
    #
    # API route registration
    CubeView.register(api)
    MapsView.register(api)
    ModelCubeView.register(api)
    PlateView.register(api)
    RSSView.register(api)
    SpaxelView.register(api)
    GeneralRequestsView.register(api)
    QueryView.register(api)
    app.register_blueprint(api)

    # Web route registration
    app.register_blueprint(index, url_prefix=url_prefix)
    app.register_blueprint(galaxy, url_prefix=url_prefix)
    app.register_blueprint(search, url_prefix=url_prefix)
    app.register_blueprint(plate, url_prefix=url_prefix)
    app.register_blueprint(images, url_prefix=url_prefix)
    app.register_blueprint(users, url_prefix=url_prefix)

    # Register all custom Jinja filters in the file.
    app.register_blueprint(jinjablue)

    # Register error handlers
    app.register_blueprint(web)

    # Initialize the Flask-Profiler ; see results at localhost:portnumber/flask-profiler
    if use_profiler:
        try:
            flask_profiler.init_app(app)
        except Exception as e:
            pass

    return app
Ejemplo n.º 16
0
## READ CONFIG
CONFIG = configparser.RawConfigParser()
CONFIG.read('./config.cfg')

HOST = CONFIG.get('flask', 'host')
PORT = int(CONFIG.get('flask', 'port'))

APP = Flask(__name__)
# flask-profiler config as follows:
APP.config["flask_profiler"] = {
    "enabled": True,
    "storage": {
        "engine": "sqlite"
    },
    "basicAuth": {
        "enabled": True,
        "username": "******",
        "password": "******"
    },
    "ignore": ["^/static/.*"]
}
flask_profiler.init_app(APP)

API = Api(app=APP, default_mediatype="application/json")
APP.register_blueprint(crawl_api)


def serve():
    APP.run(host=HOST, port=PORT)