本文整理汇总了Python中tools.safe_eval.eval函数的典型用法代码示例。如果您正苦于以下问题:Python eval函数的具体用法?Python eval怎么用?Python eval使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了eval函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _child_get
def _child_get(node, self=None, tagname=None):
for n in node:
if self and self.localcontext and n.get('rml_loop'):
for ctx in eval(n.get('rml_loop'),{}, self.localcontext):
self.localcontext.update(ctx)
if (tagname is None) or (n.tag==tagname):
if n.get('rml_except', False):
try:
eval(n.get('rml_except'), {}, self.localcontext)
except GeneratorExit:
continue
except Exception, e:
logging.getLogger('report').warning('rml_except: "%s"',n.get('rml_except',''), exc_info=True)
continue
if n.get('rml_tag'):
try:
(tag,attr) = eval(n.get('rml_tag'),{}, self.localcontext)
n2 = copy.deepcopy(n)
n2.tag = tag
n2.attrib.update(attr)
yield n2
except GeneratorExit:
yield n
except Exception, e:
logging.getLogger('report').warning('rml_tag: "%s"',n.get('rml_tag',''), exc_info=True)
yield n
else:
yield n
continue
示例2: _eval_params
def _eval_params(self, model, params):
args = []
for i, param in enumerate(params):
if isinstance(param, types.ListType):
value = self._eval_params(model, param)
elif is_ref(param):
value = self.process_ref(param)
elif is_eval(param):
value = self.process_eval(param)
elif isinstance(param, types.DictionaryType): # supports XML syntax
param_model = self.get_model(param.get('model', model))
if 'search' in param:
q = eval(param['search'], self.eval_context)
ids = param_model.search(self.cr, self.uid, q)
value = self._get_first_result(ids)
elif 'eval' in param:
local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
local_context.update(self.id_map)
value = eval(param['eval'], self.eval_context, local_context)
else:
raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
else:
value = param # scalar value
args.append(value)
return args
示例3: _tag_wizard
def _tag_wizard(self, cr, rec, data_node=None):
string = rec.get("string",'').encode('utf8')
model = rec.get("model",'').encode('utf8')
name = rec.get("name",'').encode('utf8')
xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id)
multi = rec.get('multi','') and eval(rec.get('multi','False'))
res = {'name': string, 'wiz_name': name, 'multi': multi, 'model': model}
if rec.get('groups'):
g_names = rec.get('groups','').split(',')
groups_value = []
for group in g_names:
if group.startswith('-'):
group_id = self.id_get(cr, 'res.groups', group[1:])
groups_value.append((3, group_id))
else:
group_id = self.id_get(cr, 'res.groups', group)
groups_value.append((4, group_id))
res['groups_id'] = groups_value
id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.wizard", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
self.idref[xml_id] = int(id)
# ir_set
if (not rec.get('menu') or eval(rec.get('menu','False'))) and id:
keyword = str(rec.get('keyword','') or 'client_action_multi')
value = 'ir.actions.wizard,'+str(id)
replace = rec.get("replace",'') or True
self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, string, [model], value, replace=replace, isobject=True, xml_id=xml_id)
elif self.mode=='update' and (rec.get('menu') and eval(rec.get('menu','False'))==False):
# Special check for wizard having attribute menu=False on update
value = 'ir.actions.wizard,'+str(id)
self._remove_ir_values(cr, string, value, model)
示例4: process_report
def process_report(self, node):
values = {}
for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
values[dest] = getattr(node, f)
assert values[dest], "Attribute %s of report is empty !" % (f,)
for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
if getattr(node, field):
values[dest] = getattr(node, field)
if node.auto:
values['auto'] = eval(node.auto)
if node.sxw:
sxw_content = misc.file_open(node.sxw).read()
values['report_sxw_content'] = sxw_content
if node.header:
values['header'] = eval(node.header)
values['multi'] = node.multi and eval(node.multi)
xml_id = node.id
self.validate_xml_id(xml_id)
self._set_group_values(node, values)
id = self.pool.get('ir.model.data')._update(self.cr, self.uid, "ir.actions.report.xml", \
self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
self.id_map[xml_id] = int(id)
if not node.menu or eval(node.menu):
keyword = node.keyword or 'client_print_multi'
value = 'ir.actions.report.xml,%s' % id
replace = node.replace or True
self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
示例5: onchange_tipe_history_id
def onchange_tipe_history_id(self, cr, uid, ids, tipe_history_id):
domain = {}
value = {}
obj_tipe_history = self.pool.get('hr.tipe_history')
value.update({'employee_id' : False})
domain.update({'employee_id' : [('id','in',[])]})
if tipe_history_id:
try:
tipe_history = obj_tipe_history.browse(cr, uid, [tipe_history_id])[0]
localdict = {
'self' : self,
'cr' : cr,
'uid' : uid,
'tipe_history' : tipe_history,
'karyawan_ids' : [],
'value' : value,
}
eval(tipe_history.kode_python_karyawan, localdict, mode='exec', nocopy=True)
karyawan_ids = localdict['karyawan_ids']
except:
karyawan_ids = []
value = localdict['value']
domain.update({'employee_id' : [('id','in',karyawan_ids)]})
return {'value' : value, 'domain' : domain}
示例6: _row_get
def _row_get(self, cr, uid, objs, fields, conditions, row_canvas=None, group_by=None):
result = []
tmp = []
for obj in objs:
tobreak = False
for cond in conditions:
if cond and cond[0]:
c = cond[0]
temp = c[0](eval('obj.'+c[1]))
if not eval('\''+temp+'\''+' '+c[2]+' '+'\''+str(c[3])+'\''):
tobreak = True
if tobreak:
break
levels = {}
row = []
for i in range(len(fields)):
if not fields[i]:
row.append(row_canvas and row_canvas[i])
if row_canvas[i]:
row_canvas[i]=False
elif len(fields[i])==1:
if not isinstance(obj, browse_null):
row.append(str(eval('obj.'+fields[i][0])))
else:
row.append(None)
else:
row.append(None)
levels[fields[i][0]]=True
if not levels:
result.append(row)
else:
# Process group_by data first
key = []
if group_by != None and fields[group_by] != None:
if fields[group_by][0] in levels.keys():
key.append(fields[group_by][0])
for l in levels.keys():
if l != fields[group_by][0]:
key.append(l)
else:
key = levels.keys()
for l in key:
objs = eval('obj.'+l)
if not isinstance(objs, browse_record_list) and type(objs) <> type([]):
objs = [objs]
field_new = []
cond_new = []
for f in range(len(fields)):
if (fields[f] and fields[f][0])==l:
field_new.append(fields[f][1:])
cond_new.append(conditions[f][1:])
else:
field_new.append(None)
cond_new.append(None)
if len(objs):
result += self._row_get(cr, uid, objs, field_new, cond_new, row, group_by)
else:
result.append(row)
return result
示例7: _rule_eval
def _rule_eval(self, cr, uid, rule, obj_name, obj, context):
expr = rule.code
space = self._exception_rule_eval_context(cr, uid, obj_name, obj,
context=context)
try:
eval(expr, space,
mode='exec', nocopy=True) # nocopy allows to return 'result'
except Exception, e:
raise except_osv(_('Error'), _('Error when evaluating the sale exception rule :\n %s \n(%s)') %
(rule.name, e))
示例8: get_pg_type
def get_pg_type(f):
'''Override the original method in order to accept fields.serialized'''
type_dict = {
fields.boolean: 'bool',
fields.integer: 'int4',
fields.integer_big: 'int8',
fields.text: 'text',
fields.date: 'date',
fields.time: 'time',
fields.datetime: 'timestamp',
fields.binary: 'bytea',
fields.many2one: 'int4',
}
if type(f) in type_dict:
f_type = (type_dict[type(f)], type_dict[type(f)])
elif isinstance(f, fields.float):
if f.digits:
f_type = ('numeric', 'NUMERIC')
else:
f_type = ('float8', 'DOUBLE PRECISION')
elif isinstance(f, (fields.char, fields.reference)):
f_type = ('varchar', 'VARCHAR(%d)' % (f.size,))
elif isinstance(f, fields.selection):
if isinstance(f.selection, list) and isinstance(f.selection[0][0], (str, unicode)):
f_size = reduce(lambda x, y: max(x, len(y[0])), f.selection, f.size or 16)
elif isinstance(f.selection, list) and isinstance(f.selection[0][0], int):
f_size = -1
else:
f_size = getattr(f, 'size', None) or 16
if f_size == -1:
f_type = ('int4', 'INTEGER')
else:
f_type = ('varchar', 'VARCHAR(%d)' % f_size)
elif isinstance(f, (fields.function, fields.serialized)) and eval('fields.' + (f._type), globals()) in type_dict:
t = eval('fields.' + (f._type), globals())
f_type = (type_dict[t], type_dict[t])
elif isinstance(f, (fields.function, fields.serialized)) and f._type == 'float':
if f.digits:
f_type = ('numeric', 'NUMERIC')
else:
f_type = ('float8', 'DOUBLE PRECISION')
elif isinstance(f, (fields.function, fields.serialized)) and f._type == 'selection':
f_type = ('text', 'text')
elif isinstance(f, (fields.function, fields.serialized)) and f._type == 'char':
f_type = ('varchar', 'VARCHAR(%d)' % (f.size))
else:
logger = netsvc.Logger()
logger.notifyChannel("init", netsvc.LOG_WARNING, '%s type not supported!' % (type(f)))
f_type = None
return f_type
示例9: _tag_report
def _tag_report(self, cr, rec, data_node=None):
res = {}
for dest,f in (('name','string'),('model','model'),('report_name','name')):
res[dest] = rec.get(f,'').encode('utf8')
assert res[dest], "Attribute %s of report is empty !" % (f,)
for field,dest in (('rml','report_rml'),('file','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
if rec.get(field):
res[dest] = rec.get(field).encode('utf8')
if rec.get('auto'):
res['auto'] = eval(rec.get('auto','False'))
if rec.get('sxw'):
sxw_content = misc.file_open(rec.get('sxw')).read()
res['report_sxw_content'] = sxw_content
if rec.get('header'):
res['header'] = eval(rec.get('header','False'))
if rec.get('report_type'):
res['report_type'] = rec.get('report_type')
if rec.get('target_filename'):
res['target_filename'] = rec.get('target_filename')
res['multi'] = rec.get('multi') and eval(rec.get('multi','False'))
xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id)
if rec.get('groups'):
g_names = rec.get('groups','').split(',')
groups_value = []
for group in g_names:
if group.startswith('-'):
group_id = self.id_get(cr, group[1:])
groups_value.append((3, group_id))
else:
group_id = self.id_get(cr, group)
groups_value.append((4, group_id))
res['groups_id'] = groups_value
id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.report.xml", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
self.idref[xml_id] = int(id)
if not rec.get('menu') or eval(rec.get('menu','False')):
keyword = str(rec.get('keyword', 'client_print_multi'))
value = 'ir.actions.report.xml,'+str(id)
replace = rec.get('replace', True)
self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, res['name'], [res['model']], value, replace=replace, isobject=True, xml_id=xml_id)
elif self.mode=='update' and eval(rec.get('menu','False'))==False:
# Special check for report having attribute menu=False on update
value = 'ir.actions.report.xml,'+str(id)
self._remove_ir_values(cr, res['name'], value, res['model'])
return False
示例10: create_normal_update
def create_normal_update(self, rule, context):
domain = eval(rule.domain or '[]')
export_fields = eval(rule.included_fields or '[]')
if 'id' not in export_fields:
export_fields.append('id')
ids_need_to_push = self.need_to_push(cr, uid, [],
[m.group(0) for m in map(re_fieldname.match, export_fields)],
empty_ids=True,
context=context)
if not ids_need_to_push:
return 0
domain.append(('id', 'in', ids_need_to_push))
ids_to_compute = self.search_ext(cr, uid, domain, context=context)
if not ids_to_compute:
return 0
owners = self.get_destination_name(cr, uid,
ids_to_compute, rule.owner_field, context)
min_offset = 0
max_offset = len(ids_to_compute)
while min_offset < max_offset:
offset = min_offset + 200 < max_offset and min_offset +200 or max_offset
datas = self.export_data(cr, uid, ids_to_compute[min_offset:offset],
export_fields, context=context)['datas']
sdrefs = self.get_sd_ref(cr, uid, ids_to_compute,
field=['name','version','force_recreation','id'], context=context)
ustr_export_fields = tools.ustr(export_fields)
for (id, row) in zip(ids_to_compute[min_offset:offset], datas):
sdref, version, force_recreation, data_id = sdrefs[id]
for owner in (owners[id] if hasattr(owners[id], '__iter__') else [owners[id]]):
update_id = update.create(cr, uid, {
'session_id' : session_id,
'rule_id' : rule.id,
'owner' : owner,
'model' : self._name,
'sdref' : sdref,
'version' : version + 1,
'force_recreation' : force_recreation,
'fields' : ustr_export_fields,
'values' : tools.ustr(row),
'handle_priority' : rule.handle_priority,
}, context=context)
update._logger.debug("Created 'normal' update model=%s id=%d (rule sequence=%d)" % (self._name, update_id, rule.id))
min_offset += 200
self.clear_synchronization(cr, uid, ids_to_compute, context=context)
return len(ids_to_compute)
示例11: _process_text
def _process_text(self, txt):
if not self.localcontext:
return str2xml(txt)
if not txt:
return ''
result = ''
sps = _regex.split(txt)
while sps:
# This is a simple text to translate
to_translate = tools.ustr(sps.pop(0))
result += tools.ustr(self.localcontext.get('translate', lambda x:x)(to_translate))
if sps:
try:
txt = None
expr = sps.pop(0)
txt = eval(expr, self.localcontext)
if txt and isinstance(txt, basestring):
txt = tools.ustr(txt)
except Exception:
pass
if isinstance(txt, basestring):
result += txt
elif txt and (txt is not None) and (txt is not False):
result += ustr(txt)
return str2xml(result)
示例12: _create_birt_report
def _create_birt_report(self, cr, uid, ids, data, report_birt, context=None):
if len(ids) != 1:
raise NotImplementedError("Report on multiple object not implemented")
table_obj = pooler.get_pool(cr.dbname).get(self.table)
objs = table_obj.browse(cr, uid, ids, list_class=None, context=context, fields_process=None)
obj = objs[0]
fields_def = obj._table.fields_get(cr, uid, None, context)
report_file = report_birt.birt_report
format = report_birt.birt_format
local = dict((k, getattr(obj, k)) for k, v in fields_def.iteritems())
local.update(context)
local['user'] = pooler.get_pool(cr.dbname) \
.get('res.users') \
.browse(cr, uid, context['uid'], context=context)
params = dict((o['name'],
o['value'] if not o['eval'] else
eval(o['value'], globals(), local))
for o in report_birt.birt_report_params)
birt_factory = birt.BirtConnection(report_birt.birt_url)
return birt_factory(report_file, format, params)
示例13: _domain_force_get
def _domain_force_get(self, cr, uid, ids, field_name, arg, context={}):
res = {}
for rule in self.browse(cr, uid, ids, context):
eval_user_data = {'user': self.pool.get('res.users').browse(cr, 1, uid),
'time':time}
res[rule.id] = eval(rule.domain_force, eval_user_data)
return res
示例14: process_workflow
def process_workflow(self, node):
workflow, values = node.items()[0]
if self.isnoupdate(workflow) and self.mode != 'init':
return
if workflow.ref:
id = self.get_id(workflow.ref)
else:
if not values:
raise YamlImportException('You must define a child node if you do not give a ref.')
if not len(values) == 1:
raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
value = values[0]
if not 'model' in value and (not 'eval' in value or not 'search' in value):
raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
value_model = self.get_model(value['model'])
local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)}
local_context.update(self.id_map)
id = eval(value['eval'], self.eval_context, local_context)
if workflow.uid is not None:
uid = workflow.uid
else:
uid = self.uid
self.cr.execute('select distinct signal from wkf_transition')
signals=[x['signal'] for x in self.cr.dictfetchall()]
if workflow.action not in signals:
raise YamlImportException('Incorrect action %s. No such action defined' % workflow.action)
wf_service = netsvc.LocalService("workflow")
wf_service.trg_validate(uid, workflow.model, id, workflow.action, self.cr)
示例15: action_launch
def action_launch(self, cr, uid, ids, context=None):
""" Launch Action of Wizard"""
wizard_id = ids and ids[0] or False
wizard = self.browse(cr, uid, wizard_id, context=context)
if wizard.type in ('automatic', 'once'):
wizard.write({'state': 'done'})
# Load action
act_type = self.pool.get('ir.actions.actions').read(cr, uid, wizard.action_id.id, ['type'], context=context)
res = self.pool.get(act_type['type']).read(cr, uid, wizard.action_id.id, [], context=context)
if act_type<>'ir.actions.act_window':
return res
res.setdefault('context','{}')
res['nodestroy'] = True
# Open a specific record when res_id is provided in the context
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
ctx = eval(res['context'], {'user': user})
if ctx.get('res_id'):
res.update({'res_id': ctx.pop('res_id')})
# disable log for automatic wizards
if wizard.type == 'automatic':
ctx.update({'disable_log': True})
res.update({'context': ctx})
return res