示例#1
0
def create_app(config='config/askomics.ini',
               app_name='askomics',
               blueprints=None):
    """Create the AskOmics app

    Parameters
    ----------
    config : str, optional
        Path to the config file
    app_name : str, optional
        Application name
    blueprints : None, optional
        Flask blueprints

    Returns
    -------
    Flask
        AskOmics Flask application
    """
    conf = configparser.ConfigParser()
    conf.read(config)

    sentry_dsn = None
    try:
        sentry_dsn = conf['sentry']['server_dsn']
    except Exception:
        pass

    if sentry_dsn:
        version = get_distribution('askomics').version
        name = get_distribution('askomics').project_name
        sentry_sdk.init(dsn=sentry_dsn,
                        release="{}@{}".format(name, version),
                        integrations=[FlaskIntegration(),
                                      CeleryIntegration()])

    app = Flask(app_name, static_folder='static', template_folder='templates')

    app.iniconfig = conf
    app.secret_key = app.iniconfig.get("flask", "secret_key")

    with app.app_context():

        proxy_path = None
        try:
            proxy_path = app.iniconfig.get('askomics', 'reverse_proxy_path')
            app.config['REVERSE_PROXY_PATH'] = proxy_path
        except Exception:
            pass

        if blueprints is None:
            blueprints = BLUEPRINTS

        for blueprint in blueprints:
            app.register_blueprint(blueprint)

    if proxy_path:
        ReverseProxyPrefixFix(app)

    return app
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    app.config['REVERSE_PROXY_PATH'] = '/api'
    ReverseProxyPrefixFix(app)
    db.init_app(app)
    flask_bcrypt.init_app(app)
    return app
示例#3
0
def create_app(config_name):
    app = Flask(__name__)

    # Config
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Extensions
    db.init_app(app)
    auth.init_app(app=app)

    # Middleware / Wrappers
    if app.config['APP_ENABLE_PROXY_FIX']:
        ReverseProxyPrefixFix(app)
    if app.config['APP_ENABLE_REQUEST_ID']:
        RequestID(app)
    if app.config['APP_ENABLE_SENTRY']:
        sentry_sdk.init(**app.config['SENTRY_CONFIG'])

    # Logging
    formatter = RequestFormatter(
        '[%(asctime)s] [%(levelname)s] [%(request_id)s] [%(url)s]: %(message)s'
    )
    default_handler.setFormatter(formatter)
    default_handler.setLevel(app.config['LOGGING_LEVEL'])

    # Error handlers
    app.register_error_handler(BadRequest, error_handler_generic_bad_request)
    app.register_error_handler(NotFound, error_handler_generic_not_found)
    app.register_error_handler(UnprocessableEntity,
                               error_handler_generic_unprocessable_entity)
    app.register_error_handler(InternalServerError,
                               error_handler_generic_internal_server_error)

    # CLI commands
    app.cli.add_command(seeding_cli_group)
    app.cli.add_command(importing_cli_group)

    # Routes
    app.add_url_rule('/', 'index', index_route)
    app.add_url_rule('/meta/health/canary',
                     'canary_health_check',
                     healthcheck_canary_route,
                     methods=['get', 'options'])

    # Resource blueprints
    app.register_blueprint(projects_blueprint)
    app.register_blueprint(people_blueprint)
    app.register_blueprint(grants_blueprint)
    app.register_blueprint(organisations_blueprint)
    app.register_blueprint(category_schemes_blueprint)
    app.register_blueprint(category_terms_blueprint)
    app.register_blueprint(participants_blueprint)
    app.register_blueprint(allocations_blueprint)
    app.register_blueprint(categorisations_blueprint)

    return app
