Esempio n. 1
0
def create_admin(app=None):
    admin = Admin(app,name='YuanshanAdmin',index_view=MyIndexView(),
              base_template='admin/master.html')
    admin.add_view(UserView(User,db.session))
    admin.add_view(PostView(Post,db.session))
#    admin.add_view(ModelView(Friend_link, db.session))
    admin.add_view(MyAdminView(Tag, db.session))
Esempio n. 2
0
def create_app(config='config.ProductionDevelopmentConfig'):
    app = Flask(__name__)

    app.config.from_object(config)

    db.init_app(app)

    mixer.init_app(app)

    app.before_request(setup_authomatic(app))
    app.before_request(load_user)

    app.add_url_rule('/', 'index', index)

    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(issues_bp, url_prefix='/issues')
    app.register_blueprint(comments_bp, url_prefix='/comments')
    app.register_blueprint(organizations_bp, url_prefix='/organizations')

    admin = Admin(app)

    # add admin views.
    admin.add_view(AdminView(User, db.session))
    admin.add_view(AdminView(Issue, db.session))
    admin.add_view(AdminView(Comment, db.session))
    admin.add_view(AdminView(Organization, db.session))
    admin.add_view(AdminView(Vote, db.session))

    return app
Esempio n. 3
0
def init_admin():
    admin = Admin(app)
    admin.add_view(UserModelView(User, db.session, category='Auth'))
    admin.add_view(AdminModelView(Role, db.session, category='Auth'))
    admin.add_view(AdminModelView(SomeStuff, db.session))
    admin.add_view(LogoutView(name='Logout', endpoint='logout'))
    admin.add_view(LoginView(name='Login', endpoint='login'))
Esempio n. 4
0
def init_admin(self, index_view=None):
    from .. import db
    from ..models import User, Role
    from ..views import AdminIndex, UserAdmin, RoleAdmin, public_blueprint

    admin = Admin(
        name=self.app.config['PROJECT_NAME'] or 'Admin',
        base_template='admin/extended_base.html',
        index_view=index_view or AdminIndex(url='/admin'),
        template_mode='bootstrap3'
    )

    admin.init_app(self.app)

    admin.add_view(UserAdmin(User, db.session, name='用户管理', category='系统管理'))
    admin.add_view(RoleAdmin(Role, db.session, name='角色管理', category='系统管理'))

    with self.app.app_context():
        @_security.context_processor
        def security_context_processor():
            return dict(
                admin_base_template=admin.base_template,
                admin_view=admin.index_view,
                h=admin_helpers,
            )

        @public_blueprint.context_processor
        def public_context_processor():
            return dict(
                admin_base_template=admin.base_template,
                admin_view=admin.index_view,
                h=admin_helpers,
            )

    return admin
Esempio n. 5
0
def create_app(settings_override=None):
    """Returns the Overholt dashboard application instance"""
    app = factory.create_app(__name__, __path__, settings_override)

    # Configure sentry to track errors on the production app
    Sentry(app)

    # Configure flask moment to show nice timestamps
    Moment(app)

    # Configure Admin
    admin = Admin(app, index_view=MyHomeView())
    admin.add_view(UserView(db.session, category="Users"))
    admin.add_view(AdminModel(Role, db.session, category="Users"))

    # Register custom error handlers
    if not app.debug:
        for e in [500, 404]:
            app.errorhandler(e)(handle_error)

    app.jinja_env.filters['gravatar'] = gravatar
    app.jinja_env.filters['format_currency'] = format_currency
    app.jinja_env.filters['nl2br'] = nl2br
    app.jinja_env.filters['firstname'] = firstname
    app.jinja_env.filters['pretty_date'] = pretty_date
    app.jinja_env.globals.update(current_date=current_date())

    return app
Esempio n. 6
0
def create_app(name, config_filename):
    app = Flask(name,
                template_folder='app/templates',
                static_folder='app/static')
    app.config.from_pyfile(config_filename)

    from app.models import db
    db.init_app(app)
    db.app = app
    from app.sms import mail
    mail.init_app(app)
    mail.app = app

    from app.views import main
    app.register_blueprint(main)

    #TODO: Secure admin view
    admin = Admin()
    admin.init_app(app)
    admin.app = app
    admin.add_view(ModelView(User, db.session))

    if not (app.debug or app.config.get('LOGGING_DISABLE', False)):
        import logging
        from logging import Formatter
        from logging.handlers import SMTPHandler, RotatingFileHandler
        mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                                   fromaddr=app.config['LOGGING_SENDER'],
                                   toaddrs=app.config['ADMINS'],
                                   subject='dci-notify Server Error',
                                   credentials=(app.config['MAIL_USERNAME'],
                                                app.config['MAIL_PASSWORD']))

        file_handler = RotatingFileHandler(filename=os.path.join(basedir,
                                                                 'app.log'),
                                           maxBytes=1048756,
                                           backupCount=5)

        mail_handler.setLevel(logging.ERROR)
        file_handler.setLevel(logging.WARNING)
        mail_handler.setFormatter(Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''))

        file_handler.setFormatter(Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'
        ))
        app.logger.addHandler(mail_handler)
        app.logger.addHandler(file_handler)

    return app
Esempio n. 7
0
def register_classes_for_admin(db_session, show_pks=True, name='admin'):
    """Registers classes for the Admin view that ultimately creates the admin
    interface.

    :param db_session: handle to database session
    :param list classes: list of classes to register with the admin
    :param bool show_pks: show primary key columns in the admin?

    """

    with app.app_context():
        admin_view = Admin(current_app, name=name)
        for cls in set(cls for cls in current_app.class_references.values()
                       if cls.use_admin):
            column_list = [
                column.name for column in cls.__table__.columns.values()
            ]
            if hasattr(cls, '__view__'):
                # allow ability for model classes to specify model views
                admin_view_class = type('AdminView', (cls.__view__, ),
                                        {'form_columns': column_list})
            elif show_pks:
                # the default of Flask-SQLAlchemy is to not show primary
                # classes, which obviously isn't acceptable in some cases
                admin_view_class = type('AdminView', (AdminModelViewWithPK, ),
                                        {'form_columns': column_list})
            else:
                admin_view_class = ModelView
            admin_view.add_view(admin_view_class(cls, db_session))
