本文整理汇总了Python中uliweb.utils.common.import_attr函数的典型用法代码示例。如果您正苦于以下问题:Python import_attr函数的具体用法?Python import_attr怎么用?Python import_attr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了import_attr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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
示例4: run
def run(self):
"""
直接运行当前的命令
"""
f = import_attr(self.function)
ret = f(**self.parameters)
return ret
示例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
示例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
示例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]
示例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}
示例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
示例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)
示例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
示例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]
示例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)
示例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
示例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