• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python common.import_attr函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中uliweb.utils.common.import_attr函数的典型用法代码示例。如果您正苦于以下问题:Python import_attr函数的具体用法?Python import_attr怎么用?Python import_attr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了import_attr函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: function

def function(fname, *args, **kwargs):
    func = settings.get_var('FUNCTIONS/'+fname)
    if func:
        if args or kwargs:
            return import_attr(func)(*args, **kwargs)
        else:
            return import_attr(func)
    else:
        raise UliwebError("Can't find the function [%s] in settings" % fname)
开发者ID:lssebastian,项目名称:uliweb,代码行数:9,代码来源:SimpleFrame.py


示例2: call

def call(sender, topic, *args, **kwargs):
    """
    Invoke receiver functions according topic, it'll invoke receiver functions one by one,
    and it'll not return anything, so if you want to return a value, you should
    use get function.
    """
    if not topic in _receivers:
        return
    items = _receivers[topic]
    def _cmp(x, y):
        return cmp(x[0], y[0])
    
    items.sort(_cmp)
    for i in range(len(items)):
        nice, f = items[i]
        _f = f['func']
        if not _f:
            try:
                _f = import_attr(f['func_name'])
            except (ImportError, AttributeError) as e:
                logging.error("Can't import function %s" % f['func_name'])
                raise
            f['func'] = _f
        if callable(_f):
            kw = kwargs.copy()
            if not _test(kw, f):
                continue
            try:
                _f(sender, *args, **kw)
            except:
                func = _f.__module__ + '.' + _f.__name__
                logging.exception('Calling dispatch point [%s] %s(%r, %r) error!' % (topic, func, args, kw))
                raise
        else:
            raise Exception, "Dispatch point [%s] %r can't been invoked" % (topic, _f)
开发者ID:biluo1989,项目名称:uliweb,代码行数:35,代码来源:dispatch.py


示例3: linci_artifact_types

def linci_artifact_types():
    for id,sort_num,type_class in settings.LINCI.artifact_type:
        if type_class:
            type_class = import_attr(type_class)
        else:
            type_class = None
        yield id,sort_num,type_class
开发者ID:wangjun,项目名称:shapps,代码行数:7,代码来源:__init__.py


示例4: run

 def run(self):
     """
     直接运行当前的命令
     """
     f = import_attr(self.function)
     ret = f(**self.parameters)
     return ret
开发者ID:limodou,项目名称:uliweb-apps,代码行数:7,代码来源:__init__.py


示例5: get

def get(sender, topic, *args, **kwargs):
    """
    Invoke receiver functions according topic, it'll invoke receiver functions one by one,
    and if one receiver function return non-None value, it'll return it and break
    the loop.
    """
    if not topic in _receivers:
        return
    items = _receivers[topic]
    items.sort()
    for i in range(len(items)):
        nice, f = items[i]
        _f = f['func']
        if not _f:
            try:
                _f = import_attr(f['func_name'])
            except ImportError:
                logging.error("Can't import function %s" % f['func_name'])
                raise
            f['func'] = _f
        if callable(_f):
            if not _test(kwargs, f):
                continue
            try:
                v = _f(sender, *args, **kwargs)
            except:
                logging.exception('Calling dispatch point [%s] error!' % topic)
                raise
            if v is not None:
                return v
        else:
            raise "Dispatch point [%s] can't been invoked" % topic
开发者ID:datakungfu,项目名称:uliweb,代码行数:32,代码来源:dispatch.py


示例6: _validate

def _validate(menu, context, validators=None):
    from uliweb.utils.common import import_attr
    
    #validate permission
    validators = validators or []
    
    check = menu.get('check')
    if check and not isinstance(check, (list, tuple)):
        check = [check]
    else:
        check = []
    
    validators = validators + check
    
    if validators:
        flag = False
        for v in validators:
            if not v: continue
            if isinstance(v, (str, unicode)):
                func = import_attr(v)
            else:
                func = v
            flag = func(menu, context)
            if flag:
                flag = True
                break
    else:
        flag = True
        
    return flag
开发者ID:zhangchunlin,项目名称:plugs,代码行数:30,代码来源:__init__.py


