예제 #1
2
def loader_meta(app=None):

    from .views import core
    app.register_blueprint(core)

    from flask_bootstrap import Bootstrap
    bootstrap = Bootstrap()
    bootstrap.init_app(app)

    from flask_menu import Menu
    menu = Menu()
    menu.init_app(app)

    from flask import render_template
    app.errorhandler(404)(lambda e: (render_template('core/404.html'), 404))
    app.errorhandler(500)(lambda e: (render_template('core/404.html'), 500))
예제 #2
0
class INSPIRETheme(object):
    """Invenio theme extension."""

    def __init__(self, app=None, **kwargs):
        """Extension initialization."""
        self.menu_ext = Menu()
        self.menu = None
        self.breadcrumbs = Breadcrumbs()

        if app:
            self.init_app(app, **kwargs)
            self.setup_app(app)

    def init_app(self, app, assets=None, **kwargs):
        """Initialize application object."""
        self.init_config(app.config)

        # Initialize extensions
        self.menu_ext.init_app(app)
        self.menu = app.extensions['menu']
        self.breadcrumbs.init_app(app)

        app.register_blueprint(blueprint)

        # Configure Jinja2 environment.
        app.jinja_env.add_extension('jinja2.ext.do')
        app.jinja_env.lstrip_blocks = True
        app.jinja_env.trim_blocks = True

        # Register errors handlers.
        app.register_error_handler(401, unauthorized)
        app.register_error_handler(403, insufficient_permissions)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(500, internal_error)

        user_logged_in.connect(load_user_collections, app)

        # Save reference to self on object
        app.extensions['inspire-theme'] = self

    def init_config(self, config):
        """Initialize configuration."""
        # Set JS bundles to exclude for purpose of avoiding double jQuery etc.
        # when other modules are building their JS bundles.
        config.setdefault("THEME_BASE_BUNDLES_EXCLUDE_JS", [js])
        config.setdefault("BASE_TEMPLATE", "inspirehep_theme/page.html")

    def setup_app(self, app):
        """Initialize Gravatar extension."""
        gravatar = Gravatar(app,
                            size=app.config.get('GRAVATAR_SIZE', 100),
                            rating=app.config.get('GRAVATAR_RATING', 'g'),
                            default=app.config.get(
                                'GRAVATAR_DEFAULT', 'retro'),
                            force_default=False,
                            force_lower=False)
        del gravatar
        return app
예제 #3
0
파일: ext.py 프로젝트: tind/invenio-theme
    def __init__(self, app=None, **kwargs):
        """Extension initialization."""
        self.menu_ext = Menu()
        self.menu = None
        self.breadcrumbs = Breadcrumbs()

        if app:
            self.init_app(app, **kwargs)
예제 #4
0
파일: ext.py 프로젝트: kaplun/inspire-next
    def __init__(self, app=None, **kwargs):
        """Extension initialization."""
        self.menu_ext = Menu()
        self.menu = None
        self.breadcrumbs = Breadcrumbs()
        self.weblinks = self.init_weblinks_dictionary()

        if app:
            self.init_app(app, **kwargs)
            self.setup_app(app)
예제 #5
0
class InvenioTheme(object):
    """Invenio theme extension."""

    def __init__(self, app=None, **kwargs):
        """Extension initialization."""
        self.menu_ext = Menu()
        self.menu = None
        self.breadcrumbs = Breadcrumbs()

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, assets=None, **kwargs):
        """Initialize application object."""
        self.init_config(app.config)

        # Initialize extensions
        self.menu_ext.init_app(app)
        self.menu = app.extensions['menu']
        self.breadcrumbs.init_app(app)

        # Register blueprint in order to register template and static folder.
        blueprint = Blueprint(
            'invenio_theme',
            __name__,
            template_folder='templates',
            static_folder='static',
        )
        app.register_blueprint(blueprint)

        # Save reference to self on object
        app.extensions['invenio-theme'] = self

    def init_config(self, config):
        """Initialize configuration."""
        config.setdefault("THEME_SITENAME", _("Invenio"))
        config.setdefault("THEME_GOOGLE_SITE_VERIFICATION", [])
        config.setdefault('BASE_TEMPLATE', 'invenio_theme/page.html')
        config.setdefault(
            'THEME_BASE_TEMPLATE', config['BASE_TEMPLATE'])
        config.setdefault(
            'THEME_ERROR_TEMPLATE', 'invenio_theme/error.html')
예제 #6
0
def create_app(config=Config):
    prepare_env()
    app = Flask(__name__)
    app.config.from_object(config)
    app.secret_key = os.urandom(24)
    app.register_blueprint(main)
    Menu(app=app)
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = "main.login"
    login_manager.login_message_category = "warning"
    return app
