当前位置: 首页>>代码示例>>Python>>正文


Python safe_eval.safe_eval函数代码示例

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


在下文中一共展示了safe_eval函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: retry

    def retry(self, cr, uid, ids, context=None):
        if isinstance(ids, int):
            ids = [ids]

        for log in self.browse(cr, uid, ids, context=context):
            origin_context = safe_eval(log.origin_context)
            origin_defaults = safe_eval(log.origin_defaults)

            # keep the id of the line to update it with the result
            origin_context['retry_report_line_id'] = log.id
            # force export of the resource
            origin_context['force_export'] = True
            origin_context['force'] = True
            
            ##TODO remove : not needed since magento 6.1 ########
            origin_context['do_not_update_date'] = True         #
            #####################################################
            
            mapping = self.pool.get(log.res_model).\
            report_action_mapping(cr, uid, context=context)

            method = mapping.get(log.action, False)
            if not method:
                raise Exception("No python method defined for action %s" %
                                (log.action,))
            method(cr, uid,
                   log.res_id,
                   log.external_id,
                   log.external_report_id.external_referential_id.id,
                   origin_defaults,
                   origin_context)

        return True
开发者ID:3dfxmadscientist,项目名称:odoo-extra-1,代码行数:33,代码来源:report.py

示例2: _check_evalexpr

 def _check_evalexpr(self, cr, uid, ids, context=None):
     action = self.browse(cr, uid, ids[0], context=context)
     if action.trg_evalexpr:
         #Test if expression is valid, against an empty dict
         #Newlines are tolerated
         safe_eval(action.trg_evalexpr.replace('\n', ' '),
             {}, DEFAULT_EVALDICT)
     return True
开发者ID:Cywaithaka,项目名称:LibrERP,代码行数:8,代码来源:base_action_rule.py

示例3: build_product_field

    def build_product_field(self, cr, uid, ids, field, context=None):
        def get_description_sale(product):
            description_sale = product.product_tmpl_id.description_sale
            return self.parse(cr, uid, product, description_sale, context=context)

        def get_name(product):
            if context.get('variants_values', False):
                return ((product.product_tmpl_id.name or '')
                        + ' '
                        + (context['variants_values'][product.id] or ''))
            return (product.product_tmpl_id.name or '') + ' ' + (product.variants or '')

        if not context:
            context = {}
        context['is_multi_variants'] = True
        obj_lang = self.pool.get('res.lang')
        lang_ids = obj_lang.search(cr, uid, [('translatable', '=', True)], context=context)
        langs = obj_lang.read(cr, uid, lang_ids, ['code'], context=context)
        lang_code = [x['code'] for x in langs]
        for code in lang_code:
            context['lang'] = code
            for product in self.browse(cr, uid, ids, context=context):
                new_field_value = eval("get_" + field + "(product)")  # TODO convert to safe_eval
                cur_field_value = safe_eval("product." + field, {'product': product})
                if new_field_value != cur_field_value:
                    self.write(cr, uid, product.id, {field: new_field_value}, context=context)
        return True
开发者ID:3dfxsoftware,项目名称:customaddons,代码行数:27,代码来源:product.py

示例4: _cleanup_action_context

    def _cleanup_action_context(self, context_str, user_id):
        """Returns a dict representing the context_str evaluated (safe_eval) as
           a dict where items that are not useful for shared actions
           have been removed. If the evaluation of context_str as a
           dict fails, context_str is returned unaltered.

           :param user_id: the integer uid to be passed as 'uid' in the
                           evaluation context
           """
        result = False
        if context_str:
            try:
                context = safe_eval(context_str, tools.UnquoteEvalContext(), nocopy=True)
                result = dict(context)
                for key in context:
                    # Remove all context keys that seem to toggle default
                    # filters based on the current user, as it makes no sense
                    # for shared users, who would not see any data by default.
                    if key and key.startswith('search_default_') and 'user_id' in key:
                        result.pop(key)
            except Exception:
                # Note: must catch all exceptions, as UnquoteEvalContext may cause many
                #       different exceptions, as it shadows builtins.
                self._logger.debug("Failed to cleanup action context as it does not parse server-side", exc_info=True)
                result = context_str
        return result
开发者ID:goldenboy,项目名称:razvoj,代码行数:26,代码来源:share_wizard.py

示例5: get_sys_logs

def get_sys_logs(cr, uid):
    """
    Utility method to send a publisher warranty get logs messages.
    """
    pool = pooler.get_pool(cr.dbname)

    dbuuid = pool.get("ir.config_parameter").get_param(cr, uid, "database.uuid")
    db_create_date = pool.get("ir.config_parameter").get_param(cr, uid, "database.create_date")
    nbr_users = pool.get("res.users").search(cr, uid, [], count=True)
    contractosv = pool.get("publisher_warranty.contract")
    contracts = contractosv.browse(cr, uid, contractosv.search(cr, uid, []))
    user = pool.get("res.users").browse(cr, uid, uid)
    msg = {
        "dbuuid": dbuuid,
        "nbr_users": nbr_users,
        "dbname": cr.dbname,
        "db_create_date": db_create_date,
        "version": release.version,
        "contracts": [c.name for c in contracts],
        "language": user.context_lang,
    }

    add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
    arguments = {"arg0": msg, "action": "update"}
    arguments_raw = urllib.urlencode(arguments)
    url = config.get("publisher_warranty_url")
    uo = urllib2.urlopen(url, arguments_raw, **add_arg)
    try:
        submit_result = uo.read()
    finally:
        uo.close()

    result = safe_eval(submit_result) if submit_result else {}

    return result
开发者ID:goldenboy,项目名称:razvoj,代码行数:35,代码来源:publisher_warranty.py

示例6: create_returns

    def create_returns(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        move_obj = self.pool.get('stock.move')
        pick_obj = self.pool.get('stock.picking')
        mem_obj  = self.pool.get('stock.return.picking.memory')
        wf_service = netsvc.LocalService("workflow")

        return_context = context.copy()
        return_context['confirm_return'] = False
        ret = super(stock_return_picking, self).create_returns(cr, uid, ids, context=return_context)

        prm_datas = self.read(cr, uid, ids, ['product_return_moves'], context=context)
        for prm_data in prm_datas:
            mem_ids = prm_data['product_return_moves']
            mem_data = mem_obj.read(cr, uid, mem_ids, ['move_id', 'location_dest_id'], context=context)
            move_to_dest = {}
            for data in mem_data:
                move_to_dest.update({data['move_id'][0] : data['location_dest_id'][0]})
            move_ids = [mem['move_id'][0] for mem in mem_data]
            move_datas = move_obj.read(cr, uid, move_ids, ['location_dest_id','move_history_ids2'], context=context)
            for move_data in move_datas:
                new_move_ids = move_data['move_history_ids2']
                for new_move_id in new_move_ids:
                    move_id = move_data['id']
                    move_obj.write(cr, uid, new_move_id, {'location_dest_id' : move_to_dest[move_id]}, context=context)

            new_picking = pick_obj.search(cr, uid, safe_eval(ret['domain']), context=context).pop()
            wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
            pick_obj.force_assign(cr, uid, [new_picking], context)
        return ret
开发者ID:SportPursuit,项目名称:credativ-addons,代码行数:32,代码来源:stock_return_picking.py

示例7: update_menu

    def update_menu(self, cr, uid, action_report, context=None):

        if action_report.created_menu_id and not action_report.linked_menu_id:
            self.delete_menu(cr, uid, action_report.created_menu_id.id, context=context)

        if action_report.linked_menu_id:
            groups_id = [(6, 0, map(lambda x: x.id, action_report.groups_id))]
            if not action_report.created_menu_id:
                result = self.create_menu(cr, uid, {'name' : action_report.name,
                                                    'linked_menu_id': action_report.linked_menu_id.id,
                                                    'report_name' : action_report.report_name,
                                                    'groups_id' : groups_id,
                                                    }, context=context)
            else:
                action = action_report.created_menu_id.action
                if action and action._model._name == 'ir.actions.act_window':
                    existing_context = safe_eval(self.pool.get('ir.actions.act_window').browse(cr, uid, action.id, context=context).context)
                    new_context = existing_context if type(existing_context) == dict else {}
                    new_context['service_name'] = action_report.report_name or ''
                    self.pool.get('ir.actions.act_window').write(cr, uid, [action.id], {'name' : action_report.name or 'Pentaho Report',
                                                                                        'context' : str(new_context),
                                                                                        }, context=context)

                self.pool.get('ir.ui.menu').write(cr, uid, [action_report.created_menu_id.id], {'name' : action_report.name or 'Pentaho Report',
                                                                                                'parent_id' : action_report.linked_menu_id.id,
                                                                                                'groups_id' : groups_id,
                                                                                                }, context=context)
                result = action_report.created_menu_id.id
        else:
            result = 0

        return result
开发者ID:anasmaach,项目名称:ao-openerp,代码行数:32,代码来源:ui.py

示例8: do_check

 def do_check(self, cr, uid, action, obj, context={}):
     ok = super(base_action_rule, self).do_check(cr, uid, action, obj, context=context)
     if action.trg_evalexpr:
         old = None
         #Find in the list this obj's old 
         for x in context.get('_action_old', []):
             old = x.get('id') == obj.id and x
         #Convert tuples (id, name) into id only
         for x in old or []:
             if type(old[x]) == tuple:
                 old[x] = old[x][0]
         #Build dict with new and old and eval the expression
         eval_dict = {
             'old': old,
             'new': context.get('_action_new')}
         try:
             ok = safe_eval(action.trg_evalexpr, {}, eval_dict)
         except (ValueError, KeyError, TypeError):
             ok = False
         #Debug Log
         if ok: 
             _logger.debug('Activated rule %s on record id %d.' % (action.name, obj.id) )
             #print '********************************************************************'
             #print '\n==== Rule:', action.name, action.trg_evalexpr, '===='  '\n---- old:: ', eval_dict['old'], '\n---- new::', eval_dict['new'] 
     return ok
开发者ID:Mwatchorn26,项目名称:odoo-addons,代码行数:25,代码来源:reis_base_action_rule.py

示例9: retry

    def retry(self, cr, uid, ids, context=None):
        if isinstance(ids, (int, long)):
            ids = [ids]

        for log in self.browse(cr, uid, ids, context=context):
            mapping = self.pool.get(log.res_model).\
            report_action_mapping(cr, uid, context=context)

            method = mapping.get(log.action, False)
            if not method:
                raise Exception("No python method defined for action %s" %
                                (log.action,))

            kwargs = {}
            for field, value in method['fields'].items():
                kwargs[field] = safe_eval(value, {'log': log, 'self': self})

            if not kwargs.get('context', False):
                kwargs['context'] = {}

            # keep the id of the line to update it with the result
            kwargs['context']['retry_report_line_id'] = log.id
            # force export of the resource
            kwargs['context']['force_export'] = True
            kwargs['context']['force'] = True

            method['method'](cr, uid, **kwargs)
        return True
开发者ID:ashishoist91,项目名称:Amazon,代码行数:28,代码来源:report.py

示例10: send

    def send(self, cr, uid, tb, explanations, remarks=None, issue_name=None):
        """ Method called by the client to send a problem to the publisher warranty server. """

        if not remarks:
            remarks = ""

        valid_contracts = self._get_valid_contracts(cr, uid)
        valid_contract = valid_contracts[0]

        try:
            origin = "client"
            dbuuid = self.pool.get("ir.config_parameter").get_param(cr, uid, "database.uuid")
            db_create_date = self.pool.get("ir.config_parameter").get_param(cr, uid, "database.create_date")
            user = self.pool.get("res.users").browse(cr, uid, uid)
            user_name = user.name
            email = user.email

            msg = {
                "contract_name": valid_contract.name,
                "tb": tb,
                "explanations": explanations,
                "remarks": remarks,
                "origin": origin,
                "dbname": cr.dbname,
                "dbuuid": dbuuid,
                "db_create_date": db_create_date,
                "issue_name": issue_name,
                "email": email,
                "user_name": user_name,
            }

            add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
            uo = urllib2.urlopen(
                config.get("publisher_warranty_url"), urllib.urlencode({"arg0": msg, "action": "send"}), **add_arg
            )
            try:
                submit_result = uo.read()
            finally:
                uo.close()

            result = safe_eval(submit_result)

            crm_case_id = result

            if not crm_case_id:
                return False

        except osv.except_osv:
            raise
        except Exception:
            _logger.warning("Error sending problem report", exc_info=1)
            raise osv.except_osv(_("Error"), _("Error during communication with the publisher warranty server."))

        return True
开发者ID:goldenboy,项目名称:razvoj,代码行数:54,代码来源:publisher_warranty.py

示例11: compute_product_dimension_extra_price

    def compute_product_dimension_extra_price(self, cr, uid, product_id, product_price_extra=False, dim_price_margin=False, dim_price_extra=False, context=None):
        if context is None:
            context = {}
        dimension_extra = 0.0
        product = self.browse(cr, uid, product_id, context=context)
        for dim in product.dimension_value_ids:
            if product_price_extra and dim_price_margin and dim_price_extra:
                dimension_extra += safe_eval('product.' + product_price_extra, {'product': product}) * safe_eval('dim.' + dim_price_margin, {'dim': dim}) + safe_eval('dim.' + dim_price_extra, {'dim': dim})
            elif not product_price_extra and not dim_price_margin and dim_price_extra:
                dimension_extra += safe_eval('dim.' + dim_price_extra, {'dim': dim})
            elif product_price_extra and dim_price_margin and not dim_price_extra:
                dimension_extra += safe_eval('product.' + product_price_extra, {'product': product}) * safe_eval('dim.' + dim_price_margin, {'dim': dim})
            elif product_price_extra and not dim_price_margin and dim_price_extra:
                dimension_extra += safe_eval('product.' + product_price_extra, {'product': product}) + safe_eval('dim.' + dim_price_extra, {'dim': dim})

        if 'uom' in context:
            product_uom_obj = self.pool.get('product.uom')
            uom = product.uos_id or product.uom_id
            dimension_extra = product_uom_obj._compute_price(cr, uid,
                uom.id, dimension_extra, context['uom'])
        return dimension_extra
开发者ID:Arsalan88,项目名称:openerp-extra-6.1,代码行数:21,代码来源:product_variant.py

示例12: parse

 def parse(self, cr, uid, o, text, context=None):
     if not text:
         return ''
     vals = text.split('[_')
     description = ''
     for val in vals:
         if '_]' in val:
             sub_val = val.split('_]')
             description += (safe_eval(sub_val[0], {'o' :o, 'context':context}) or '' ) + sub_val[1]
         else:
             description += val
     return description
开发者ID:eoconsulting,项目名称:product_variant_multi,代码行数:12,代码来源:product_variant.py

示例13: eval

    def eval(self, record, expr):
#TODO: support remote variables (eg address.title) in expr
# how to do that: parse the string, find dots, replace those dotted variables by temporary
# "simple ones", fetch the value of those variables and add them (temporarily) to the _data
# dictionary passed to eval

#FIXME: it wont work if the data hasn't been fetched yet... this could
# happen if the eval node is the first one using this browse_record
# the next line is a workaround for the problem: it causes the resource to be loaded
#Pinky: Why not this ? eval(expr, browser) ?
#       name = browser.name
#       data_dict = browser._data[self.get_value(browser, 'id')]
        return safe_eval(expr, {}, {'obj': record})
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:13,代码来源:print_xml.py

示例14: parse

 def parse(self, cr, uid, o, text, context=None):
     if not text:
         return ''
     vals = text.split('[_')
     description = ''
     for val in vals:
         if '_]' in val:
             sub_val = val.split('_]')
             try:
                 description += (safe_eval(sub_val[0], {'o' :o, 'context':context}) or '' ) + sub_val[1]
             except:
                 LOGGER.notifyChannel('product_variant_multi', netsvc.LOG_ERROR, "%s can't eval. Description is blank" % (sub_val[0]))
                 description += ''
         else:
             description += val
     return description
开发者ID:Arsalan88,项目名称:openerp-extra-6.1,代码行数:16,代码来源:product_variant.py

示例15: _action_calc_formula

    def _action_calc_formula(self, cr, uid, ids, field_names, args, context):
        result = {}.fromkeys(ids, 0)
        for test in self.browse(cr, uid, ids, context):
            vals = {}
            for line in test.test_line_ids:
                if line.name and line.proof_type == 'quantitative':
                    vals[line.name] = line.actual_value_qt

            if not test.formula:
                result[test.id] = 0
                continue

            try:
                value = safe_eval(test.formula, vals)
                result[test.id] = value
            except NameError:
                pass
                #raise osv.except_osv( _('Error:'), msg )
        return result
开发者ID:jeffery9,项目名称:nan_quality_control,代码行数:19,代码来源:quality_control.py


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