Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
0
def init_public_admin(app):
    public_admin_url = '/public'
    public_admin = Admin(index_view = PublicAdminPanel(url=public_admin_url, endpoint = 'public_admin'), name = lazy_gettext(u"Public laboratories"), url = public_admin_url, endpoint = 'public-admin')
    public_admin.add_view(PublicSystemsPanel( db.session, name = lazy_gettext(u"Show public systems"), endpoint = 'public_admin_systems', url = 'systems/public'))
    public_admin.add_view(PublicLaboratoriesPanel( db.session, name = lazy_gettext(u"Show public labs"), endpoint = 'public_admin_labs', url = 'labs/public'))
    public_admin.add_view(RedirectView('index', name = lazy_gettext(u"Back"), endpoint = 'public_admin_logout', url = 'back'))
    public_admin.init_app(app)
Exemplo n.º 4
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
Exemplo n.º 5
0
def create_app():
   app = Flask(__name__, static_folder='', template_folder='app/admin/templates')
   print app.root_path
   #load config
   app.config.from_object(AdminProdConfig)
   
   #init extension
   db.init_app(app)
   
   #init login
   login_manager.login_view = "frontend.login"
   @login_manager.user_loader
   def load_user(id):
       return AdminUser.by_id(id)
       
   login_manager.init_app(app)
   
   #init admin
   admin = Admin(name='DD Admin', index_view=HomeView(),url='/admin')
   admin.init_app(app)
   
   admin.add_view(getAdminUserView())
   admin.add_view(getAdminEmailView())
   admin.add_view(getAdminSellingPostView())
   admin.add_view(getAdminBuyRequestView())
   admin.add_view(getAdminHashtagView())
   admin.add_view(getAdminBugPostView())
   
   admin.add_view(LogoutView(name="Logout"))
   
   #register blueprint
   app.register_blueprint(frontend)

   return app
Exemplo n.º 6
0
def init_admin(app):
    admin_url = '/admin'
    admin = Admin(index_view=AdminPanel(url=admin_url),
                  name=lazy_gettext(u"Lab Manager"),
                  url=admin_url,
                  endpoint=admin_url)
    i18n_LMSmngmt = lazy_gettext(u'LT Management')
    admin.add_view(
        LTPanel(db.session,
                category=i18n_LMSmngmt,
                name=lazy_gettext(u"LT"),
                endpoint='lt/lt'))
    admin.add_view(
        PermissionToLtPanel(db.session,
                            category=i18n_LMSmngmt,
                            name=lazy_gettext(u"LT Permissions"),
                            endpoint='lt/permissions'))
    admin.add_view(
        LtUsersPanel(db.session,
                     category=i18n_LMSmngmt,
                     name=lazy_gettext(u"LT Users"),
                     endpoint='lt/users'))
    admin.add_view(
        LabRequestsPanel(db.session,
                         category=i18n_LMSmngmt,
                         name=lazy_gettext(u"LT Requests"),
                         endpoint='lt/requests'))
    i18n_ReLMSmngmt = lazy_gettext(u'ReLMS Management')
    admin.add_view(
        RLMSPanel(db.session,
                  category=i18n_ReLMSmngmt,
                  name=lazy_gettext(u"RLMS"),
                  endpoint='rlms/rlms'))
    admin.add_view(
        LaboratoryPanel(db.session,
                        category=i18n_ReLMSmngmt,
                        name=lazy_gettext(u"Registered labs"),
                        endpoint='rlms/labs'))
    admin.add_view(
        UsersPanel(db.session,
                   category=lazy_gettext(u'Users'),
                   name=lazy_gettext(u"Labmanager Users"),
                   endpoint='users/labmanager'))
    if app.config.get('GOLAB'):
        admin.add_view(
            EmbedApplicationsPanel(db.session,
                                   category="Go-Lab",
                                   name="Embed Apps",
                                   endpoint='golab/embed'))
        admin.add_view(
            GoLabUsersPanel(db.session,
                            category="Go-Lab",
                            name="Go-Lab users",
                            endpoint='golab/users'))
    admin.add_view(
        RedirectView('logout',
                     name=lazy_gettext(u"Log out"),
                     endpoint='admin/logout'))
    admin.init_app(app)
Exemplo n.º 7
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
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 10
0
def initialize_admin_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 = '/admin'
    admin = Admin(index_view = AdminView(url = url, endpoint = 'admin'), name=lazy_gettext('Admin Profile'), endpoint = "home-admin")
    admin.add_view(UsersView(name=lazy_gettext('Users'), url = 'users', endpoint = 'admin.users'))
    admin.add_view(AdminAppsView(name=lazy_gettext('Apps'), url = 'apps-admin', endpoint = 'admin.admin-apps'))      
    admin.add_view(RedirectView('user.profile.index', name=lazy_gettext('My Profile'), url = 'profile', endpoint = 'admin.profile'))
    admin.add_view(RedirectView('index', name=lazy_gettext('Back'), url = 'back', endpoint = 'admin.back'))
    admin.init_app(app)
Exemplo n.º 11
0
def init_ple_admin(app):
    ple_admin_url = '/ple_admin'
    i18n_labs = lazy_gettext(u'Labs')
    ple_admin = Admin(index_view=PleAdminPanel(url=ple_admin_url,
                                               endpoint='ple_admin'),
                      name=lazy_gettext(u'PLE admin'),
                      url=ple_admin_url,
                      endpoint='ple-admin')
    ple_admin.add_view(
        PleInstructorLaboratoriesPanel(db.session,
                                       category=i18n_labs,
                                       name=lazy_gettext(u"Available labs"),
                                       endpoint='ple_admin_labs',
                                       url='labs/available'))
    ple_admin.add_view(
        PleInstructorRequestLaboratoriesPanel(
            db.session,
            category=i18n_labs,
            name=lazy_gettext(u"Request new labs"),
            endpoint='ple_admin_request_labs',
            url='labs/request'))

    i18n_spaces = lazy_gettext(u'Spaces')
    ple_admin.add_view(
        PleNewSpacesPanel(db.session,
                          category=i18n_spaces,
                          name=lazy_gettext(u'New'),
                          endpoint='ple_admin_new_courses',
                          url='spaces/create'))
    ple_admin.add_view(
        PleSpacesPanel(db.session,
                       category=i18n_spaces,
                       name=lazy_gettext(u'Spaces'),
                       endpoint='ple_admin_courses',
                       url='spaces'))
    ple_admin.add_view(
        PlePermissionToSpacePanel(db.session,
                                  category=i18n_spaces,
                                  name=lazy_gettext(u'Permissions'),
                                  endpoint='ple_admin_course_permissions',
                                  url='spaces/permissions'))

    ple_admin.add_view(
        PleUsersPanel(db.session,
                      name=lazy_gettext(u'Users'),
                      endpoint='ple_admin_users',
                      url='users'))
    ple_admin.add_view(
        RedirectView('logout',
                     name=lazy_gettext(u'Log out'),
                     endpoint='ple_admin_logout',
                     url='logout'))
    ple_admin.init_app(app)
Exemplo n.º 12
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
Exemplo n.º 13
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 create_admin(app):
    """ Create an Admin object on Flask instance `app` and return it.
    """
    admin = Admin(name='Daycare Ethics')
    ses = db.session
    admin.add_view(MediaView(ses))
    admin.add_view(CasesView(ses))
    admin.add_view(VotesView(ses))
    admin.add_view(BrainTeasersView(ses))
    admin.add_view(ResponsesView(ses))
    admin.add_view(TipsView(ses))
    admin.init_app(app)
    return admin
Exemplo n.º 15
0
def init_lms_admin(app):
    lms_admin_url = '/lms_admin'
    lms_admin = Admin(index_view = LmsAdminPanel(url=lms_admin_url, endpoint = 'lms_admin'), name = lazy_gettext(u'LMS admin'), url = lms_admin_url, endpoint = 'lms-admin')
    lms_admin.add_view(LmsInstructorLaboratoriesPanel( db.session, name = lazy_gettext(u"Lab"), endpoint = 'lms_admin_labs', url = 'labs'))
    i18n_courses=lazy_gettext(u"Courses")
    lms_admin.add_view(LmsCoursesPanel(db.session,    category = i18n_courses, name     = lazy_gettext(u"Courses"), endpoint = 'lms_admin_courses', url = 'courses'))
    lms_admin.add_view(LmsCourseDiscoveryPanel(db.session,    category = i18n_courses, name     = lazy_gettext(u'Discover'), endpoint = 'lms_admin_course_discover', url = 'courses/discover'))
    lms_admin.add_view(LmsPermissionToCoursesPanel(db.session,    category =i18n_courses, name     = lazy_gettext(u'Permissions'), endpoint = 'lms_admin_course_permissions', url = 'courses/permissions'))
    i18n_users=lazy_gettext(u'Users')
    lms_admin.add_view(LmsUsersPanel(db.session,      category = i18n_users, name     = lazy_gettext(u'Users'), endpoint = 'lms_admin_users', url = 'users'))
    lms_admin.add_view(PermissionToLmsUserPanel(db.session,      category = i18n_users, name     = lazy_gettext(u'Permissions'), endpoint = 'lms_admin_user_permissions', url = 'user_permissions'))
    lms_admin.add_view(RedirectView('logout',         name = lazy_gettext(u'Log out'), endpoint = 'lms_admin_logout', url = 'logout'))
    lms_admin.init_app(app)
Exemplo n.º 16
0
def init_admin(app):
    admin_url = '/admin'
    admin = Admin(index_view = AdminPanel(url=admin_url), name = lazy_gettext(u"Lab Manager"), url = admin_url, endpoint = admin_url)
    i18n_LMSmngmt = lazy_gettext(u'LT Management')
    admin.add_view(LTPanel(db.session,        category = i18n_LMSmngmt, name = lazy_gettext(u"LT"),     endpoint = 'lt/lt'))
    admin.add_view(PermissionToLtPanel(db.session, category = i18n_LMSmngmt, name = lazy_gettext(u"LT Permissions"),    endpoint = 'lt/permissions'))
    admin.add_view(LtUsersPanel(db.session,   category = i18n_LMSmngmt, name = lazy_gettext(u"LT Users"),        endpoint = 'lt/users'))
    admin.add_view(LabRequestsPanel(db.session,   category = i18n_LMSmngmt, name = lazy_gettext(u"LT Requests"),        endpoint = 'lt/requests'))
    i18n_ReLMSmngmt = lazy_gettext(u'ReLMS Management')
    admin.add_view(RLMSPanel(db.session,       category = i18n_ReLMSmngmt, name = lazy_gettext(u"RLMS"),            endpoint = 'rlms/rlms'))
    admin.add_view(LaboratoryPanel(db.session, category = i18n_ReLMSmngmt, name = lazy_gettext(u"Registered labs"), endpoint = 'rlms/labs'))
    admin.add_view(UsersPanel(db.session,      category = lazy_gettext(u'Users'), name = lazy_gettext(u"Labmanager Users"), endpoint = 'users/labmanager'))
    admin.add_view(RedirectView('logout',      name = lazy_gettext(u"Log out"), endpoint = 'admin/logout'))
    admin.init_app(app)
Exemplo n.º 17
0
def configure_create_admin(app):
	from app.admin_views import MyAdminIndexView
	admin_app = Admin(name='chahua3287',index_view=MyAdminIndexView())
	from admin import *
	admin_app.add_view(ModelView_User(db.session,name=u'用户管理'))
	admin_app.add_view(ModelView_Article(db.session,name=u'文章管理'))
	admin_app.add_view(ModelView_Category(db.session,name=u'栏目管理'))
	admin_app.add_view(ModelView_CategoryTop(db.session,name=u'顶级栏目'))
	# admin_app.add_view(ModelView(User_msg,db.session,name=u'留言管理'))
	# admin_app.add_view(ModelView(Category_attribute,db.session,name=u'栏目属性表(不要随意更改)'))
	# admin_app.add_view(ModelView(Comment,db.session,name=u'评论管理'))
	admin_app.add_view(Admin_static_file(path,'/static', name=u'文件管理'))
	admin_app.add_view(Admin_logout(name=u'退出'))
	admin_app.init_app(app)
Exemplo n.º 18
0
    def setup_app(self, app, app_name):
        assert self.app == None
        if not self.app:
            self.app = app

        self.__bp = Blueprint('admin_bp', __name__)

        admin = Admin(name=app_name,
                      index_view=MyIndexView(endpoint='adminview'))
        admin.init_app(self.app)

        # adding user view
        admin.add_view(UnaccessibleModelView(User, db.session))

        # adding blog post view
        admin.add_view(PostModelView(Post, db.session, category='Blog'))

        # adding PortletSlot
        admin.add_view(UnaccessibleModelView(PortletSlot, db.session,
                                                    category="Portlets"))

        # adding TextPortlet
        admin.add_view(PortletView(TextPortlet, db.session,
                                                    category="Portlets"))

        # adding pages view
        admin.add_view(PageModelView(Page, db.session, category="Contents"))

        # adding social_buttons view
        admin.add_view(SocialButtonView(SocialButton, db.session,
                                                    category="Contents"))

        # adding fileadmin view and creating the media path
        media_path = os.path.join(self.app.instance_path, 'media')
        if not os.path.exists(media_path):
            os.mkdir(media_path)
        admin.add_view(FileAdmin(media_path, '/media/', name='Files',
                                                    category='Blog'))

        # TIP: In a production environment media folder should be served by the
        # webserver itself or through a  CDN - as the static too
        @self.__bp.route('/media/<path:filename>')
        def media(filename):
            # Only for testing purpose
            if self.app.config.get('TESTING', None) and filename == 'anything':
                return 'OK'
            return send_from_directory(media_path, filename)

        self.app.register_blueprint(self.__bp)
Exemplo n.º 19
0
def create_app(config_object=ProdConfig):
    '''An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/

    :param config_object: The configuration object to use.
    '''
    app = Flask(__name__)
    app.name = "synthesis"
    app.config.from_object(config_object)
    app.mongocl = MongoClient('mongodb://%s:%s/'%("localhost", "27017"))    
    register_extensions(app)

    # Normally would go in extensions, but pytest does not play nice with
    # Flask-Admin unless it is encapsulated in the create_app, (ie. here)
    from flask.ext.admin import Admin
    admin = Admin(name="Synthesis", 
                  template_mode='bootstrap3',
                  index_view=SynAdminView())
    with app.app_context():
        admin.add_view(ReportConfigView(mongo.db['report_configs'],
                                        name="PFT Report Configuration",
                                        endpoint="pftConfig",
                                        category="Skillet"))
        admin.add_view(PFTReportView(current_app.config["PFT_DIR"],
                                 name="PFT Files",
                                 endpoint="pftFiles",
                                 category="Skillet"))
        admin.add_view(SurveyConfigView(mongo.db['survey_configs'],
                                        name="Survey Configuration",
                                        endpoint="SurveyConfig",
                                        category="SurveyCommander"))
        admin.add_view(SurveyFileView(current_app.config["SUR_DIR"],
                                      name="Survey Files",
                                      endpoint="SurveyManagement",
                                      category="SurveyCommander"))
        admin.add_view(SurcomView(mongo.db['surcom_sessions'],
                                  name="Cleaning Sessions",
                                  endpoint="SurveySessions",
                                  category="SurveyCommander"))
        admin.add_view(SurveyRulesView(mongo.db["survey_rules"],
                                       name="Survey Rules",
                                       endpoint="SurveyRules",
                                       category="SurveyCommander"))
        
    admin.init_app(app)

    register_blueprints(app)
    register_errorhandlers(app)
    return app
Exemplo n.º 20
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)
Exemplo n.º 21
0
def init_ple_admin(app):
    ple_admin_url = '/ple_admin'
    i18n_labs = lazy_gettext(u'Labs')
    ple_admin = Admin(index_view = PleAdminPanel(url=ple_admin_url, endpoint = 'ple_admin'), name = lazy_gettext(u'PLE admin'), url = ple_admin_url, endpoint = 'ple-admin')
    ple_admin.add_view(PleInstructorLaboratoriesPanel( db.session,  category = i18n_labs, name = lazy_gettext(u"Available labs"), endpoint = 'ple_admin_labs', url = 'labs/available'))
    ple_admin.add_view(PleInstructorRequestLaboratoriesPanel( db.session, category = i18n_labs, name = lazy_gettext(u"Request new labs"), endpoint = 'ple_admin_request_labs', url = 'labs/request'))

    i18n_spaces = lazy_gettext(u'Spaces')
    ple_admin.add_view(PleNewSpacesPanel(db.session,             category = i18n_spaces, name     = lazy_gettext(u'New'), endpoint = 'ple_admin_new_courses', url = 'spaces/create'))
    ple_admin.add_view(PleSpacesPanel(db.session,                   category = i18n_spaces, name     = lazy_gettext(u'Spaces'), endpoint = 'ple_admin_courses', url = 'spaces'))
    ple_admin.add_view(PlePermissionToSpacePanel(db.session,  category = i18n_spaces, name     = lazy_gettext(u'Permissions'), endpoint = 'ple_admin_course_permissions', url = 'spaces/permissions'))

    ple_admin.add_view(PleUsersPanel(db.session,      name = lazy_gettext(u'Users'), endpoint = 'ple_admin_users', url = 'users'))
    ple_admin.add_view(RedirectView('logout',         name = lazy_gettext(u'Log out'), endpoint = 'ple_admin_logout', url = 'logout'))
    ple_admin.init_app(app)
Exemplo n.º 22
0
def configure_extensions(app):
    # flask-sqlalchemy
    db.init_app(app)

    # flask-mail
    mail.init_app(app)

    # flask-cache
    cache.init_app(app)

    # flask-babel
    babel = Babel(app)
    @babel.localeselector
    def get_locale():
        override = request.args.get('lang')
        if override:
            session['lang'] = override
            return session.get('lang', 'en')
        else:
            accept_languages = app.config.get('ACCEPT_LANGUAGES')
            return request.accept_languages.best_match(accept_languages)

    # flask-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(id)
    login_manager.setup_app(app)

    # flask-admin
    admin = Admin()
    # Setup locale
    admin.locale_selector(get_locale)
    # Views
    # Model admin
    admin.add_view(ModelView(User, db.session, endpoint='usermodel', category='Model'))
    admin.add_view(ModelView(UserDetail, db.session, endpoint='userdetailmodel', category='Model'))
    admin.add_view(ModelView(Role, db.session, endpoint='rolemodel', category='Model'))
    # File admin 
    path = os.path.join(os.path.dirname(__file__), 'static/img/users')
    # Create directory if existed.
    try:
        os.mkdir(path)
    except OSError:
        pass
    admin.add_view(FileAdmin(path, '/static/img/users', endpoint='useravatar', name='User Avatars', category='Image'))
    admin.init_app(app)
Exemplo n.º 23
0
def register_admin_window(app):
    admin = Admin(name='DragonLite Admin')
    admin.init_app(app)
    admin.add_view(AdminView
                   (UserGroup, db.session, columns=('name', 'users')))
    admin.add_view(AdminView(User, db.session, endpoint='all'))
    admin.add_view(AdminView(Repo, db.session))
    permission_validations = dict(
        permission=dict(
            validators=[WhiteList(['RW+', 'RW', 'W', 'R'])]))
    ssh_validations = dict(
        ssh_key=dict(
            validators=[SSHValidator()]))
    admin.add_view(AdminView(Permission, db.session, validations=permission_validations))
    admin.add_view(AdminView(Key, db.session, validations=ssh_validations))
    return None
Exemplo n.º 24
0
def setup_app(app):
    """Register all administration views with the Flask application."""
    app.config.setdefault("ADMIN_CONFIG", dict(
        name="Admin",
        url="/admin/",
        template_mode='bootstrap3',
    ))

    # Initialize app
    admin = Admin(**app.config['ADMIN_CONFIG'])
    admin.init_app(app)

    # Create registry and run discovery
    app.extensions['registry']['admin'] = AdminDiscoveryRegistry(
        'admin', app=app, with_setup=True, admin=admin
    )
Exemplo n.º 25
0
    def setup_app(self, app, app_name):
        assert self.app == None
        if not self.app:
            self.app = app

        self.__bp = Blueprint('admin_bp', __name__)

        admin = Admin(name=app_name,
                      index_view=MyIndexView(endpoint='adminview'))
        admin.init_app(self.app)

        # adding user view
        admin.add_view(UserView(User, db.session))

        admin.add_view(ProjectView(Projects, db.session))

        self.app.register_blueprint(self.__bp)
Exemplo n.º 26
0
class AdminView(object):

    def __init__(self, app, app_name):
        self.app = app
        self.admin = Admin(name=app_name)

    def init(self):
        self.admin.init_app(self.app)
        self._add_views()

    def _add_views(self):
        self.admin.add_view(ModelView(Event, db.session))
        self.admin.add_view(ModelView(Sponsor, db.session))
        self.admin.add_view(ModelView(Speaker, db.session))
        self.admin.add_view(ModelView(Session, db.session))
        self.admin.add_view(ModelView(Track, db.session))
        self.admin.add_view(ModelView(Microlocation, db.session))
Exemplo n.º 27
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)
Exemplo n.º 28
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)
Exemplo n.º 29
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)
Exemplo n.º 30
0
def setup_app(app):
    """
    Register all administration views with the Flask application
    """
    app.config.setdefault("ADMIN_NAME", "Invenio")

    # Initialize app
    admin = Admin(
        name=app.config['ADMIN_NAME'],
        index_view=AdminIndexView(),
        base_template="admin_base.html",
        template_mode='bootstrap3'
    )
    admin.init_app(app)

    # Create registry and run discovery
    app.extensions['registry']['admin'] = AdminDiscoveryRegistry(
        'admin', app=app, with_setup=True, admin=admin
    )
Exemplo n.º 31
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
Exemplo n.º 32
0
def create_app(config_name='development'):
    """Flask factory function"""

    # Configure from config.py
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)

    # Configure Flask-Admin
    admin = Admin(name='demo', template_mode='bootstrap3')
    from .admin_views import DbView
    admin.add_view(DbView(Group, db.session))
    admin.add_view(DbView(User, db.session))
    admin.init_app(app)

    # Blueprints
    from .api import groups_bp
    app.register_blueprint(groups_bp, url_prefix='/api/groups')

    from .api import users_bp
    app.register_blueprint(users_bp, url_prefix='/api/users')
    #

    @app.before_first_request
    def create_tables():
        db.create_all()

    # Ensure all errors thrown are json
    # http://flask.pocoo.org/snippets/83/
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException)
                                else 500)
        return response

    for code in default_exceptions.keys():
        app.error_handler_spec[None][code] = make_json_error

    return app
Exemplo n.º 33
0
def create_app(config_object=ProdConfig):
    '''An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/

    :param config_object: The configuration object to use.
    '''
    app = Flask(__name__)
    app.config.from_object(config_object)
    register_extensions(app)
    
     # Normally would go in extensions, but pytest does not play nice with
    # Flask-Admin unless it is encapsulated in the create_app, (ie. here)
    from flask.ext.admin import Admin
    admin = Admin(name="RoodKamer", 
                  template_mode='bootstrap3',
                  index_view=RkAdminView())
    admin.init_app(app)
    register_blueprints(app)
    register_errorhandlers(app)
    return app
Exemplo n.º 34
0
def register_extenstions(app):
    """
    Register Flask extenstions with application context

    :param app: Flask application instance
    :type app: flask.app.Flask
    """

    # Database (Flask-SQLAlchemy)
    db.init_app(app)

    # Migrations
    migrate.init_app(app, db)

    # Flask Security
    from soon.auth.models import User, Role
    datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, datastore=datastore)

    # Gravatar
    gravatar.init_app(app)

    # Admin
    from flask.ext.admin import Admin
    from soon.views.admin.home import AdminHomeView

    global admin

    admin = Admin(
        name='soon',
        index_view=AdminHomeView(name='Dashboard'),
        base_template='layout/admin.html')
    admin.init_app(app)

    # Static Collect
    collect.init_app(app)

    # Velox
    velox.init_app(app)
Exemplo n.º 35
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
Exemplo 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)
Exemplo n.º 37
0
def init_public_admin(app):
    public_admin_url = '/public'
    public_admin = Admin(index_view=PublicAdminPanel(url=public_admin_url,
                                                     endpoint='public_admin'),
                         name=lazy_gettext(u"Public laboratories"),
                         url=public_admin_url,
                         endpoint='public-admin')
    public_admin.add_view(
        PublicSystemsPanel(db.session,
                           name=lazy_gettext(u"Show public systems"),
                           endpoint='public_admin_systems',
                           url='systems/public'))
    public_admin.add_view(
        PublicLaboratoriesPanel(db.session,
                                name=lazy_gettext(u"Show public labs"),
                                endpoint='public_admin_labs',
                                url='labs/public'))
    public_admin.add_view(
        RedirectView('index',
                     name=lazy_gettext(u"Back"),
                     endpoint='public_admin_logout',
                     url='back'))
    public_admin.init_app(app)
Exemplo n.º 38
0
def register_admin(app):
    """
    Register all administration views with the Flask application
    """
    from invenio.errorlib import register_exception
    from invenio.importutils import autodiscover_modules

    # Initialize app
    admin = Admin(name="Invenio",
                  index_view=InvenioAdminIndexView(),
                  base_template="admin_base.html")
    admin.init_app(app)

    # Call register() in admin module to register views.
    modules = autodiscover_modules(['invenio'],
                                   '(?!oai_harvest_admin).+_admin\.py')
    for m in modules:
        register_func = getattr(m, 'register_admin', None)
        if register_func and callable(register_func):
            try:
                register_func(app, admin)
            except Exception:
                register_exception()
Exemplo n.º 39
0
def create_app():
    app = Flask(__name__,
                static_folder='',
                template_folder='app/admin/templates')
    print app.root_path
    #load config
    app.config.from_object(AdminProdConfig)

    #init extension
    db.init_app(app)

    #init login
    login_manager.login_view = "frontend.login"

    @login_manager.user_loader
    def load_user(id):
        return AdminUser.by_id(id)

    login_manager.init_app(app)

    #init admin
    admin = Admin(name='DD Admin', index_view=HomeView(), url='/admin')
    admin.init_app(app)

    admin.add_view(getAdminUserView())
    admin.add_view(getAdminEmailView())
    admin.add_view(getAdminSellingPostView())
    admin.add_view(getAdminBuyRequestView())
    admin.add_view(getAdminHashtagView())
    admin.add_view(getAdminBugPostView())

    admin.add_view(LogoutView(name="Logout"))

    #register blueprint
    app.register_blueprint(frontend)

    return app
