本文整理匯總了Python中Cerebrum.Utils類的典型用法代碼示例。如果您正苦於以下問題:Python Utils類的具體用法?Python Utils怎麽用?Python Utils使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Utils類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: is_str_or_unicode_test
def is_str_or_unicode_test():
""" Utils.is_str_or_unicode accepts unicode, str, rejects others. """
assert Utils.is_str_or_unicode('Hello world!')
assert Utils.is_str_or_unicode(u'Hello world!')
assert not Utils.is_str_or_unicode(None)
assert Utils.is_str_or_unicode(str(None))
assert Utils.is_str_or_unicode(unicode(None))
示例2: is_str_test
def is_str_test():
""" Utils.is_str accepts str, rejects unicode and others. """
assert Utils.is_str('Hello world!')
assert not Utils.is_str(u'Hello world!')
assert not Utils.is_str(None)
assert Utils.is_str(str(None))
assert not Utils.is_str(unicode(None))
示例3: _send_mail
def _send_mail(mail_to, mail_from, subject, body, logger,
mail_cc=None, debug_enabled=False):
if debug_enabled:
logger.debug("Sending mail to %s. Subject: %s", mail_to, subject)
# logger.debug("Body: %s" % body)
return True
try:
Utils.sendmail(
toaddr=mail_to,
fromaddr=mail_from,
subject=subject,
body=body,
cc=mail_cc,
debug=debug_enabled)
except smtplib.SMTPRecipientsRefused as e:
failed_recipients = e.recipients
for mail, condition in failed_recipients.iteritems():
logger.exception("Failed when notifying %s (%s): %s",
mail_to, mail, condition)
return False
except Exception as e:
logger.error("Error when notifying %s: %s" % (mail_to, e))
return False
return True
示例4: serve
def serve(config, num_workers, enable_listener, enable_collectors):
channels = [TARGET_SYSTEM, ]
exchanged = utils.ProcessHandler(manager=Manager)
event_queue = exchanged.mgr.queue()
queues = []
Handler = getattr(Utils.dyn_import(config.handler.handler_mod),
config.handler.handler_class)
for i in range(0, num_workers):
exchanged.add_process(
Handler(
daemon=True,
queue=event_queue,
log_queue=exchanged.log_queue,
running=exchanged.run_trigger,
config=config,
mock=config.client.mock))
if (config.deferred_handler.handler_mod and
config.deferred_handler.handler_class):
group_event_queue = exchanged.mgr.queue()
hand = getattr(Utils.dyn_import(config.deferred_handler.handler_mod),
config.deferred_handler.handler_class)
exchanged.add_process(
hand(
daemon=True,
queue=group_event_queue,
log_queue=exchanged.log_queue,
running=exchanged.run_trigger,
config=config,
mock=config.client.mock))
queues.append(group_event_queue)
if enable_listener:
exchanged.add_process(
evhandlers.EventLogListener(
daemon=True,
queue=event_queue,
fan_out_queues=queues,
log_queue=exchanged.log_queue,
running=exchanged.run_trigger,
channels=channels))
if enable_collectors:
for chan in channels:
exchanged.add_process(
evhandlers.EventLogCollector(
daemon=True,
queue=event_queue,
fan_out_queues=queues,
log_queue=exchanged.log_queue,
running=exchanged.run_trigger,
channel=chan,
config=config.eventcollector))
exchanged.serve()
示例5: dyn_import_test
def dyn_import_test():
""" Utils.dyn_import puts modules in sys.modules. """
for name in ("Cerebrum.Utils", "Cerebrum.modules", "Cerebrum.modules.no"):
Utils.dyn_import(name)
assert name in sys.modules
x = "Cerebrum.modules.no"
assert Utils.dyn_import(x) is sys.modules[x]
示例6: serve
def serve(logger, config, num_workers, enable_listener,
enable_collectors):
logger.info('Starting {!r} event utils'.format(TARGET_SYSTEM))
channels = [TARGET_SYSTEM, ]
exchanged = utils.ProcessHandler(logger=logger, manager=Manager)
event_queue = exchanged.mgr.queue()
queues = []
Handler = getattr(Utils.dyn_import(config.handler.handler_mod),
config.handler.handler_class)
for i in range(0, num_workers):
exchanged.add_process(
Handler,
queue=event_queue,
log_queue=exchanged.log_queue,
running=exchanged.run_trigger,
config=config,
mock=config.client.mock)
if (config.deferred_handler.handler_mod and
config.deferred_handler.handler_class):
group_event_queue = exchanged.mgr.queue()
hand = getattr(Utils.dyn_import(config.deferred_handler.handler_mod),
config.deferred_handler.handler_class)
exchanged.add_process(
hand,
queue=group_event_queue,
log_queue=exchanged.log_queue,
running=exchanged.run_trigger,
config=config,
mock=config.client.mock)
queues.append(group_event_queue)
if enable_listener:
exchanged.add_process(
evhandlers.DBEventListener,
queue=event_queue,
fan_out_queues=queues,
log_queue=exchanged.log_queue,
running=exchanged.run_trigger,
channels=channels)
if enable_collectors:
for chan in channels:
exchanged.add_process(
evhandlers.DBEventCollector,
queue=event_queue,
fan_out_queues=queues,
log_queue=exchanged.log_queue,
running=exchanged.run_trigger,
channel=chan,
config=config.eventcollector)
exchanged.serve()
示例7: email_report
def email_report(to_address, from_address, report):
"""Send the report by email."""
import smtplib
try:
Utils.sendmail(to_address, from_address, 'ePhorte role report',
report, cc=None)
except smtplib.SMTPRecipientsRefused, e:
failed_recipients = e.recipients
logger.info("Failed to notify <%d> users", len(failed_recipients))
for email, condition in failed_recipients.iteritems():
logger.info("Failed to notify: %s", condition)
示例8: update_mappings
def update_mappings(progname, config):
events = getattr(Utils.dyn_import(config.handler.handler_mod),
config.handler.handler_class).event_map.events
if (config.deferred_handler.handler_mod and
config.deferred_handler.handler_class):
events.extend(getattr(Utils.dyn_import(
config.deferred_handler.handler_mod),
config.deferred_handler.handler_class).event_map.events)
utils.update_system_mappings(
progname, TARGET_SYSTEM, events)
示例9: main
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'hsdf:',
['help', 'summary', 'detail',
'min=', 'max=',
'mail-to=', 'mail-from=',
'file='])
except getopt.GetoptError:
usage("Argument error!", 1)
detail = False
minimum = 1
maxmum = None
report_type = 'screen'
outputstream = sys.stdout
mail_to = None
mail_from = None
persons = 'person_id'
for opt, val in opts:
if opt in ('-h', '--help'):
usage()
elif opt in ('-s', '--summary'):
pass
elif opt in ('-d', '--detail'):
detail = True
elif opt in ('--min'):
minimum = int(val)
if minimum < 0:
usage("Error: the value of parameter --min should be at least 1", 2)
elif opt in ('--max'):
maxmum = int(val)
if maxmum < 0:
usage("Error: the value of parameter --max should be at least 1", 3)
elif opt in ('-f', '--file'):
report_type = 'file'
outputstream = open(val, 'w')
outputstream.write("==== Results of checking active accounts in Cerebrum ====\n")
outputstream.write("person_id\tNr_accounts\taccount_names\n")
elif opt in ('--mail-to'):
report_type = 'mail'
mail_to = val
elif opt in ('--mail-from'):
mail_from = val
else:
usage("Error: Unknown parameter '%s'" % opt, 4)
persons += checkACaccount(minimum,maxmum,detail,report_type,outputstream)
if mail_to:
count = persons.count("\n")
subject = "Warning: these following %s persons have more than %s active accounts." % (count,minimum)
Utils.sendmail(mail_to, mail_from, subject, persons)
示例10: wrapped_separate_entries_test
def wrapped_separate_entries_test():
""" Utils.{keep,reject}_entries() filters as expected. """
rows = [MetaRow(('a', 'b', 'c'))(row) for row in ((1, 2, 3),
(1, 2, 4),
(1, 3, 4))]
predicate = (('a', 1), ('b', 2), ('c', 3)) # Matches only the first row
# keep_entries
assert rows[0] in Utils.keep_entries(rows, *predicate)
assert rows[1] not in Utils.keep_entries(rows, *predicate)
# reject_entries
assert rows[0] not in Utils.reject_entries(rows, *predicate)
assert rows[1] in Utils.reject_entries(rows, *predicate)
示例11: proc_sympa_remove
def proc_sympa_remove(request):
"""Execute the request for removing a sympa mailing list.
@type request: ??
@param request:
A dict-like object containing all the parameters for sympa list
removal.
"""
try:
state = pickle.loads(str(request["state_data"]))
except:
logger.exception("Corrupt request state for sympa request %s: %s",
request["request_id"], request["state_data"])
return True
try:
listname = state["listname"]
host = state["run_host"]
except KeyError:
logger.error("No listname/runhost specified for request %s",
request["request_id"])
return True
cmd = [cereconf.SYMPA_SCRIPT, host, 'rmlist', listname]
return Utils.spawn_and_log_output(cmd) == EXIT_SUCCESS
示例12: delete_user
def delete_user(uname, old_host, old_home, operator, mail_server):
account = get_account(name=uname)
generation = account.get_trait(const.trait_account_generation)
if generation:
generation = generation['numval'] + 1
else:
generation = 1
args = [
SUDO_CMD, cereconf.RMUSER_SCRIPT,
'--username', account.account_name,
'--deleted-by', operator,
'--homedir', old_home,
'--generation', str(generation)
]
if DEBUG:
args.append('--debug')
cmd = SSH_CEREBELLUM + [" ".join(args), ]
if Utils.spawn_and_log_output(cmd, connect_to=[old_host]) == EXIT_SUCCESS:
account.populate_trait(const.trait_account_generation,
numval=generation)
account.write_db()
return True
return False
示例13: wrapper
def wrapper(self, *rest, **kw_args):
# This gives us a wrapped method that ignores the suitable
# exceptions ...
func = Utils.exception_wrapper(functor, exc_list, return_on_exc,
self.logger)
# ... and here we call the wrapped method.
return func(self, *rest, **kw_args)
示例14: send_mail
def send_mail(mailto, mail_template, substitute, debug=False):
ret = Utils.mail_template(mailto, mail_template, substitute=substitute,
debug=debug)
if ret:
logger.debug("Not sending mail:\n%s" % ret)
else:
logger.debug("Sending mail to: %s" % mailto)
示例15: test_argument_to_sql_droptables
def test_argument_to_sql_droptables():
""" Utils.argument_to_sql with Bobby Tables. """
binds = {}
name = "Robert'; DROP TABLE Students;--"
sql = Utils.argument_to_sql(name, 'name', binds)
assert sql == '(name = :name)'
assert binds == {'name': name} # This function should not sanitize. That's