예제 #7
0
    def __init__(self, app=None, **kwargs):
        r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.
        """
        self.menu_ext = Menu()
        self.menu = None
        self.breadcrumbs = Breadcrumbs()

        if app:
            self.init_app(app, **kwargs)
예제 #8
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()

    app_ = Flask(__name__, instance_path=instance_path)
    app_.config.update(
        SQLALCHEMY_DATABASE_URI=os.getenv(
            'SQLALCHEMY_DATABASE_URI',
            'postgresql+psycopg2://localhost/circulation_test'),
        OAUTH2SERVER_CLIENT_ID_SALT_LEN=40,
        OAUTH2SERVER_CLIENT_SECRET_SALT_LEN=60,
        OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN=60,
        SECRET_KEY='changeme',
        SERVER_NAME='localhost:5000',
        REPLACE_REFS=False,
        TESTING=True,
        CIRCULATION_ACTION_LOAN_URL=(
            '/hooks/receivers/circulation_loan/events/'),
        CIRCULATION_ACTION_REQUEST_URL=(
            '/hooks/receivers/circulation_request/events/'),
        CIRCULATION_ACTION_RETURN_URL=(
            '/hooks/receivers/circulation_return/events/'),
    )

    app_.url_map.converters['pid'] = PIDConverter

    Babel(app_)
    Menu(app_)
    Breadcrumbs(app_)
    InvenioAccounts(app_)
    InvenioAssets(app_)
    InvenioDB(app_)
    InvenioIndexer(app_)
    InvenioJSONSchemas(app_)
    InvenioPIDStore(app_)
    InvenioRecords(app_)
    InvenioRecordsREST(app_)
    InvenioWebhooks(app_)
    InvenioOAuth2Server(app_)
    InvenioCirculation(app_)
    InvenioCirculationREST(app_)
    InvenioSearch(app_)

    app_.register_blueprint(server_blueprint)
    app_.register_blueprint(settings_blueprint)
    app_.register_blueprint(webhooks_blueprint)
    app_.register_blueprint(circulation_blueprint)

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
예제 #9
0
def test_permission(app):
    """Test permission control to records."""
    app.config.update(
        WTF_CSRF_ENABLED=False,
        SECRET_KEY='CHANGEME',
        SECURITY_PASSWORD_SALT='CHANGEME',
        # conftest switches off permission checking, so re-enable it for this
        # app.
        RECORDS_UI_DEFAULT_PERMISSION_FACTORY='helpers:'
                                              'only_authenticated_users',
    )
    Menu(app)
    InvenioRecordsUI(app)
    app.register_blueprint(create_blueprint_from_app(app))
    accounts = InvenioAccounts(app)
    app.register_blueprint(accounts_blueprint)
    InvenioAccess(app)
    setup_record_fixture(app)

    # Create admin
    with app.app_context():
        accounts.datastore.create_user(
            email='*****@*****.**',
            password=encrypt_password('123456'),
            active=True,
        )

        # Get record 1
        r = Resolver(pid_type='recid', object_type='rec',
                     getter=Record.get_record)
        dummy_pid, record = r.resolve('1')

        db.session.commit()

    with app.test_request_context():
        login_url = url_for('security.login')
        record_url = url_for('invenio_records_ui.recid', pid_value='1')

    # Access record 1 as admin
    with app.test_client() as client:
        res = client.get(record_url)
        assert res.status_code == 302
        res = client.post(login_url, data={
            'email': '*****@*****.**', 'password': '******'})
        assert res.status_code == 302
        res = client.get(record_url)
        res.status_code == 200

    # Access record 1 as anonymous
    with app.test_client() as client:
        res = client.get(record_url)
        res.status_code == 403
예제 #10
0
    def test_kwargs(self):
        """Test optional arguments."""
        Menu(self.app)
        count = 5

        @self.app.route('/test')
        @register_menu(self.app, 'test', 'Test', count=count)
        def test():
            return 'count'

        with self.app.test_client() as c:
            c.get('/test')
            assert count == current_menu.submenu('test').count
예제 #11
0
def app(request):
    """Flask application fixture."""
    app = Flask('testapp')
    app.config.update(
        ACCOUNTS_JWT_ENABLE=False,
        BROKER_TRANSPORT='redis',
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND='memory',
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND='cache',
        CELERY_TRACK_STARTED=True,
        LOGIN_DISABLED=False,
        OAUTH2_CACHE_TYPE='simple',
        OAUTHLIB_INSECURE_TRANSPORT=True,
        SECRET_KEY='test_key',
        SECURITY_DEPRECATED_PASSWORD_SCHEMES=[],
        SECURITY_PASSWORD_HASH='plaintext',
        SECURITY_PASSWORD_SCHEMES=['plaintext'],
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI',
                                          'sqlite:///test.db'),
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    celeryext = FlaskCeleryExt(app)
    celeryext.celery.flask_app = app  # Make sure both apps are the same!
    Babel(app)
    Mail(app)
    Menu(app)
    Breadcrumbs(app)
    InvenioDB(app)
    InvenioAccounts(app)
    app.register_blueprint(accounts_blueprint)
    InvenioOAuth2Server(app)
    InvenioOAuth2ServerREST(app)
    app.register_blueprint(server_blueprint)
    app.register_blueprint(settings_blueprint)
    InvenioWebhooks(app)
    app.register_blueprint(blueprint)

    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            drop_database(str(db.engine.url))

    request.addfinalizer(teardown)
    return app
예제 #12
0
def create_app(config=Config):
    app = Flask(__name__)
    app.config.from_object(config)
    app.secret_key = os.urandom(24)
    app.register_blueprint(main)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    Menu(app=app)
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = "main.login"
    login_manager.login_message_category = "warning"
    mail.init_app(app)
    cache.init_app(app)
    return app
예제 #13
0
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    app.config.update(ACCOUNTS_USE_CELERY=False)
    Babel(app)
    Mail(app)
    Menu(app)
    InvenioDB(app)
    InvenioAccounts(app)
    ext = WekoUserProfiles(app)
    assert 'weko-user-profiles' in app.extensions

    app = Flask('testapp')
    app.config.update(ACCOUNTS_USE_CELERY=False)
    Babel(app)
    Mail(app)
    Menu(app)
    InvenioDB(app)
    InvenioAccounts(app)
    ext = WekoUserProfiles()
    assert 'weko-user-profiles' not in app.extensions
    ext.init_app(app)
    assert 'weko-user-profiles' in app.extensions
예제 #14
0
    def init_app(self, app):
        """Flask application initialization."""
        self.init_config(app)
        Menu(app=app)

        @app.before_first_request
        def connect_signals():
            """Connect OAuthClient signals."""
            from invenio_oauthclient.signals import account_info_received

            from .utils import _create_and_associate_reana_user

            account_info_received.connect(
                _create_and_associate_reana_user
            )
예제 #15
0
    def test_active_checks_segment_not_prefix(self):
        Menu(self.app)

        @register_menu(self.app, 'object', 'Object')
        @self.app.route('/object')
        def object():
            return 'object'

        @register_menu(self.app, 'objects', 'Objects')
        @self.app.route('/objects')
        def objects():
            return 'objects'

        with self.app.test_client() as c:
            c.get('/objects')
            assert current_menu.submenu('object').active is not True
예제 #16
0
    def test_classy_endpoint_with_args(self):
        from flask_classy import FlaskView, route

        class MyEndpoint(FlaskView):
            route_base = '/'

            @classy_menu_item('withid.page1', 'Page 1')
            @route('/<int:id>/page1')
            def page1(self, id):
                return 'page1'

            @classy_menu_item('withid.page2', 'Page 2')
            @route('/<int:id>/page2')
            def page2(self, id):
                return 'page2'

        Menu(self.app)
        MyEndpoint.register(self.app)
        register_flaskview(self.app, MyEndpoint)

        data = {
            '/1/page1': {
                'withid.page1': True,
                'withid.page2': False,
            },
            '/1/page2': {
                'withid.page1': False,
                'withid.page2': True,
            }
        }

        for (path, v) in data.items():
            with self.app.test_client() as c:
                c.get(path)
                for (endpoint, active_should) in v.items():
                    active_is = current_menu.submenu(endpoint).active
                    self.assertEqual(
                        active_is,
                        active_should,
                        'path="{0}" submenu_by_endpoint="{1}" '
                        'active_is={2} active_should={3}'.format(
                            path,
                            endpoint,
                            active_is,
                            active_should
                        )
                    )
예제 #17
0
    def test_external_url(self):
        """Test that external_url works, and is not overriding endpoint."""
        Menu(self.app)
        menu = self.app.extensions['menu']

        url = 'https://python.org'

        item1 = menu.submenu('menuitem1')

        # Do not allow endpoint and external_url at the same time.
        self.assertRaises(TypeError,
                          item1.register,
                          endpoint='test',
                          text='Test',
                          external_url=url)

        item1.register(text='Test', external_url=url)
        assert menu.submenu('menuitem1').url == url
예제 #18
0
def app(instance_path, static_folder):
    """Flask application fixture."""
    app = Flask(
        'testapp',
        instance_path=instance_path,
        static_folder=static_folder,
    )
    app.config.from_object(config)
    app.config.update(
        TESTING=True,
        BASE_TEMPLATE='cernopendata_pages/base.html',
    )
    Babel(app)
    Menu(app)
    Breadcrumbs(app)

    app.register_blueprint(blueprint)
    return app
예제 #19
0
파일: conftest.py 프로젝트: kaorisakai/weko
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        TESTING=True,
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND="cache",
        COMMUNITIES_MAIL_ENABLED=False,
        SECRET_KEY='CHANGE_ME',
        SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO',
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        SEARCH_ELASTIC_HOSTS=os.environ.get('SEARCH_ELASTIC_HOSTS', None),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        OAISERVER_REGISTER_RECORD_SIGNALS=True,
        OAISERVER_REGISTER_SET_SIGNALS=False,
        OAISERVER_ID_PREFIX='oai:localhost:recid/',
        SERVER_NAME='inveniosoftware.org',
        THEME_SITEURL='https://inveniosoftware.org',
        MAIL_SUPPRESS_SEND=True,
    )
    FlaskCeleryExt(app)
    Menu(app)
    Babel(app)
    InvenioDB(app)
    InvenioAccounts(app)
    InvenioAssets(app)
    InvenioSearch(app)
    InvenioRecords(app)
    InvenioIndexer(app)
    InvenioOAIServer(app)
    InvenioCommunities(app)
    InvenioMail(app)

    app.register_blueprint(ui_blueprint)
    app.register_blueprint(api_blueprint, url_prefix='/api/communities')

    with app.app_context():
        yield app

    shutil.rmtree(instance_path)
예제 #20
0
    def test_visible_when_with_dynamic(self):
        Menu(self.app)

        @self.app.route('/always')
        @register_menu(self.app, 'always', 'Always', visible_when=lambda: True)
        def always():
            return 'never'

        @self.app.route('/never')
        @register_menu(self.app, 'never', 'Never', visible_when=lambda: False)
        def never():
            return 'never'

        @register_menu(self.app, 'normal', 'Normal')
        @self.app.route('/normal/<int:id>/')
        def normal(id):
            return 'normal'

        data = {
            'never': {'never': False, 'always': True, 'normal': True},
            'always': {'never': False, 'always': True, 'normal': True},
            'normal': {'never': False, 'always': True, 'normal': True},
        }
        for (k, v) in data.items():
            with self.app.test_client() as c:
                c.get('/' + k)
                for (endpoint, visible) in v.items():
                    self.assertEqual(current_menu.submenu(endpoint).visible,
                                     visible)

        with self.app.test_request_context():
            current_menu.submenu('always').hide()

        data = {
            'never': {'never': False, 'always': False, 'normal': True},
            'always': {'never': False, 'always': False, 'normal': True},
            'normal': {'never': False, 'always': False, 'normal': True},
        }
        for (k, v) in data.items():
            with self.app.test_client() as c:
                c.get('/' + k)
                for (endpoint, visible) in v.items():
                    self.assertEqual(current_menu.submenu(endpoint).visible,
                                     visible)
예제 #21
0
    def test_dynamic_url(self):
        Menu(self.app)

        @self.app.route('/<int:id>/<string:name>')
        @register_menu(self.app, 'test', 'Test',
                       endpoint_arguments_constructor=lambda: {
                           'id': request.view_args['id'],
                           'name': request.view_args['name'],
                       })
        def test(id, name):
            return str(id) + ':' + name

        with self.app.test_request_context():
            url = url_for('test', id=1, name='foo')

        with self.app.test_client() as c:
            c.get(url)
            assert url == current_menu.submenu('test').url
            assert current_menu.submenu('missing').url == '#'
예제 #22
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        ACCOUNTS_USE_CELERY=False,
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND="cache",
        MAIL_SUPPRESS_SEND=True,
        SECRET_KEY="CHANGE_ME",
        SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        TESTING=True,
        LOGIN_DISABLED=False,
        WTF_CSRF_ENABLED=False,
        SERVER_NAME='example.com',
    )
    FlaskCLI(app)
    Menu(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)

    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            drop_database(str(db.engine.url))
            # Delete sessions in kvsession store
            if hasattr(app, 'kvsession_store'):
                for key in app.kvsession_store.iter_keys():
                    app.kvsession_store.delete(key)
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)
    return app
예제 #23
0
def app(request):
    """Flask application fixture for E2E/integration/selenium tests.

    Overrides the `app` fixture found in `../conftest.py`. Tests/files in this
    folder and subfolders will see this variant of the `app` fixture.
    """
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        ACCOUNTS_USE_CELERY=False,
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND="cache",
        MAIL_SUPPRESS_SEND=True,
        SECRET_KEY="CHANGE_ME",
        SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        TESTING=True,
        LOGIN_DISABLED=False,
    )
    FlaskCLI(app)
    Menu(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)
    InvenioAccounts(app)
    app.register_blueprint(blueprint)

    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)
    return app
def base_app(instance_path, editor_config):
    """Flask application fixture."""
    app = Flask("testapp", instance_path=instance_path)

    app.config.update(
        SECRET_KEY="SECRET_KEY", TESTING=True, SERVER_NAME="localhost"
    )
    app.config.update(RECORDS_EDITOR_UI_CONFIG=editor_config)

    InvenioAccounts(app)
    InvenioAssets(app)
    InvenioJSONSchemas(app)
    InvenioRecordsEditor(app)
    Menu(app)

    from invenio_accounts.views.settings import blueprint
    app.register_blueprint(blueprint)

    app.register_blueprint(create_editor_blueprint(app))
    return app
예제 #25
0
    def init_app(self, app):
        """Flask application initialization."""
        self.init_config(app)
        Menu(app=app)

        @app.teardown_appcontext
        def shutdown_reana_db_session(response_or_exc):
            """Close session on app teardown."""
            from reana_db.database import Session as reana_db_session
            from invenio_db import db as invenio_db
            reana_db_session.remove()
            invenio_db.session.remove()
            return response_or_exc

        @app.before_first_request
        def connect_signals():
            """Connect OAuthClient signals."""
            from invenio_oauthclient.signals import account_info_received

            from .utils import _create_and_associate_reana_user

            account_info_received.connect(_create_and_associate_reana_user)
예제 #26
0
def app(request):
    """
    Flask application fixture.

    :param request: Request.
    :return: App object.
    """
    instance_path = tempfile.mkdtemp()
    app = Flask('weko_groups_app', instance_path=instance_path)
    app.config.update(
        LOGIN_DISABLED=False,
        MAIL_SUPPRESS_SEND=True,
        SECRET_KEY='1qertgyujk345678ijk',
        SQLALCHEMY_DATABASE_URI='sqlite:///weko_groups.db',
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    Babel(app)
    Menu(app)
    Breadcrumbs(app)
    InvenioDB(app)
    InvenioAccounts(app)
    WekoGroups(app)

    with app.app_context():
        if str(db.engine.url) != 'sqlite://' and \
           not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            if str(db.engine.url) != 'sqlite://':
                drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)
    return app
예제 #27
0
    def test_active_item(self):
        """Test active_item method."""
        Menu(self.app)

        @self.app.route('/')
        @register_menu(self.app, 'root', 'root')
        def root():
            return "root"

        @self.app.route('/sub1/item1')
        @register_menu(self.app, 'root.sub1.item1', 'Sub 1 - Item 1')
        def sub1_item1():
            return "sub1_item1"

        @self.app.route('/sub2/item1')
        @register_menu(self.app, 'root.sub2.item1', 'Sub 2 - Item 1')
        def sub2_item1():
            return "sub2_item1"

        @self.app.route('/sub2/item2')
        @register_menu(self.app, 'root.sub2.item2', 'Sub 2 - Item 2')
        def sub2_item2():
            return "sub2_item2"

        with self.app.test_client() as c:
            c.get('/')
            self.assertEqual(current_menu.active_item,
                             current_menu.submenu('root'))
            c.get('/sub1/item1')
            self.assertEqual(current_menu.active_item,
                             current_menu.submenu('root.sub1.item1'))
            sub1 = current_menu.submenu('root.sub1')
            self.assertEqual(sub1.active_item,
                             current_menu.submenu('root.sub1.item1'))
            sub2 = current_menu.submenu('root.sub2')
            self.assertIsNone(sub2.active_item)
            c.get('/sub2/item2')
            self.assertEqual(sub2.active_item,
                             current_menu.submenu('root.sub2.item2'))
예제 #28
0
def accounts(app):
    """Accounts."""
    app.config.update(
        WTF_CSRF_ENABLED=False,
        SECRET_KEY='CHANGEME',
        SECURITY_PASSWORD_SALT='CHANGEME',
        # conftest switches off permission checking, so re-enable it for this
        # app.
        RECORDS_REST_DEFAULT_CREATE_PERMISSION_FACTORY=
        'permissions:create_permission_factory',  # noqa
        RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY=
        'permissions:read_permission_factory',  # noqa
        RECORDS_REST_DEFAULT_UPDATE_PERMISSION_FACTORY=
        'permissions:update_permission_factory',  # noqa
        RECORDS_REST_DEFAULT_DELETE_PERMISSION_FACTORY=
        'permissions:delete_permission_factory',  # noqa
    )
    # FIXME: use OAuth authentication instead of UI authentication
    Menu(app)
    accounts = InvenioAccounts(app)
    app.register_blueprint(accounts_blueprint)
    InvenioAccess(app)
    return accounts
예제 #29
0
def app(request):
    """Flask application fixture."""
    app = Flask('testapp')
    app.config.update(
        TESTING=True,
        LOGIN_DISABLED=False,
        SECRET_KEY='test_key',
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI',
                                          'sqlite:///test.db'),
        WTF_CSRF_ENABLED=False,
        OAUTHLIB_INSECURE_TRANSPORT=True,
        OAUTH2_CACHE_TYPE='simple',
        SECURITY_PASSWORD_HASH='plaintext',
        SECURITY_PASSWORD_SCHEMES=['plaintext'],
    )
    FlaskCLI(app)
    Babel(app)
    Mail(app)
    Menu(app)
    Breadcrumbs(app)
    InvenioDB(app)
    InvenioAccounts(app)
    app.register_blueprint(accounts_blueprint)
    InvenioOAuth2Server(app)
    app.register_blueprint(server_blueprint)
    app.register_blueprint(settings_blueprint)

    with app.app_context():
        db.create_all()

    def teardown():
        with app.app_context():
            db.drop_all()

    request.addfinalizer(teardown)
    return app
예제 #30
0
def base_app():
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app_ = Flask('test_weko_admin_app', instance_path=instance_path)
    app_.config.update(
        ACCOUNTS_USE_CELERY=False,
        LOGIN_DISABLED=False,
        SECRET_KEY='testing_key',
        SQLALCHEMY_DATABASE_URI='sqlite:///test.db',
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_ECHO=False,
        TEST_USER_EMAIL='*****@*****.**',
        TEST_USER_PASSWORD='******',
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    app_.testing = True
    app_.login_manager = dict(_login_disabled=True)
    Babel(app_)
    Mail(app_)
    Menu(app_)
    InvenioDB(app_)
    WekoAdmin(app_)
    InvenioAccounts(app_)
    app_.register_blueprint(blueprint)

    with app_.app_context():
        if str(db.engine.url) != "sqlite://" \
                and not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    yield app_

    with app_.app_context():
        drop_database(str(db.engine.url))
    shutil.rmtree(instance_path)
예제 #31
0
 def init_app(app):
     app.config.update(
         LOGIN_DISABLED=False,
         MAIL_SUPPRESS_SEND=True,
         OAUTH2_CACHE_TYPE='simple',
         OAUTHLIB_INSECURE_TRANSPORT=True,
         SECRET_KEY='CHANGE_ME',
         SECURITY_DEPRECATED_PASSWORD_SCHEMES=[],
         SECURITY_PASSWORD_HASH='plaintext',
         SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO',
         SECURITY_PASSWORD_SCHEMES=['plaintext'],
         SQLALCHEMY_DATABASE_URI=os.getenv(
             'SQLALCHEMY_DATABASE_URI',
             'sqlite:///' + os.path.join(instance_path, 'test.db')),
         SQLALCHEMY_TRACK_MODIFICATIONS=True,
         TESTING=True,
         WTF_CSRF_ENABLED=False,
     )
     Babel(app)
     Mail(app)
     Menu(app)
     Breadcrumbs(app)
     InvenioDB(app)
     InvenioOAuth2Server(app)
예제 #32
0
def base_app(app_config):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    base_app = Flask(__name__, instance_path=instance_path)
    base_app.config.update(app_config)

    Babel(base_app)
    Mail(base_app)
    Menu(base_app)
    InvenioDB(base_app)
    InvenioAccounts(base_app)
    base_app.register_blueprint(accounts_blueprint)

    with base_app.app_context():
        if str(db.engine.url) != "sqlite://" and \
                not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    yield base_app

    with base_app.app_context():
        drop_database(str(db.engine.url))
    shutil.rmtree(instance_path)
예제 #33
0
def base_app():
    """Flask application fixture."""
    app_ = Flask('testapp')
    app_.config.update(
        TESTING=True,
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///:memory:'),
        WTF_CSRF_ENABLED=False,
        SERVER_NAME='invenio.org',
        SECURITY_PASSWORD_SALT='TEST_SECURITY_PASSWORD_SALT',
        SECRET_KEY='TEST_SECRET_KEY',
        FILES_REST_MULTIPART_CHUNKSIZE_MIN=2,
        FILES_REST_MULTIPART_CHUNKSIZE_MAX=20,
        FILES_REST_MULTIPART_MAX_PARTS=100,
    )

    FlaskCLI(app_)
    FlaskCeleryExt(app_)
    InvenioDB(app_)
    Babel(app_)
    Menu(app_)

    return app_
예제 #34
0
                          os.environ['RECAPTCHA_PUBLIC_KEY'])
    app.config.setdefault('RECAPTCHA_PRIVATE_KEY',
                          os.environ['RECAPTCHA_PRIVATE_KEY'])

Babel(app)
Mail(app)
InvenioDB(app)
InvenioAccounts(app)
InvenioI18N(app)

if INVENIO_ASSETS_AVAILABLE:
    InvenioAssets(app)
if INVENIO_THEME_AVAILABLE:
    InvenioTheme(app)
else:
    Menu(app)
if INVENIO_ADMIN_AVAILABLE:
    InvenioAdmin(app,
                 permission_factory=lambda x: x,
                 view_class_factory=lambda x: x)
app.register_blueprint(blueprint)


@app.route("/")
def index():
    """Basic test view."""
    if current_user.is_authenticated:
        return render_template("authenticated.html")
    else:
        return render_template("anonymous.html")
예제 #35
0
class InvenioTheme(object):
    """Invenio theme extension."""

    def __init__(self, app=None, **kwargs):
        r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.
        """
        self.menu_ext = Menu()
        self.menu = None
        self.breadcrumbs = Breadcrumbs()

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, **kwargs):
        """Initialize application object.

        :param app: An instance of :class:`~flask.Flask`.
        """
        self.init_config(app.config)

        # Initialize extensions
        self.menu_ext.init_app(app)
        self.menu = app.extensions['menu']
        self.breadcrumbs.init_app(app)

        # Register blueprint in order to register template and static folder.
        blueprint = Blueprint(
            'invenio_theme',
            __name__,
            template_folder='templates',
            static_folder='static',
        )
        app.register_blueprint(blueprint)

        # Initialize breadcrumbs.
        item = self.menu.submenu('breadcrumbs')
        item.register(app.config['THEME_BREADCRUMB_ROOT_ENDPOINT'], _('Home'))

        # Register errors handlers.
        app.register_error_handler(401, unauthorized)
        app.register_error_handler(403, insufficient_permissions)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(500, internal_error)

        # Save reference to self on object
        app.extensions['invenio-theme'] = self

    def init_config(self, config):
        """Initialize configuration.

        :param config: A dict like object where default values should be set.
        """
        config.setdefault('SASS_BIN', 'node-sass')
        config.setdefault('THEME_SITENAME', 'Invenio')
        config.setdefault('THEME_LOGO', 'images/invenio-color.svg')
        config.setdefault('THEME_LOGO_ADMIN', 'images/invenio-white.svg')
        config.setdefault('REQUIREJS_CONFIG', 'js/build.js')
        config.setdefault('THEME_GOOGLE_SITE_VERIFICATION', [])
        config.setdefault('BASE_TEMPLATE', 'invenio_theme/page.html')
        config.setdefault(
            'COVER_TEMPLATE', 'invenio_theme/page_cover.html')
        config.setdefault(
            'SETTINGS_TEMPLATE', 'invenio_theme/page_settings.html')
        config.setdefault(
            'HEADER_TEMPLATE', 'invenio_theme/header.html')
        config.setdefault(
            'THEME_BASE_TEMPLATE', config['BASE_TEMPLATE'])
        config.setdefault(
            'THEME_COVER_TEMPLATE', config['COVER_TEMPLATE'])
        config.setdefault(
            'THEME_SETTINGS_TEMPLATE', config['SETTINGS_TEMPLATE'])
        config.setdefault(
            'THEME_ERROR_TEMPLATE', 'invenio_theme/error.html')
        config.setdefault(
            'THEME_401_TEMPLATE', 'invenio_theme/401.html')
        config.setdefault(
            'THEME_403_TEMPLATE', 'invenio_theme/403.html')
        config.setdefault(
            'THEME_404_TEMPLATE', 'invenio_theme/404.html')
        config.setdefault(
            'THEME_500_TEMPLATE', 'invenio_theme/500.html')

        config.setdefault('THEME_SEARCHBAR', True)
        config.setdefault('THEME_SEARCH_ENDPOINT', '/search')
        config.setdefault('THEME_BREADCRUMB_ROOT_ENDPOINT', '')
        # Integration with Invenio-Admin:
        config.setdefault(
            'ADMIN_BASE_TEMPLATE', 'invenio_theme/admin.html')
예제 #36
0
from flask import Flask
from flask_menu import Menu

from app.mod_home.controllers import mod_home
from app.mod_heating.controllers import mod_heating
from app.mod_watersupply.controllers import mod_watersupply
from app.mod_electric.controllers import mod_electric
from app.mod_ventilation.controllers import mod_ventilation
from app.mod_constructing.controllers import mod_constructing
from app.mod_contacts.controllers import mod_contacts

app = Flask(__name__)
Menu(app=app)

app.config.from_object('config')

app.register_blueprint(mod_home)
app.register_blueprint(mod_heating)
app.register_blueprint(mod_watersupply)
app.register_blueprint(mod_electric)
app.register_blueprint(mod_ventilation)
app.register_blueprint(mod_constructing)
app.register_blueprint(mod_contacts)
예제 #37
0
from flask_menu import Menu

menu = Menu()


def configure(app):
    menu.init_app(app)


예제 #38
0
파일: ext.py 프로젝트: kaplun/inspire-next
class INSPIRETheme(object):
    """Invenio theme extension."""

    def __init__(self, app=None, **kwargs):
        """Extension initialization."""
        self.menu_ext = Menu()
        self.menu = None
        self.breadcrumbs = Breadcrumbs()
        self.weblinks = self.init_weblinks_dictionary()

        if app:
            self.init_app(app, **kwargs)
            self.setup_app(app)

    def init_app(self, app, assets=None, **kwargs):
        """Initialize application object."""
        self.init_config(app.config)

        # Initialize extensions
        self.menu_ext.init_app(app)
        self.menu = app.extensions['menu']
        self.breadcrumbs.init_app(app)

        app.register_blueprint(blueprint)

        # Add Jinja2 extensions.
        app.jinja_env.add_extension('jinja2.ext.do')

        # Register errors handlers.
        app.register_error_handler(401, unauthorized)
        app.register_error_handler(403, insufficient_permissions)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(500, internal_error)

        # Save reference to self on object
        app.extensions['inspire-theme'] = self

    def init_config(self, config):
        """Initialize configuration."""
        from .bundles import js
        # Set JS bundles to exclude for purpose of avoiding double jQuery etc.
        # when other modules are building their JS bundles.
        config.setdefault("THEME_BASE_BUNDLES_EXCLUDE_JS", [js])
        config.setdefault("BASE_TEMPLATE", "inspirehep_theme/page.html")

    def setup_app(self, app):
        """Initialize Gravatar extension."""
        from flask_gravatar import Gravatar
        gravatar = Gravatar(app,
                            size=app.config.get('GRAVATAR_SIZE', 100),
                            rating=app.config.get('GRAVATAR_RATING', 'g'),
                            default=app.config.get(
                                'GRAVATAR_DEFAULT', 'retro'),
                            force_default=False,
                            force_lower=False)
        del gravatar
        return app

    def init_weblinks_dictionary(self):
        """Initialize the dictionary for HEP detailed record external links."""
        weblinks_dictionary = {}
        with open(resource_filename('inspirehep', 'kbs/weblinks.kb'), 'r') as kb_file:
            for line in kb_file:
                (key, val) = line.split('---')
                weblinks_dictionary[key] = val
            return weblinks_dictionary
