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

Python safe_eval.eval函数代码示例

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

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



在下文中一共展示了eval函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:kevin-garnett,项目名称:openerp-from-oneyoung,代码行数:30,代码来源:utils.py


示例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
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:25,代码来源:yaml_import.py


示例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)
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:33,代码来源:convert.py


示例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)
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:31,代码来源:yaml_import.py


示例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}
开发者ID:fofowisworkingattelenais,项目名称:modulmodul,代码行数:35,代码来源:hr_contract.py


示例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 
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:59,代码来源:custom.py


示例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))
开发者ID:devenmoga,项目名称:openerp-extra-6.1,代码行数:10,代码来源:sale.py


示例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
开发者ID:BorgERP,项目名称:edifact,代码行数:51,代码来源:orm_get_pg_type.py


示例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
开发者ID:hectord,项目名称:unifield,代码行数:51,代码来源:convert.py


示例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)
开发者ID:hectord,项目名称:unifield,代码行数:50,代码来源:update.py


示例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)
开发者ID:kevin-garnett,项目名称:openerp-from-oneyoung,代码行数:25,代码来源:utils.py


示例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)
开发者ID:abdo3247,项目名称:report_birt,代码行数:26,代码来源:birt_report.py


示例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
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:7,代码来源:ir_rule.py


示例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)
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:29,代码来源:yaml_import.py


示例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
开发者ID:ovnicraft,项目名称:openerp-server,代码行数:28,代码来源:ir_actions.py


示例16: _edi_generate_report_attachment

 def _edi_generate_report_attachment(self, cr, uid, record, context=None):
     """Utility method to generate the first PDF-type report declared for the
        current model with ``usage`` attribute set to ``default``.
        This must be called explicitly by models that need it, usually
        at the beginning of ``edi_export``, before the call to ``super()``."""
     ir_actions_report = self.pool.get('ir.actions.report.xml')
     matching_reports = ir_actions_report.search(cr, uid, [('model','=',self._name),
                                                           ('report_type','=','pdf'),
                                                           ('usage','=','default')])
     if matching_reports:
         report = ir_actions_report.browse(cr, uid, matching_reports[0])
         report_service = 'report.' + report.report_name
         service = netsvc.LocalService(report_service)
         (result, format) = service.create(cr, uid, [record.id], {'model': self._name}, context=context)
         eval_context = {'time': time, 'object': record}
         if not report.attachment or not eval(report.attachment, eval_context):
             # no auto-saving of report as attachment, need to do it manually
             result = base64.b64encode(result)
             file_name = record.name_get()[0][1]
             file_name = re.sub(r'[^a-zA-Z0-9_-]', '_', file_name)
             file_name += ".pdf"
             ir_attachment = self.pool.get('ir.attachment').create(cr, uid,
                                                                   {'name': file_name,
                                                                    'datas': result,
                                                                    'datas_fname': file_name,
                                                                    'res_model': self._name,
                                                                    'res_id': record.id,
                                                                    'type': 'binary'},
                                                                   context=context)
开发者ID:ShantiSR,项目名称:openerp-addons,代码行数:29,代码来源:edi.py


示例17: hitung_ketentuan

	def hitung_ketentuan(self, cr, uid, id, localdict, context=None):
		obj_ketentuan_absensi = self.pool.get('hr.ketentuan_absensi')
		
		ketentuan_absensi = obj_ketentuan_absensi.browse(cr, uid, [id])[0]
		
		
		#try:
		eval(ketentuan_absensi.perhitungan_python, localdict, mode='exec', nocopy=True)
		val =	{
				'name' : ketentuan_absensi.name,
				'kode' : ketentuan_absensi.kode,
				'satuan_ukur_id' : ketentuan_absensi.satuan_ukur_id.id,
				'hasil' : localdict['hasil'],
				}
				
		return val
开发者ID:fofowisworkingattelenais,项目名称:modulmodul,代码行数:16,代码来源:ketentuan_absensi.py


示例18: upgrade_graph

def upgrade_graph(graph, cr, module_list, force=None):
    if force is None:
        force = []
    packages = []
    len_graph = len(graph)
    for module in module_list:
        mod_path = get_module_path(module)
        terp_file = get_module_resource(module, '__openerp__.py')
        if not terp_file or not os.path.isfile(terp_file):
            terp_file = get_module_resource(module, '__terp__.py')

        if not mod_path or not terp_file:
            logger.notifyChannel('init', netsvc.LOG_WARNING, 'module %s: not found, skipped' % (module))
            continue

        if os.path.isfile(terp_file) or zipfile.is_zipfile(mod_path+'.zip'):
            try:
                info = eval(tools.file_open(terp_file).read())
            except:
                logger.notifyChannel('init', netsvc.LOG_ERROR, 'module %s: eval file %s' % (module, terp_file))
                raise
            if info.get('installable', True):
                packages.append((module, info.get('depends', []), info))
            else:
                logger.notifyChannel('init', netsvc.LOG_WARNING, 'module %s: not installable, skipped' % (module))

    dependencies = dict([(p, deps) for p, deps, data in packages])
    current, later = set([p for p, dep, data in packages]), set()

    while packages and current > later:
        package, deps, data = packages[0]

        # if all dependencies of 'package' are already in the graph, add 'package' in the graph
        if reduce(lambda x, y: x and y in graph, deps, True):
            if not package in current:
                packages.pop(0)
                continue
            later.clear()
            current.remove(package)
            graph.addNode(package, deps)
            node = Node(package, graph)
            node.data = data
            for kind in ('init', 'demo', 'update'):
                if package in tools.config[kind] or 'all' in tools.config[kind] or kind in force:
                    setattr(node, kind, True)
        else:
            later.add(package)
            packages.append((package, deps, data))
        packages.pop(0)

    graph.update_from_db(cr)

    for package in later:
        unmet_deps = filter(lambda p: p not in graph, dependencies[package])
        logger.notifyChannel('init', netsvc.LOG_ERROR, 'module %s: Unmet dependencies: %s' % (package, ', '.join(unmet_deps)))

    result = len(graph) - len_graph
    if result != len(module_list):
        logger.notifyChannel('init', netsvc.LOG_WARNING, 'Not all modules have loaded.')
    return result
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:60,代码来源:__init__.py


示例19: get_list_of_lines

 def get_list_of_lines(self, cr, uid, ids, message, context=None):
     """
     Return list of lists representing the values of each line of the report.
     """
     if context is None:
         context = {}
     config_values = self.read(cr, uid, ids[0], ['code'], context)
     space_code = self.get_space_code(cr, uid, ids, context)
     try:
         expr_code = config_values['code']
         eval(expr_code, space_code,
              mode='exec', nocopy=True)  # nocopy allows to return 'result'
     except Exception, e:
         del(space_code['__builtins__'])
         message += """
         Something went wrong when generating the report: %s.
         """ % (e,)
开发者ID:ccdos,项目名称:openerp-addons-1,代码行数:17,代码来源:report_config.py


示例20: get_header

 def get_header(self, cr, uid, ids, message, context=None):
     """
     Return one list of list representing the header of the report.
     """
     if context is None:
         context = {}
     config_values = self.read(cr, uid, ids[0], ['columns_header'], context)
     space_header = self.get_space_header(cr, uid, ids, context)
     try:
         expr_header = config_values['columns_header']
         eval(expr_header, space_header,
              mode='exec', nocopy=True)  # nocopy allows to return 'result'
     except Exception, e:
         del(space_header['__builtins__'])
         message += """
         Something went wrong when generating the report: %s
         """ % (e,)
开发者ID:ccdos,项目名称:openerp-addons-1,代码行数:17,代码来源:report_config.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python safe_eval.safe_eval函数代码示例发布时间:2022-05-27
下一篇:
Python prefs.get函数代码示例发布时间: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