Esempio n. 8
0
def build_app(app):
    app.register_blueprint(auth_bundle)
    app.register_blueprint(home_bundle)
    app.register_blueprint(api_bundle)
    app.register_blueprint(profile_bundle)
    app.register_blueprint(content_bundle)
    app.register_blueprint(search_bundle)
    # Config to Flask from objects
    # app.config.from_object('fedora_college.core.ProductionConfig')
    app.config.from_object('fedora_college.core.config.DevelopmentConfig')
    db.init_app(app)

    # FAS OpenID Instance
    with app.app_context():
        whooshalchemy.whoosh_index(app, Content)
        whooshalchemy.whoosh_index(app, Media)
        DebugToolbarExtension(app)
        admin = Admin(
            app, 'Auth', index_view=FedoraAdminIndexView())
        admin.add_view(FedoraModelView(UserProfile, db.session))
        admin.add_view(FedoraModelView(Content, db.session))
        admin.add_view(FedoraModelView(Media, db.session))
        admin.add_view(FedoraModelView(Tags, db.session))
        admin.add_view(
            FedoraFileView(
                current_app.config['STATIC_FOLDER'],
                name='Static Files'
            )
        )
        current_app.config['fas'] = FAS(app)
Esempio n. 9
0
    def get_app(self):
        app = Flask(__name__)

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

        class HomeView(AdminIndexView):

            @expose("/")
            def index(self):
                return redirect('/admin/dashboard')

        admin = Admin(
            app,
            name="Honeypot",
            index_view=HomeView())
        admin._menu = []
        view = Dashboard(
                table=self.table_name,
                sql_conn_id=self.sql_conn_id,
                sample_data=False)
        admin.add_view(view)

        return app
Esempio n. 10
0
def create_app(config='config.ProductionDevelopmentConfig'):
    app = Flask(__name__)

    app.config.from_object(config)

    db.init_app(app)

    mixer.init_app(app)

    app.before_request(setup_authomatic(app))
    app.before_request(load_user)

    app.add_url_rule('/', 'index', index)

    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(issues_bp, url_prefix='/issues')
    app.register_blueprint(comments_bp, url_prefix='/comments')
    app.register_blueprint(organizations_bp, url_prefix='/organizations')

    admin = Admin(app)

    # add admin views.
    admin.add_view(AdminView(User, db.session))
    admin.add_view(AdminView(Issue, db.session))
    admin.add_view(AdminView(Comment, db.session))
    admin.add_view(AdminView(Organization, db.session))
    admin.add_view(AdminView(Vote, db.session))

    return app
Esempio n. 11
0
def configure_extensions(app):
    # configure extensions
    # sqlalchemy
    db.init_app(app)
    db_ean.init_app(app)
    # mail
    mail.init_app(app)
    # cache
    cache.init_app(app)
    # babel
    babel = Babel(app)
    # login
    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.reauth'

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    login_manager.setup_app(app)
    # security and Social
    app.flask_security = Security(app, SQLAlchemyUserDatastore(db, User, Role))
    #app.flask_social = Social(app, SQLAlchemyConnectionDatastore(db, Connection))
    # admin
    admin = Admin(app)
    #admin.add_view(ModelView(GenomeRule, db.session))
    admin.add_view(GenomeRuleView(db.session, name="Genome Rules"))
    admin.add_view(GenomeCategoryView(db.session, name="Genome Categories"))
Esempio n. 12
0
def create_admin(app=None):
    admin = Admin(app,
                  name="CleanBlogAdmin",
                  index_view=MyIndexView(),
                  base_template='admin/my_master.html')
    admin.add_view(UserView(User))
    admin.add_view(PostView(Post))
Esempio n. 13
0
def test_admin(app):
    """Test flask-admin interace."""
    InvenioOAuthClient(app)

    assert isinstance(remote_account_adminview, dict)
    assert isinstance(remote_token_adminview, dict)

    assert 'model' in remote_account_adminview
    assert 'modelview' in remote_account_adminview
    assert 'model' in remote_token_adminview
    assert 'modelview' in remote_token_adminview

    admin = Admin(app, name='Test')

    user_model = remote_account_adminview.pop('model')
    user_view = remote_account_adminview.pop('modelview')
    admin.add_view(user_view(user_model, db.session,
                             **remote_account_adminview))

    with app.app_context():
        # create user and save url for testing
        request_url = url_for('remoteaccount.index_view')

    with app.app_context():
        with app.test_client() as client:
            res = client.get(
                request_url,
                follow_redirects=True
            )
            assert res.status_code == 200
            assert 'Extra Data' in str(res.get_data())
            assert 'Tokens' in str(res.get_data())
Esempio n. 14
0
def build_app(app):
    app.register_blueprint(auth_bundle)
    app.register_blueprint(home_bundle)
    app.register_blueprint(api_bundle)
    app.register_blueprint(profile_bundle)
    app.register_blueprint(content_bundle)
    app.register_blueprint(search_bundle)
    # Config to Flask from objects
    # app.config.from_object('fedora_college.core.ProductionConfig')
    app.config.from_object('fedora_college.core.config.DevelopmentConfig')
    db.init_app(app)

    # FAS OpenID Instance
    with app.app_context():
        whooshalchemy.whoosh_index(app, Content)
        whooshalchemy.whoosh_index(app, Media)
        DebugToolbarExtension(app)
        admin = Admin(app, 'Auth', index_view=FedoraAdminIndexView())
        admin.add_view(FedoraModelView(UserProfile, db.session))
        admin.add_view(FedoraModelView(Content, db.session))
        admin.add_view(FedoraModelView(Media, db.session))
        admin.add_view(FedoraModelView(Tags, db.session))
        admin.add_view(
            FedoraFileView(current_app.config['STATIC_FOLDER'],
                           name='Static Files'))
        current_app.config['fas'] = FAS(app)
Esempio n. 15
0
def activate_admin_classes():
    prepare_relationships()
    admin = Admin(app)
    with app.app_context():
        for cls in (cls for cls in current_app.classes_by_name.values()
                    if cls._use_admin == True):
            admin.add_view(ModelView(cls, db.session))
Esempio n. 16
0
def register_admin(app):
    """Register admin application."""
    admin = Admin(
        app,
        template_mode='bootstrap3'
    )
    admin.add_view(AdminUserView(User, db.session))
Esempio n. 17
0
def create_app(name=__name__, config={},
               static_folder='static', template_folder='templates'):

    app = Flask(name, static_folder=static_folder,
                template_folder=template_folder)
    app.secret_key = os.environ.get('SECRET', 'secret')
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DB_URI']
    app.config['DEBUG'] = bool(os.environ.get('DEBUG', False))

    app.config.update(config)

    from finance.models import db
    db.init_app(app)

    from finance.main import main_module
    app.register_blueprint(main_module, url_prefix='')

    admin = Admin(app, name='finance', template_mode='bootstrap3')
    from finance.models import (
        Account, Asset, AssetValue, Portfolio, Record, Transaction, User)
    classes = [Account, Asset, AssetValue, Portfolio, Record, Transaction,
               User]
    for cls in classes:
        admin.add_view(ModelView(cls, db.session,
                                 endpoint=cls.__name__))

    login_manager = LoginManager(app)
    login_manager.login_view = 'user.login'

    from finance.utils import date_range
    app.jinja_env.filters['date_range'] = date_range

    return app
Esempio n. 18
0
def init_app(app):
    config = {
        'url': '/',
    }
    imv = ItemManutencaoView()
    file_upload_path = os.path.join(app.instance_path, u'storage')
    if not os.path.isdir(file_upload_path):
        os.makedirs(file_upload_path)
    views = [
        # endereco
        RegiaoView(),
        BairroView(),
        LogradouroView(),
        # protocolos
        PlanilhaUploadView(base_path=file_upload_path, name=u'Upload de planilha de protocolos',
                           category=u'Protocolos'),
        ProtocoloView(),
        PosteView(imv),
        imv,  # Retirar em prod
        OrdemServicoView(),
        # equipamentos
        EquipamentoView(),
        PrecoEquipamentoView(),
        # usuarios
        UserView(),
        RoleView(),

    ]
    index = IndexView(name='Principal', **config)
    admin = Admin(app, template_mode='bootstrap3', index_view=index, name='Cidade Iluminada',
                  **config)
    for view in views:
        admin.add_view(view)
Esempio n. 19
0
def register_classes_for_admin(db_session, show_pks=True, name='admin'):
    """Registers classes for the Admin view that ultimately creates the admin
    interface.

    :param db_session: handle to database session
    :param list classes: list of classes to register with the admin
    :param bool show_pks: show primary key columns in the admin?

    """

    with app.app_context():
        admin_view = Admin(current_app, name=name)
        for cls in set(
            cls for cls in current_app.class_references.values() if
                cls.use_admin):
            column_list = [column.name for column in
                           cls.__table__.columns.values()]
            if hasattr(cls, '__view__'):
                # allow ability for model classes to specify model views
                admin_view_class = type(
                    'AdminView',
                    (cls.__view__,),
                    {'form_columns': column_list})
            elif show_pks:
                # the default of Flask-SQLAlchemy is to not show primary
                # classes, which obviously isn't acceptable in some cases
                admin_view_class = type(
                    'AdminView',
                    (AdminModelViewWithPK,),
                    {'form_columns': column_list})
            else:
                admin_view_class = ModelView
            admin_view.add_view(admin_view_class(cls, db_session))
Esempio n. 20
0
def activate(admin=True):
    """Activate each registered model for non-admin use"""
    with app.app_context():
        if getattr(current_app, 'endpoint_classes', None) is None:
            current_app.endpoint_classes = {}
            current_app.classes_by_name = {}
            current_app.table_to_endpoint = {}
            current_app.classes = []
        if not current_app.endpoint_classes:
            db.metadata.reflect(bind=db.engine)
            for name, table in db.metadata.tables.items():
                try:
                    cls = type(str(name), (sandman_model, db.Model),
                               {'__tablename__': name})
                    register(cls)
                except:
                    print name + ' unable to be registered'
        else:
            Model.prepare(db.engine)
    if admin:
        _prepare_relationships()
        admin = Admin(app)
        with app.app_context():
            for cls in (cls for cls in current_app.classes
                        if cls.use_admin == True):
                admin.add_view(ModelView(cls, db.session))
        webbrowser.open('http://localhost:5000/admin')
Esempio n. 21
0
def test_admin(app):
    """Test flask-admin interace."""
    InvenioUserProfiles(app)

    assert isinstance(user_profile_adminview, dict)

    assert 'model' in user_profile_adminview
    assert 'modelview' in user_profile_adminview

    admin = Admin(app, name="Test")

    user_model = user_profile_adminview.pop('model')
    user_view = user_profile_adminview.pop('modelview')
    admin.add_view(user_view(user_model, db.session,
                             **user_profile_adminview))

    with app.test_request_context():
        request_url = url_for('userprofile.index_view')

    with app.app_context():
        with app.test_client() as client:
            res = client.get(
                request_url,
                follow_redirects=True
            )
            assert res.status_code == 200
            assert b'Display Name' in (res.get_data())
            assert b'Full Name' in (res.get_data())