예제 #39
0
파일: ext.py 프로젝트: tind/invenio-theme
class InvenioTheme(object):
    """Invenio theme extension."""

    def __init__(self, app=None, **kwargs):
        """Extension initialization."""
        self.menu_ext = Menu()
        self.menu = None
        self.breadcrumbs = Breadcrumbs()

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, assets=None, **kwargs):
        """Initialize application object."""
        self.init_config(app.config)

        # Initialize extensions
        self.menu_ext.init_app(app)
        self.menu = app.extensions['menu']
        self.breadcrumbs.init_app(app)

        # Register blueprint in order to register template and static folder.
        blueprint = Blueprint(
            'invenio_theme',
            __name__,
            template_folder='templates',
            static_folder='static',
        )
        app.register_blueprint(blueprint)

        # Register errors handlers.
        app.register_error_handler(401, unauthorized)
        app.register_error_handler(403, insufficient_permissions)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(500, internal_error)

        # Save reference to self on object
        app.extensions['invenio-theme'] = self

    def init_config(self, config):
        """Initialize configuration."""
        config.setdefault('SASS_BIN', 'node-sass')
        config.setdefault("THEME_SITENAME", _("Invenio"))
        config.setdefault("THEME_LOGO", "images/invenio-color.svg")
        config.setdefault("REQUIREJS_CONFIG", 'js/build.js')
        config.setdefault("THEME_GOOGLE_SITE_VERIFICATION", [])
        config.setdefault('BASE_TEMPLATE', 'invenio_theme/page.html')
        config.setdefault(
            'COVER_TEMPLATE', 'invenio_theme/page_cover.html')
        config.setdefault(
            'SETTINGS_TEMPLATE', 'invenio_theme/page_settings.html')
        config.setdefault(
            'THEME_BASE_TEMPLATE', config['BASE_TEMPLATE'])
        config.setdefault(
            'THEME_COVER_TEMPLATE', config['COVER_TEMPLATE'])
        config.setdefault(
            'THEME_SETTINGS_TEMPLATE', config['SETTINGS_TEMPLATE'])
        config.setdefault(
            'THEME_ERROR_TEMPLATE', 'invenio_theme/error.html')
        config.setdefault(
            'THEME_401_TEMPLATE', 'invenio_theme/401.html')
        config.setdefault(
            'THEME_403_TEMPLATE', 'invenio_theme/403.html')
        config.setdefault(
            'THEME_404_TEMPLATE', 'invenio_theme/404.html')
        config.setdefault(
            'THEME_500_TEMPLATE', 'invenio_theme/500.html')