コード例 #1
0
ファイル: commands.py プロジェクト: zhangchunlin/uliweb-ui
    def handle(self, options, global_options, *args):
        from uliweb.utils.pyini import Ini
        from uliweb.utils.common import pkg
        from uliweb.contrib.template.tags import find
        from uliweb.contrib.staticfiles import url_for_static
        from uliweb import json_dumps
        import ConfigParser

        if not options.dest and not options.app:
            print("Error: Please use -d to specify output app")
            sys.exit(1)

        app = self.get_application(global_options)

        from uliweb import settings

        if options.dest:
            module = options.dest
            filename = pkg.resource_filename(options.dest, 'gulp_settings.ini')
        else:
            module = options.app
            filename = pkg.resource_filename(options.app, 'gulp_settings.ini')

        with open(filename, 'wb') as f:
            template_gulp = settings.get("TEMPLATE_GULP",
                                         {})  # 导出settings中的gulp配置
            template_use_keys = settings.get(
                "TEMPLATE_USE", {}).keys()  # 导出settings中的plugins的名字
            for dist, items in template_gulp.items():
                # 有序遍历gulp的concat配置
                item_dist = dist
                for name in items:
                    if name in template_use_keys:
                        # 如果plugins中有该插件则在ini中写入该配置
                        s = find(name)
                        m = s[0] + s[1]
                        f.write("[template_use." + name + "]\r\n")
                        for i in m:
                            #if no_js then skip javascript files
                            if options.no_js and (i.startswith('<!--')
                                                  or i.endswith('.js')):
                                continue
                            if not i.startswith('<!--'):
                                f.write("toplinks[] = " +
                                        app.get_file(i, 'static') + "\r\n")
                        f.write("dist = " + item_dist + "\r\n")
                    f.write("\r\n")

        gulp_dist = pkg.resource_filename(module, '/static')
        gulp_settings = filename
        gulp_path = pkg.resource_filename("uliweb_ui", "")
        import os
        terminal_command = "cd " + gulp_path + " && gulp  --dist " + gulp_dist + " --settings " + gulp_settings
        print(">>> {}".format(terminal_command))
        os.system(terminal_command)
コード例 #2
0
ファイル: SimpleFrame.py プロジェクト: hb44/uliweb
    def init(self, project_dir, apps_dir):
        if not project_dir:
            project_dir = norm_path(os.path.join(apps_dir, '..'))

        Dispatcher.project_dir = project_dir
        Dispatcher.apps_dir = norm_path(os.path.join(project_dir, 'apps'))
        Dispatcher.apps = get_apps(self.apps_dir, self.include_apps,
                                   self.settings_file,
                                   self.local_settings_file)
        Dispatcher.modules = self.collect_modules()

        self.install_settings(self.modules['settings'])

        self.debug = settings.GLOBAL.get('DEBUG', False)

        #process global_objects
        self.install_global_objects()

        #process binds
        self.install_binds()

        dispatch.call(self, 'after_init_settings')

        Dispatcher.settings = settings

        #process domains
        self.process_domains(settings)

        #setup log
        self.set_log()

        #set app rules
        rules.set_app_rules(dict(settings.get('URL', {})))
        rules.set_urlroute_rules(dict(settings.get('URL_ROUTE', {})))

        Dispatcher.env = self._prepare_env()
        Dispatcher.template_dirs = self.get_template_dirs()
        Dispatcher.template_loader = self.install_template_loader(
            Dispatcher.template_dirs)

        #begin to start apps
        self.install_apps()
        dispatch.call(self, 'after_init_apps')
        #process views
        self.install_views(self.modules['views'])
        #process exposes
        self.install_exposes()
        #process middlewares
        Dispatcher.middlewares = self.install_middlewares()

        dispatch.call(self, 'prepare_default_env', Dispatcher.env)
        Dispatcher.default_template = pkg.resource_filename(
            'uliweb.core', 'default.html')

        Dispatcher.installed = True