示例7: install_middlewares

    def install_middlewares(self):
        #middleware process
        #middleware can be defined as
        #middleware_name = middleware_class_path[, order]
        #middleware_name = <empty> will be skip
        middlewares = []
        index = {}
        for middleware_name, v in settings.get('MIDDLEWARES', {}).iteritems():
            #process duplication of middleware, later will replace former
            if middleware_name in index:
                middlewares.pop(middleware_name)

            if not v:
                continue
            
            order = None
            if isinstance(v, (list, tuple)):
                if len(v) > 2:
                    raise UliwebError('Middleware %s difinition is not right' % middleware_name)
                middleware_path = v[0]
                if len(v) == 2:
                    order = v[1]
            else:
                middleware_path = v
            cls = import_attr(middleware_path)
            
            if order is None:
                order = getattr(cls, 'ORDER', 500)
            middlewares.append((order, cls))
            #remember the middleware index, so that can be used for easily remove
            index[middleware_name] = len(middlewares) - 1
        
        middlewares.sort(cmp=lambda x, y: cmp(x[0], y[0]))
            
        return [x[1] for x in middlewares]
开发者ID:bobgao,项目名称:uliweb,代码行数:35,代码来源:SimpleFrame.py


示例8: authenticate

def authenticate(username, password, auth_type=None):
    from uliweb import settings

    auth_type = auth_type or settings.AUTH.AUTH_DEFAULT_TYPE

    err_msg = ''
    if not isinstance(auth_type, (list, tuple)):
        auth_type = [auth_type]

    for t in auth_type:
        if t in settings.AUTH_CONFIG:
            func_path = settings.AUTH_CONFIG[t].get('authenticate')
            if func_path:
                func = import_attr(func_path)
                f, d = func(username, password)
                if f:
                    log.info("login successfully, auth_type: %s"%(t))
                    return f, d
                else:
                    log.error("fail to login, auth_type: %s, err: %s"%(t,d))
                    err_msg = d
        else:
            log.error("auth_type %s not in config"%(t))

    return False, {'username':err_msg}
开发者ID:28sui,项目名称:uliweb,代码行数:25,代码来源:__init__.py


示例9: dispatch_event

    def dispatch_event(self, event_type, **attrs):
        if isinstance(event_type, Event):
            e = event_type
        else:
            e = Event(event_type, self)

        if event_type in self._events.keys():
            for k, v in attrs.iteritems():
                setattr(e, k, v)
            listeners = self._events[e.type]
            for listener in listeners:
                _f = listener['func']
                if not _f:
                    try:
                        _f = import_attr(listener['func_name'])
                    except (ImportError, AttributeError) as e:
                        LOG.error("Can't import function %s" % listener['func_name'])
                        raise ImportError
                    listener['func'] = _f
                if callable(_f):
                    try:
                        _f(e)
                    except:
                        func = _f.__module__ + '.' + _f.__name__
                        LOG.exception('Calling dispatch event [%s] %s() error!' % (event_type, func))
                        raise
开发者ID:chu888chu888,项目名称:Python--uliweb-redbreast,代码行数:26,代码来源:utils.py


示例10: startup_installed

def startup_installed(sender):
    from uliweb import settings
    import uliweb.form.uliform as form
    from uliweb.utils.common import import_attr

    for k, v in settings.get_var('FORM_FIELDS_MAP', {}).items():
        form.fields_mapping[k] = import_attr(v)
开发者ID:28sui,项目名称:uliweb,代码行数:7,代码来源:__init__.py


示例11: has_role

def has_role(user, *roles, **kwargs):
    """
    Judge is the user belongs to the role, and if does, then return the role object
    if not then return False. kwargs will be passed to role_func.
    """
    Role = get_model("role")
    if isinstance(user, (unicode, str)):
        User = get_model("user")
        user = User.get(User.c.username == user)

    for role in roles:
        if isinstance(role, (str, unicode)):
            role = Role.get(Role.c.name == role)
            if not role:
                continue
        name = role.name

        func = __role_funcs__.get(name, None)
        if func:
            if isinstance(func, (unicode, str)):
                func = import_attr(func)

            assert callable(func)

            para = kwargs.copy()
            para["user"] = user
            flag = call_func(func, para)
            if flag:
                return role
        flag = role.users.has(user)
        if flag:
            return role
    return False
开发者ID:psusfy,项目名称:uliweb,代码行数:33,代码来源:rbac.py