示例#4
0
def create_app_with_middleware():
    app = Flask(__name__)

    # Configure and load Middleware
    app.config['REVERSE_PROXY_PATH'] = '/test'
    ReverseProxyPrefixFix(app)

    @app.route("/sample")
    def sample():
        payload = {'links': {'self': url_for('.sample', _external=True)}}

        return jsonify(payload)

    return app
    def test_with_prefix(self):
        self.app = create_app_with_middleware()
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client()

        self.app.config['REVERSE_PROXY_PATH'] = '/foo'
        ReverseProxyPrefixFix(self.app)

        expected_url = 'http://localhost:9000/test/sample'

        response = self.client.get('/sample', base_url='http://localhost:9000')
        json_response = response.get_json()
        self.assertEqual(response.status_code, HTTPStatus.OK)
        self.assertIn('links', json_response.keys())
        self.assertIn('self', json_response['links'].keys())
        self.assertEqual(expected_url, json_response['links']['self'])
示例#6
0
def register_extensions(app):
    """Register Flask extensions."""
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    ma.init_app(app)
    pagination.init_app(app, db)
    flask_static_digest.init_app(app)
    rq.init_app(app)
    if app.config['REVERSE_PROXY'] != 0:
        from flask_reverse_proxy_fix.middleware import ReverseProxyPrefixFix
        ReverseProxyPrefixFix(app)

    return None
示例#7
0
def create_app():
    user_datastore = SQLAlchemyUserDatastore(sqlalchemy_db, User, Role)
    app = Flask(__name__)

    if os.getenv('SEMI_PROD', False):
        app.config.from_pyfile('{}.py'.format(
            os.path.join('settings', 'semi_production')))
    else:
        app.config.from_pyfile('{}.py'.format(
            os.path.join('settings', os.getenv('FLASK_ENV', 'development'))))
    if 'REVERSE_PROXY_PATH' in app.config:
        ReverseProxyPrefixFix(app)

    app.logger.setLevel(logging.DEBUG)
    app.logger.addHandler(create_logger(app.config['LOG_PATH']))

    sqlalchemy_db.init_app(app)
    Security(app, user_datastore, login_form=ExtendedLoginForm)

    # register filters
    app.jinja_env.filters['datetime'] = format_date

    # Propagate background task exceptions
    app.config['EXECUTOR_PROPAGATE_EXCEPTIONS'] = True
    # register blueprints
    app.register_blueprint(main)
    app.register_blueprint(collection)
    app.register_blueprint(verification)
    app.register_blueprint(token)
    app.register_blueprint(recording)
    app.register_blueprint(session)
    app.register_blueprint(user)
    app.register_blueprint(application)
    app.register_blueprint(configuration)
    app.register_blueprint(shop)
    app.register_blueprint(mos)

    app.executor = Executor(app)
    app.user_datastore = user_datastore

    return app
示例#8
0
def create_app():
    app = Flask(__name__)
    if os.getenv('SEMI_PROD', False):
        app.config.from_pyfile('{}.py'.format(
            os.path.join('settings/', 'semi_production')))
    else:
        app.config.from_pyfile('{}.py'.format(
            os.path.join('settings/', os.getenv('FLASK_ENV', 'development'))))
    app.logger.setLevel(logging.DEBUG)
    app.logger.addHandler(logHandler)
    if 'REVERSE_PROXY_PATH' in app.config:
        ReverseProxyPrefixFix(app)

    db.init_app(app)
    security = Security(app, user_datastore, login_form=ExtendedLoginForm)

    # register filters
    app.jinja_env.filters['datetime'] = format_date

    # Propagate background task exceptions
    app.config['EXECUTOR_PROPAGATE_EXCEPTIONS'] = True

    return app
示例#9
0
from timeseries import time_series

import requests
import sys
import time
import os

import plotly
import plotly.graph_objs as go
import numpy as np

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['REVERSE_PROXY_PATH'] = '/analytics'
ReverseProxyPrefixFix(app)


def handle_varnish(request, response):
    if 'X-Varnish' in request.headers:
        response.headers['X-Varnish'] = request.headers['X-Varnish']

    if 'Age' in request.headers:
        response.headers['Age'] = request.headers['Age']

    return response


def make_request(url, headers=None):
    startr = time.time()