コード例 #3
0
ファイル: SimpleFrame.py プロジェクト: hb44/uliweb
    def init(self, project_dir, apps_dir):
        if not project_dir:
            project_dir = norm_path(os.path.join(apps_dir, '..'))
        
        Dispatcher.project_dir = project_dir
        Dispatcher.apps_dir = norm_path(os.path.join(project_dir, 'apps'))
        Dispatcher.apps = get_apps(self.apps_dir, self.include_apps, self.settings_file, self.local_settings_file)
        Dispatcher.modules = self.collect_modules()

        self.install_settings(self.modules['settings'])

        self.debug = settings.GLOBAL.get('DEBUG', False)

        #process global_objects
        self.install_global_objects()
        
        #process binds
        self.install_binds()
        
        dispatch.call(self, 'after_init_settings')
        
        Dispatcher.settings = settings
        
        #process domains
        self.process_domains(settings)
        
        #setup log
        self.set_log()
        
        #set app rules
        rules.set_app_rules(dict(settings.get('URL', {})))
        rules.set_urlroute_rules(dict(settings.get('URL_ROUTE', {})))

        Dispatcher.env = self._prepare_env()
        Dispatcher.template_dirs = self.get_template_dirs()
        Dispatcher.template_loader = self.install_template_loader(Dispatcher.template_dirs)

        #begin to start apps
        self.install_apps()
        dispatch.call(self, 'after_init_apps')
        #process views
        self.install_views(self.modules['views'])
        #process exposes
        self.install_exposes()
        #process middlewares
        Dispatcher.middlewares = self.install_middlewares()

        dispatch.call(self, 'prepare_default_env', Dispatcher.env)
        Dispatcher.default_template = pkg.resource_filename('uliweb.core', 'default.html')
        
        Dispatcher.installed = True
コード例 #4
0
ファイル: commands.py プロジェクト: uliwebext/uliweb-ui
    def handle(self, options, global_options, *args):
        from uliweb.utils.pyini import Ini
        from uliweb.utils.common import pkg
        from uliweb.contrib.template.tags import find
        from uliweb.contrib.staticfiles import url_for_static
        from uliweb import json_dumps
        import ConfigParser

        if not options.dest and not options.app:
            print "Error: Please use -d to specify output app"
            sys.exit(1)

        app = self.get_application(global_options)

        from uliweb import settings

        if options.dest:
            module = options.dest
            filename = pkg.resource_filename(options.dest, 'gulp_settings.ini')
        else:
            module = options.app
            filename = pkg.resource_filename(options.app, 'gulp_settings.ini')

        with open(filename, 'wb') as f:
            template_gulp = settings.get("TEMPLATE_GULP", {}) # 导出settings中的gulp配置
            template_use_keys = settings.get("TEMPLATE_USE", {}).keys() # 导出settings中的plugins的名字
            for dist,items in template_gulp.items():
                # 有序遍历gulp的concat配置
                item_dist = dist
                for name in items:
                    if name in template_use_keys:
                        # 如果plugins中有该插件则在ini中写入该配置
                        s = find(name)
                        m = s[0] + s[1]
                        f.write("[template_use." + name + "]\r\n")
                        for i in m:
                            if not i.startswith('<!--'):
                                f.write("toplinks[] = " + app.get_file(i, 'static') + "\r\n")
                        f.write("dist = " + item_dist + "\r\n")
                    f.write("\r\n")

        gulp_dist = pkg.resource_filename(module, '/static');
        gulp_settings = filename
        gulp_path = pkg.resource_filename("uliweb_ui","")
        import os
        terminal_command = "cd "+gulp_path+ " && gulp  --dist " + gulp_dist + " --settings " + gulp_settings
        print ">>> {}".format(terminal_command)
        os.system(terminal_command)
コード例 #5
0
ファイル: middle_session.py プロジェクト: 28sui/uliweb
    def __init__(self, application, settings):
        from datetime import timedelta
        self.options = dict(settings.get('SESSION_STORAGE', {}))
        self.options['data_dir'] = application_path(self.options['data_dir'])
        if 'url' not in self.options:
            _url = (settings.get_var('ORM/CONNECTION', '') or
            settings.get_var('ORM/CONNECTIONS', {}).get('default', {}).get('CONNECTION', ''))
            if _url:
                self.options['url'] = _url
        
        #process Session options
        self.remember_me_timeout = settings.SESSION.remember_me_timeout
        self.session_storage_type = settings.SESSION.type
        self.timeout = settings.SESSION.timeout
        Session.force = settings.SESSION.force
        
        #process Cookie options
        SessionCookie.default_domain = settings.SESSION_COOKIE.domain
        SessionCookie.default_path = settings.SESSION_COOKIE.path
        SessionCookie.default_secure = settings.SESSION_COOKIE.secure
        SessionCookie.default_cookie_id = settings.SESSION_COOKIE.cookie_id

        if isinstance(settings.SESSION_COOKIE.timeout, int):
            timeout = timedelta(seconds=settings.SESSION_COOKIE.timeout)
        else:
            timeout = settings.SESSION_COOKIE.timeout
        SessionCookie.default_expiry_time = timeout
コード例 #6
0
ファイル: SimpleFrame.py プロジェクト: lssebastian/uliweb
 def install_exposes(self):
     #EXPOSES format
     #endpoint = topic              #bind_name will be the same with function
     #expose_name = topic, func        
     #expose_name = topic, func, {args}
     d = settings.get('EXPOSES', {})
     for name, args in d.iteritems():
         if not args:
             continue
         is_wrong = False
         if isinstance(args, (tuple, list)):
             if len(args) == 2:
                 expose(args[0], name=name)(args[1])
             elif len(args) == 3:
                 if not isinstance(args[2], dict):
                     is_wrong = True
                 else:
                     expose(args[0], name=name, **args[2])(args[1])
             else:
                 is_wrong = True
         elif isinstance(args, (str, unicode)):
             expose(args)(name)
         else:
             is_wrong = True
         if is_wrong:
             log.error('EXPOSES definition should be "endpoint=url" or "name=url, endpoint" or "name=url, endpoint, {"args":value1,...}"')
             raise UliwebError('EXPOSES definition [%s=%r] is not right' % (name, args))
コード例 #7
0
ファイル: middle_session.py プロジェクト: limodou/uliweb3
    def __init__(self, application, settings):
        from datetime import timedelta
        self.options = dict(settings.get('SESSION_STORAGE', {}))
        self.options['data_dir'] = application_path(self.options['data_dir'])
        if 'url' not in self.options:
            _url = (settings.get_var('ORM/CONNECTION', '')
                    or settings.get_var('ORM/CONNECTIONS', {}).get(
                        'default', {}).get('CONNECTION', ''))
            if _url:
                self.options['url'] = _url

        #process Session options
        self.remember_me_timeout = settings.SESSION.remember_me_timeout
        self.session_storage_type = settings.SESSION.type
        self.timeout = settings.SESSION.timeout
        Session.force = settings.SESSION.force

        #process Cookie options
        SessionCookie.default_domain = settings.SESSION_COOKIE.domain
        SessionCookie.default_path = settings.SESSION_COOKIE.path
        SessionCookie.default_secure = settings.SESSION_COOKIE.secure
        SessionCookie.default_cookie_id = settings.SESSION_COOKIE.cookie_id

        if isinstance(settings.SESSION_COOKIE.timeout, int):
            timeout = timedelta(seconds=settings.SESSION_COOKIE.timeout)
        else:
            timeout = settings.SESSION_COOKIE.timeout
        SessionCookie.default_expiry_time = timeout
コード例 #8
0
ファイル: __init__.py プロジェクト: sdoom/shapps
def get_session(key=None):
    options = dict(settings.get('SESSION_STORAGE', {}))
    options['data_dir'] = application_path(options['data_dir'])
    if 'url' not in options:
        _url = (settings.get_var('ORM/CONNECTION', '') or settings.get_var(
            'ORM/CONNECTIONS', {}).get('default', {}).get('CONNECTION', ''))
        if _url:
            options['url'] = _url

    #process Session options
    session_storage_type = settings.SESSION.type
    Session.force = settings.SESSION.force

    serial_cls_path = settings.SESSION.serial_cls
    if serial_cls_path:
        serial_cls = import_attr(serial_cls_path)
    else:
        serial_cls = None

    session = Session(key,
                      storage_type=session_storage_type,
                      options=options,
                      expiry_time=settings.SESSION.timeout,
                      serial_cls=serial_cls)
    return session
コード例 #9
0
ファイル: SimpleFrame.py プロジェクト: FashtimeDotCom/uliweb
 def install_exposes(self):
     #EXPOSES format
     #endpoint = topic              #bind_name will be the same with function
     #expose_name = topic, func        
     #expose_name = topic, func, {args}
     d = settings.get('EXPOSES', {})
     for name, args in d.items():
         if not args:
             continue
         is_wrong = False
         if isinstance(args, (tuple, list)):
             if len(args) == 2:
                 expose(args[0], name=name)(args[1])
             elif len(args) == 3:
                 if not isinstance(args[2], dict):
                     is_wrong = True
                 else:
                     expose(args[0], name=name, **args[2])(args[1])
             else:
                 is_wrong = True
         elif isinstance(args, (str, unicode)):
             expose(args)(name)
         else:
             is_wrong = True
         if is_wrong:
             log.error('EXPOSES definition should be "endpoint=url" or "name=url, endpoint" or "name=url, endpoint, {"args":value1,...}"')
             raise UliwebError('EXPOSES definition [%s=%r] is not right' % (name, args))
コード例 #10
0
ファイル: SimpleFrame.py プロジェクト: FashtimeDotCom/uliweb
 def install_binds(self):
     #process DISPATCH hooks
     #BINDS format
     #func = topic              #bind_name will be the same with function
     #bind_name = topic, func        
     #bind_name = topic, func, {args}
     d = settings.get('BINDS', {})
     for bind_name, args in d.items():
         if not args:
             continue
         is_wrong = False
         if isinstance(args, (tuple, list)):
             if len(args) == 2:
                 dispatch.bind(args[0])(args[1])
             elif len(args) == 3:
                 if not isinstance(args[2], dict):
                     is_wrong = True
                 else:
                     dispatch.bind(args[0], **args[2])(args[1])
             else:
                 is_wrong = True
         elif isinstance(args, (str, unicode)):
             dispatch.bind(args)(bind_name)
         else:
             is_wrong = True
         if is_wrong:
             log.error('BINDS definition should be "function=topic" or "bind_name=topic, function" or "bind_name=topic, function, {"args":value1,...}"')
             raise UliwebError('BINDS definition [%s=%r] is not right' % (bind_name, args))
コード例 #11
0
ファイル: SimpleFrame.py プロジェクト: bluesky4485/uliweb
 def install_middlewares(self):
     m = self._sort_middlewares(settings.get('MIDDLEWARES', {}).values())
     req_classes, res_classes, ex_classes = self._get_middlewares_classes(m)
     Dispatcher.process_request_classes = req_classes
     Dispatcher.process_response_classes = res_classes
     Dispatcher.process_exception_classes = ex_classes
     return m
コード例 #12
0
ファイル: SimpleFrame.py プロジェクト: lssebastian/uliweb
 def install_binds(self):
     #process DISPATCH hooks
     #BINDS format
     #func = topic              #bind_name will be the same with function
     #bind_name = topic, func        
     #bind_name = topic, func, {args}
     d = settings.get('BINDS', {})
     for bind_name, args in d.iteritems():
         if not args:
             continue
         is_wrong = False
         if isinstance(args, (tuple, list)):
             if len(args) == 2:
                 dispatch.bind(args[0])(args[1])
             elif len(args) == 3:
                 if not isinstance(args[2], dict):
                     is_wrong = True
                 else:
                     dispatch.bind(args[0], **args[2])(args[1])
             else:
                 is_wrong = True
         elif isinstance(args, (str, unicode)):
             dispatch.bind(args)(bind_name)
         else:
             is_wrong = True
         if is_wrong:
             log.error('BINDS definition should be "function=topic" or "bind_name=topic, function" or "bind_name=topic, function, {"args":value1,...}"')
             raise UliwebError('BINDS definition [%s=%r] is not right' % (bind_name, args))