Exemplo n.º 40
0
def configure_extensions(app):
    # flask-sqlalchemy
    db.init_app(app)

    # flask-mail
    mail.init_app(app)

    # flask-cache
    cache.init_app(app)

    # flask-babel
    babel = Babel(app)
    @babel.localeselector
    def get_locale():
        accept_languages = app.config.get('ACCEPT_LANGUAGES')
        return request.accept_languages.best_match(accept_languages)

    # flask-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)

    # flask-admin
    admin = Admin()
    # Views
    # Model admin
    admin.add_view(ModelView(User, db.session, endpoint='usermodel', category='Model'))
    admin.add_view(ModelView(UserDetail, db.session, endpoint='userdetailmodel', category='Model'))
    admin.add_view(ModelView(Role, db.session, endpoint='rolemodel', category='Model'))
    # File admin 
    path = os.path.join(os.path.dirname(__file__), 'static/img/users')
    admin.add_view(FileAdmin(path, '/static/img/users', endpoint='useravatar', name='User Avatars', category='Image'))
    admin.init_app(app)
Exemplo n.º 41
0
def create_app(config=None, register_blueprints=True, init_admin=True):
    """Create a Flask app"""
    app = Flask('spkrepo')

    # Configuration
    app.config.from_object(default_config)
    app.config.from_envvar('SPKREPO_CONFIG', silent=True)
    if config is not None:
        app.config.from_object(config)

    # Extra template path
    if app.config['TEMPLATE_PATH'] is not None:
        app.jinja_loader = jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(app.config['TEMPLATE_PATH']),
            app.jinja_loader
        ])

    # Blueprints
    if register_blueprints:
        app.register_blueprint(frontend)
        app.register_blueprint(api, url_prefix='/api')
        app.register_blueprint(nas, url_prefix='/nas')

    # Admin
    if init_admin:
        admin = Admin(index_view=IndexView())
        admin.add_view(UserView())
        admin.add_view(ArchitectureView())
        admin.add_view(FirmwareView())
        admin.add_view(ScreenshotView())
        admin.add_view(PackageView())
        admin.add_view(VersionView())
        admin.add_view(BuildView())
        admin.init_app(app)

    # SQLAlchemy
    db.init_app(app)

    # Security
    security.init_app(app,
                      user_datastore,
                      confirm_register_form=SpkrepoConfirmRegisterForm)

    # Migrate
    migrate.init_app(app, db, directory=app.config['MIGRATE_DIRECTORY'])

    # Mail
    mail.init_app(app)

    # Cache
    cache.init_app(app)

    # Debug Toolbar
    debug_toolbar.init_app(app)

    # Jinja2 helpers
    @app.template_filter()
    def is_hidden_field(field):
        return isinstance(field, HiddenField)

    @app.template_filter()
    def sort_fields(form, field_names=None):
        fields = []
        for field in form:
            if field.name in field_names:
                fields.insert(field_names.index(field.name), field)
            else:
                fields.append(field)
        return fields

    return app
Exemplo n.º 42
0
flask_via.examples.admin
========================

A simple ``Flask-Admin`` example Flask application.
"""

from flask import Flask
from flask.ext.admin import Admin
from flask.ext.via import Via
from flask_admin import BaseView, expose
from flask.ext.via.routers.admin import AdminRoute

app = Flask(__name__)

admin = Admin(name='Admin')
admin.init_app(app)


class FooAdminView(BaseView):
    @expose('/')
    def index(self):
        return 'foo'


routes = [AdminRoute(FooAdminView(name='Foo'))]

via = Via()
via.init_app(app, routes_module='flask_via.examples.admin', flask_admin=admin)

if __name__ == '__main__':
    app.run(debug=True)
Exemplo n.º 43
0
def initialize_admin_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 = '/admin'
    admin = Admin(index_view=AdminView(url=url, endpoint='admin'),
                  name=lazy_gettext('Admin Profile'),
                  endpoint="home-admin")
    category_users = lazy_gettext("Users")

    admin.add_view(
        UsersView(name=lazy_gettext('Regular Users'),
                  category=category_users,
                  url='users',
                  endpoint='admin.users'))
    admin.add_view(
        GoLabOAuthUserView(name=lazy_gettext('Go-Lab Users'),
                           category=category_users,
                           url='golab_users',
                           endpoint='admin.golab-users'))
    admin.add_view(
        AdminAppsView(name=lazy_gettext('Apps'),
                      url='apps-admin',
                      endpoint='admin.admin-apps'))
    admin.add_view(
        RedirectView('user.profile.index',
                     name=lazy_gettext('My Profile'),
                     url='profile',
                     endpoint='admin.profile'))
    admin.add_view(
        RedirectView('index',
                     name=lazy_gettext('Back'),
                     url='back',
                     endpoint='admin.back'))

    category_translator = lazy_gettext("Translator")
    admin.add_view(
        TranslationApplicationView(name=lazy_gettext('Translation apps'),
                                   category=category_translator,
                                   endpoint='admin.translation-apps'))
    admin.add_view(
        TranslationBundleView(name=lazy_gettext('Translation bundles'),
                              category=category_translator,
                              endpoint='admin.translation-bundles'))
    admin.add_view(
        TranslationMessageHistoryView(name=lazy_gettext('Translation history'),
                                      category=category_translator,
                                      endpoint='admin.translation-history'))
    admin.add_view(
        KeySuggestionsView(name=lazy_gettext('Suggestions by key'),
                           category=category_translator,
                           endpoint='admin.suggestions-key'))
    admin.add_view(
        ValueSuggestionsView(name=lazy_gettext('Suggestions by value'),
                             category=category_translator,
                             endpoint='admin.suggestions-value'))
    admin.add_view(
        ActiveTranslationMessageView(name=lazy_gettext('Active translations'),
                                     category=category_translator,
                                     endpoint='admin.active-translations'))
    admin.init_app(app)
Exemplo n.º 44
0
from flask.ext.admin.base import MenuLink
from app import app
from flask.ext.admin.form import rules
from flask.ext.admin.contrib.mongoengine import ModelView
from models import User, Post, Upload
from flask.ext.security import login_required, logout_user, current_user
from flask import redirect, url_for, request, flash, render_template
from flask.ext.uploads import UploadSet, IMAGES, configure_uploads
from config import UPLOADS_DEFAULT_DEST
from flask.ext.admin.contrib import fileadmin
import os.path as op

# Add administrative views here
admin = Admin(name='Admin')
# Add views here
admin.init_app(app)

uploads = UploadSet('uploads', IMAGES)
configure_uploads(app, uploads)

def get_image_url(id):
    photo = Upload.objects.get_or_404(id=id)
    return uploads.url(photo.image_url)
app.jinja_env.filters['get_image_url'] = get_image_url

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        filename = uploads.save(request.files['photo'])
        rec = Upload(image_url=filename)
        rec.save()
Exemplo n.º 45
0
class AdministrationApplication(object):

    def __init__(self, app, cfg_manager, core_server, bypass_authz = False):
        super(AdministrationApplication, self).__init__()
        app.json_encoder = CustomJSONEncoder
        
        self.cfg_manager = cfg_manager
        pub_directory = os.path.join(os.path.abspath(self.cfg_manager.get('deployment_dir', '')), 'pub')
        self.config = cfg_manager
        db.initialize(cfg_manager)

        self.core_server = core_server

        db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=db.engine))

        files_directory = cfg_manager.get_doc_value(configuration_doc.CORE_STORE_STUDENTS_PROGRAMS_PATH)
        core_server_url  = cfg_manager.get_value( 'core_server_url', '' )
        self.script_name = urlparse.urlparse(core_server_url).path.split('/weblab')[0] or ''

        self.app = app

        static_folder = os.path.abspath(os.path.join(os.path.dirname(web.__file__), 'static'))

        # Not allowed
        @app.route('/weblab/not_allowed')
        def not_allowed():
            return "You are logged in, but not allowed to see this content. Please log in with a proper account"

        # Back
        @app.route('/weblab/back')
        def back_to_client():
            return redirect(url_for('core_webclient.labs'))
   
        ################################################
        # 
        #  Administration panel for administrators
        # 
        # 

        admin_url = '/weblab/admin'
        category_system = lazy_gettext("System")
        category_users = lazy_gettext("Users")
        category_logs = lazy_gettext("Logs")
        category_experiments = lazy_gettext("Experiments")
        category_permissions = lazy_gettext("Permissions")
        self.admin = Admin(index_view = admin_views.HomeView(db_session, url = admin_url),name = lazy_gettext('WebLab-Deusto Admin'), url = admin_url, endpoint = admin_url, base_template = 'weblab-master.html', template_mode = 'bootstrap3')
        self.admin.weblab_admin_app = self

        self.admin.add_view(admin_views.SystemProperties(db_session, category = category_system, name = lazy_gettext('Settings'), endpoint = 'system/settings', url='settings'))
        self.admin.add_view(admin_views.AuthsPanel(db_session, category = category_system, name = lazy_gettext('Authentication'), endpoint = 'system/auth', url='auth'))
        if not os.path.exists(pub_directory):
            try:
                os.mkdir(pub_directory)
            except (IOError, OSError) as e:
                print("WARNING: %s not found. Create it to upload files to it." % pub_directory)
                    
        if os.path.exists(pub_directory):
            self.admin.add_view(admin_views.AdministratorFileAdmin(pub_directory, category = category_system, name = lazy_gettext('Public directory'), endpoint = 'system/pub', url='pub'))

        self.admin.add_view(admin_views.UsersAddingView(db_session,  category = category_users, name = lazy_gettext('Add multiple users'),  endpoint = 'users/multiple'))
        self.admin.add_view(admin_views.UsersPanel(db_session,  category = category_users, name = lazy_gettext('Users'),  endpoint = 'users/users', url='users'))
        self.admin.add_view(admin_views.GroupsPanel(db_session, category = category_users, name = lazy_gettext('Groups'), endpoint = 'users/groups', url='groups'))
        self.admin.add_view(admin_views.InvitationsPanel(db_session, category = category_users, name = lazy_gettext('Invitations'),
                                                         endpoint = 'users/invitations', url='invitations'))

        self.admin.add_view(admin_views.UserUsedExperimentPanel(files_directory, db_session, category = category_logs, name = lazy_gettext('User logs'), endpoint = 'logs/users', url='logs'))

        self.admin.add_view(admin_views.ExperimentCategoryPanel(db_session, category = category_experiments, name = lazy_gettext('Categories'),  endpoint = 'experiments/categories', url='experiments/categories'))
        self.admin.add_view(admin_views.ExperimentPanel(db_session,         category = category_experiments, name = lazy_gettext('Experiments'), endpoint = 'experiments/experiments', url='experiments'))
        # TODO: Until finished, do not display
        # self.admin.add_view(admin_views.SchedulerPanel(db_session,         category = category_experiments, name = lazy_gettext('Schedulers'), endpoint = 'experiments/schedulers'))

        self.admin.add_view(admin_views.PermissionsAddingView(db_session,  category = category_permissions, name = lazy_gettext('Create'), endpoint = 'permissions/create', url='permissions'))
        self.admin.add_view(admin_views.UserPermissionPanel(db_session,  category = category_permissions, name = lazy_gettext('User'),   endpoint = 'permissions/user'))
        self.admin.add_view(admin_views.GroupPermissionPanel(db_session, category = category_permissions, name = lazy_gettext('Group'),  endpoint = 'permissions/group'))
        self.admin.add_view(admin_views.RolePermissionPanel(db_session,  category = category_permissions, name = lazy_gettext('Roles'),  endpoint = 'permissions/role'))

        self.admin.add_link(MenuLink(endpoint='instructor.index', name = lazy_gettext('Instructor panel'), icon_type='glyph', icon_value='glyphicon-stats'))
        self.admin.add_link(MenuLink(endpoint='profile.index', name = lazy_gettext('My profile'), icon_type='glyph', icon_value='glyphicon-user'))
        self.admin.add_link(MenuLink(endpoint = 'back_to_client', name = lazy_gettext('Back'), icon_type='glyph', icon_value='glyphicon-log-out'))

        self.admin.init_app(self.app)

        self.full_admin_url = self.script_name + admin_url

        ################################################
        # 
        #  Profile panel
        # 

        profile_url = '/weblab/profile'
        self.profile = Admin(index_view = profile_views.ProfileHomeView(db_session, url = profile_url, endpoint = 'profile'),name = lazy_gettext('WebLab-Deusto profile'), url = profile_url, endpoint = profile_url, base_template = 'weblab-master.html', template_mode='bootstrap3')
        self.profile.weblab_admin_app = self

        self.profile.add_view(profile_views.ProfileEditView(db_session, name = lazy_gettext('Edit'), endpoint = 'edit'))

        self.profile.add_view(profile_views.MyAccessesPanel(files_directory, db_session,  name = lazy_gettext('My accesses'), endpoint = 'accesses'))
        self.profile.add_link(MenuLink(endpoint = 'back_to_client', name = lazy_gettext('Back'), icon_type='glyph', icon_value='glyphicon-log-out'))

        self.profile.init_app(self.app)

        ################################################
        # 
        #  Instructors panel
        # 
    
        # TODO. There should be able a new M2M relation between instructors and groups.
        # 
        # Instructor should be able to:
        # 
        # a) Create new groups (of which they are in charge)
        # b) Make other instructors in charge of these groups
        # c) Add students (and only students) to the system; forcing a group
        # d) Edit users (only students; of those groups that the administrator is in charge of)
        # e) Assign permissions on these courses
        # f) Manage the permissions on these courses
        # g) See the logs of their own students
        # h) See a panel with analytics of each of these groups (this panel is common to the administrator, and has not been implemented)

        instructor_url = '/weblab/instructor'
        instructor_home = instructor_views.InstructorHomeView(db_session, url = instructor_url, endpoint = 'instructor')
        instructor_home.static_folder = static_folder
        self.instructor = Admin(index_view = instructor_home, name = lazy_gettext("Weblab-Deusto instructor"), url = instructor_url, endpoint = instructor_url, base_template = 'weblab-master.html', template_mode='bootstrap3')
        self.instructor.weblab_admin_app = self
        
        category_general = lazy_gettext("General")
        category_stats = lazy_gettext("Stats")
        self.instructor.add_view(instructor_views.UsersPanel(db_session, category = category_general, name = lazy_gettext('Users'), endpoint = 'users'))
        self.instructor.add_view(instructor_views.GroupsPanel(db_session, category = category_general, name = lazy_gettext('Groups'), endpoint = 'groups'))
        self.instructor.add_view(instructor_views.UserUsedExperimentPanel(db_session, category = category_general, name = lazy_gettext('Raw accesses'), endpoint = 'logs'))

        self.instructor.add_view(instructor_views.GroupStats(db_session, category = category_stats, name = lazy_gettext('Group'), endpoint = 'stats/groups'))
        self.instructor.add_link(MenuLink(endpoint='profile.index', name = lazy_gettext('My profile'), icon_type='glyph', icon_value='glyphicon-user'))
        self.instructor.add_link(MenuLink(endpoint = 'back_to_client', name = lazy_gettext('Back'), icon_type='glyph', icon_value='glyphicon-log-out'))

        self.instructor.init_app(self.app)

        ################################################
        # 
        #  Other
        # 
        self.bypass_authz = bypass_authz

    @property
    def db(self):
        return self.core_server.db

    def get_db(self):
        return self.core_server.db

    def is_admin(self):
        if self.bypass_authz:
            return True

        try:
            session_id = (request.cookies.get('weblabsessionid') or '').split('.')[0]
            if not session_id:
                return False
            
            with weblab_api(self.core_server, session_id = session_id):
                is_admin = weblab_api.is_admin
            
            return is_admin
        except:
            traceback.print_exc()
            return False

    def get_user_role(self):
        if self.bypass_authz:
            return 'admin'

        try:
            session_id = (request.cookies.get('weblabsessionid') or '').split('.')[0]
            if session_id:
                try:
                    with weblab_api(self.core_server, session_id = session_id):
                        user_info = weblab.core.server.get_user_information()
                except SessionNotFoundError:
                    # Gotcha
                    traceback.print_exc()
                else:
                    return user_info.role.name
            return None
        except:
            traceback.print_exc()
            return None

    def _reserve_fake_session(self):
        fake_names = ('student1', 'porduna', 'user7', 'admin')
        exc = None
        for fake_name in fake_names:
            try:
                session_id, route = self.core_server._reserve_session(ValidDatabaseSessionId(fake_name, 'administrator'))
            except Exception as exc:
                pass
            else:
                return session_id, route
        raise exc

    def get_permissions(self):
        if self.bypass_authz:
            session_id, _ = self._reserve_fake_session()
            with weblab_api(self.core_server, session_id = session_id.id):
                return weblab.core.server.get_user_permissions()

        session_id = (request.cookies.get('weblabsessionid') or '').split('.')[0]
        if session_id:
            try:
                with weblab_api(self.core_server, session_id = session_id):
                    return weblab.core.server.get_user_permissions()
            except:
                traceback.print_exc()
        return None

    def get_user_information(self):
        if self.bypass_authz:
            session_id, _ = self._reserve_fake_session()
            with weblab_api(self.core_server, session_id = session_id.id):
                return weblab.core.server.get_user_information()

        session_id = (request.cookies.get('weblabsessionid') or '').split('.')[0]
        if session_id:
            try:
                with weblab_api(self.core_server, session_id = session_id):
                    return weblab.core.server.get_user_information()
            except SessionNotFoundError:
                pass
        return None
Exemplo n.º 46
0
# Flask-Babel
babel = Babel(app=app, default_locale='en', default_timezone='UTC')

# Flask Security
login_manager = LoginManager(app)
login_manager.init_app(app)
login_manager.session_protection = 'strong'

# Security Initialization
user_datastore = MongoEngineUserDatastore(db, Users, Role)
security = Security(app, user_datastore)

# Flask Admin
admin_init = Admin()
register_models(admin_init)
admin_init.init_app(app)

# Flask SocketIO
monkey.patch_all()
socketio = SocketIO(app)

# Flask Images
images = Images(app)

# Debug Toolbar
toolbar = DebugToolbarExtension(app)

# Redis
r = redis.StrictRedis(*config.REDIS_CONFIG)
app.session_interface = RedisSessionInterface(r, 'session:')
Exemplo n.º 47
0
def register_adminview(app):
    from flask.ext.admin import Admin
    from admin.MyModelView import MyAdminIndexView
    admin = Admin(name='PinPin Admin',
                  index_view=MyAdminIndexView(), template_mode='bootstrap3')
    admin.init_app(app)

    # register module admin view
    from module.user.user import User as UserModule
    from module.user.user_wechat import UserWechat as UserWechatModel
    from module.user.user_signin import UserSignIn as UserSignInModel
    from admin.MyModelView import MyModelView
    from module.user.useraddress import UserAddress as UserAddressModule
    from module.user.InviteCode import InviteCode as InviteCodeModule
    from module.user.useralipay import UserAlipay as UserAlipayModule
    from module.group.group import Group as GroupModule
    from module.group.grouphead import GroupHead as GroupHeadModule
    from module.group.groupad import GroupAd as GroupAdModule
    from module.workflow.workflow import Workflow as WorkflowModule
    from module.image.checkfile import CheckFile as CheckFileModule
    from module.order.order import Order as OrderModule
    from module.order.orderhead import OrderHead as OrderHeadModule
    from module.order.orderline import OrderLine as OrderLineModule
    from module.transport.transport import Transport as TransportModule
    from module.feedback.feedback import Feedback as FeedbackModule
    from module.payment.alipay_log import Alipay_Log as Alipay_LogModule
    from module.payment.wechat_pay_log import Wechat_Pay_Log as Wechat_Pay_LogModule
    from module.payment.PaymentLog import PaymentLog as PaymentLogModule
    from module.report.dailyreport import DailyReport as DailyReportModule
    from module.List.BuyList import BuyList as BuyListModule
    from module.log.UserLogon import (
        UserLogon as UserLogonModule,
        UserLastLogon as UserLastLogonModule
    )
    from module.log.wechat_text_log import WechatTextLog as WechatTextLogModule
    from module.monitor import CacheHitStats
    from module.log.notifymail import NotifyMail
    from module.report.UserDeviceFact import UserDeviceFact as UserDeviceFactModule
    from module.sku import SkuInfo, SkuImg, SkuRefGroup
    from module.blog import Blog as BlogModule
    admin.add_view(
        MyModelView(UserModule, db.session, endpoint='info', category='User'))
    admin.add_view(
        MyModelView(UserWechatModel, db.session, endpoint='wechat', category='User'))
    admin.add_view(
        MyModelView(UserSignInModel, db.session, endpoint='signin', category='User'))
    admin.add_view(
        MyModelView(UserAddressModule, db.session, endpoint='address', category='User'))
    admin.add_view(
        MyModelView(InviteCodeModule, db.session, endpoint='invitecode', category='User'))
    admin.add_view(
        MyModelView(UserAlipayModule, db.session, endpoint='useralipay', category='User'))
    admin.add_view(
        MyModelView(FeedbackModule, db.session, endpoint='feedback', category='User'))
    admin.add_view(
        MyModelView(GroupModule, db.session, endpoint='group', category='Group'))
    admin.add_view(
        MyModelView(GroupHeadModule, db.session, endpoint='grouphead', category='Group'))
    admin.add_view(
        MyModelView(GroupAdModule, db.session, endpoint='ad', category='Group'))
    admin.add_view(
        MyModelView(WorkflowModule, db.session, endpoint='workflow', category='Group'))
    admin.add_view(
        MyModelView(CheckFileModule, db.session, endpoint='checkfile', category='Group'))
    admin.add_view(
        MyModelView(BuyListModule, db.session, endpoint='skulist', category='Group'))
    admin.add_view(
        MyModelView(SkuInfo, db.session, endpoint='skuinfo', category='Sku'))
    admin.add_view(
        MyModelView(SkuImg, db.session, endpoint='skuimage', category='Sku'))
    admin.add_view(
        MyModelView(SkuRefGroup, db.session, endpoint='skurefgroup', category='Sku'))
    admin.add_view(
        MyModelView(BlogModule, db.session, endpoint='blog', category='Sku'))
    admin.add_view(
        MyModelView(OrderModule, db.session, endpoint='order', category='Order'))
    admin.add_view(
        MyModelView(OrderHeadModule, db.session, endpoint='orderhead', category='Order'))
    admin.add_view(
        MyModelView(OrderLineModule, db.session, endpoint='orderline', category='Order'))
    admin.add_view(
        MyModelView(TransportModule, db.session, endpoint='transport', category='Order'))
    admin.add_view(
        MyModelView(Alipay_LogModule, db.session, endpoint='alipay', category='Log'))
    admin.add_view(
        MyModelView(Wechat_Pay_LogModule, db.session, endpoint='wechatpay', category='Log'))
    admin.add_view(
        MyModelView(PaymentLogModule, db.session, endpoint='payment', category='Log'))
    admin.add_view(
        MyModelView(UserLogonModule, db.session, endpoint='logon', category='Log'))
    admin.add_view(
        MyModelView(UserLastLogonModule, db.session, endpoint='lastlogon', category='Log'))
    admin.add_view(
        MyModelView(NotifyMail, db.session, endpoint='notifymail', category='Log'))
    admin.add_view(
        MyModelView(CacheHitStats, db.session, endpoint='cachehit', category='Log'))
    admin.add_view(
        MyModelView(WechatTextLogModule, db.session, endpoint='wechat_text', category='Log'))
    admin.add_view(
        MyModelView(DailyReportModule, db.session, endpoint='daily', category='Report'))
    admin.add_view(
        MyModelView(UserDeviceFactModule, db.session, endpoint='device', category='Report'))
Exemplo n.º 48
0
def attach_admin(app):

    # Admin setup
    # -----------
    admin = Admin(name='Index', index_view=AdminIndexView(url='/db_admin'))

    # Forums
    admin.add_view(ModelView(forum_models.Board, db.session,
                             category='Forum',
                             name='Boards'))
    admin.add_view(ModelView(forum_models.Thread, db.session,
                             category='Forum',
                             name='Threads'))
    admin.add_view(ModelView(forum_models.Post, db.session,
                             category='Forum',
                             name='Posts'))
    # Users
    admin.add_view(UserView(app_models.Users, db.session,
                            category='Users',
                            name='Users'))
    admin.add_view(ModelView(models.Watches, db.session,
                             category='Users',
                             name='Watches'))



    # Releases
    # Language
    # classtype,
    # Feeds
    # FeedAuthors
    # FeedTags
    # Watches

    admin.add_view(SeriesView(models.Series, db.session,
                             category='Content',
                             name='Series'))
    admin.add_view(ModelView(models.Tags, db.session,
                             category='Content',
                             name='Tags'))
    admin.add_view(ModelView(models.Genres, db.session,
                             category='Content',
                             name='Genres'))
    admin.add_view(ModelView(models.Author, db.session,
                             category='Content',
                             name='Author'))
    admin.add_view(ModelView(models.Illustrators, db.session,
                             category='Content',
                             name='Illustrators'))
    admin.add_view(ModelView(models.AlternateNames, db.session,
                             category='Content',
                             name='AlternateNames'))
    admin.add_view(ModelView(models.AlternateTranslatorNames, db.session,
                             category='Content',
                             name='AlternateTranslatorNames'))
    admin.add_view(ModelView(models.Translators, db.session,
                             category='Content',
                             name='Translators'))
    admin.add_view(ModelView(models.Publishers, db.session,
                             category='Content',
                             name='Publishers'))
    admin.add_view(ModelView(models.Covers, db.session,
                             category='Content',
                             name='Covers'))
    admin.add_view(ModelView(models.Language, db.session,
                             category='Content',
                             name='Language'))




    admin.add_view(ModelView(models.Releases, db.session,
                             category='Releases',
                             name='Releases'))

    admin.add_view(ModelView(models.News_Posts, db.session,
                             category='News',
                             name='NewsPosts'))




    admin.init_app(app)
Exemplo n.º 49
0
Arquivo: app.py Projeto: danhyun/fbone
def configure_extensions(app):
    # flask-sqlalchemy
    db.init_app(app)

    # flask-mail
    mail.init_app(app)

    # flask-cache
    cache.init_app(app)

    # flask-babel
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        override = request.args.get('lang')
        if override:
            session['lang'] = override
            return session.get('lang', 'en')
        else:
            accept_languages = app.config.get('ACCEPT_LANGUAGES')
            return request.accept_languages.best_match(accept_languages)

    # flask-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(id)

    login_manager.setup_app(app)

    # flask-admin
    admin = Admin()
    # Setup locale
    admin.locale_selector(get_locale)
    # Views
    # Model admin
    admin.add_view(
        ModelView(User, db.session, endpoint='usermodel', category='Model'))
    admin.add_view(
        ModelView(UserDetail,
                  db.session,
                  endpoint='userdetailmodel',
                  category='Model'))
    admin.add_view(
        ModelView(UserRole, db.session, endpoint='rolemodel',
                  category='Model'))
    # File admin
    path = os.path.join(os.path.dirname(__file__), 'static/img/users')
    # Create directory if existed.
    try:
        os.mkdir(path)
    except OSError:
        pass
    admin.add_view(
        FileAdmin(path,
                  '/static/img/users',
                  endpoint='useravatar',
                  name='User Avatars',
                  category='Image'))
    admin.init_app(app)