示例12: sort_middlewares

 def sort_middlewares(self, middlewares):
     #middleware process
     #middleware can be defined as
     #middleware_name = middleware_class_path[, order]
     #middleware_name = <empty> will be skip
     m = []
     for v in middlewares:
         if not v:
             continue
         
         order = None
         if isinstance(v, (list, tuple)):
             if len(v) > 2:
                 raise UliwebError('Middleware %r difinition is not right' % v)
             middleware_path = v[0]
             if len(v) == 2:
                 order = v[1]
         else:
             middleware_path = v
         cls = import_attr(middleware_path)
         
         if order is None:
             order = getattr(cls, 'ORDER', 500)
         m.append((order, cls))
     
     m.sort(cmp=lambda x, y: cmp(x[0], y[0]))
         
     return [x[1] for x in m]
开发者ID:lssebastian,项目名称:uliweb,代码行数:28,代码来源:SimpleFrame.py


示例13: after_init_apps

def after_init_apps(sender):
    from uliweb import orm
    from uliweb.utils.common import import_attr
    from uliweb.core.SimpleFrame import __app_alias__
    
    orm.set_debug_query(settings.get_var('ORM/DEBUG_LOG'))
    orm.set_auto_create(settings.get_var('ORM/AUTO_CREATE'))
    orm.set_pk_type(settings.get_var('ORM/PK_TYPE'))
    orm.set_auto_set_model(False)
    orm.set_lazy_model_init(True)
    orm.set_check_max_length(settings.get_var('ORM/CHECK_MAX_LENGTH'))
    orm.set_nullable(settings.get_var('ORM/NULLABLE'))
    orm.set_server_default(settings.get_var('ORM/SERVER_DEFAULT'))
    orm.set_manytomany_index_reverse(settings.get_var('ORM/MANYTOMANY_INDEX_REVERSE'))
    convert_path = settings.get_var('ORM/TABLENAME_CONVERTER')
    convert = import_attr(convert_path) if convert_path else None
    orm.set_tablename_converter(convert)
    
    #judge if transaction middle has not install then set
    #AUTO_DOTRANSACTION is False
    if 'transaction' in settings.MIDDLEWARES:
        orm.set_auto_dotransaction(False)
    else:
        orm.set_auto_dotransaction(settings.get_var('ORM/AUTO_DOTRANSACTION'))
    
    d = {'connection_string':settings.get_var('ORM/CONNECTION'),
        'connection_type':settings.get_var('ORM/CONNECTION_TYPE'),
        'debug_log':settings.get_var('ORM/DEBUG_LOG'),
        'connection_args':settings.get_var('ORM/CONNECTION_ARGS'),
        'strategy':settings.get_var('ORM/STRATEGY'),
        }
    orm.engine_manager.add('default', d)
    
    for name, d in settings.get_var('ORM/CONNECTIONS').items():
        x = {'connection_string':d.get('CONNECTION', ''),
            'debug_log':d.get('DEBUG_LOG', None),
            'connection_args':d.get('CONNECTION_ARGS', {}),
            'strategy':d.get('STRATEGY', 'threadlocal'),
            'connection_type':d.get('CONNECTION_TYPE', 'long')
        }
        orm.engine_manager.add(name, x)

    if 'MODELS' in settings:
        for name, model_path in settings.MODELS.items():
            if not model_path: continue
            if isinstance(model_path, (str, unicode)):
                path = model_path
                engine_name = 'default'
            else:
                path, engine_name = model_path
            for k, v in __app_alias__.iteritems():
                if path.startswith(k):
                    path = v + path[len(k):]
                    break
            orm.set_model(path, name, engine_name=engine_name)

    if 'MODELS_CONFIG' in settings:
        for name, v in settings.MODELS_CONFIG.items():
            orm.set_model_config(name, v)
开发者ID:08haozi,项目名称:uliweb,代码行数:59,代码来源:__init__.py


示例14: __getattr__

 def __getattr__(self, name):
     if name in self.__objects:
         return self.__objects[name]
     if name not in settings[self.__section]:
         raise UliwebError("Object %s is not existed!" % name)
     obj = import_attr(settings[self.__section].get(name))
     self.__objects[name] = obj
     return obj
开发者ID:lssebastian,项目名称:uliweb,代码行数:8,代码来源:SimpleFrame.py


示例15: __getattr__

 def __getattr__(self, name):
     if name in self.__functions__:
         return self.__functions__[name]
     if name not in settings.FUNCTIONS:
         raise UliwebError("function %s is not existed!" % name)
     func = import_attr(settings.FUNCTIONS.get(name))
     self.__functions__[name] = func
     return func
开发者ID:bobgao,项目名称:uliweb,代码行数:8,代码来源:SimpleFrame.py


示例16: __getattr__

 def __getattr__(self, name):
     if name in self.__functions__:
         return self.__functions__[name]
     if name not in conf.settings.FUNCTIONS:
         raise Exception, "function %s is not existed!" % name
     func = import_attr(conf.settings.FUNCTIONS.get(name))
     self.__functions__[name] = func
     return func
开发者ID:datakungfu,项目名称:uliweb,代码行数:8,代码来源:SimpleFrame.py


示例17: install_global_objects

 def install_global_objects(self):
     """
     Process [GLOBAL_OBJECTS], and inject all object to uliweb module, so
     user can import from uliweb
     """
     import uliweb
     for k, v in settings.GLOBAL_OBJECTS.items():
         setattr(uliweb, k, import_attr(v))
开发者ID:lssebastian,项目名称:uliweb,代码行数:8,代码来源:SimpleFrame.py


示例18: create_client

 def create_client(sns_name):
     from uliweb import settings
     from uliweb.utils.common import import_attr
     servers = settings.get_var("Parrot/ServerList")
     server = servers[sns_name]
     return import_attr(server['info'][1])(
         server['client_id'], 
         server['client_secret'],
         server['redirect_uri'])
开发者ID:uliwebext,项目名称:uliweb-parrot,代码行数:9,代码来源:client.py


示例19: install_template_loader

    def install_template_loader(self, dirs):
        Loader = import_attr(settings.get_var('TEMPLATE_PROCESSOR/loader'))
        args = settings.get_var('TEMPLATE')

        if self.debug:
            args['check_modified_time'] = True
            args['log'] = log
            args['debug'] = settings.get_var('GLOBAL/DEBUG_TEMPLATE', False)
        return Loader(dirs, **args)
开发者ID:bluesky4485,项目名称:uliweb,代码行数:9,代码来源:SimpleFrame.py


示例20: soap

 def soap(self):
     from pysimplesoap.server import SoapDispatcher
     import uliweb.contrib.soap as soap
     from uliweb.utils.common import import_attr
     from uliweb import application as app, response, url_for
     from functools import partial
     
     global __soap_dispatcher__
     
     if not __soap_dispatcher__:
         location = "%s://%s%s" % (
             request.environ['wsgi.url_scheme'],
             request.environ['HTTP_HOST'],
             request.path)
         namespace = functions.get_var(self.config).get('namespace') or location
         documentation = functions.get_var(self.config).get('documentation')
         dispatcher = SoapDispatcher(
             name = functions.get_var(self.config).get('name'),
             location = location,
             action = '', # SOAPAction
             namespace = namespace,
             prefix=functions.get_var(self.config).get('prefix'),
             documentation = documentation,
             exception_handler = partial(exception_handler, response=response),
             ns = True)
         for name, (func, returns, args, doc) in soap.__soap_functions__.get(self.config, {}).items():
             if isinstance(func, (str, unicode)):
                 func = import_attr(func)
             dispatcher.register_function(name, func, returns, args, doc)
     else:
         dispatcher = __soap_dispatcher__
         
     if 'wsdl' in request.GET:
         # Return Web Service Description
         response.headers['Content-Type'] = 'text/xml'
         response.write(dispatcher.wsdl())
         return response
     elif request.method == 'POST':
         def _call(func, args):
             rule = SimpleRule()
             rule.endpoint = func
             mod, handler_cls, handler = app.prepare_request(request, rule)
             result = app.call_view(mod, handler_cls, handler, request, response, _wrap_result, kwargs=args)
             r = _fix_soap_datatype(result)
             return r
         # Process normal Soap Operation
         response.headers['Content-Type'] = 'text/xml'
         log.debug("---request message---")
         log.debug(request.data)
         result = dispatcher.dispatch(request.data, call_function=_call)
         log.debug("---response message---")
         log.debug(result)
         response.write(result)
         return response
开发者ID:08haozi,项目名称:uliweb,代码行数:54,代码来源:views.py



注:本文中的uliweb.utils.common.import_attr函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python log.error函数代码示例发布时间:2022-05-27
下一篇:
Python common.extract_dirs函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap