def scenario_convert_file(cr, module, filename, idref, mode='update', noupdate=False, kind=None, report=None, pathname=None): if pathname is None: pathname = os.path.join(module, filename) directory, filename = os.path.split(pathname) extension = os.path.splitext(filename)[1].lower() if extension == '.scenario': fp = misc.file_open(pathname) try: with openerp.api.Environment.manage(): uid = openerp.SUPERUSER_ID env = openerp.api.Environment(cr, uid, {'active_test': False}) import_scenario(env, module, fp.read(), mode, directory, filename) finally: fp.close() else: convert_file(cr, module, filename, idref, mode=mode, noupdate=noupdate, kind=kind, report=report, pathname=pathname)
def get_xml(self, default_filters=[]): f, filename = file_open("addons/report_spreadsheet/report/spreadsheet_writer_xls.mako", pathinfo=True) f.close() tmpl = Template( filename=filename, input_encoding="utf-8", output_encoding="utf-8", default_filters=default_filters ) return tmpl.render(objects=self.datas, headers=self.headers, title=self.title)
def get_file_list(self, *args, **kargs): m = kargs['m'] #src=misc.file_open('rozzi_module_files_manager').name #dirname= misc.file_open('rozzi_module_files_manager/__init__.py').name print m src = misc.file_open(m + '\\__init__.py').name print src addons_path = os.path.dirname(os.path.dirname(src)) dirname = addons_path + '\\' + m + '\\' print dirname result = [] for maindir, subdir, file_name_list in os.walk(dirname): print 'maindir==========' print maindir print 'subdir==========' print subdir print 'file_name_list==========' print file_name_list for filename in file_name_list: print 'filename==========' + filename if filename.find('.pyc') > -1: pass else: apath = os.path.join(maindir, filename) apath = apath.replace(dirname, '') result.append(apath) print result ret = {'files': result} return json.dumps(ret)
def from_data(self, fields, rows, file_address): if file_address: bk = xlrd.open_workbook(misc.file_open(file_address).name, formatting_info=True) workbook = xlutils.copy.copy(bk) worksheet = workbook.get_sheet(0) for i, fieldname in enumerate(fields): self.setOutCell(worksheet, 0, i, fieldname) for row, row_vals in enumerate(rows): for col, col_value in enumerate(row_vals): if isinstance(col_value, basestring): col_value = re.sub("\r", " ", col_value) self.setOutCell(worksheet, col, row + 1, col_value) else: workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Sheet 1') base_style = xlwt.easyxf('align: wrap yes') date_style = xlwt.easyxf('align: wrap yes', num_format_str='YYYY-MM-DD') datetime_style = xlwt.easyxf('align: wrap yes', num_format_str='YYYY-MM-DD HH:mm:SS') for row_index, row in enumerate(rows): for cell_index, cell_value in enumerate(row): cell_style = base_style if isinstance(cell_value, basestring): cell_value = re.sub("\r", " ", cell_value) elif isinstance(cell_value, datetime.datetime): cell_style = datetime_style elif isinstance(cell_value, datetime.date): cell_style = date_style worksheet.write(row_index + 1, cell_index, cell_value, cell_style) fp_currency = StringIO.StringIO() workbook.save(fp_currency) fp_currency.seek(0) data = fp_currency.read() fp_currency.close() return data
def run_config_env(self): # check module installed self.model_obj = self.pool["ir.module.module"] if not self.model_obj.search_id(self.cr, 1, [("state", "=", "installed"), ("name", "=", self.params.module)]): _logger.error("No module %s installed!" % self.params.module) return export_filename = os.path.join(self.langdir, self.langfile) export_f = file(export_filename, "w") try: ignore = None ignore_filename = "%s.ignore" % export_filename if os.path.exists(ignore_filename): _logger.info("Load ignore file %s" % ignore_filename) ignore = set() fileobj = misc.file_open(ignore_filename) reader = tools.TinyPoFile(fileobj) for row in reader: if not row[4]: ignore.add(row) _logger.info('Writing %s', export_filename) tools.trans_export(self.lang, [self.params.module], export_f, "po", self.cr, ignore=ignore) finally: export_f.close()
def init(self, cr): tools.drop_view_if_exists(cr, 'budget_entries_report_noa') sql_fn='budget_entries_report_view_noanalytics_v1.2.sql' fp=file_open('budget_report/%s'%sql_fn) query=fp.read() fp.close() cr.execute(query)
def init(self, cr): tools.drop_view_if_exists(cr, 'budget_entries_report_noa') sql_fn = 'budget_entries_report_view_noanalytics_v1.2.sql' fp = file_open('budget_report/%s' % sql_fn) query = fp.read() fp.close() cr.execute(query)
def test_web_favicon(self): original_request = http.request http.request = FakeRequest(self.env) from openerp.addons.web_favicon.controllers.web_favicon import\ WebFavicon company = self.env['res.company'].search([], limit=1) # default icon company.write({ 'favicon_backend': False, 'favicon_backend_mimetype': False, }) data = WebFavicon().icon() self.assertEqual(data.headers['Content-Type'], 'image/x-icon') # our own icon company.write({ 'favicon_backend': base64.b64encode( file_open('web_favicon/static/description/icon.png').read()), 'favicon_backend_mimetype': 'image/png', }) data = WebFavicon().icon() self.assertEqual(data.headers['Content-Type'], company.favicon_backend_mimetype) http.request = original_request
def from_data(self, fields, rows, file_address): if file_address: bk = xlrd.open_workbook(misc.file_open(file_address).name, formatting_info=True) workbook = xlutils.copy.copy(bk) worksheet = workbook.get_sheet(0) for i, fieldname in enumerate(fields): self.setOutCell(worksheet, 0, i, fieldname) for row, row_vals in enumerate(rows): for col, col_value in enumerate(row_vals): if isinstance(col_value, basestring): col_value = re.sub("\r", " ", col_value) self.setOutCell(worksheet, col, row + 1, col_value) else: workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Sheet 1') style, colour_style, base_style, float_style, date_style, datetime_style = self.style_data() worksheet.write_merge(0, 0, 0, len(fields) - 1, fields[0], style=style) worksheet.row(0).height = 400 worksheet.row(2).height = 400 [worksheet.write(1, i, '', style=xlwt.easyxf('border: left thin,right thin,top thin,bottom thin')) for i in xrange(len(fields))] columnwidth = {} for row_index, row in enumerate(rows): for cell_index, cell_value in enumerate(row): if cell_index in columnwidth: if len("%s"%(cell_value)) > columnwidth.get(cell_index): columnwidth.update({cell_index: len("%s"%(cell_value))}) else: columnwidth.update({cell_index: len("%s"%(cell_value))}) if row_index == 1: cell_style = colour_style elif row_index != len(rows) - 1: cell_style = base_style if isinstance(cell_value, basestring): cell_value = re.sub("\r", " ", cell_value) elif isinstance(cell_value, datetime.datetime): cell_style = datetime_style elif isinstance(cell_value, datetime.date): cell_style = date_style elif isinstance(cell_value, float) or isinstance(cell_value, int): cell_style = float_style else: cell_style = xlwt.easyxf('border: left thin,right thin,top thin,bottom thin') worksheet.write(row_index + 1, cell_index, cell_value, cell_style) for column, widthvalue in columnwidth.items(): """参考 下面链接关于自动列宽(探讨)的代码 http://stackoverflow.com/questions/6929115/python-xlwt-accessing-existing-cell-content-auto-adjust-column-width""" if (widthvalue + 2) * 367 >= 65536: widthvalue = 300 worksheet.col(column).width = (widthvalue+4) * 256 worksheet.set_panes_frozen(True) # frozen headings instead of split panes worksheet.set_horz_split_pos(3) # in general, freeze after last heading row worksheet.set_remove_splits(True) # if user does unfreeze, don't leave a split there fp_currency = StringIO.StringIO() workbook.save(fp_currency) fp_currency.seek(0) data = fp_currency.read() fp_currency.close() return data
def trans_load(cr, filename, lang, verbose=True, module_name=None, context=None): try: with file_open(filename) as fileobj: _logger.info("loading %s", filename) fileformat = os.path.splitext(filename)[-1][1:].lower() result = trans_load_data(cr, fileobj, fileformat, lang, verbose=verbose, module_name=module_name, context=context) return result except IOError: if verbose: _logger.error("couldn't read translation file %s", filename) return None
def read_file(self, *args, **kargs): m = kargs['m'] f = kargs['f'] src = misc.file_open(m + '\\' + f).name with open(src, 'r') as input_stream: filecontent = input_stream.read() ret = {'data': filecontent} return json.dumps(ret)
def get_xml(self, default_filters=[]): f, filename = file_open( 'addons/report_spreadsheet/report/spreadsheet_writer_xls.mako', pathinfo=True) f.close() tmpl = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8', default_filters=default_filters) return tmpl.render(objects=self.datas, headers=self.headers, title=self.title)
def test_zip_import(self): """Test import of multiple statements from zip file.""" with file_open( 'account_bank_statement_import_camt/test_files/test-camt053.zip' ) as testfile: action = self.env['account.bank.statement.import'].create({ 'data_file': base64.b64encode(testfile.read()), }).import_file() for statement in self.env['account.bank.statement'].browse( action['context']['statement_ids']): self.assertTrue(statement.line_ids)
def update_banks(self): """ Force the update of the banks from the XML file """ data_obj = self.env['ir.model.data'] entries = data_obj.search([('module', '=', MODULE), ('model', '=', 'res.bank')]) # If the records in 'ir.model.data' have noupdate to True, # the XML records won't be updated entries.write({'noupdate': False}) filepath = get_module_resource(MODULE, 'bank.xml') with closing(misc.file_open(filepath)) as fp: force_xml_import(self.env.cr, fp) entries.write({'noupdate': True}) return True
def import_csv_file(self, cr, uid, args, context=None): """ Import a CSV file from an xml file """ context = context or {} context.update({ 'mail_create_nolog': True, 'mail_notrack': True, }) try: model = args[0] filename = args[1] except: _logger.error('Bad arguments: %s', args) return False try: fp = misc.file_open(filename) content = fp.read() except: _logger.error('Bad file name: %s', filename) return False fp.close() vals = { 'res_model': model, 'file': content, 'file_name': filename, 'file_type': 'application/vnd.ms-excel', } imp_id = self.create(cr, uid, vals, context=context) options = { 'encoding': 'utf-8', 'separator': ',', 'headers': True, 'quoting': '"', } preview = self.parse_preview(cr, uid, imp_id, options, context=context) fields = [f for f in preview['headers'] if not f.startswith('__dummy')] _logger.info('Importing file %s' % filename) res = self.do(cr, uid, imp_id, fields, options, context=context) if any(m['type'] == 'error' for m in res): _logger.error('Importing fails with following messages:') for m in res: _logger.error(m['message']) return res
def icon(self): request = http.request if 'uid' in request.env.context: user = request.env['res.users'].browse(request.env.context['uid']) company = user.sudo(user.id).company_id else: company = request.env['res.company'].search([], limit=1) favicon = company.favicon_backend favicon_mimetype = company.favicon_backend_mimetype if not favicon: favicon = file_open('web/static/src/img/favicon.ico') favicon_mimetype = 'image/x-icon' else: favicon = StringIO.StringIO(base64.b64decode(favicon)) return request.make_response(favicon.read(), [('Content-Type', favicon_mimetype)])
def icon(self): request = http.request if 'uid' in request.env.context: user = request.env['res.users'].browse(request.env.context['uid']) company = user.sudo(user.id).company_id else: company = request.env['res.company'].search([], limit=1) favicon = company.favicon_backend favicon_mimetype = company.favicon_backend_mimetype if not favicon: favicon = file_open('web/static/src/img/favicon.ico') favicon_mimetype = 'image/x-icon' else: favicon = StringIO.StringIO(base64.b64decode(favicon)) return request.make_response( favicon.read(), [('Content-Type', favicon_mimetype)])
def create_source_docx(self, cr, uid, ids, report, context=None): data = DataModelProxy(self.get_docx_data(cr, uid, ids, report, context)) foldname = os.getcwd() temp_out_file = os.path.join(foldname, 'temp_out_%s.docx' % os.getpid()) report_stream = '' doc = DocxTemplate(misc.file_open(report.template_file).name) doc.render({'obj': data}) doc.save(temp_out_file) with open(temp_out_file, 'rb') as input_stream: report_stream = input_stream.read() os.remove(temp_out_file) return (report_stream, report.report_type)
def test_statement_import(self): """Test correct creation of single statement.""" action = {} with file_open( 'account_bank_statement_import_camt/test_files/test-camt053' ) as testfile: action = self.env['account.bank.statement.import'].create({ 'data_file': base64.b64encode(testfile.read()), }).import_file() for statement in self.env['account.bank.statement'].browse( action['context']['statement_ids']): self.assertTrue( any( all(line[key] == self.transactions[0][key] for key in ['amount', 'date', 'ref']) and line.bank_account_id.acc_number == self.transactions[0] ['account_number'] for line in statement.line_ids))
def _open_image(filename, path=None): """Attempt to open a binary file and return the descriptor """ if os.path.isfile(filename): return open(filename, 'rb') for p in (path or []): if p and os.path.isabs(p): fullpath = os.path.join(p, filename) if os.path.isfile(fullpath): return open(fullpath, 'rb') try: if p: fullpath = os.path.join(p, filename) else: fullpath = filename return file_open(fullpath) except IOError: pass raise IOError("File %s cannot be found in image path" % filename)
def create_source_docx(self, cr, uid, ids, report, context=None): data = self.get_docx_data(cr, uid, ids, report, context) foldname = os.getcwd() temp_out_file = os.path.join(foldname, 'temp_out_%s.docx' % os.getpid()) report_stream = '' try: doc = DocxTemplate(misc.file_open(report.template_file).name) doc.render({'obj': data}) doc.save(temp_out_file) with open(temp_out_file, 'r') as input_stream: report_stream = input_stream.read() except Exception: raise Exception finally: os.remove(temp_out_file) return (report_stream, report.report_type)
def save_file(self, *args, **kargs): m = kargs['m'] f = kargs['f'] data = kargs['data'] src = misc.file_open(m + '\\' + f).name fileobj = file(src, 'w+') try: fileobj.write(data) except Exception: raise Exception finally: fileobj.close() # your treatment return 'save completed'
def test_web_favicon(self): original_request = http.request http.request = FakeRequest(self.env) from openerp.addons.web_favicon.controllers.web_favicon import\ WebFavicon company = self.env['res.company'].search([], limit=1) # default icon company.write({ 'favicon_backend': False, 'favicon_backend_mimetype': False, }) data = WebFavicon().icon() self.assertEqual(data.headers['Content-Type'], 'image/x-icon') # our own icon company.write({ 'favicon_backend': base64.b64encode(file_open( 'web_favicon/static/description/icon.png').read()), 'favicon_backend_mimetype': 'image/png', }) data = WebFavicon().icon() self.assertEqual(data.headers['Content-Type'], company.favicon_backend_mimetype) http.request = original_request
def trans_generate(lang, modules, cr): env = openerp.api.Environment(cr, SUPERUSER_ID, {}) to_translate = set() def push_translation(module, type, name, id, source, comments=None): # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. sanitized_term = (source or '').strip() try: # verify the minimal size without eventual xml tags # wrap to make sure html content like '<a>b</a><c>d</c>' is accepted by lxml wrapped = "<div>%s</div>" % sanitized_term node = etree.fromstring(wrapped) sanitized_term = etree.tostring(node, encoding='UTF-8', method='text') except etree.ParseError: pass # remove non-alphanumeric chars sanitized_term = re.sub(r'\W+', '', sanitized_term) if not sanitized_term or len(sanitized_term) <= 1: return tnx = (module, source, name, id, type, tuple(comments or ())) to_translate.add(tnx) query = 'SELECT name, model, res_id, module FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model'""" if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module IN %s' query_param = (tuple(modules),) else: query += ' WHERE module != %s' query_models += ' AND imd.module != %s' query_param = ('__export__',) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) for (xml_name, model, res_id, module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if model not in env: _logger.error("Unable to find object %r", model) continue record = env[model].browse(res_id) if not record._translate: # explicitly disabled continue if not record.exists(): _logger.warning("Unable to find object %r with id %d", model, res_id) continue if model=='ir.model.fields': try: field_name = encode(record.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue field_model = env.get(record.model) if (field_model is None or not field_model._translate or field_name not in field_model._fields): continue field = field_model._fields[field_name] if isinstance(getattr(field, 'selection', None), (list, tuple)): name = "%s,%s" % (encode(record.model), field_name) for dummy, val in field.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model=='ir.actions.report.xml': name = encode(record.report_name) fname = "" if record.report_rml: fname = record.report_rml parse_func = trans_parse_rml report_type = "report" elif record.report_xsl: continue if fname and record.report_type in ('pdf', 'xsl'): try: with file_open(fname) as report_file: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) except (IOError, etree.XMLSyntaxError): _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname)
def import_scenario(env, module, scenario_xml, mode, directory, filename): model_obj = env['ir.model'] company_obj = env['res.company'] warehouse_obj = env['stock.warehouse'] user_obj = env['res.users'] group_obj = env['res.groups'] ir_model_data_obj = env['ir.model.data'] xml_doc = StringIO(scenario_xml) root = parse(xml_doc).getroot() steps = [] transitions = [] scenario_values = {} noupdate = root.get('noupdate', False) # parse of the scenario for node in root.getchildren(): # the node of the Step and Transition are put in other list if node.tag == 'Step': steps.append(node) elif node.tag == 'Transition': transitions.append(node) elif node.tag == 'warehouse_ids': if 'warehouse_ids' not in scenario_values: scenario_values['warehouse_ids'] = [] warehouse_ids = warehouse_obj.search([('name', '=', node.text)]) if warehouse_ids: scenario_values['warehouse_ids'].append( (4, warehouse_ids[0].id)) elif node.tag == 'group_ids': if 'group_ids' not in scenario_values: scenario_values['group_ids'] = [] group_ids = group_obj.search([ ('full_name', '=', node.text), ]) if group_ids: scenario_values['group_ids'].append((4, group_ids[0].id)) else: scenario_values['group_ids'].append( (4, env.ref(node.text).id), ) elif node.tag == 'user_ids': if 'user_ids' not in scenario_values: scenario_values['user_ids'] = [] user_ids = user_obj.search([ ('login', '=', node.text), ]) if user_ids: scenario_values['user_ids'].append((4, user_ids[0].id)) elif node.tag in ('active', 'shared_custom'): scenario_values[node.tag] = safe_eval(node.text) or False else: scenario_values[node.tag] = node.text or False # Transition from old format to new format scenario_xml_id = get_xml_id(_('scenario'), module, scenario_values) if scenario_values['model_id']: scenario_values['model_id'] = model_obj.search([ ('model', '=', scenario_values['model_id']), ]).id or False if not scenario_values['model_id']: logger.error('Model not found') return if scenario_values.get('company_id'): scenario_values['company_id'] = company_obj.search([ ('name', '=', scenario_values['company_id']), ]).id or False if not scenario_values['company_id']: logger.error('Company not found') return if scenario_values.get('parent_id'): if '.' not in scenario_values['parent_id']: scenario_values['parent_id'] = '%s.%s' % ( module, scenario_values['parent_id'] ) scenario_values['parent_id'] = env.ref(scenario_values['parent_id']).id if not scenario_values['parent_id']: logger.error('Parent not found') return # Create or update the scenario ir_model_data_obj._update( 'scanner.scenario', module, scenario_values, xml_id=scenario_xml_id, mode=mode, noupdate=noupdate, ) scenario = env.ref(scenario_xml_id) # Create or update steps resid = {} for node in steps: step_values = {} for key, item in node.items(): if item == 'False': item = False step_values[key] = item # Get scenario id step_values['scenario_id'] = scenario.id # Transition from old to new format step_xml_id = get_xml_id(_('step'), module, step_values) # Get python source python_filename = '%s/%s.py' % ( directory, step_xml_id, ) # Alow to use the id without module name for the current module try: python_file = misc.file_open(python_filename) except IOError: if module == step_xml_id.split('.')[0]: python_filename = '%s/%s.py' % ( directory, step_xml_id.split('.')[1], ) python_file = misc.file_open(python_filename) # Load python code and check syntax try: step_values['python_code'] = python_file.read() finally: python_file.close() # Create or update ir_model_data_obj._update( 'scanner.scenario.step', module, step_values, xml_id=step_xml_id, mode=mode, noupdate=noupdate, ) step = env.ref(step_xml_id) resid[step_xml_id] = step.id # Create or update transitions for node in transitions: transition_values = {} for key, item in node.items(): if key in ['to_id', 'from_id']: item = resid[get_xml_id(_('step'), module, {'id': item})] transition_values[key] = item # Create or update ir_model_data_obj._update( 'scanner.scenario.transition', module, transition_values, xml_id=get_xml_id(_('transition'), module, transition_values), mode=mode, noupdate=noupdate, )
def _load_data(cr, module_name, idref, mode, kind): """ kind: data, demo, test, init_xml, update_xml, demo_xml. noupdate is False, unless it is demo data or it is csv data in init mode. """ module_files = [] module_modified = True if mode == 'update' and kind == 'data': cr.execute("select id from ir_module_module where name=%s", (module_name, )) module_id = cr.fetchone()[0] for filename in _get_files_of_kind(kind): cr.execute( "select id,checksum from ir_module_module_file" " where module_id=%s and filename=%s", (module_id, filename)) checksum = cr.fetchone() module_file_id = checksum and checksum[0] or False checksum = checksum and checksum[1] or '' sha256 = hashlib.sha256() sha256.update( misc.file_open(os.path.join(module_name, filename)).read()) module_files += [{ 'checksum': checksum, 'checksum_new': sha256.hexdigest(), 'module_file_id': module_file_id, 'module_id': module_id, 'filename': filename }] if len(module_files) == len([ 1 for f in module_files if f['checksum'] == f['checksum_new'] ]): module_modified = bool( tools.config.options.get('force_update', False)) try: if kind in ('demo', 'test'): threading.currentThread().testing = True for filename in _get_files_of_kind(kind): _logger.info("%s %s/%s", module_modified and 'loading' or 'no changes', module_name, filename) noupdate = False if kind in ('demo', 'demo_xml') or (filename.endswith('.csv') and kind in ('init', 'init_xml')): noupdate = True if module_modified: tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report) finally: if kind in ('demo', 'test'): threading.currentThread().testing = False if module_modified and mode == 'update' and kind == 'data': for module_file in [ f for f in module_files if f['checksum'] != f['checksum_new'] ]: if module_file['module_file_id']: cr.execute( "update ir_module_module_file set checksum=%s, write_date=now() where id=%s", (module_file['checksum_new'], module_file['module_file_id'])) else: cr.execute( "insert into ir_module_module_file(filename,module_id,checksum,create_date,create_uid,write_date,write_uid)" " values(%s,%s,%s,now(),1,now(),1)", (module_file['filename'], module_file['module_id'], module_file['checksum_new'])) return module_modified
def from_data(self, fields, rows, file_address): if file_address: bk = xlrd.open_workbook(misc.file_open(file_address).name, formatting_info=True) workbook = xlutils.copy.copy(bk) worksheet = workbook.get_sheet(0) for i, fieldname in enumerate(fields): self.setOutCell(worksheet, 0, i, fieldname) for row, row_vals in enumerate(rows): for col, col_value in enumerate(row_vals): if isinstance(col_value, basestring): col_value = re.sub("\r", " ", col_value) self.setOutCell(worksheet, col, row + 1, col_value) else: workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Sheet 1') style, colour_style, base_style, float_style, date_style, datetime_style = self.style_data( ) worksheet.write_merge(0, 0, 0, len(fields) - 1, fields[0], style=style) worksheet.row(0).height = 400 worksheet.row(2).height = 400 [ worksheet.write( 1, i, '', style=xlwt.easyxf( 'border: left thin,right thin,top thin,bottom thin')) for i in xrange(len(fields)) ] columnwidth = {} for row_index, row in enumerate(rows): for cell_index, cell_value in enumerate(row): if cell_index in columnwidth: if len("%s" % (cell_value)) > columnwidth.get(cell_index): columnwidth.update( {cell_index: len("%s" % (cell_value))}) else: columnwidth.update( {cell_index: len("%s" % (cell_value))}) if row_index == 1: cell_style = colour_style elif row_index != len(rows) - 1: cell_style = base_style if isinstance(cell_value, basestring): cell_value = re.sub("\r", " ", cell_value) elif isinstance(cell_value, datetime.datetime): cell_style = datetime_style elif isinstance(cell_value, datetime.date): cell_style = date_style elif isinstance(cell_value, float) or isinstance( cell_value, int): cell_style = float_style else: cell_style = xlwt.easyxf( 'border: left thin,right thin,top thin,bottom thin' ) worksheet.write(row_index + 1, cell_index, cell_value, cell_style) for column, widthvalue in columnwidth.items(): """参考 下面链接关于自动列宽(探讨)的代码 http://stackoverflow.com/questions/6929115/python-xlwt-accessing-existing-cell-content-auto-adjust-column-width""" if (widthvalue + 2) * 367 >= 65536: widthvalue = 300 worksheet.col(column).width = (widthvalue + 4) * 256 worksheet.set_panes_frozen( True) # frozen headings instead of split panes worksheet.set_horz_split_pos( 3) # in general, freeze after last heading row worksheet.set_remove_splits( True) # if user does unfreeze, don't leave a split there fp_currency = StringIO.StringIO() workbook.save(fp_currency) fp_currency.seek(0) data = fp_currency.read() fp_currency.close() return data
def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, module_name=None, context=None): """Populates the ir_translation table.""" if verbose: _logger.info('loading translation file for language %s', lang) env = openerp.api.Environment(cr, SUPERUSER_ID, context or {}) Lang = env['res.lang'] Translation = env['ir.translation'] try: if not Lang.search_count([('code', '=', lang)]): # lets create the language with locale information Lang.load_lang(lang=lang, lang_name=lang_name) # Parse also the POT: it will possibly provide additional targets. # (Because the POT comments are correct on Launchpad but not the # PO comments due to a Launchpad limitation. See LP bug 933496.) pot_reader = [] # now, the serious things: we read the language file fileobj.seek(0) if fileformat == 'csv': reader = csv.reader(fileobj, quotechar='"', delimiter=',') # read the first line of the file (it contains columns titles) for row in reader: fields = row break elif fileformat == 'po': reader = PoFile(fileobj) fields = ['type', 'name', 'res_id', 'src', 'value', 'comments'] # Make a reader for the POT file and be somewhat defensive for the # stable branch. if fileobj.name.endswith('.po'): try: # Normally the path looks like /path/to/xxx/i18n/lang.po # and we try to find the corresponding # /path/to/xxx/i18n/xxx.pot file. # (Sometimes we have 'i18n_extra' instead of just 'i18n') addons_module_i18n, _ignored = os.path.split(fileobj.name) addons_module, i18n_dir = os.path.split(addons_module_i18n) addons, module = os.path.split(addons_module) pot_handle = file_open(os.path.join( addons, module, i18n_dir, module + '.pot')) pot_reader = PoFile(pot_handle) except: pass else: _logger.info('Bad file format: %s', fileformat) raise Exception(_('Bad file format: %s') % fileformat) # Read the POT references, and keep them indexed by source string. class Target(object): def __init__(self): self.value = None self.targets = set() # set of (type, name, res_id) self.comments = None pot_targets = defaultdict(Target) for type, name, res_id, src, _ignored, comments in pot_reader: if type is not None: target = pot_targets[src] target.targets.add((type, name, res_id)) target.comments = comments # read the rest of the file irt_cursor = Translation._get_import_cursor() def process_row(row): """Process a single PO (or POT) entry.""" # dictionary which holds values for this line of the csv file # {'lang': ..., 'type': ..., 'name': ..., 'res_id': ..., # 'src': ..., 'value': ..., 'module':...} dic = dict.fromkeys(('type', 'name', 'res_id', 'src', 'value', 'comments', 'imd_model', 'imd_name', 'module')) dic['lang'] = lang dic.update(zip(fields, row)) # discard the target from the POT targets. src = dic['src'] if src in pot_targets: target = pot_targets[src] target.value = dic['value'] target.targets.discard((dic['type'], dic['name'], dic['res_id'])) # This would skip terms that fail to specify a res_id res_id = dic['res_id'] if not res_id: return if isinstance(res_id, (int, long)) or \ (isinstance(res_id, basestring) and res_id.isdigit()): dic['res_id'] = int(res_id) if module_name: dic['module'] = module_name else: # res_id is an xml id dic['res_id'] = None dic['imd_model'] = dic['name'].split(',')[0] if '.' in res_id: dic['module'], dic['imd_name'] = res_id.split('.', 1) else: dic['module'], dic['imd_name'] = module_name, res_id irt_cursor.push(dic) # First process the entries from the PO file (doing so also fills/removes # the entries from the POT file). for row in reader: process_row(row) # Then process the entries implied by the POT file (which is more # correct w.r.t. the targets) if some of them remain. pot_rows = [] for src, target in pot_targets.iteritems(): if target.value: for type, name, res_id in target.targets: pot_rows.append((type, name, res_id, src, target.value, target.comments)) pot_targets.clear() for row in pot_rows: process_row(row) irt_cursor.finish() Translation.clear_caches() if verbose: _logger.info("translation file loaded succesfully") except IOError: iso_lang = get_iso_codes(lang) filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat) _logger.exception("couldn't read translation file %s", filename)
def extend_trans_generate(lang, modules, cr): dbname = cr.dbname registry = openerp.registry(dbname) trans_obj = registry['ir.translation'] model_data_obj = registry['ir.model.data'] uid = 1 query = 'SELECT name, model, res_id, module' \ ' FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model' """ if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " query_param = None if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module in %s' query_param = (tuple(modules),) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) _to_translate = set() def push_translation(module, type, name, id, source, comments=None): # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. if not source or len(source.strip()) <= 1: return tnx = (module, source, name, id, type, tuple(comments or ())) _to_translate.add(tnx) def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s def push(mod, type, name, res_id, term): term = (term or '').strip() if len(term) > 2 or term in ENGLISH_SMALL_WORDS: push_translation(mod, type, name, res_id, term) def get_root_view(xml_id): view = model_data_obj.xmlid_to_object(cr, uid, xml_id) if view: while view.mode != 'primary': view = view.inherit_id xml_id = view.get_external_id(cr, uid).get(view.id, xml_id) return xml_id for (xml_name,model,res_id,module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if model not in registry: _logger.error("Unable to find object %r", model) continue Model = registry[model] if not Model._translate: # explicitly disabled continue obj = Model.browse(cr, uid, res_id) if not obj.exists(): _logger.warning("Unable to find object %r with id %d", model, res_id) continue if model=='ir.ui.view': d = etree.XML(encode(obj.arch)) if obj.type == 'qweb': view_id = get_root_view(xml_name) push_qweb = lambda t,l: push(module, 'view', 'website', view_id, t) _extract_translatable_qweb_terms(d, push_qweb) else: push_view = lambda t,l: push(module, 'view', obj.model, xml_name, t) trans_parse_view(d, push_view) elif model=='ir.actions.wizard': pass # TODO Can model really be 'ir.actions.wizard' ? elif model=='ir.model.fields': try: field_name = encode(obj.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue objmodel = registry.get(obj.model) if (objmodel is None or field_name not in objmodel._columns or not objmodel._translate): continue field_def = objmodel._columns[field_name] name = "%s,%s" % (encode(obj.model), field_name) push_translation(module, 'field', name, 0, encode(field_def.string)) if field_def.help: push_translation(module, 'help', name, 0, encode(field_def.help)) if field_def.translate: ids = objmodel.search(cr, uid, []) obj_values = objmodel.read(cr, uid, ids, [field_name]) for obj_value in obj_values: res_id = obj_value['id'] if obj.name in ('ir.model', 'ir.ui.menu'): res_id = 0 model_data_ids = model_data_obj.search(cr, uid, [ ('model', '=', model), ('res_id', '=', res_id), ]) if not model_data_ids: push_translation(module, 'model', name, 0, encode(obj_value[field_name])) if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)): for dummy, val in field_def.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model=='ir.actions.report.xml': name = encode(obj.report_name) fname = "" ##### Changes for Aeroo ###### if obj.report_type == 'aeroo': trans_ids = trans_obj.search(cr, uid, [('type', '=', 'report'),('res_id', '=', obj.id)]) for t in trans_obj.read(cr, uid, trans_ids, ['name','src']): push_translation(module, "report", t['name'], xml_name, t['src'].encode('UTF-8')) ############################## else: if obj.report_rml: fname = obj.report_rml parse_func = trans_parse_rml report_type = "report" elif obj.report_xsl: fname = obj.report_xsl parse_func = trans_parse_xsl report_type = "xsl" if fname and obj.report_type in ('pdf', 'xsl'): try: report_file = misc.file_open(fname) try: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) finally: report_file.close() except (IOError, etree.XMLSyntaxError): _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname)
def apple_touch_icon_152x152(self): icon = file_open( 'theme_dermanord/static/ico/apple-touch-icon-152x152.png') icon_mimetype = 'image/x-icon' return http.request.make_response(icon.read(), [('Content-Type', icon_mimetype)])
def extend_trans_generate(lang, modules, cr): dbname = cr.dbname pool = pooler.get_pool(dbname) trans_obj = pool.get('ir.translation') model_data_obj = pool.get('ir.model.data') uid = 1 l = pool.models.items() l.sort() query = 'SELECT name, model, res_id, module' \ ' FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model' """ if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " query_param = None if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module in %s' query_param = (tuple(modules),) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) _to_translate = [] def push_translation(module, type, name, id, source, comments=None): tuple = (module, source, name, id, type, comments or []) # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. if not source or len(source.strip()) <= 1: _logger.debug("Ignoring empty or 1-letter source term: %r", tuple) return if tuple not in _to_translate: _to_translate.append(tuple) def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s for (xml_name,model,res_id,module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if not pool.get(model): _logger.error("Unable to find object %r", model) continue exists = pool.get(model).exists(cr, uid, res_id) if not exists: _logger.warning("Unable to find object %r with id %d", model, res_id) continue obj = pool.get(model).browse(cr, uid, res_id) if model=='ir.ui.view': d = etree.XML(encode(obj.arch)) for t in trans_parse_view(d): push_translation(module, 'view', encode(obj.model), 0, t) elif model=='ir.model.fields': try: field_name = encode(obj.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue objmodel = pool.get(obj.model) if not objmodel or not field_name in objmodel._columns: continue field_def = objmodel._columns[field_name] name = "%s,%s" % (encode(obj.model), field_name) push_translation(module, 'field', name, 0, encode(field_def.string)) if field_def.help: push_translation(module, 'help', name, 0, encode(field_def.help)) if field_def.translate: ids = objmodel.search(cr, uid, []) obj_values = objmodel.read(cr, uid, ids, [field_name]) for obj_value in obj_values: res_id = obj_value['id'] if obj.name in ('ir.model', 'ir.ui.menu'): res_id = 0 model_data_ids = model_data_obj.search(cr, uid, [ ('model', '=', model), ('res_id', '=', res_id), ]) if not model_data_ids: push_translation(module, 'model', name, 0, encode(obj_value[field_name])) if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)): for dummy, val in field_def.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model=='ir.actions.report.xml': name = encode(obj.report_name) fname = "" ##### Changes for Aeroo ###### if obj.report_type == 'aeroo': trans_ids = trans_obj.search(cr, uid, [('type', '=', 'report'),('res_id', '=', obj.id)]) for t in trans_obj.read(cr, uid, trans_ids, ['name','src']): push_translation(module, "report", t['name'], xml_name, t['src'].encode('UTF-8')) ############################## else: if obj.report_rml: fname = obj.report_rml parse_func = trans_parse_rml report_type = "report" elif obj.report_xsl: fname = obj.report_xsl parse_func = trans_parse_xsl report_type = "xsl" if fname and obj.report_type in ('pdf', 'xsl'): try: report_file = misc.file_open(fname) try: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) finally: report_file.close() except (IOError, etree.XMLSyntaxError): _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname)
def extend_trans_generate(lang, modules, cr): dbname = cr.dbname pool = pooler.get_pool(dbname) trans_obj = pool.get('ir.translation') model_data_obj = pool.get('ir.model.data') uid = 1 l = pool.models.items() l.sort() query = 'SELECT name, model, res_id, module' \ ' FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model' """ if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " query_param = None if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module in %s' query_param = (tuple(modules),) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) _to_translate = [] def push_translation(module, type, name, id, source, comments=None): tuple = (module, source, name, id, type, comments or []) # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. if not source or len(source.strip()) <= 1: _logger.debug("Ignoring empty or 1-letter source term: %r", tuple) return if tuple not in _to_translate: _to_translate.append(tuple) def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s for (xml_name,model,res_id,module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if not pool.get(model): _logger.error("Unable to find object %r", model) continue exists = pool.get(model).exists(cr, uid, res_id) if not exists: _logger.warning("Unable to find object %r with id %d", model, res_id) continue obj = pool.get(model).browse(cr, uid, res_id) if model=='ir.ui.view': d = etree.XML(encode(obj.arch)) push_view = lambda t,l: push_translation(module, 'view', obj.model, xml_name, t) trans_parse_view(d, push_view) elif model=='ir.model.fields': try: field_name = encode(obj.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue objmodel = pool.get(obj.model) if not objmodel or not field_name in objmodel._columns: continue field_def = objmodel._columns[field_name] name = "%s,%s" % (encode(obj.model), field_name) push_translation(module, 'field', name, 0, encode(field_def.string)) if field_def.help: push_translation(module, 'help', name, 0, encode(field_def.help)) if field_def.translate: ids = objmodel.search(cr, uid, []) obj_values = objmodel.read(cr, uid, ids, [field_name]) for obj_value in obj_values: res_id = obj_value['id'] if obj.name in ('ir.model', 'ir.ui.menu'): res_id = 0 model_data_ids = model_data_obj.search(cr, uid, [ ('model', '=', model), ('res_id', '=', res_id), ]) if not model_data_ids: push_translation(module, 'model', name, 0, encode(obj_value[field_name])) if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)): for dummy, val in field_def.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model=='ir.actions.report.xml': name = encode(obj.report_name) fname = "" ##### Changes for Aeroo ###### if obj.report_type == 'aeroo': trans_ids = trans_obj.search(cr, uid, [('type', '=', 'report'),('res_id', '=', obj.id)]) for t in trans_obj.read(cr, uid, trans_ids, ['name','src']): push_translation(module, "report", t['name'], xml_name, t['src'].encode('UTF-8')) ############################## else: if obj.report_rml: fname = obj.report_rml parse_func = trans_parse_rml report_type = "report" elif obj.report_xsl: fname = obj.report_xsl parse_func = trans_parse_xsl report_type = "xsl" if fname and obj.report_type in ('pdf', 'xsl'): try: report_file = misc.file_open(fname) try: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) finally: report_file.close() except (IOError, etree.XMLSyntaxError): _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname)
def extend_trans_generate(lang, modules, cr): dbname = cr.dbname registry = openerp.registry(dbname) trans_obj = registry['ir.translation'] model_data_obj = registry['ir.model.data'] uid = 1 query = 'SELECT name, model, res_id, module' \ ' FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model' """ if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " query_param = None if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module in %s' query_param = (tuple(modules), ) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) _to_translate = set() def push_translation(module, type, name, id, source, comments=None): # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. if not source or len(source.strip()) <= 1: return tnx = (module, source, name, id, type, tuple(comments or ())) _to_translate.add(tnx) def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s def push(mod, type, name, res_id, term): term = (term or '').strip() if len(term) > 2 or term in ENGLISH_SMALL_WORDS: push_translation(mod, type, name, res_id, term) def get_root_view(xml_id): view = model_data_obj.xmlid_to_object(cr, uid, xml_id) if view: while view.mode != 'primary': view = view.inherit_id xml_id = view.get_external_id(cr, uid).get(view.id, xml_id) return xml_id for (xml_name, model, res_id, module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if model not in registry: _logger.error("Unable to find object %r", model) continue Model = registry[model] if not Model._translate: # explicitly disabled continue obj = Model.browse(cr, uid, res_id) if not obj.exists(): _logger.warning("Unable to find object %r with id %d", model, res_id) continue if model == 'ir.ui.view': d = etree.XML(encode(obj.arch)) if obj.type == 'qweb': view_id = get_root_view(xml_name) push_qweb = lambda t, l: push(module, 'view', 'website', view_id, t) _extract_translatable_qweb_terms(d, push_qweb) # else: # push_view = lambda t,l: push(module, 'view', obj.model, xml_name, t) # trans_parse_view(d, push_view) elif model == 'ir.actions.wizard': pass # TODO Can model really be 'ir.actions.wizard' ? elif model == 'ir.model.fields': try: field_name = encode(obj.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue objmodel = registry.get(obj.model) if (objmodel is None or (field_name not in objmodel._columns and field_name not in objmodel._fields) or not objmodel._translate): continue field_def = objmodel._columns.get(field_name, objmodel._fields[field_name]) name = "%s,%s" % (encode(obj.model), field_name) push_translation(module, 'field', name, 0, encode(field_def.string)) if field_def.help: push_translation(module, 'help', name, 0, encode(field_def.help)) if getattr(field_def, 'translate', None): ids = objmodel.search(cr, uid, []) obj_values = objmodel.read(cr, uid, ids, [field_name]) for obj_value in obj_values: res_id = obj_value['id'] if obj.name in ('ir.model', 'ir.ui.menu'): res_id = 0 model_data_ids = model_data_obj.search( cr, uid, [ ('model', '=', model), ('res_id', '=', res_id), ]) if not model_data_ids: push_translation(module, 'model', name, 0, encode(obj_value[field_name])) if hasattr(field_def, 'selection') and isinstance( field_def.selection, (list, tuple)): for dummy, val in field_def.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model == 'ir.actions.report.xml': name = encode(obj.report_name) fname = "" ##### Changes for Aeroo ###### if obj.report_type == 'aeroo': trans_ids = trans_obj.search(cr, uid, [('type', '=', 'report'), ('res_id', '=', obj.id)]) for t in trans_obj.read(cr, uid, trans_ids, ['name', 'src']): push_translation(module, "report", t['name'], xml_name, t['src'].encode('UTF-8')) ############################## else: if obj.report_rml: fname = obj.report_rml parse_func = trans_parse_rml report_type = "report" # elif obj.report_xsl: # fname = obj.report_xsl # parse_func = trans_parse_xsl # report_type = "xsl" if fname and obj.report_type in ('pdf', 'xsl'): try: report_file = misc.file_open(fname) try: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) finally: report_file.close() except (IOError, etree.XMLSyntaxError): _logger.exception( "couldn't export translation for report %s %s %s", name, report_type, fname)
def extend_trans_generate(lang, modules, cr): dbname = cr.dbname pool = pooler.get_pool(dbname) trans_obj = pool.get('ir.translation') model_data_obj = pool.get('ir.model.data') uid = 1 l = pool.models.items() l.sort() query = 'SELECT name, model, res_id, module' \ ' FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model' """ if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " query_param = None if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module in %s' query_param = (tuple(modules), ) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) _to_translate = [] def push_translation(module, type, name, id, source, comments=None): tuple = (module, source, name, id, type, comments or []) # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. if not source or len(source.strip()) <= 1: _logger.debug("Ignoring empty or 1-letter source term: %r", tuple) return if tuple not in _to_translate: _to_translate.append(tuple) def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s for (xml_name, model, res_id, module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if not pool.get(model): _logger.error("Unable to find object %r", model) continue exists = pool.get(model).exists(cr, uid, res_id) if not exists: _logger.warning("Unable to find object %r with id %d", model, res_id) continue obj = pool.get(model).browse(cr, uid, res_id) if model == 'ir.ui.view': d = etree.XML(encode(obj.arch)) #for t in trans_parse_view(d): # push_translation(module, 'view', encode(obj.model), 0, t) trans_parse_view( d, lambda t, s: push_translation(module, 'view', encode(obj.model), 0, t)) elif model == 'ir.actions.wizard': service_name = 'wizard.' + encode(obj.wiz_name) import openerp.netsvc as netsvc if netsvc.Service._services.get(service_name): obj2 = netsvc.Service._services[service_name] for state_name, state_def in obj2.states.iteritems(): if 'result' in state_def: result = state_def['result'] if result['type'] != 'form': continue name = "%s,%s" % (encode(obj.wiz_name), state_name) def_params = { 'string': ('wizard_field', lambda s: [encode(s)]), 'selection': ('selection', lambda s: [ encode(e[1]) for e in ((not callable(s)) and s or []) ]), 'help': ('help', lambda s: [encode(s)]), } # export fields if not result.has_key('fields'): _logger.warning("res has no fields: %r", result) continue for field_name, field_def in result[ 'fields'].iteritems(): res_name = name + ',' + field_name for fn in def_params: if fn in field_def: transtype, modifier = def_params[fn] for val in modifier(field_def[fn]): push_translation( module, transtype, res_name, 0, val) # export arch arch = result['arch'] if arch and not isinstance(arch, UpdateableStr): d = etree.XML(arch) for t in trans_parse_view(d): push_translation(module, 'wizard_view', name, 0, t) # export button labels for but_args in result['state']: button_name = but_args[0] button_label = but_args[1] res_name = name + ',' + button_name push_translation(module, 'wizard_button', res_name, 0, button_label) elif model == 'ir.model.fields': try: field_name = encode(obj.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue objmodel = pool.get(obj.model) if not objmodel or not field_name in objmodel._columns: continue field_def = objmodel._columns[field_name] name = "%s,%s" % (encode(obj.model), field_name) push_translation(module, 'field', name, 0, encode(field_def.string)) if field_def.help: push_translation(module, 'help', name, 0, encode(field_def.help)) if field_def.translate: ids = objmodel.search(cr, uid, []) obj_values = objmodel.read(cr, uid, ids, [field_name]) for obj_value in obj_values: res_id = obj_value['id'] if obj.name in ('ir.model', 'ir.ui.menu'): res_id = 0 model_data_ids = model_data_obj.search( cr, uid, [ ('model', '=', model), ('res_id', '=', res_id), ]) if not model_data_ids: push_translation(module, 'model', name, 0, encode(obj_value[field_name])) if hasattr(field_def, 'selection') and isinstance( field_def.selection, (list, tuple)): for dummy, val in field_def.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model == 'ir.actions.report.xml': name = encode(obj.report_name) fname = "" ##### Changes for Aeroo ###### if obj.report_type == 'aeroo': trans_ids = trans_obj.search(cr, uid, [('type', '=', 'report'), ('res_id', '=', obj.id)]) for t in trans_obj.read(cr, uid, trans_ids, ['name', 'src']): push_translation(module, "report", t['name'], xml_name, t['src']) if obj.in_format in ['oo-odt', 'oo-ods']\ and obj.report_sxw_content: template_io = StringIO() template_io.write( base64.decodestring(obj.report_sxw_content)) serializer = OOSerializer(template_io) basic = Template(source=template_io, serializer=serializer) def push_oo_translations(nodes): for node in nodes: if not isinstance(node, tuple): continue if node[0] == 'TEXT': push_translation(module, obj.report_type, name, 0, node[1], [str(node[2][2])]) if node[0] == 'SUB': for n in node[1]: push_oo_translations(n) push_oo_translations(basic.stream) ############################## else: if obj.report_rml: fname = obj.report_rml parse_func = trans_parse_rml report_type = "report" elif obj.report_xsl: fname = obj.report_xsl parse_func = trans_parse_xsl report_type = "xsl" if fname and obj.report_type in ('pdf', 'xsl'): try: report_file = misc.file_open(fname) try: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) finally: report_file.close() except (IOError, etree.XMLSyntaxError): _logger.exception( "couldn't export translation for report %s %s %s", name, report_type, fname)
def favicon_ico(self): favicon = file_open('theme_dermanord/static/ico/favicon.ico') favicon_mimetype = 'image/x-icon' return http.request.make_response(favicon.read(), [('Content-Type', favicon_mimetype)])
def extend_trans_generate(lang, modules, cr): dbname = cr.dbname pool = pooler.get_pool(dbname) trans_obj = pool.get('ir.translation') model_data_obj = pool.get('ir.model.data') uid = 1 l = pool.models.items() l.sort() query = 'SELECT name, model, res_id, module' \ ' FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model' """ if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " query_param = None if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module in %s' query_param = (tuple(modules),) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) _to_translate = [] def push_translation(module, type, name, id, source, comments=None): tuple = (module, source, name, id, type, comments or []) # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. if not source or len(source.strip()) <= 1: _logger.debug("Ignoring empty or 1-letter source term: %r", tuple) return if tuple not in _to_translate: _to_translate.append(tuple) def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s for (xml_name,model,res_id,module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if not pool.get(model): _logger.error("Unable to find object %r", model) continue exists = pool.get(model).exists(cr, uid, res_id) if not exists: _logger.warning("Unable to find object %r with id %d", model, res_id) continue obj = pool.get(model).browse(cr, uid, res_id) if model=='ir.ui.view': d = etree.XML(encode(obj.arch)) #for t in trans_parse_view(d): # push_translation(module, 'view', encode(obj.model), 0, t) trans_parse_view(d, lambda t,s: push_translation(module, 'view', encode(obj.model), 0, t)) elif model=='ir.actions.wizard': service_name = 'wizard.'+encode(obj.wiz_name) import openerp.netsvc as netsvc if netsvc.Service._services.get(service_name): obj2 = netsvc.Service._services[service_name] for state_name, state_def in obj2.states.iteritems(): if 'result' in state_def: result = state_def['result'] if result['type'] != 'form': continue name = "%s,%s" % (encode(obj.wiz_name), state_name) def_params = { 'string': ('wizard_field', lambda s: [encode(s)]), 'selection': ('selection', lambda s: [encode(e[1]) for e in ((not callable(s)) and s or [])]), 'help': ('help', lambda s: [encode(s)]), } # export fields if not result.has_key('fields'): _logger.warning("res has no fields: %r", result) continue for field_name, field_def in result['fields'].iteritems(): res_name = name + ',' + field_name for fn in def_params: if fn in field_def: transtype, modifier = def_params[fn] for val in modifier(field_def[fn]): push_translation(module, transtype, res_name, 0, val) # export arch arch = result['arch'] if arch and not isinstance(arch, UpdateableStr): d = etree.XML(arch) for t in trans_parse_view(d): push_translation(module, 'wizard_view', name, 0, t) # export button labels for but_args in result['state']: button_name = but_args[0] button_label = but_args[1] res_name = name + ',' + button_name push_translation(module, 'wizard_button', res_name, 0, button_label) elif model=='ir.model.fields': try: field_name = encode(obj.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue objmodel = pool.get(obj.model) if not objmodel or not field_name in objmodel._columns: continue field_def = objmodel._columns[field_name] name = "%s,%s" % (encode(obj.model), field_name) push_translation(module, 'field', name, 0, encode(field_def.string)) if field_def.help: push_translation(module, 'help', name, 0, encode(field_def.help)) if field_def.translate: ids = objmodel.search(cr, uid, []) obj_values = objmodel.read(cr, uid, ids, [field_name]) for obj_value in obj_values: res_id = obj_value['id'] if obj.name in ('ir.model', 'ir.ui.menu'): res_id = 0 model_data_ids = model_data_obj.search(cr, uid, [ ('model', '=', model), ('res_id', '=', res_id), ]) if not model_data_ids: push_translation(module, 'model', name, 0, encode(obj_value[field_name])) if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)): for dummy, val in field_def.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model=='ir.actions.report.xml': name = encode(obj.report_name) fname = "" ##### Changes for Aeroo ###### if obj.report_type == 'aeroo': trans_ids = trans_obj.search(cr, uid, [('type', '=', 'report'),('res_id', '=', obj.id)]) for t in trans_obj.read(cr, uid, trans_ids, ['name','src']): push_translation(module, "report", t['name'], xml_name, t['src']) if obj.in_format in ['oo-odt', 'oo-ods']\ and obj.report_sxw_content: template_io = StringIO() template_io.write( base64.decodestring(obj.report_sxw_content)) serializer = OOSerializer(template_io) basic = Template(source=template_io, serializer=serializer) def push_oo_translations(nodes): for node in nodes: if not isinstance(node, tuple): continue if node[0] == 'TEXT': push_translation( module, obj.report_type, name, 0, node[1], [str(node[2][2])]) if node[0] == 'SUB': for n in node[1]: push_oo_translations(n) push_oo_translations(basic.stream) ############################## else: if obj.report_rml: fname = obj.report_rml parse_func = trans_parse_rml report_type = "report" elif obj.report_xsl: fname = obj.report_xsl parse_func = trans_parse_xsl report_type = "xsl" if fname and obj.report_type in ('pdf', 'xsl'): try: report_file = misc.file_open(fname) try: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) finally: report_file.close() except (IOError, etree.XMLSyntaxError): _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname)