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

Python misc.ustr函数代码示例

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

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



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

示例1: parameter

def parameter(dico, resource):
    """
    Convert value to a parameter for SOAP query

    @type  dico: dict
    @param dico: Contain parameter starts with OERP_
    @type  resource: dict
    @param resource: Contain parameter starts with WIZARD_
    @rtype: xmlstring
    @return: XML String representation
    """
    res = ''
    for key in resource:
        _logger.debug(' PARAMETER -> RESOURCE: %s' % key)
        if key in 'xml_data':
            continue
        e = Element('parameter')
        e.set('name', 'OERP_%s' % key.upper())
        e.text = ustr(resource[key])
        res += tostring(e) + '\n'

    for key in dico:
        _logger.debug(' PARAMETER -> DICO: %s' % key)
        if key in 'params':
            continue
        val = dico[key]
        e = Element('parameter')
        e.set('name', 'WIZARD_%s' % key.upper())
        if isinstance(val, list):
            if isinstance(val[0], tuple):
                e.text = ','.join(map(str, val[0][2]))
            else:
                e.text = ','.join(map(str, val))
        else:
            e.text = val and ustr(val) or ''
        res += tostring(e) + '\n'

    for key, val in [('REPORT_LOCALE', 'fr_FR'), ('IS_JASPERSERVER', 'yes')]:
        e = Element('parameter')
        e.set('name', key)
        e.text = ustr(val)
        res += tostring(e) + '\n'

    res = entities(res)
    if resource.get('xml_data'):
        res += '<parameter class="java.lang.String" name="XML_DATA">'
        res += '<![CDATA["%s"]]></parameter>' % resource['xml_data']
    return res
开发者ID:goldenboy,项目名称:razvoj,代码行数:48,代码来源:common.py


示例2: apply_promotions

 def apply_promotions(self, cursor, user, order_id, context=None):
     """
     Applies promotions
     @param cursor: Database Cursor
     @param user: ID of User
     @param order_id: ID of sale order
     @param context: Context(no direct use).
     """
     order = self.pool.get('sale.order').browse(cursor, user,
                                                order_id, context=context)
     active_promos = self.search(cursor, user,
                                 [('active', '=', True)],
                                 context=context)
     for promotion_rule in self.browse(cursor, user,
                                       active_promos, context):
         result = self.evaluate(cursor, user,
                                promotion_rule, order,
                                context)
         # If evaluates to true
         if result:
             try:
                 self.execute_actions(cursor, user,
                                  promotion_rule, order_id,
                                  context)
             except Exception, e:
                 raise osv.except_osv(
                                      "Promotions",
                                      ustr(e)
                                      )
             # If stop further is true
             if promotion_rule.stop_further:
                 return True
开发者ID:3stratum,项目名称:mmh,代码行数:32,代码来源:rules.py


示例3: put

    def put(self, uri, data, content_type=None):
        """ put the object into the filesystem """
        self.parent.log_message('Putting %s (%d), %s'%( misc.ustr(uri), data and len(data) or 0, content_type))
        cr, uid, pool,dbname, uri2 = self.get_cr(uri)
        if not dbname:
            if cr: cr.close()
            raise DAV_Forbidden
        try:
            node = self.uri2object(cr, uid, pool, uri2[:])
        except Exception:
            node = False
        
        objname = misc.ustr(uri2[-1])
        
        ret = None
        if not node:
            dir_node = self.uri2object(cr, uid, pool, uri2[:-1])
            if not dir_node:
                cr.close()
                raise DAV_NotFound('Parent folder not found')

            newchild = self._try_function(dir_node.create_child, (cr, objname, data),
                    "create %s" % objname, cr=cr)
            if not newchild:
                cr.commit()
                cr.close()
                raise DAV_Error(400, "Failed to create resource")
            
            uparts=urlparse.urlparse(uri)
            fileloc = '/'.join(newchild.full_path())
            if isinstance(fileloc, unicode):
                fileloc = fileloc.encode('utf-8')
            # the uri we get is a mangled one, where the davpath has been removed
            davpath = self.parent.get_davpath()
            
            surl = '%s://%s' % (uparts[0], uparts[1])
            uloc = urllib.quote(fileloc)
            hurl = False
            if uri != ('/'+uloc) and uri != (surl + '/' + uloc):
                hurl = '%s%s/%s/%s' %(surl, davpath, dbname, uloc)
            etag = False
            try:
                etag = str(newchild.get_etag(cr))
            except Exception, e:
                self.parent.log_error("Cannot get etag for node: %s" % e)
            ret = (str(hurl), etag)
开发者ID:fofowisworkingattelenais,项目名称:modulmodul,代码行数:46,代码来源:dav_fs.py


示例4: create

 def create(self, cursor, user, vals, context=None):
     """
     Serialise before save
     @param cursor: Database Cursor
     @param user: ID of User
     @param vals: Values of current record.
     @param context: Context(no direct use).
     """
     try:
         self.validate(cursor, user, vals, context)
     except Exception, e:
         raise osv.except_osv("Invalid Expression", ustr(e))
开发者ID:3stratum,项目名称:mmh,代码行数:12,代码来源:rules.py


示例5: close

    def close(self):
        # TODO: locking in init, close()
        fname = self.__file.name
        self.__file.close()

        if self.mode in ('w', 'w+', 'r+'):
            par = self._get_parent()
            cr = pooler.get_db(par.context.dbname).cursor()
            icont = ''
            mime = ''
            filename = par.path
            if isinstance(filename, (tuple, list)):
                filename = '/'.join(filename)
            
            try:
                mime, icont = cntIndex.doIndex(None, filename=filename,
                        content_type=None, realfname=fname)
            except Exception:
                _logger.debug('Cannot index file:', exc_info=True)
                pass

            try:
                icont_u = ustr(icont)
            except UnicodeError:
                icont_u = ''

            try:
                fsize = os.stat(fname).st_size
                cr.execute("UPDATE ir_attachment " \
                            " SET index_content = %s, file_type = %s, " \
                            " file_size = %s " \
                            "  WHERE id = %s",
                            (icont_u, mime, fsize, par.file_id))
                par.content_length = fsize
                par.content_type = mime
                cr.commit()
                cr.close()
            except Exception:
                _logger.warning('Cannot save file indexed content:', exc_info=True)

        elif self.mode in ('a', 'a+' ):
            try:
                par = self._get_parent()
                cr = pooler.get_db(par.context.dbname).cursor()
                fsize = os.stat(fname).st_size
                cr.execute("UPDATE ir_attachment SET file_size = %s " \
                            "  WHERE id = %s",
                            (fsize, par.file_id))
                par.content_length = fsize
                cr.commit()
                cr.close()
            except Exception:
                _logger.warning('Cannot save file appended content:', exc_info=True)
开发者ID:adrianorissi,项目名称:openobject-addons,代码行数:53,代码来源:document_storage.py


示例6: close

    def close(self):
        # TODO: locking in init, close()
        fname = self.__file.name
        self.__file.close()

        if self.mode in ("w", "w+", "r+"):
            par = self._get_parent()
            cr = pooler.get_db(par.context.dbname).cursor()
            icont = ""
            mime = ""
            filename = par.path
            if isinstance(filename, (tuple, list)):
                filename = "/".join(filename)

            try:
                mime, icont = cntIndex.doIndex(None, filename=filename, content_type=None, realfname=fname)
            except Exception:
                logging.getLogger("document.storage").debug("Cannot index file:", exc_info=True)
                pass

            try:
                icont_u = ustr(icont)
            except UnicodeError:
                icont_u = ""

            try:
                fsize = os.stat(fname).st_size
                cr.execute(
                    "UPDATE ir_attachment "
                    " SET index_content = %s, file_type = %s, "
                    " file_size = %s "
                    "  WHERE id = %s",
                    (icont_u, mime, fsize, par.file_id),
                )
                par.content_length = fsize
                par.content_type = mime
                cr.commit()
                cr.close()
            except Exception:
                logging.getLogger("document.storage").warning("Cannot save file indexed content:", exc_info=True)

        elif self.mode in ("a", "a+"):
            try:
                par = self._get_parent()
                cr = pooler.get_db(par.context.dbname).cursor()
                fsize = os.stat(fname).st_size
                cr.execute("UPDATE ir_attachment SET file_size = %s " "  WHERE id = %s", (fsize, par.file_id))
                par.content_length = fsize
                cr.commit()
                cr.close()
            except Exception:
                logging.getLogger("document.storage").warning("Cannot save file appended content:", exc_info=True)
开发者ID:proxly,项目名称:ntm_project,代码行数:52,代码来源:document_storage.py


示例7: action_validate

    def action_validate(self, cr, uid, ids, context=None):
        if not ids:
            return False

        module_proxy = self.pool.get('ir.module.module')
        module_ids = module_proxy.search(cr, uid, [('state', '=', 'installed')])
        modules = module_proxy.read(cr, uid, module_ids, ['name', 'installed_version'])

        contract = self.read(cr, uid, ids, ['name', 'password'])[0]
        
        try:
            contract_info = tm.remote_contract(contract['name'], contract['password'], modules)
        except tm.RemoteContractException, rce:
            raise osv.except_osv(_('Error'), ustr(rce))
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:14,代码来源:maintenance.py


示例8: close

    def close(self):
        # we now open a *separate* cursor, to update the data.
        # FIXME: this may be improved, for concurrency handling
        par = self._get_parent()
        # uid = par.context.uid
        cr = pooler.get_db(par.context.dbname).cursor()
        try:
            if self.mode in ('w', 'w+', 'r+'):
                data = self.getvalue()
                icont = ''
                mime = ''
                filename = par.path
                if isinstance(filename, (tuple, list)):
                    filename = '/'.join(filename)

                try:
                    mime, icont = cntIndex.doIndex(data, filename=filename,
                            content_type=None, realfname=None)
                except Exception:
                    _logger.debug('Cannot index file:', exc_info=True)
                    pass

                try:
                    icont_u = ustr(icont)
                except UnicodeError:
                    icont_u = ''

                out = psycopg2.Binary(data)
                cr.execute("UPDATE ir_attachment " \
                            "SET db_datas = %s, file_size=%s, " \
                            " index_content= %s, file_type=%s " \
                            " WHERE id = %s",
                    (out, len(data), icont_u, mime, par.file_id))
            elif self.mode == 'a':
                data = self.getvalue()
                out = psycopg2.Binary(data)
                cr.execute("UPDATE ir_attachment " \
                    "SET db_datas = COALESCE(db_datas,'') || %s, " \
                    "    file_size = COALESCE(file_size, 0) + %s " \
                    " WHERE id = %s",
                    (out, len(data), par.file_id))
            cr.commit()
        except Exception:
            _logger.exception('Cannot update db file #%d for close.', par.file_id)
            raise
        finally:
            cr.close()
        StringIO.close(self)
开发者ID:ShantiSR,项目名称:openerp-addons,代码行数:48,代码来源:document_storage.py


示例9: write

 def write(self, cursor, user, ids, vals, context):
     """
     Validate before Write
     @param cursor: Database Cursor
     @param user: ID of User
     @param vals: Values of current record.
     @param context: Context(no direct use).
     """
     # Validate before save
     if type(ids) in [list, tuple] and ids:
         ids = ids[0]
     try:
         old_vals = self.read(cursor, user, ids, ["action_type", "product_code", "arguments"], context)
         old_vals.update(vals)
         old_vals.has_key("id") and old_vals.pop("id")
         self.validate(cursor, user, old_vals, context)
     except Exception, e:
         raise osv.except_osv("Invalid Expression", ustr(e))
开发者ID:wanfgh,项目名称:openerp-usa,代码行数:18,代码来源:rules.py


示例10: evaluate

 def evaluate(self, cursor, user, promotion_rule, order, context=None):
     """
     Evaluates if a promotion is valid
     @param cursor: Database Cursor
     @param user: ID of User
     @param promotion_rule: Browse Record
     @param order: Browse Record
     @param context: Context(no direct use).
     """
     if not context:
         context = {}
     expression_obj = self.pool.get("promos.rules.conditions.exps")
     try:
         self.check_primary_conditions(cursor, user, promotion_rule, order, context)
     except Exception, e:
         if DEBUG:
             netsvc.Logger().notifyChannel("Promotions", netsvc.LOG_INFO, ustr(e))
         return False
开发者ID:wanfgh,项目名称:openerp-usa,代码行数:18,代码来源:rules.py


示例11: write

 def write(self, cursor, user, ids, vals, context):
     """
     Serialise before Write
     @param cursor: Database Cursor
     @param user: ID of User
     @param ids: ID of current record.
     @param vals: Values of current record.
     @param context: Context(no direct use).
     """
     # Validate before save
     if type(ids) in [list, tuple] and ids:
         ids = ids[0]
     try:
         old_vals = self.read(cursor, user, ids,
                              ['attribute', 'comparator', 'value'],
                              context)
         old_vals.update(vals)
         old_vals.has_key('id') and old_vals.pop('id')
         self.validate(cursor, user, old_vals, context)
     except Exception, e:
         raise osv.except_osv("Invalid Expression", ustr(e))
开发者ID:3stratum,项目名称:mmh,代码行数:21,代码来源:rules.py


示例12: check_vat_mx

    def check_vat_mx(self, vat):
        ''' Mexican VAT verification

        Verificar RFC México
        '''
        # we convert to 8-bit encoding, to help the regex parse only bytes
        vat = ustr(vat).encode('iso8859-1')
        m = self.__check_vat_mx_re.match(vat)
        if not m:
            #No valid format
            return False
        try:
            ano = int(m.group('ano'))
            if ano > 30:
                ano = 1900 + ano
            else:
                ano = 2000 + ano
            datetime.date(ano, int(m.group('mes')), int(m.group('dia')))
        except ValueError:
            return False

        #Valid format and valid date
        return True
开发者ID:EnVenteLibre,项目名称:openerp,代码行数:23,代码来源:base_vat.py


示例13: _

            # US_263: get employee destination, if haven't get default destination
            if employee_id:
                emp = self.pool.get('hr.employee').browse(cr, uid, employee_id, context=context)
                if destination_id and destination_id !=  emp.destination_id.id:
                    to_update_employee = True # turn the flag to update the employee

                if not destination_id and emp.destination_id: # US-671: Only update if the destination from the import is not valid
                    destination_id = emp.destination_id.id
            if not destination_id:
                if not account.default_destination_id:
                    raise osv.except_osv(_('Warning'), _('No default Destination defined for this account: %s') % (account.code or '',))
                destination_id = account.default_destination_id and account.default_destination_id.id or False

        # Fetch description
        if not name:
            name = description and description[0] and ustr(description[0]) or ''
        if is_payroll_rounding:
            name = 'Payroll rounding'
        if not employee_id:
            if second_description and second_description[0]:
                ref = ustr(second_description[0])
        # Check if currency exists
        if not currency and not currency[0]:
            raise osv.except_osv(_('Warning'), _('One currency is missing!'))
        currency_ids = self.pool.get('res.currency').search(cr, uid, [('name', '=', ustr(currency[0])), ('active', '=', True)])
        if not currency_ids:
            raise osv.except_osv(_('Error'), _('No \'%s\' currency or non-active currency.') % (ustr(currency[0]),))
        if len(currency_ids) > 1:
            raise osv.except_osv(_('Error'), _('More than one currency \'%s\' found.') % (ustr(currency[0]),))
        currency_id = currency_ids[0]
        # Create the payroll entry
开发者ID:hectord,项目名称:unifield,代码行数:31,代码来源:hr_payroll_import.py


示例14: button_validate

    def button_validate(self, cr, uid, ids, context=None):
        """
        Import XLS file
        """
        # Some verifications
        if not context:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        for wiz in self.browse(cr, uid, ids):
            # Prepare some values
            created = 0
            updated = 0
            processed = 0
            errors = []
            # Check that a file is given
            if not wiz.file:
                raise osv.except_osv(_('Error'), _('No file given'))
            # Check file extension
            if wiz.filename.split('.')[-1] != 'xml':
                raise osv.except_osv(_('Warning'), _('This wizard only accept XML files.'))
            # Read file
            fileobj = SpreadsheetXML(xmlstring=decodestring(wiz.file))
            reader = fileobj.getRows()
            reader.next()
            start = 1
            column_list = ['name', 'identification_id'] #, 'job', 'dest', 'cc', 'fp', 'f1', 'f2']
            for num, line in enumerate(reader):
                processed += 1
                # Fetch values
                vals = {}
                if line.cells:
                    for i, el in enumerate(column_list):
                        if len(line.cells) > i:
                            vals[el] = ustr(line.cells[i])
                        else:
                            vals[el] = False
                # Check values
                employee_id = False
                try:
                    vals, employee_id = self.update_or_create_employee(cr, uid, vals, context)
                except osv.except_osv, e:
                    errors.append('Line %s, %s' % (start+num, e.value))
                    continue
                # Do creation/update
                context.update({'from': 'import'})
                if employee_id:
                    self.pool.get('hr.employee').write(cr, uid, [employee_id], vals, context)
                    updated += 1
                else:
                    self.pool.get('hr.employee').create(cr, uid, vals, context)
                    created += 1
            for error in errors:
                self.pool.get('hr.payroll.employee.import.errors').create(cr, uid, {'wizard_id': wiz.id, 'msg': error})
            if errors:
                context.update({'employee_import_wizard_ids': wiz.id})

            context.update({'message': ' '})
            
            view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'msf_homere_interface', 'payroll_import_confirmation')
            view_id = view_id and view_id[1] or False
            
            # This is to redirect to Employee Tree View
            context.update({'from': 'nat_staff_import'})
            
            res_id = self.pool.get('hr.payroll.import.confirmation').create(cr, uid, {'created': created, 'updated': updated, 'total': processed, 'state': 'employee', 'filename': wiz.filename or False,}, context=context)
            
            return {
                'name': 'National staff employee import confirmation',
                'type': 'ir.actions.act_window',
                'res_model': 'hr.payroll.import.confirmation',
                'view_mode': 'form',
                'view_type': 'form',
                'view_id': [view_id],
                'res_id': res_id,
                'target': 'new',
                'context': context,
            }
开发者ID:hectord,项目名称:unifield,代码行数:78,代码来源:hr_nat_staff_import.py


示例15: lock

    def lock(self, uri, lock_data):
        """ Lock (may create) resource.
            Data is a dict, may contain:
                depth, token, refresh, lockscope, locktype, owner
        """
        cr, uid, pool, dbname, uri2 = self.get_cr(uri)
        created = False
        if not dbname:
            if cr: cr.close()
            raise DAV_Error, 409

        try:
            node = self.uri2object(cr, uid, pool, uri2[:])
        except Exception:
            node = False
        
        objname = misc.ustr(uri2[-1])
        
        if not node:
            dir_node = self.uri2object(cr, uid, pool, uri2[:-1])
            if not dir_node:
                cr.close()
                raise DAV_NotFound('Parent folder not found')

            # We create a new node (file) but with empty data=None,
            # as in RFC4918 p. 9.10.4
            node = self._try_function(dir_node.create_child, (cr, objname, None),
                    "create %s" % objname, cr=cr)
            if not node:
                cr.commit()
                cr.close()
                raise DAV_Error(400, "Failed to create resource")
            
            created = True

        try:
            node_fn = node.dav_lock
        except AttributeError:
            # perhaps the node doesn't support locks
            cr.close()
            raise DAV_Error(400, 'No locks for this resource')

        # Obtain the lock on the node
        lres, pid, token = self._try_function(node_fn, (cr, lock_data), "lock %s" % objname, cr=cr)

        if not lres:
            cr.commit()
            cr.close()
            raise DAV_Error(423, "Resource already locked")
        
        assert isinstance(lres, list), 'lres: %s' % repr(lres)
        
        try:
            data = mk_lock_response(self, uri, lres)
            cr.commit()
        except Exception:
            cr.close()
            raise

        cr.close()
        return created, data, token
开发者ID:fofowisworkingattelenais,项目名称:modulmodul,代码行数:61,代码来源:dav_fs.py


示例16: fields_view_get

 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
     """
     Verify that all lines have an analytic distribution.
     Create all non-analytic-a-holic lines to give a third parties
     """
     if not context:
         context = {}
     res = super(hr_payroll_validation, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu)
     # Verification and sorting lines as explained in UTP-342
     line_ids = self.pool.get('hr.payroll.msf').search(cr, uid, [('state', '=', 'draft')], order='account_id, name')
     for line in self.pool.get('hr.payroll.msf').browse(cr, uid, line_ids):
         if line.account_id and line.account_id.is_analytic_addicted and line.analytic_state != 'valid':
             raise osv.except_osv(_('Warning'), _('Some lines have analytic distribution problems!'))
     if view_type == 'form':
         form = ET.fromstring(res['arch'])
         field = form.find('.//label')
         parent = field.getparent()
         for el in self.pool.get('hr.payroll.msf').browse(cr, uid, line_ids):
             if el.account_id and not el.account_id.is_analytic_addicted:
                 third = 'third' + str(el.id)
                 fourth = 'fourth' + str(el.id)
                 fifth = 'fifth' + str(el.id)
                 is_required = False
                 if el.account_id.type_for_register and el.account_id.type_for_register == 'payroll':
                     is_required = True
                 parent.insert(parent.index(field)+1, ET.XML('<group col="4" colspan="4" invisible="%s"> <label string="%s"/><group col="6" colspan="1"><field name="%s" readonly="1"/><field name="%s" readonly="1"/><field name="%s" required="%s"/></group></group>' % (not is_required, ustr(el.name) + ' - ' + ustr(el.ref), fourth, fifth, third, is_required)))
         res['arch'] = ET.tostring(form)
     return res
开发者ID:hectord,项目名称:unifield,代码行数:28,代码来源:hr_payroll_validation.py


示例17: button_validate

    def button_validate(self, cr, uid, ids, context=None):
        """
        Open ZIP file and search staff.csv
        """
        if not context:
            context = {}
        # Prepare some values
        staff_file = 'staff.csv'
        contract_file = 'contrat.csv'
        job_file = 'fonction.csv'
        res = False
        message = _("Employee import FAILED.")
        created = 0
        updated = 0
        processed = 0
        filename = ""
        registered_keys = {}
        # Delete old errors
        error_ids = self.pool.get('hr.payroll.employee.import.errors').search(cr, uid, [])
        if error_ids:
            self.pool.get('hr.payroll.employee.import.errors').unlink(cr, uid, error_ids)
        for wiz in self.browse(cr, uid, ids):
            if not wiz.file:
                raise osv.except_osv(_('Error'), _('Nothing to import.'))
            fileobj = NamedTemporaryFile('w+b', delete=False)
            fileobj.write(decodestring(wiz.file))
            # now we determine the file format
            filename = fileobj.name
            fileobj.close()
            job_reader, contract_reader, staff_reader, desc_to_close, tmpdir = self.read_files(cr, uid, filename)
            filename = wiz.filename or ""

            job_ids = False
            if job_reader:
                job_ids = self.update_job(cr, uid, ids, job_reader, context=context)
            # Do not raise error for job file because it's just a useful piece of data, but not more.
            # read the contract file
            contract_ids = False
            if contract_reader:
                contract_ids = self.update_contract(cr, uid, ids, contract_reader, context=context)
            # UF-2472: Read all lines to check employee's code before importing
            staff_data = []
            staff_codes = []
            duplicates = []
            staff_seen = []
            for line in staff_reader:
                staff_seen.append(line)
                data = self.read_employee_infos(cr, uid, line)
                processed += 1
                if data: # to avoid False value in staff_data list
                    staff_data.append(data)
                    code = data[0]
                    if code in staff_codes:
                        duplicates.append(code)
                    staff_codes.append(code)
            # Delete duplicates of… duplicates!
            duplicates = list(set(duplicates))
            details = []
            for employee_infos in staff_data:
                employee_code = employee_infos[0]
                if employee_code in duplicates:
                    details.append(','.join([ustr(employee_infos[1]), ustr(employee_infos[2])]))
            res = True
            if not details:
                created = 0
                processed = 0
                updated = 0
                # UF-2504 read staff file again for next enumeration
                # (because already read/looped above for staff codes)
                for i, employee_data in enumerate(staff_seen):
                    update, nb_created, nb_updated = self.update_employee_infos(
                        cr, uid, employee_data, wiz.id, i,
                        registered_keys=registered_keys)
                    if not update:
                        res = False
                    created += nb_created
                    updated += nb_updated
                    processed += 1
            else:
                res = False
                message = _('Several employees have the same unique code: %s.') % (';'.join(details))
                self.pool.get('hr.payroll.employee.import.errors').create(cr, uid, {'wizard_id': wiz.id, 'msg': message})
            # Close Temporary File
            # Delete previous created lines for employee's contracts
            if contract_ids:
                self.pool.get('hr.contract.msf').unlink(cr, uid, contract_ids)
            for to_close in desc_to_close:
                to_close.close()
            if tmpdir:
                shutil.rmtree(tmpdir)
        del registered_keys
        if res:
            message = _("Employee import successful.")
        else:
            context.update({'employee_import_wizard_ids': ids})
        context.update({'message': message})

        view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'msf_homere_interface', 'payroll_import_confirmation')
        view_id = view_id and view_id[1] or False

#.........这里部分代码省略.........
开发者ID:hectord,项目名称:unifield,代码行数:101,代码来源:hr_payroll_employee_import.py


示例18: ustr

        # 2nd phase: store the metadata
        try:
            icont = ''
            mime = ira.file_type
            if not mime:
                mime = ""
            try:
                mime, icont = cntIndex.doIndex(data, ira.datas_fname,
                ira.file_type or None, fname)
            except Exception:
                _logger.debug('Cannot index file:', exc_info=True)
                pass

            try:
                icont_u = ustr(icont)
            except UnicodeError:
                icont_u = ''

            # a hack: /assume/ that the calling write operation will not try
            # to write the fname and size, and update them in the db concurrently.
            # We cannot use a write() here, because we are already in one.
            cr.execute('UPDATE ir_attachment SET store_fname = %s, file_size = %s, index_content = %s, file_type = %s WHERE id = %s',
                (store_fname, filesize, icont_u, mime, file_node.file_id))
            file_node.content_length = filesize
            file_node.content_type = mime
            return True
        except Exception, e :
            self._logger.warning("Couldn't save data:", exc_info=True)
            # should we really rollback once we have written the actual data?
            # at the db case (only), that rollback would be safe
开发者ID:adrianorissi,项目名称:openobject-addons,代码行数:30,代码来源:document_storage.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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