示例#10
0
def create_app(db_file=None):
    """create app."""
    app = FlaskAPI(__name__)
    per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
    per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
    app.config['BUKUSERVER_PER_PAGE'] = per_page
    url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE)
    if url_render_mode not in ('full', 'netloc'):
        url_render_mode = views.DEFAULT_URL_RENDER_MODE
    app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
    app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24)
    app.config['BUKUSERVER_DISABLE_FAVICON'] = \
        get_bool_from_env_var('BUKUSERVER_DISABLE_FAVICON', True)
    app.config['BUKUSERVER_OPEN_IN_NEW_TAB'] = \
        get_bool_from_env_var('BUKUSERVER_OPEN_IN_NEW_TAB', False)
    app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE') or db_file
    reverse_proxy_path = os.getenv('BUKUSERVER_REVERSE_PROXY_PATH')
    if reverse_proxy_path:
        if not reverse_proxy_path.startswith('/'):
            print('Warning: reverse proxy path should include preceding slash')
        if reverse_proxy_path.endswith('/'):
            print('Warning: reverse proxy path should not include trailing slash')
        app.config['REVERSE_PROXY_PATH'] = reverse_proxy_path
        if ReverseProxyPrefixFix:
            ReverseProxyPrefixFix(app)
        else:
            raise ImportError('Failed to import ReverseProxyPrefixFix')
    bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE'])
    app.app_context().push()
    setattr(flask.g, 'bukudb', bukudb)

    @app.shell_context_processor
    def shell_context():
        """Shell context definition."""
        return {'app': app, 'bukudb': bukudb}

    app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc  # pylint: disable=no-member

    Bootstrap(app)
    admin = Admin(
        app, name='buku server', template_mode='bootstrap3',
        index_view=views.CustomAdminIndexView(
            template='bukuserver/home.html', url='/'
        )
    )
    # routing
    #  api
    tag_api_view = ApiTagView.as_view('tag_api')
    app.add_url_rule('/api/tags', defaults={'tag': None}, view_func=tag_api_view, methods=['GET'])
    app.add_url_rule('/api/tags/<tag>', view_func=tag_api_view, methods=['GET', 'PUT'])
    bookmark_api_view = ApiBookmarkView.as_view('bookmark_api')
    app.add_url_rule('/api/bookmarks', defaults={'rec_id': None}, view_func=bookmark_api_view, methods=['GET', 'POST', 'DELETE'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>', view_func=bookmark_api_view, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmark', refresh_bookmark, defaults={'rec_id': None}, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET'])
    app.add_url_rule('/api/network_handle', 'network_handle', handle_network, methods=['POST'])
    bookmark_range_api_view = ApiBookmarkRangeView.as_view('bookmark_range_api')
    app.add_url_rule(
        '/api/bookmarks/<int:starting_id>/<int:ending_id>',
        view_func=bookmark_range_api_view, methods=['GET', 'PUT', 'DELETE'])
    bookmark_search_api_view = ApiBookmarkSearchView.as_view('bookmark_search_api')
    app.add_url_rule('/api/bookmarks/search', view_func=bookmark_search_api_view, methods=['GET', 'DELETE'])
    bookmarklet_view = BookmarkletView.as_view('bookmarklet')
    app.add_url_rule('/bookmarklet', view_func=bookmarklet_view, methods=['GET'])
    #  non api
    admin.add_view(views.BookmarkModelView(
        bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode))
    admin.add_view(views.TagModelView(
        bukudb, 'Tags', page_size=per_page))
    admin.add_view(views.StatisticView(
        bukudb, 'Statistic', endpoint='statistic'))
    return app
示例#11
0
def configure_app(application):
    application.register_blueprint(file_handler)
    application.config['REVERSE_PROXY_PATH'] = proxy_server
    application.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    ReverseProxyPrefixFix(application)
示例#12
0
def create_app(config='config/genocrowd.ini',
               app_name='genocrowd',
               blueprints=None):
    """Create the Genocrowd app

    Parameters
    ----------
    config : str, optional
        Path to the config file
    app_name : str, optional
        Application name
    blueprints : None, optional
        Flask blueprints

    Returns
    -------
    Flask
        Genocrowd Flask application
    """
    conf = configparser.ConfigParser()
    conf.read(config)
    sentry_dsn = None
    try:
        sentry_dsn = conf['sentry']['server_dsn']
    except Exception:
        pass
    if sentry_dsn:
        version = get_distribution('genocrowd').version
        name = get_distribution('genocrowd').project_name
        sentry_sdk.init(dsn=sentry_dsn,
                        release="{}@{}".format(name, version),
                        integrations=[FlaskIntegration(),
                                      CeleryIntegration()])
    app = Flask(app_name, static_folder='static', template_folder='templates')
    app.iniconfig = FlaskIni()
    with app.app_context():
        app.iniconfig.read(config)
        proxy_path = None
        try:
            proxy_path = app.iniconfig.get('genocrowd', 'reverse_proxy_path')
            app.config['REVERSE_PROXY_PATH'] = proxy_path
        except Exception:
            pass
        mongo_dbname = app.iniconfig.get('flask', 'mongo_dbname')
        app.config['MONGO_DBNAME'] = mongo_dbname
        mongo_uri = app.iniconfig.get('flask', 'mongo_uri')
        app.config['MONGO_URI'] = mongo_uri
        if not mongo_uri:
            raise Exception("Missing mongo_uri in config file")
        if not mongo_dbname:
            raise Exception("Missing mongo_dbname in config file")
        app.mongo = PyMongo(app)
        app.bcrypt = Bcrypt(app)
        users = app.mongo.db.users
        app.mongo.db.genes
        app.mongo.db.answers
        groups = app.mongo.db.groups

        app.genocrowd_admin_email = app.iniconfig.get('genocrowd',
                                                      'genocrowd_admin_email')
        app.genocrowd_admin_password = app.iniconfig.get(
            'genocrowd', 'genocrowd_admin_password')

        app.apollo_admin_email = app.iniconfig.get('genocrowd',
                                                   'apollo_admin_email')
        app.apollo_admin_password = app.iniconfig.get('genocrowd',
                                                      'apollo_admin_password')
        app.apollo_dataset_path = app.iniconfig.get('genocrowd',
                                                    'apollo_dataset_path')
        app.apollo_org_id = app.iniconfig.get('genocrowd', 'apollo_org_id')
        app.apollo_url = app.iniconfig.get('genocrowd', 'apollo_url')
        # We don't want ending slash
        if app.apollo_url.endswith("/"):
            app.apollo_url = app.apollo_url[:-1]

        app.apollo_url_ext = app.iniconfig.get('genocrowd', 'apollo_url_ext')
        # We don't want ending slash
        if app.apollo_url_ext.endswith("/"):
            app.apollo_url_ext = app.apollo_url_ext[:-1]

        configure_logging(app)

        if users.find_one() is None:
            # Create default admin user
            local_auth = LocalAuth(app, None)
            local_auth.add_user_to_database('admin', app.genocrowd_admin_email,
                                            app.genocrowd_admin_password,
                                            'admin', 'admin')

        if blueprints is None:
            blueprints = BLUEPRINTS

        for blueprint in blueprints:
            app.register_blueprint(blueprint)

        if groups.find_one() is None:
            # Initiate the groups database
            data = Data(app, None)
            data.initiate_groups()

    if proxy_path:
        ReverseProxyPrefixFix(app)
    return app
def create_app(config_name):
    app = Flask(__name__)

    # Config
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Logging
    class RequestFormatter(logging.Formatter):
        def format(self, record):
            record.url = 'NA'
            record.request_id = 'NA'

            if has_request_context():
                record.url = request.url
                if app.config['APP_ENABLE_REQUEST_ID']:
                    record.request_id = request.environ.get("HTTP_X_REQUEST_ID")

            return super().format(record)
    formatter = RequestFormatter(
        '[%(asctime)s] [%(levelname)s] [%(request_id)s] [%(url)s] %(module)s: %(message)s'
    )
    default_handler.setFormatter(formatter)
    default_handler.setLevel(app.config['LOGGING_LEVEL'])

    # Middleware / Wrappers
    if app.config['APP_ENABLE_PROXY_FIX']:
        ReverseProxyPrefixFix(app)
    if app.config['APP_ENABLE_REQUEST_ID']:
        RequestID(app)
    if app.config['APP_ENABLE_SENTRY']:
        sentry_sdk.init(**app.config['SENTRY_CONFIG'])

    # API client
    if not app.config['TESTING']:
        arctic_projects_api_auth = BackendApplicationClient(client_id=app.config['AZURE_OAUTH_APPLICATION_ID'])
        arctic_projects_api_auth_session = OAuth2Session(client=arctic_projects_api_auth)
        arctic_projects_api_auth_token = arctic_projects_api_auth_session.fetch_token(
            token_url=app.config['AZURE_OAUTH_TOKEN_URL'],
            client_id=app.config['AZURE_OAUTH_APPLICATION_ID'],
            client_secret=app.config['AZURE_OAUTH_APPLICATION_SECRET'],
            scope=app.config['AZURE_OAUTH_NERC_ARCTIC_OFFICE_SCOPES']
        )
        arctic_projects_api = Session(
            'https://api.bas.ac.uk/arctic-office-projects/testing',
            request_kwargs={'headers': {'authorization': f"bearer {arctic_projects_api_auth_token['access_token']}"}})

    # Templates
    app.jinja_loader = PrefixLoader({
        'app': PackageLoader('arctic_office_projects_manager'),
        'bas_style_kit': PackageLoader('bas_style_kit_jinja_templates'),
    })
    app.config['bsk_templates'] = BskTemplates()
    app.config['bsk_templates'].site_styles.append({
        'href': 'https://cdn.web.bas.ac.uk/libs/font-awesome-pro/5.3.1/css/all.min.css'
    })
    app.config['bsk_templates'].site_styles.append({
        'href': 'https://cdn.rawgit.com/jpswalsh/academicons/master/css/academicons.min.css'
    })
    app.config['bsk_templates'].site_styles.append({'href': '/static/css/app.css'})
    app.config['bsk_templates'].site_title = 'NERC Arctic Office Projects Manager'
    app.config['bsk_templates'].bsk_site_nav_brand_text = 'NERC Arctic Office Projects Manager'
    app.config['bsk_templates'].site_description = 'Management application for projects in the NERC Arctic Office ' \
                                                   'Projects Database'
    app.config['bsk_templates'].bsk_site_feedback_href = 'mailto:[email protected]'
    app.config['bsk_templates'].bsk_site_nav_primary.append({
        'value': 'Projects',
        'href': '/projects'
    })
    app.config['bsk_templates'].bsk_site_nav_launcher.append({
        'value': 'Arctic Office Website',
        'href': 'https://www.arctic.ac.uk'
    })

    # Routes
    #

    @app.route('/')
    def index():
        return redirect(url_for('projects_index'))

    @app.route('/projects')
    def projects_index():
        projects = arctic_projects_api.get('projects')
        # noinspection PyUnresolvedReferences
        return render_template(f"app/views/projects_index.j2", projects=projects)

    @app.route('/projects/<project_id>')
    def project_details(project_id: str):
        project = arctic_projects_api.get('projects', project_id)

        mermaid_asset = False
        for style in app.config['bsk_templates'].site_scripts:
            if style['href'] == 'https://unpkg.com/[email protected]/dist/mermaid.min.js':
                mermaid_asset = True
        if not mermaid_asset:
            app.config['bsk_templates'].site_scripts.append({
                'href': 'https://unpkg.com/[email protected]/dist/mermaid.min.js'
            })
        # noinspection PyUnresolvedReferences
        return render_template(f"app/views/project_details.j2", project=project, active_nav_item='/projects')

    @app.route('/meta/health/canary', methods=['get', 'options'])
    def meta_healthcheck_canary():
        """
        Returns whether this service is healthy

        This healthcheck checks the application itself (assumed to be healthy if this method can be executed).

        If healthy a 204 No Content response is returned, if unhealthy a 503 Service Unavailable response is returned.
        This healthcheck is binary and does not return any details to reduce payload size and prevent leaking sensitive
        data.

        Other healthcheck's should be used where more details are required. This healthcheck is intended for use with
        load balancers to give early indication of a service not being available.
        """
        return '', HTTPStatus.NO_CONTENT

    return app