本文整理汇总了Python中getattr函数的典型用法代码示例。如果您正苦于以下问题:Python getattr函数的具体用法?Python getattr怎么用?Python getattr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getattr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _handle
def _handle(self, args):
if len(args) == 0:
self._raise_omni_error('Insufficient number of arguments - Missing command to run')
call = args[0].lower()
# disallow calling private methods
if call.startswith('_'):
return
if hasattr(self, call):
return getattr(self, call)(args[1:])
elif hasattr(self.chhandler, call):
return getattr(self.chhandler, call)(args[1:])
elif hasattr(self.amhandler, call):
# Extract the slice name arg and put it in an option
self.amhandler.opts.sliceName = self.amhandler._extractSliceArg(args)
# Try to auto-correct API version
msg = self.amhandler._correctAPIVersion(args)
if msg is None:
msg = ""
(message, val) = getattr(self.amhandler,call)(args[1:])
if message is None:
message = ""
return (msg+message, val)
else:
self._raise_omni_error('Unknown function: %s' % call)
示例2: connectToDB
def connectToDB():
"""
_connectToDB_
Connect to the database specified in the WMAgent config.
"""
if not os.environ.has_key("WMAGENT_CONFIG"):
print "Please set WMAGENT_CONFIG to point at your WMAgent configuration."
sys.exit(1)
if not os.path.exists(os.environ["WMAGENT_CONFIG"]):
print "Can't find config: %s" % os.environ["WMAGENT_CONFIG"]
sys.exit(1)
wmAgentConfig = loadConfigurationFile(os.environ["WMAGENT_CONFIG"])
if not hasattr(wmAgentConfig, "CoreDatabase"):
print "Your config is missing the CoreDatabase section."
socketLoc = getattr(wmAgentConfig.CoreDatabase, "socket", None)
connectUrl = getattr(wmAgentConfig.CoreDatabase, "connectUrl", None)
(dialect, junk) = connectUrl.split(":", 1)
myWMInit = WMInit()
myWMInit.setDatabaseConnection(dbConfig = connectUrl, dialect = dialect,
socketLoc = socketLoc)
return
示例3: event_update_participant_status
def event_update_participant_status(profile, event):
if request.is_xhr:
if profile.userid not in g.user.user_organizations_owned_ids():
abort(403)
participantid = int(request.form['participantid'])
status = int(request.form['status'])
participant = Participant.query.get(participantid)
if participant.event != event:
abort(403)
if participant.status == PARTICIPANT_STATUS.WITHDRAWN:
abort(403)
if participant.status != status:
participant.status = status
try:
text_message = unicode(getattr(event, (participants_email_attrs[status] + '_text')))
text_message = text_message.replace("*|FULLNAME|*", participant.user.fullname)
message = unicode(getattr(event, participants_email_attrs[status]))
message = message.replace("*|FULLNAME|*", participant.user.fullname)
if message and g.user.email:
send_email(sender=(g.user.fullname, g.user.email), to=participant.email,
subject="%s - Hacknight participation status" % event.title , body=text_message, html=message)
except KeyError:
pass
db.session.commit()
return "Done"
abort(403)
示例4: tohtml
def tohtml( self ) :
etp = self.macronode.parser.etparser
app = etp.app
etp.dynamictext = True
try : # To handle test cases.
p = getattr( app.c, 'project', None )
except :
p = None
if self.project :
p = app.projcomp.get_project( unicode(self.project ))
cntnr = lhtml.Element(
'div',
{ 'name' : 'projectvers',
'class': 'verdescr etmacro-projectversions',
'style' : self.style
}
)
e = lhtml.Element( 'h3', { 'style' : "border-bottom : 1px solid cadetBlue; color: cadetBlue" })
e.text= 'Versions'
cntnr.append( e )
versions = p and sorted( p.versions, key=lambda v : v.created_on ) or []
for v in versions :
e = lhtml.Element( 'div', { 'style' : 'font-weight: bold' } )
e.text = v.version_name or ' ' # Don't leave the text empty
cntnr.append( e )
e = lhtml.Element( 'blockquote', {} )
try :
e.append( lhtml.fromstring( getattr( v, 'descriptionhtml', '<div> </div>' )))
except :
pass
cntnr.append( e )
return lhtml.tostring( cntnr )
示例5: __new__
def __new__(cls, name, bases, attrs):
instance = super(OptionParserMeta, cls).__new__(cls, name, bases, attrs)
if not hasattr(instance, '_mixin_setup_funcs'):
instance._mixin_setup_funcs = []
if not hasattr(instance, '_mixin_process_funcs'):
instance._mixin_process_funcs = []
if not hasattr(instance, '_mixin_after_parsed_funcs'):
instance._mixin_after_parsed_funcs = []
for base in _sorted(bases + (instance,)):
func = getattr(base, '_mixin_setup', None)
if func is not None and func not in instance._mixin_setup_funcs:
instance._mixin_setup_funcs.append(func)
func = getattr(base, '_mixin_after_parsed', None)
if func is not None and func not in instance._mixin_after_parsed_funcs:
instance._mixin_after_parsed_funcs.append(func)
# Mark process_<opt> functions with the base priority for sorting
for func in dir(base):
if not func.startswith('process_'):
continue
func = getattr(base, func)
if getattr(func, '_mixin_prio_', None) is not None:
# Function already has the attribute set, don't override it
continue
func.__func__._mixin_prio_ = getattr(base, '_mixin_prio_', 1000)
return instance
示例6: _read_file
def _read_file(self, file_type, record, options):
# guess mimetype from file content
mimetype = guess_mimetype(record.file)
(file_extension, handler, req) = FILE_TYPE_DICT.get(mimetype, (None, None, None))
if handler:
try:
return getattr(self, '_read_' + file_extension)(record, options)
except Exception:
_logger.warn("Failed to read file '%s' (transient id %d) using guessed mimetype %s",
record.file_name or '<unknown>', record.id, mimetype)
# try reading with user-provided mimetype
(file_extension, handler, req) = FILE_TYPE_DICT.get(file_type, (None, None, None))
if handler:
try:
return getattr(self, '_read_' + file_extension)(record, options)
except Exception:
_logger.warn("Failed to read file '%s' (transient id %d) using user-provided mimetype %s",
record.file_name or '<unknown>', record.id, file_type)
# fallback on file extensions as mime types can be unreliable (e.g.
# software setting incorrect mime types, or non-installed software
# leading to browser not sending mime types)
if record.file_name:
p, ext = os.path.splitext(record.file_name)
if ext in EXTENSIONS:
try:
return getattr(self, '_read_' + ext[1:])(record, options)
except Exception:
_logger.warn("Failed to read file '%s' (transient id %s) using file extension",
record.file_name, record.id)
if req:
raise ImportError(_("Unable to load \"{extension}\" file: requires Python module \"{modname}\"").format(extension=file_extension, modname=req))
raise ValueError(_("Unsupported file format \"{}\", import only supports CSV, ODS, XLS and XLSX").format(file_type))
示例7: set_proxy_server
def set_proxy_server(
self, server_obj, username=DEFAULT_USER, password=None):
"""
Saves server model representing the proxy server (compute model)
If obj does not contain the password, please provide it, it's difficult
to connect otherwise...
@param server_obj: compute model representation of server
@param username: User to log into proxy
@param password: password for compute VM
@return: None
"""
# Determine if the password is set
if password is not None:
server_obj.admin_pass = password
if (not hasattr(server_obj, 'admin_pass') or
getattr(server_obj, 'admin_pass', None) is None):
raise NoPasswordProvided()
server_obj.username = username
self._proxy_svr = server_obj
self._proxy_ip = getattr(self._proxy_svr.addresses.public,
'ipv{ver}'.format(ver=self._ip_version))
示例8: orm_item_locator
def orm_item_locator(orm_obj):
"""
This function is called every time an object that will not be exported is required.
Where orm_obj is the referred object.
We postpone the lookup to locate_object() which will be run on the generated script
"""
the_class = orm_obj._meta.object_name
original_class = the_class
pk_name = orm_obj._meta.pk.name
original_pk_name = pk_name
pk_value = getattr(orm_obj, pk_name)
while hasattr(pk_value, "_meta") and hasattr(pk_value._meta, "pk") and hasattr(pk_value._meta.pk, "name"):
the_class = pk_value._meta.object_name
pk_name = pk_value._meta.pk.name
pk_value = getattr(pk_value, pk_name)
clean_dict = make_clean_dict(orm_obj.__dict__)
for key in clean_dict:
v = clean_dict[key]
if v is not None and not isinstance(v, (six.string_types, six.integer_types, float, datetime.datetime)):
clean_dict[key] = six.u("%s" % v)
output = """ importer.locate_object(%s, "%s", %s, "%s", %s, %s ) """ % (
original_class, original_pk_name,
the_class, pk_name, pk_value, clean_dict
)
return output
示例9: get_previous_fitlered_sibling
def get_previous_fitlered_sibling(self, **filters):
"""Very simillar to original mptt method, but adds support for filters.
Returns this model instance's previous sibling in the tree, or
``None`` if it doesn't have a previous sibling.
"""
opts = self._meta
if self.is_root_node():
filters.update({
'%s__isnull' % opts.parent_attr: True,
'%s__lt' % opts.tree_id_attr: getattr(self, opts.tree_id_attr),
})
order_by = '-%s' % opts.tree_id_attr
else:
filters.update({
opts.parent_attr: getattr(self, '%s_id' % opts.parent_attr),
'%s__lt' % opts.right_attr: getattr(self, opts.left_attr),
})
order_by = '-%s' % opts.right_attr
sibling = None
try:
sibling = self._tree_manager.filter(**filters).order_by(order_by)[0]
except IndexError:
pass
return sibling
示例10: _collect_delete_marked_sub_objects
def _collect_delete_marked_sub_objects(self, seen_objs, parent=None, nullable=False, excluded_models=None):
if excluded_models is None:
excluded_models = [self.__class__]
elif not isinstance(self, Page) or self.__class__ in excluded_models:
return
pk_val = self._get_pk_val()
if seen_objs.add(self.__class__, pk_val, self, parent, nullable):
return
for related in self._meta.get_all_related_objects():
rel_opts_name = related.get_accessor_name()
if not issubclass(related.model, Page) or related.model in excluded_models:
continue
if isinstance(related.field.rel, OneToOneRel):
try:
sub_obj = getattr(self, rel_opts_name)
except ObjectDoesNotExist:
pass
else:
if sub_obj.publisher_is_draft:
continue
sub_obj._collect_delete_marked_sub_objects(seen_objs, self.__class__, related.field.null, excluded_models=excluded_models)
else:
# To make sure we can access all elements, we can't use the
# normal manager on the related object. So we work directly
# with the descriptor object.
for cls in self.__class__.mro():
if rel_opts_name in cls.__dict__:
rel_descriptor = cls.__dict__[rel_opts_name]
break
else:
raise AssertionError("Should never get here.")
delete_qs = rel_descriptor.delete_manager(self).all()
#filter(publisher_state=Publisher.PUBLISHER_STATE_DELETE)
for sub_obj in delete_qs:
if not isinstance(sub_obj, Page) or sub_obj.__class__ in excluded_models:
continue
if sub_obj.publisher_is_draft:
continue
sub_obj._collect_delete_marked_sub_objects(seen_objs, self.__class__, related.field.null, excluded_models=excluded_models)
# Handle any ancestors (for the model-inheritance case). We do this by
# traversing to the most remote parent classes -- those with no parents
# themselves -- and then adding those instances to the collection. That
# will include all the child instances down to "self".
parent_stack = [p for p in self._meta.parents.values() if p is not None]
while parent_stack:
link = parent_stack.pop()
parent_obj = getattr(self, link.name)
if parent_obj._meta.parents:
parent_stack.extend(parent_obj._meta.parents.values())
continue
# At this point, parent_obj is base class (no ancestor models). So
# delete it and all its descendents.
if parent_obj.publisher_is_draft:
continue
parent_obj._collect_delete_marked_sub_objects(seen_objs, excluded_models=excluded_models)
示例11: start_services
def start_services():
if bokeh_app.backend['type'] == 'redis' and \
bokeh_app.backend.get('start_redis', True):
work_dir = getattr(bokeh_app, 'work_dir', os.getcwd())
data_file = getattr(bokeh_app, 'data_file', 'redis.db')
stdout = getattr(bokeh_app, 'stdout', sys.stdout)
stderr = getattr(bokeh_app, 'stdout', sys.stderr)
redis_save = getattr(bokeh_app, 'redis_save', True)
mproc = services.start_redis(pidfilename=os.path.join(work_dir, "bokehpids.json"),
port=bokeh_app.backend.get('redis_port', REDIS_PORT),
data_dir=work_dir,
data_file=data_file,
stdout=stdout,
stderr=stderr,
save=redis_save)
bokeh_app.redis_proc = mproc
bokeh_app.publisher.start()
if not bokeh_app.websocket_params['no_ws_start']:
bokeh_app.subscriber = websocket.make_app(bokeh_app.url_prefix,
[bokeh_app.publisher.zmqaddr],
bokeh_app.websocket_params['ws_port']
)
bokeh_app.subscriber.start(thread=True)
atexit.register(stop_services)
示例12: _get_protocol_attrs
def _get_protocol_attrs(cls):
# Get all Protocol base classes.
protocol_bases = []
for c in cls.__mro__:
if getattr(c, '_is_protocol', False) and c.__name__ != 'Protocol':
protocol_bases.append(c)
# Get attributes included in protocol.
attrs = set()
for base in protocol_bases:
for attr in base.__dict__.keys():
# Include attributes not defined in any non-protocol bases.
for c in cls.__mro__:
if (c is not base and attr in c.__dict__ and
not getattr(c, '_is_protocol', False)):
break
else:
if (not attr.startswith(u'_abc_') and
attr != '__abstractmethods__' and
attr != '_is_protocol' and
attr != '__dict__' and
attr != '_get_protocol_attrs' and
attr != '__module__'):
attrs.add(attr)
return attrs
示例13: recordMatches
def recordMatches(record):
if operand == "and":
for fieldName, value, caseless, matchType in fields:
try:
fieldValue = getattr(record, fieldName)
if not fieldMatches(fieldValue, value, caseless,
matchType):
return False
except AttributeError:
# No property => no match
return False
# we hit on every property
return True
else: # "or"
for fieldName, value, caseless, matchType in fields:
try:
fieldValue = getattr(record, fieldName)
if fieldMatches(fieldValue, value, caseless,
matchType):
return True
except AttributeError:
# No value
pass
# we didn't hit any
return False
示例14: lookup_field
def lookup_field(name, obj, model_admin=None):
opts = obj._meta
try:
f = opts.get_field(name)
except models.FieldDoesNotExist:
# For non-field values, the value is either a method, property or
# returned via a callable.
if callable(name):
attr = name
value = attr(obj)
elif (model_admin is not None and hasattr(model_admin, name) and
not name == '__str__' and not name == '__unicode__'):
attr = getattr(model_admin, name)
value = attr(obj)
else:
if is_rel_field(name,obj):
parts = name.split("__")
rel_name,sub_rel_name = parts[0],"__".join(parts[1:])
rel_obj = getattr(obj,rel_name)
if rel_obj is not None:
return lookup_field(sub_rel_name,rel_obj,model_admin)
attr = getattr(obj, name)
if callable(attr):
value = attr()
else:
value = attr
f = None
else:
attr = None
value = getattr(obj, name)
return f, attr, value
示例15: eq
def eq(a, b):
if isinstance(a, Array):
adt = a._dtype
a = a.compute(get=dask.get)
else:
adt = getattr(a, 'dtype', None)
if isinstance(b, Array):
bdt = b._dtype
b = b.compute(get=dask.get)
else:
bdt = getattr(b, 'dtype', None)
if not str(adt) == str(bdt):
return False
try:
return np.allclose(a, b)
except TypeError:
pass
c = a == b
if isinstance(c, np.ndarray):
return c.all()
else:
return c