Esempio n. 22
0
def test_admin(models_fixture):
    """Test flask-admin interface."""
    app = models_fixture
    InvenioOAuth2Server(app)

    assert isinstance(oauth2server_tokens_adminview, dict)
    assert isinstance(oauth2server_clients_adminview, dict)

    assert 'view_class' in oauth2server_tokens_adminview
    assert 'view_class' in oauth2server_clients_adminview

    admin = Admin(app, name="Test")

    clients_view = oauth2server_clients_adminview.pop('view_class')
    clients_model, clients_session = oauth2server_clients_adminview.pop('args')
    clients_kwargs = oauth2server_clients_adminview.pop('kwargs')
    tokens_view = oauth2server_tokens_adminview.pop('view_class')
    tokens_model, tokens_session = oauth2server_tokens_adminview.pop('args')
    tokens_kwargs = oauth2server_tokens_adminview.pop('kwargs')
    admin.add_view(clients_view(clients_model, db.session, **clients_kwargs))
    admin.add_view(tokens_view(tokens_model, db.session, **tokens_kwargs))

    menu_items = {str(item.name): item for item in admin.menu()}
    assert 'User Management' in menu_items
    assert menu_items['User Management'].is_category()

    submenu_items = {
        str(item.name): item
        for item in menu_items['User Management'].get_children()
    }
    assert 'OAuth Applications' in submenu_items
    assert 'OAuth Application Tokens' in submenu_items

    with app.test_request_context():
        token_request_url = url_for('token.index_view')
        client_request_url = url_for('client.index_view')
        client_view_url = url_for('invenio_oauth2server_settings.client_view',
                                  client_id='client_test_u1c1')
        client_reset_url = url_for(
            'invenio_oauth2server_settings.client_reset',
            client_id='client_test_u1c1')
        token_view_url = url_for('invenio_oauth2server_settings.token_view',
                                 token_id='1')
        token_revoke_url = url_for(
            'invenio_oauth2server_settings.token_revoke', token_id='1')

    with app.app_context():
        with app.test_client() as client:
            res = client.get(token_request_url, follow_redirects=True)
            assert res.status_code == 200
            res = client.get(client_request_url, follow_redirects=True)
            assert res.status_code == 200
            res = client.get(client_view_url, follow_redirects=True)
            assert res.status_code == 200
            res = client.post(client_reset_url, follow_redirects=True)
            assert res.status_code == 200
            res = client.get(token_view_url, follow_redirects=True)
            assert res.status_code == 200
            res = client.post(token_revoke_url, follow_redirects=True)
            assert res.status_code == 405
Esempio n. 23
0
def create_app(name, config_filename):
    app = Flask(name,
                template_folder='app/templates',
                static_folder='app/static')
    app.config.from_pyfile(config_filename)

    from app.models import db
    db.init_app(app)
    db.app = app
    from app.sms import mail
    mail.init_app(app)
    mail.app = app

    from app.views import main
    app.register_blueprint(main)

    #TODO: Secure admin view
    admin = Admin()
    admin.init_app(app)
    admin.app = app
    admin.add_view(ModelView(User, db.session))

    if not (app.debug or app.config.get('LOGGING_DISABLE', False)):
        import logging
        from logging import Formatter
        from logging.handlers import SMTPHandler, RotatingFileHandler
        mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                                   fromaddr=app.config['LOGGING_SENDER'],
                                   toaddrs=app.config['ADMINS'],
                                   subject='dci-notify Server Error',
                                   credentials=(app.config['MAIL_USERNAME'],
                                                app.config['MAIL_PASSWORD']))

        file_handler = RotatingFileHandler(filename=os.path.join(
            basedir, 'app.log'),
                                           maxBytes=1048756,
                                           backupCount=5)

        mail_handler.setLevel(logging.ERROR)
        file_handler.setLevel(logging.WARNING)
        mail_handler.setFormatter(
            Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''))

        file_handler.setFormatter(
            Formatter('%(asctime)s %(levelname)s: %(message)s '
                      '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(mail_handler)
        app.logger.addHandler(file_handler)

    return app
Esempio n. 24
0
def activate(admin=True):
    """Activate each registered model for non-admin use"""
    with app.app_context():
        if getattr(current_app, 'endpoint_classes', None) is None:
            current_app.endpoint_classes = {}
            current_app.classes_by_name = {}
            current_app.table_to_endpoint = {}
            current_app.classes = []
        if not current_app.endpoint_classes:
            db.metadata.reflect(bind=db.engine)
            for name, table in db.metadata.tables.items():
                try:
                    cls = type(str(name), (sandman_model, db.Model), {'__tablename__': name})
                    register(cls)
                except:
                    print name + ' unable to be registered'
        else:
            Model.prepare(db.engine)
    if admin:
        _prepare_relationships()
        admin = Admin(app)
        with app.app_context():
            for cls in (cls for cls in current_app.classes if cls.use_admin == True):
                admin.add_view(ModelView(cls, db.session))
        webbrowser.open('http://localhost:5000/admin')
Esempio n. 25
0
def create_app(options):
    """
        Create the application. Files outside the app directory can import
        this function and use it to create the application
    """
    app = Flask(__name__)
    
    # config
    app.config.from_object(settings)
    app.config.update(options)
    
    # views as blueprint
    app.register_blueprint(comments_bp)
    
    # db
    db.init_app(app)
    
    # admin
    admin = Admin(app, name="Comimoc", index_view=LoginView(app.config, name="Index"))
    admin.add_view(CommentModelView())
    admin.add_view(UserModelView())
    
    # login
    login_manager = LoginManager(app)
    @login_manager.user_loader
    def load_user(user_id):
        # .first() return None if no user as Flask-Login needs
        return User.objects(id=user_id).first()
    
    # CORS
    @app.after_request
    def add_headers(response):
        '''
        Add some headers to the response
        to be able to perform some CORS request
        '''
        if not app.config.get("USE_CORS", False):
            return response
        
        origin = request.headers.get("Origin")
        if origin not in app.config['CORS_ALLOW_ORIGIN_WHITELIST']:
            return response
        
        response.headers.add('Access-Control-Allow-Origin', origin)
        if app.config['CORS_ALLOW_CREDENTIALS']:
            response.headers.add('Access-Control-Allow-Credentials', 'true')
        response.headers.add('Access-Control-Allow-Methods', app.config['CORS_ALLOW_METHODS'])
        response.headers.add('Access-Control-Allow-Headers', app.config['CORS_ALLOW_HEADERS'])
        response.headers.add('Access-Control-Max-Age', app.config['CORS_MAX_AGE'])
        
        return response
    
    # ping pong
    @app.route('/ping', methods=['GET'])
    def ping():
        return 'pong', 200
    
    
    return app
Esempio n. 26
0
def register_extensions(app):
    db.init_app(app)
    with app.app_context():
        db.create_all()
    if app.debug:
        admin = Admin(app)
        admin.add_view(ModelView(Channel, db.session))
        admin.add_view(ModelView(File, db.session))
Esempio n. 27
0
def configure_admin(app):
	from admin.admin_view import AdminIndex
	from flask.ext.admin.contrib.sqlamodel import ModelView

	admin = Admin(app, name='My App', index_view=AdminIndex())
	admin.add_view(ModelView(User, db.session))
	admin.add_view(ModelView(Patient, db.session))
	admin.add_view(ModelView(Address, db.session))
Esempio n. 28
0
def activate_admin_classes():
    """Activate each registed Model in the admin if it was registered with
    *use_admin=True*."""
    _prepare_relationships()
    admin = Admin(app)
    with app.app_context():
        for cls in (cls for cls in current_app.classes_by_name.values() if cls.use_admin == True):
            admin.add_view(ModelView(cls, db.session))
Esempio n. 29
0
def admin(app):
    admin = Admin(app)
    session = models.db.session

    admin.add_view(ProcessModelView(session))
    admin.add_view(LogfileModelView(session))

    admin.add_view(ModelView(models.Host, session))
Esempio n. 30
0
def configure_admin(app):
    admin = Admin(app, index_view=HomeAdminView())
    admin.add_view(UserAdmin(db.session, name="User", endpoint="user", category="Auth"))
    admin.add_view(UserProfileAdmin(db.session, name="UserProfile", endpoint="profile", category="Auth"))

    admin.add_view(AuthView(Section, db.session, name="Section", endpoint="section", category="BBS"))
    admin.add_view(AuthView(Node, db.session, name="Node", endpoint="node", category="BBS"))
    admin.add_view(AuthView(Topic, db.session, name="Topic", endpoint="topic", category="BBS"))
    admin.add_view(AuthView(Reply, db.session, name="Reply", endpoint="reply", category="BBS"))
def init_app(app):
    views = [
        AlunoView(),
        PalestraView(),
        PalestraAlunoView(),
    ]
    admin = Admin(app)
    for view in views:
        admin.add_view(view)
Esempio n. 32
0
def activate_admin_classes():
    """Activate each registed Model in the admin if it was registered with
    *use_admin=True*."""
    _prepare_relationships()
    admin = Admin(app)
    with app.app_context():
        for cls in (cls for cls in current_app.classes_by_name.values()
                    if cls.use_admin == True):
            admin.add_view(ModelView(cls, db.session))
Esempio n. 33
0
def create_admin(app):
    """ Create an Admin object on Flask instance `app` and return it.
    """
    admin = Admin(name="Reduced test")
    ses = db.session
    admin.add_view(BrainTeasersView(ses))
    admin.add_view(TipsView(ses))
    admin.init_app(app)
    return admin
Esempio n. 34
0
def create_app(config):
    """Creates flask application with configuration
    """
    app = App(__name__)

    # Configure application
    app.config.setdefault('DATABASE', 'db.db')
    if isinstance(config, collections.Mapping):
        app.config.update(config)
    else:
        app.config.from_object(config)

    # View registering
    views.register_views(app)

    # DB connection
    app.db_engine = create_engine(app.config['DATABASE'])
    m.Base.metadata.bind = app.db_engine
    m.Session.configure(bind=app.db_engine)

    # Image Store
    app.store = HttpExposedFileSystemStore('images', 'images/')
    app.wsgi_app = app.store.wsgi_middleware(app.wsgi_app)

    @app.before_request
    def store_before_request():
        context.push_store_context(app.store)

    @app.teardown_request
    def store_teardown_request(exception=None):
        context.pop_store_context()

    # Auth
    app.register_blueprint(auth_blueprint)

    @app.before_request
    def before_request():
        g.user = get_login_user()

    # Middlewares
    SQLAlchemyMiddleware(m.Session, app)

    # Admin
    def get_session():
        session = getattr(self, '_session', None)
        if (session is None) or not session.is_active:
            session = m.Session()
            setattr(self, '_session', session)
        return session

    session = Proxy(get_session)
    admin = Admin(app)
    admin.add_view(ModelView(m.Issue, session, category='models'))
    admin.add_view(ModelView(m.User, session, category='models'))

    return app
Esempio n. 35
0
def init_admin(app):
    admin = Admin(app, url='/admin', endpoint='admin', name = "adminapp")
    admin.add_view(ModelView(video.Video, db.session ,endpoint='mv_video'))
    admin.add_view(ModelView(user.User, db.session ,endpoint='mv_user'))
    admin.add_view(ModelView(notification.Notification, db.session ,endpoint='mv_notification'))
    admin.add_view(ModelView(follow.Follow, db.session ,endpoint='mv_follow'))
    admin.add_view(ModelView(comment.Comment, db.session ,endpoint='mv_comment'))
    #admin.add_view(ModelView(follow_table, db.session ,endpoint='mv_follow_table'))
    
    return admin
Esempio n. 36
0
def init_ple_instructor_admin(app):
    ple_instructor_url = '/ple_instructor'
    ple_instructor = Admin(index_view = PleInstructorPanel(url=ple_instructor_url, endpoint = 'ple_instructor'), name = lazy_gettext(u'PLEinstructor'), url = ple_instructor_url, endpoint = 'ple_instructor')
    ple_instructor.add_view(PleInstructorLaboratoriesPanel(db.session, name = lazy_gettext(u'Laboratories'), endpoint = 'ple_instructor_laboratories', url = 'laboratories'))
    i18n_spaces=lazy_gettext(u'Spaces')
    ple_instructor.add_view(PleInstructorNewSpacesPanel(db.session,    category = i18n_spaces, name     = lazy_gettext(u'New'), endpoint = 'ple_instructor_new_courses', url = 'spaces/create'))
    ple_instructor.add_view(PleInstructorSpacesPanel(db.session,    category = i18n_spaces, name     = lazy_gettext(u'Spaces'), endpoint = 'ple_instructor_courses', url = 'spaces'))
    ple_instructor.add_view(PleInstructorPermissionToSpacesPanel(db.session,    category = i18n_spaces, name     = lazy_gettext(u'Permissions'), endpoint = 'ple_instructor_course_permissions', url = 'spaces/permissions'))
    ple_instructor.add_view(RedirectView('logout',         name = lazy_gettext(u'Log out'), endpoint = 'ple_instructor_logout', url = 'logout'))
    ple_instructor.init_app(app)
Esempio n. 37
0
def init_admin(app):
    admin = Admin(app, name='re:dash admin', template_mode='bootstrap3')

    admin.add_view(UserModelView(models.User))
    admin.add_view(QueryModelView(models.Query))
    admin.add_view(QueryResultModelView(models.QueryResult))
    admin.add_view(DashboardModelView(models.Dashboard))

    for m in (models.Visualization, models.Widget, models.ActivityLog, models.Group, models.Event):
        admin.add_view(BaseModelView(m))
Esempio n. 38
0
def initialize_user_component(app):
    # Initialize the Admin
    # URL describes through which address we access the page.
    # Endpoint enables us to do url_for('userp') to yield the URL
    url = '/user'
    admin = Admin(index_view=HomeView(url=url, endpoint='user', name=lazy_gettext("Home")),
                  name=lazy_gettext("User Profile"), url=url, endpoint="home-user")
#    admin.add_view(ProfileEditView(name=lazy_gettext("Profile"), url='profile', endpoint='user.profile'))
    admin.add_view(AppsView(name=lazy_gettext("Apps"), url="apps", endpoint='user.apps'))
    admin.init_app(app)
Esempio n. 39
0
def init(app, db, auth):
    class AuthenticateModelView(ModelView):
        def is_accessible(self):
            user = auth.get_current_user()
            if user:
                return user.is_admin
            return False

    class UserAdminView(AuthenticateModelView):
        column_list = (
            'username',
            'is_admin',
        )
        form_columns = (
            'username',
            'is_admin',
            'password_new',
            'password_confirm',
        )
        form_extra_fields = {
            'password_new': wtf.PasswordField('Password'),
            'password_confirm': wtf.PasswordField('Password (Confirm)'),
        }

        def on_model_change(self, form, model, is_created):
            # Verify the password
            set_password = check_password_fields(
                form.password_new,
                form.password_confirm,
                required=is_created,
            )
            if set_password:
                model.password = form.password_new.data

            # Continue with the normal validation
            ret = super(UserAdminView, self).on_model_change(form, model, is_created)

            # Check if we added any errors
            if len(form.password_new.errors) > 0:
                raise ValidationError()

            return ret

    class EventView(AuthenticateModelView):
        column_list = (
            'user',
            'seen_at',
            'beacon_id',
            'beacon_distance',
        )
        column_default_sort = 'seen_at'

    admin = Admin(app)
    admin.add_view(UserAdminView(db.models.User, db.session))
    admin.add_view(EventView(db.models.Event, db.session))
Esempio n. 40
0
def create_app(config):
    """Creates flask application with configuration
    """
    app = App(__name__)

    # Configure application
    app.config.setdefault('DATABASE', 'db.db')
    if isinstance(config, collections.Mapping):
        app.config.update(config)
    else:
        app.config.from_object(config)

    # View registering
    views.register_views(app)

    # DB connection
    app.db_engine = create_engine(app.config['DATABASE'])
    m.Base.metadata.bind = app.db_engine
    m.Session.configure(bind=app.db_engine)

    # Image Store
    app.store = HttpExposedFileSystemStore('images', 'images/')
    app.wsgi_app = app.store.wsgi_middleware(app.wsgi_app)
    @app.before_request
    def store_before_request():
        context.push_store_context(app.store)

    @app.teardown_request
    def store_teardown_request(exception=None):
        context.pop_store_context()

    # Auth
    app.register_blueprint(auth_blueprint)

    @app.before_request
    def before_request():
        g.user = get_login_user()


    # Middlewares
    SQLAlchemyMiddleware(m.Session, app)

    # Admin
    def get_session():
        session = getattr(self, '_session', None)
        if (session is None) or not session.is_active:
            session = m.Session()
            setattr(self, '_session', session)
        return session
    session = Proxy(get_session)
    admin = Admin(app)
    admin.add_view(ModelView(m.Issue, session, category='models'))
    admin.add_view(ModelView(m.User, session, category='models'))

    return app
Esempio n. 41
0
def init_admin(app_):
    """
    Initializes flask-admin related objects.

    :param app_: The Flask instance.
    """

    admin = Admin(app_, ActiveConfig.APP_NAME, index_view=views.AdminMainView())

    admin.add_view(views.AdminModelView(models.AppItem, db.session, name='Applications'))
    admin.add_view(views.AdminUserModelView(models.User, db.session, name='Users'))
Esempio n. 42
0
def create_admin(app):
    # Create admin interface
    admin = Admin(app, name="Admin", url="/admin", template_mode="bootstrap3")

    # Add views
    admin.add_view(UserAdmin(User, db))
    admin.add_view(TagAdmin(Tag, db))
    
    if admin.app is None:
        admin.init_app(app)
    
    return admin
def init(app, new_cache):
	global admin
	global cache
	cache = new_cache
	admin = Admin(app, index_view=LoginView(name='Login/Logout'))
	session = getSession()
	admin.add_view(AuthModelView(RuleType, session))
	admin.add_view(AuthModelView(ScoreType, session))
	admin.add_view(AuthModelView(TournamentType, session))
	admin.add_view(AuthModelView(Team, session))
	admin.add_view(AuthModelView(TournamentExecutionError, session))
	Session.remove()
Esempio n. 44
0
def create_app(name=__name__, config={},
               static_folder='static', template_folder='templates'):
    """NOTE: `db_uri` is only a temporary solution. It shall be replaced by
    something more robust."""
    app = Flask(name, static_folder=static_folder,
                template_folder=template_folder)
    app.secret_key = 'secret'
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_URI')
    app.config['DEBUG'] = True
    app.config['REDIS_URL'] = os.environ.get(
        'REDIS_URL', 'redis://:password@localhost:6379/0')

    app.config.update(config)

    login_manager.init_app(app)
    login_manager.login_view = 'user.login'

    redis_store.init_app(app)

    from bnd.models import db
    db.init_app(app)

    from bnd.main import main_module
    from bnd.curriculum import curriculum_module
    from bnd.checkpoint import checkpoint_module
    from bnd.team import team_module
    from bnd.goal import goal_module
    from bnd.user import user_module

    # Blueprint modules
    app.register_blueprint(main_module, url_prefix='/')
    app.register_blueprint(curriculum_module, url_prefix='/curriculum')
    app.register_blueprint(team_module, url_prefix='/team')
    app.register_blueprint(checkpoint_module, url_prefix='/checkpoint')
    app.register_blueprint(goal_module, url_prefix='/goal')
    app.register_blueprint(user_module, url_prefix='/user')

    from bnd.models import User, Team, Checkpoint, Goal, Evaluation, \
        CheckpointEvaluation, Announcement

    admin = Admin()
    admin.init_app(app)
    classes = [User, Team, Checkpoint, Goal, Evaluation, CheckpointEvaluation,
               Announcement]
    for cls in classes:
        admin.add_view(AdminModelView(cls, db.session,
                                      endpoint='admin_' + cls.__name__))

    app.jinja_env.globals.update(
        checkpoint_status_class=checkpoint_status_class)

    return app
def init(app, new_cache):
	global admin
	global cache
	session = getSession()
	cache = new_cache
	admin = Admin(app, index_view=LoginView(name='Login/Logout'))

	admin.add_view(AuthModelView(RuleType, session))
	admin.add_view(AuthModelView(ScoreType, session))
	admin.add_view(AuthModelView(TournamentType, session))
	admin.add_view(AuthModelView(Team, session))
	admin.add_view(AuthModelView(TournamentExecutionError, session))
	cleanupSession()
Esempio n. 46
0
def init_admin(app):
    admin = Admin(app, name='re:dash admin')

    views = {
        models.User: UserModelView(models.User),
        models.DataSource: DataSourceModelView(models.DataSource)
    }

    for m in models.all_models:
        if m in views:
            admin.add_view(views[m])
        else:
            admin.add_view(BaseModelView(m))
Esempio n. 47
0
def register_admin(app):
    """注册Flask-Admin"""
    from flask.ext.admin import Admin
    from flask.ext.admin.contrib.sqla import ModelView
    from .models import db, Work, WorkImage, WorkType, Dynasty, Artist, Museum

    admin = Admin(app)
    admin.add_view(ModelView(Work, db.session))
    admin.add_view(ModelView(WorkImage, db.session))
    admin.add_view(ModelView(WorkType, db.session))
    admin.add_view(ModelView(Dynasty, db.session))
    admin.add_view(ModelView(Artist, db.session))
    admin.add_view(ModelView(Museum, db.session))
Esempio n. 48
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    loginManager.init_app(app)
    db.init_app(app)
    moment.init_app(app)
    bootstrap.init_app(app)

    #Blueprint
    from main import main
    app.register_blueprint(main)
    #admin

    from app.admins.adminViews import MyIndexView, PostView, UserView, FriendLinkView, TagView, CategoryView
    from app.models import User, Article, FriendLink, Tag, Category
    admin = Admin(app=app,
                  template_mode='bootstrap3',
                  name='Hei',
                  endpoint='admin',
                  index_view=MyIndexView())
    admin.add_view(PostView(Article, db.session, name=u'文章管理'))
    admin.add_view(FriendLinkView(FriendLink, db.session, name=u'友情链接'))
    admin.add_view(TagView(Tag, db.session, name=u'标签管理'))
    admin.add_view(CategoryView(Category, db.session, name=u'分类管理'))

    return app
Esempio n. 49
0
def initialize_user_component(app):
    # Initialize the Admin
    # URL describes through which address we access the page.
    # Endpoint enables us to do url_for('userp') to yield the URL
    url = '/user'
    admin = Admin(index_view=HomeView(url=url,
                                      endpoint='user',
                                      name=lazy_gettext("Home")),
                  name=lazy_gettext("User Profile"),
                  url=url,
                  endpoint="home-user")
    #    admin.add_view(ProfileEditView(name=lazy_gettext("Profile"), url='profile', endpoint='user.profile'))
    admin.add_view(
        AppsView(name=lazy_gettext("Apps"), url="apps", endpoint='user.apps'))
    admin.init_app(app)
Esempio n. 50
0
def make_admin(app):
    myadmin = Admin(app, index_view=MyAdminIndexView(),
                    base_template='my_master.html',)
                    #template_mode='bootstrap3')
    myadmin.add_view(EuFormatView(models.EuFormat))
    myadmin.add_view(EuTemplateView(models.EuTemplate))
    myadmin.add_view(TranslationRequestView(models.TranslationRequest))
    myadmin.add_view(UserView(models.User))
    return myadmin
Esempio n. 51
0
def create_app(config='dev'):
    """ Flask application factory
    :param str config: type of app to build, either "prod" or "dev"
    """
    # Create flask application
    app = Flask(__name__)
    app.config.from_object('settings')
    app.config['ENV'] = config
    app.jinja_env.trim_blocks = True

    # Debug toolbar (when debug=true)
    debug_toolbar = DebugToolbarExtension(app)
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False

    # Register Blueprints
    app.register_blueprint(views_base.base)
    app.register_blueprint(views_blog.blog)

    # Flask-Assets; bundles all css/js files in minifed file
    assets = Environment(app)
    css_all = Bundle('css/bootstrap-flatly.min.css', 'css/highlightjs.min.css', 'css/font-awesome.css', 'css/main.css',
                     filters='cssmin', output='gen/style.css')
    js_all = Bundle('js/vendor/jquery.min.js', 'js/vendor/bootstrap.min.js', 'js/vendor/showdown-gfm.min.js',
                    'js/vendor/highlight.min.js', 'js/main.js', filters='jsmin', output='gen/libs.js')
    assets.register('css_all', css_all)
    assets.register('js_all', js_all)
    if app.config['DEBUG']:
        assets.debug = True
        app.config['ASSETS_DEBUG'] = True

    # Set up Flask-User
    babel = Babel(app)
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, app)  # Init Flask-User and bind to app

    # Init the cache
    cache.init_app(app)

    Moment(app)  # moment.js
    Misaka(app, autolink=True,  # Misaka Markdown
           fenced_code=True, lax_html=True, strikethrough=True,
           superscript=True, tables=True, wrap=True)

    # Init Admin page
    admin = Admin(app, index_view=AdminMain(endpoint='admin'))
    admin.add_view(PostAdminView())
    admin.add_view(NewPostView())
    admin.add_view(ModelView(Comment, db.session))
    static_path = os.path.join(BASE_DIR, 'app', 'static')
    admin.add_view(FileAdminView(static_path, '/static/', name='Static Files'))

    # Initialize DB
    db.init_app(app)

    return app
Esempio n. 52
0
def setup_admin_for(app):

    modules_path = modules.__file__.rsplit(os.sep, 1)[0]
    findedmodules = discover_modules_on(modules_path)
    loadedviews = dict()

    admin = Admin(name='PyMyAdmin')

    for modname, module in findedmodules.iteritems():
        views = load_views_from_module(module)
        for viewname, view in views.iteritems():
            loadedviews[viewname] = view

    for viewname, view in loadedviews.iteritems():
        viewinstance = make_view_instance(viewname, view)
        admin.add_view(viewinstance)

    admin.init_app(app)
Esempio n. 53
0
def init_instructor_admin(app):
    lms_instructor_url = '/lms_instructor'
    lms_instructor = Admin(index_view=LmsInstructorPanel(
        url=lms_instructor_url, endpoint='lms_instructor'),
                           name=lazy_gettext(u'LMS instructor'),
                           url=lms_instructor_url,
                           endpoint='lms-instructor')
    lms_instructor.add_view(
        PermissionToLmsUserPanel(db.session,
                                 name=lazy_gettext(u'Permissions'),
                                 endpoint='lms_instructor_permissions',
                                 url='permissions'))
    lms_instructor.add_view(
        RedirectView('logout',
                     name=lazy_gettext(u'Log out'),
                     endpoint='lms_instructor_logout',
                     url='logout'))
    lms_instructor.init_app(app)
Esempio n. 54
0
def configure_admin(app):
    class UserView(ModelView):
        def is_accessible(self):
            return login.current_user.is_authenticated()

    class AppointmentView(ModelView):
        column_formatters = {
            "start_time":
            lambda v, c, m, p: datetime.utcfromtimestamp(m.start_time),  # NOQA
            "end_time":
            lambda v, c, m, p: datetime.utcfromtimestamp(m.end_time)  # NOQA
        }

        def is_accessible(self):
            return login.current_user.is_authenticated()

    admin = Admin(app)
    admin.add_view(UserView(User, db.session))
    admin.add_view(AppointmentView(Appointment, db.session))
Esempio n. 55
0
def create_app(config={}):
    app = Flask(__name__, instance_relative_config=True)
    if not config:
        app.config.from_pyfile('settings.py')
    else:
        app.config.update(config)
    db.init_app(app)
    app.register_blueprint(views)

    app.secret_key = app.config['PRIVATE_KEY']

    if app.config.get('SENTRY_DSN'):
        from raven.contrib.flask import Sentry
        Sentry(app)

    @app.errorhandler(403)
    def permission_denied(error):
        return render_template("denied.html"), 403

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        if identity.id:
            user = User.query.get(identity.id)
            if user and user.is_admin:
                identity.provides.add(RoleNeed('admin'))

    login_manager = LoginManager()

    @login_manager.user_loader
    def load_user(userid):
        try:
            return User.query.get(userid)
        except:
            return None

    login_manager.setup_app(app)

    Principal(app)
    admin = Admin(app)
    admin.add_view(AdminModelView(User, db.session))
    admin.add_view(AdminModelView(Project, db.session))

    return app
Esempio n. 56
0
    def administration(self, index_view=None, app_models=None):
        """
        Initialize the Administrative GUI.

        :param index_view: the View that will act as the index page of the admin GUI.
        :type index_view: AdminIndexView
        :returns: None

        The administration GUI is substantially derived from `Flask-Admin
        <http://flask-admin.readthedocs.org/en/latest/>`_. When this function
        is called, it will instantiate blueprints so the application serves
        the admin GUI via the URL http://localhost/admin.

        Typically, you will want to call this function even if you override
        it.  The following example illustrates using super() to invoke this
        administration() function from within your own application.

        >>> admin = super(MyApp, self).administration(
        >>>     index_view=MyApp.modelviews.RedirectView(name="Home")
        >>> )
        """

        from . import administration
        admin = Admin(name=self.app.config["PROJECT_NAME"],
                      base_template='admin/login_base.html',
                      index_view=index_view
                      or administration.ForceLoginView(name="Home"))

        if not app_models:
            from . import models
        else:
            models = app_models

        admin.add_view(
            administration.UserView(models.User, db.session, category="Admin"))
        admin.add_view(
            administration.AdminModelView(models.Role,
                                          db.session,
                                          category="Admin"))

        admin.init_app(self.app)
        return admin
Esempio n. 57
0
    def get_app(self):
        app = Flask(__name__)

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

        class HomeView(AdminIndexView):
            @expose("/")
            def index(self):
                return redirect('/admin/dashboard')

        admin = Admin(app, name="Honeypot", index_view=HomeView())
        admin._menu = []
        view = Dashboard(table=self.table_name,
                         sql_conn_id=self.sql_conn_id,
                         sample_data=False)
        admin.add_view(view)

        return app