コード例 #13
0
ファイル: SimpleFrame.py プロジェクト: hb44/uliweb
 def install_middlewares(self):
     m = self._sort_middlewares(settings.get('MIDDLEWARES', {}).values())
     req_classes, res_classes, ex_classes = self._get_middlewares_classes(m)
     Dispatcher.process_request_classes = req_classes
     Dispatcher.process_response_classes = res_classes
     Dispatcher.process_exception_classes = ex_classes
     return m
コード例 #14
0
def after_init_apps(sender):
    import mimetypes
    from uliweb import settings

    for k, v in settings.get('MIME_TYPES').items():
        if not k.startswith('.'):
            k = '.' + k
        mimetypes.add_type(v, k)
コード例 #15
0
ファイル: __init__.py プロジェクト: 08haozi/uliweb
def after_init_apps(sender):
    import mimetypes
    from uliweb import settings
    
    for k, v in settings.get('MIME_TYPES').items():
        if not k.startswith('.'):
            k = '.' + k
        mimetypes.add_type(v, k)
コード例 #16
0
ファイル: __init__.py プロジェクト: 08haozi/uliweb
def init_static_combine():
    """
    Process static combine, create md5 key according each static filename
    """
    from uliweb import settings
    from hashlib import md5
    import os
    
    d = {}
    for k, v in settings.get('STATIC_COMBINE', {}).items():
        key = '_cmb_'+md5(''.join(v)).hexdigest()+os.path.splitext(v[0])[1]
        d[key] = v
        
    return d
コード例 #17
0
ファイル: __init__.py プロジェクト: ustbgaofan/uliweb
def init_static_combine():
    """
    Process static combine, create md5 key according each static filename
    """
    from uliweb import settings
    from hashlib import md5
    import os

    d = {}
    for k, v in settings.get('STATIC_COMBINE', {}).items():
        key = '_cmb_' + md5(''.join(v)).hexdigest() + os.path.splitext(v[0])[1]
        d[key] = v

    return d
コード例 #18
0
ファイル: SimpleFrame.py プロジェクト: biluo1989/uliweb
    def init(self, project_dir, apps_dir):
        if not project_dir:
            project_dir = norm_path(os.path.join(apps_dir, ".."))
        Dispatcher.project_dir = project_dir
        Dispatcher.apps_dir = norm_path(os.path.join(project_dir, "apps"))
        Dispatcher.apps = get_apps(self.apps_dir, self.include_apps, self.settings_file, self.local_settings_file)
        Dispatcher.modules = self.collect_modules()

        self.install_settings(self.modules["settings"])

        # process global_objects
        self.install_global_objects()

        # process binds
        self.install_binds()

        dispatch.call(self, "after_init_settings")

        Dispatcher.settings = settings

        # process domains
        self.process_domains(settings)

        # setup log
        self.set_log()

        # set app rules
        rules.set_app_rules(dict(settings.get("URL", {})))

        Dispatcher.env = self._prepare_env()
        Dispatcher.template_dirs = self.get_template_dirs()
        Dispatcher.template_processors = {}
        self.install_template_processors()

        # begin to start apps
        self.install_apps()
        dispatch.call(self, "after_init_apps")
        # process views
        self.install_views(self.modules["views"])
        # process exposes
        self.install_exposes()
        # process middlewares
        Dispatcher.middlewares = self.install_middlewares()

        self.debug = settings.GLOBAL.get("DEBUG", False)
        dispatch.call(self, "prepare_default_env", Dispatcher.env)
        Dispatcher.default_template = pkg.resource_filename("uliweb.core", "default.html")

        Dispatcher.installed = True
コード例 #19
0
def after_init_apps(sender):

    # set workflow engine to load spec from database
    LOG.info(" * Initialize CoreWFManager with database storage")
    from redbreast.core.spec import CoreWFManager
    from redbreast.core.spec import WFDatabaseStorage
    from uliweb import settings
    storage = WFDatabaseStorage()
    CoreWFManager.set_storage(storage)

    bindable = settings.get_var('REDBREAST/ENABLE_EVENT_BIND', True)
    if bindable:
        LOG.info(" * Setup EVENT_BIND for CoreWFManage")
        from redbreast.core.spec import CoreWFManager, WFManagerBindPlugin
        plugin = WFManagerBindPlugin()
        d = settings.get('REDBREAST_BINDS', {})
        for bind_name, args in d.items():
            plugin.bind(args[0], args[1], args[2])

        CoreWFManager.register_plugin(plugin)
コード例 #20
0
def after_init_apps(sender):

    # set workflow engine to load spec from database
    LOG.info(" * Initialize CoreWFManager with database storage")
    from redbreast.core.spec import CoreWFManager
    from redbreast.core.spec import WFDatabaseStorage
    from uliweb import settings
    storage = WFDatabaseStorage()
    CoreWFManager.set_storage(storage)

    bindable = settings.get_var('REDBREAST/ENABLE_EVENT_BIND', True)
    if bindable:
        LOG.info(" * Setup EVENT_BIND for CoreWFManage")
        from redbreast.core.spec import CoreWFManager, WFManagerBindPlugin
        plugin = WFManagerBindPlugin()
        d = settings.get('REDBREAST_BINDS', {})
        for bind_name, args in d.items():
            plugin.bind(args[0], args[1], args[2])

        CoreWFManager.register_plugin(plugin)
コード例 #21
0
ファイル: views.py プロジェクト: wangjun/shapps
def get_session(key=None):
    options = dict(settings.get('SESSION_STORAGE', {}))
    options['data_dir'] = application_path(options['data_dir'])
    if 'url' not in options:
        _url = (settings.get_var('ORM/CONNECTION', '') or
        settings.get_var('ORM/CONNECTIONS', {}).get('default', {}).get('CONNECTION', ''))
        if _url:
            options['url'] = _url

    #process Session options
    session_storage_type = settings.SESSION.type
    Session.force = settings.SESSION.force

    serial_cls_path = settings.SESSION.serial_cls
    if serial_cls_path:
        serial_cls = import_attr(serial_cls_path)
    else:
        serial_cls = None

    session = Session(key, storage_type=session_storage_type,
        options=options, expiry_time=settings.SESSION.timeout, serial_cls=serial_cls)
    return session
コード例 #22
0
def process_panel():
    p = settings.get('PANEL', {})
    for data in p.items():
        panel(**data).save()
コード例 #23
0
ファイル: SimpleFrame.py プロジェクト: lssebastian/uliweb
 def install_middlewares(self):
     return self.sort_middlewares(settings.get('MIDDLEWARES', {}).values())
コード例 #24
0
def process_layout():
    l = settings.get('PANELLAYOUT', {})
    for data in l.items():
        layout(**data).save()
コード例 #25
0
def process_dashboard():
    d = settings.get('DASHBOARD', {})
    for name, layout in d.items():
        data = {'name': name, 'layout': layout}
        dashboard(**data).save()
コード例 #26
0
ファイル: SimpleFrame.py プロジェクト: FashtimeDotCom/uliweb
 def install_middlewares(self):
     return self.sort_middlewares(settings.get('MIDDLEWARES', {}).values())
コード例 #27
0
ファイル: dbinit.py プロジェクト: wangjun/shapps
def dbinit():
    RbacOrg = get_model('rbacorg')
    RbacScheme = get_model('rbacscheme')
    Role = get_model('role')
    Perm = get_model('permission')
    User = get_model('user')
    UserGroup = get_model('usergroup')
    OrgRole = get_model('orgrole')
    Rel = get_model('role_perm_rel')

    for k,v in settings.get('RBACSCHEME', {}).items():
        scheme_name,gorg_name,rp_list = v
        if not gorg_name:
            gorg_name = "%s_gorg"%(scheme_name)
        gorg = RbacOrg.get(RbacOrg.c.name==gorg_name)
        if not gorg:
            print "Add gorg(%s) of RbacScheme(%s)"%(gorg_name, scheme_name)
            gorg = RbacOrg(name=gorg_name)
            flag = gorg.save(); assert(flag)
        rbacscheme = RbacScheme.get(RbacScheme.c.name==scheme_name)
        if not rbacscheme:
            print "Add RbacScheme(%s)"%(scheme_name)
            rbacscheme = RbacScheme(name=scheme_name,gorg=gorg)
            flag = rbacscheme.save(); assert(flag)
        for role_name,perm_name in rp_list:
            role = Role.get(Role.c.name==role_name)
            if not role:
                print "Add Role(%s)"%(role_name)
                role = Role(name=safe_str(role_name))
                flag = role.save(); assert(flag)
            perm = Perm.get(Perm.c.name==perm_name)
            if not perm:
                print "Add Permission(%s)"%(perm_name)
                perm = Perm(name=safe_str(perm_name))
                flag = perm.save(); assert(flag)
            rel = Rel.get(and_(Rel.c.role==role.id,
                Rel.c.permission==perm.id,
                Rel.c.scheme==rbacscheme.id))
            if not rel:
                print "Add Role_Perm_Rel(%s,%s,%s)"%(role_name,perm_name,scheme_name)
                rel = Rel(role=role,permission=perm,scheme=rbacscheme)
                flag = rel.save(); assert(flag)

    for k,v in settings.get('RBACORG', {}).items():
        rbacorg_name,rbacscheme_name = v
        rbacscheme = RbacScheme.get(RbacScheme.c.name==rbacscheme_name)
        if not rbacscheme:
            raise Exception, 'RbacScheme [%s] not found.' % rbacscheme
        rbacorg = RbacOrg.get(RbacOrg.c.name==rbacorg_name)
        if not rbacorg:
            print "Add RbacOrg(%s,%s)"%(rbacorg_name, rbacscheme_name)
            rbacorg = RbacOrg(name=rbacorg_name,rbacscheme=rbacscheme)
            flag = rbacorg.save(); assert(flag)
        elif (not rbacorg.rbacscheme) or (rbacorg.rbacscheme.id!=rbacscheme.id):
            print "Update RbacOrg[%s]'s scheme to %s"%(rbacorg_name,rbacscheme_name)
            rbacorg.update(rbacscheme=rbacscheme)
            rbacorg.save()

    for k,v in settings.get('ORGROLE').items():
        role_name, rbacorg_name, usernames, usergroupnames = v
        role = Role.get(Role.c.name==role_name)
        if not role:
            raise Exception, 'Role [%s] not found.' % role_name
        rbacorg = RbacOrg.get(RbacOrg.c.name==rbacorg_name)
        if not rbacorg:
            raise Exception, 'RbacOrg [%s] not found.' % rbacorg_name
        orgrole = OrgRole.get(and_(OrgRole.c.role==role.id,
            OrgRole.c.organization==rbacorg.id))
        if not orgrole:
            print "Add OrgRole(%s,%s)"%(role_name, rbacorg_name)
            orgrole = OrgRole(role=role,organization=rbacorg)
            flag = orgrole.save(); assert(flag)
        for username in usernames:
            user = User.get(User.c.username==username)
            if user:
                if not orgrole.users.has(user):
                    print "Add User(%s) to OrgRole(%s,%s)"%(username, role_name, rbacorg_name)
                    orgrole.users.add(user)
        for usergroupname in usergroupnames:
            usergroup = UserGroup.get(UserGroup.c.name==usergroupname)
            if usergroup:
                if not orgrole.usergroups.has(usergroup):
                    print "Add UserGroup(%s) to OrgRole(%s,%s)"%(usergroupname, role_name, rbacorg_name)
                    orgrole.usergroups.add(usergroup)
コード例 #28
0
def dbinit():
    RbacOrg = get_model('rbacorg')
    RbacScheme = get_model('rbacscheme')
    Role = get_model('role')
    Perm = get_model('permission')
    User = get_model('user')
    UserGroup = get_model('usergroup')
    OrgRole = get_model('orgrole')
    Rel = get_model('role_perm_rel')

    for k, v in settings.get('RBACSCHEME', {}).items():
        scheme_name, gorg_name, rp_list = v
        if not gorg_name:
            gorg_name = "%s_gorg" % (scheme_name)
        gorg = RbacOrg.get(RbacOrg.c.name == gorg_name)
        if not gorg:
            print "Add gorg(%s) of RbacScheme(%s)" % (gorg_name, scheme_name)
            gorg = RbacOrg(name=gorg_name)
            flag = gorg.save()
            assert (flag)
        rbacscheme = RbacScheme.get(RbacScheme.c.name == scheme_name)
        if not rbacscheme:
            print "Add RbacScheme(%s)" % (scheme_name)
            rbacscheme = RbacScheme(name=scheme_name, gorg=gorg)
            flag = rbacscheme.save()
            assert (flag)
        for role_name, perm_name in rp_list:
            role = Role.get(Role.c.name == role_name)
            if not role:
                print "Add Role(%s)" % (role_name)
                role = Role(name=safe_str(role_name))
                flag = role.save()
                assert (flag)
            perm = Perm.get(Perm.c.name == perm_name)
            if not perm:
                print "Add Permission(%s)" % (perm_name)
                perm = Perm(name=safe_str(perm_name))
                flag = perm.save()
                assert (flag)
            rel = Rel.get(
                and_(Rel.c.role == role.id, Rel.c.permission == perm.id,
                     Rel.c.scheme == rbacscheme.id))
            if not rel:
                print "Add Role_Perm_Rel(%s,%s,%s)" % (role_name, perm_name,
                                                       scheme_name)
                rel = Rel(role=role, permission=perm, scheme=rbacscheme)
                flag = rel.save()
                assert (flag)

    for k, v in settings.get('RBACORG', {}).items():
        rbacorg_name, rbacscheme_name = v
        rbacscheme = RbacScheme.get(RbacScheme.c.name == rbacscheme_name)
        if not rbacscheme:
            raise Exception, 'RbacScheme [%s] not found.' % rbacscheme
        rbacorg = RbacOrg.get(RbacOrg.c.name == rbacorg_name)
        if not rbacorg:
            print "Add RbacOrg(%s,%s)" % (rbacorg_name, rbacscheme_name)
            rbacorg = RbacOrg(name=rbacorg_name, rbacscheme=rbacscheme)
            flag = rbacorg.save()
            assert (flag)
        elif (not rbacorg.rbacscheme) or (rbacorg.rbacscheme.id !=
                                          rbacscheme.id):
            print "Update RbacOrg[%s]'s scheme to %s" % (rbacorg_name,
                                                         rbacscheme_name)
            rbacorg.update(rbacscheme=rbacscheme)
            rbacorg.save()

    for k, v in settings.get('ORGROLE').items():
        role_name, rbacorg_name, usernames, usergroupnames = v
        role = Role.get(Role.c.name == role_name)
        if not role:
            raise Exception, 'Role [%s] not found.' % role_name
        rbacorg = RbacOrg.get(RbacOrg.c.name == rbacorg_name)
        if not rbacorg:
            raise Exception, 'RbacOrg [%s] not found.' % rbacorg_name
        orgrole = OrgRole.get(
            and_(OrgRole.c.role == role.id,
                 OrgRole.c.organization == rbacorg.id))
        if not orgrole:
            print "Add OrgRole(%s,%s)" % (role_name, rbacorg_name)
            orgrole = OrgRole(role=role, organization=rbacorg)
            flag = orgrole.save()
            assert (flag)
        for username in usernames:
            user = User.get(User.c.username == username)
            if user:
                if not orgrole.users.has(user):
                    print "Add User(%s) to OrgRole(%s,%s)" % (
                        username, role_name, rbacorg_name)
                    orgrole.users.add(user)
        for usergroupname in usergroupnames:
            usergroup = UserGroup.get(UserGroup.c.name == usergroupname)
            if usergroup:
                if not orgrole.usergroups.has(usergroup):
                    print "Add UserGroup(%s) to OrgRole(%s,%s)" % (
                        usergroupname, role_name, rbacorg_name)
                    orgrole.usergroups.add(usergroup)