def export_data(self, fname, fields, export_as="csv", add_names=False, import_compat=False, **kw): params, data = TinyDict.split(kw) proxy = rpc.RPCProxy(params.model) if isinstance(fields, basestring): fields = [fields] ctx = params.context or {} ctx.update(rpc.session.context.copy()) ctx['import_comp'] = import_compat domain = params.seach_domain or [] ids = params.ids or proxy.search(domain, 0, 0, 0, ctx) result = datas_read(ids, params.model, fields, context=ctx) if result.get('warning', False): common.warning(unicode(result.get('warning', False)), _('Export Error!')) return False result = result.get('datas',[]) if import_compat: params.fields2 = fields if export_as == 'xls': try: import xlwt except Exception, e: raise common.warning(_('Please Install xlwt Library.\nTo create spreadsheet files compatible with MS Excel.'), _('Import Error.')) ezxf = xlwt.easyxf fp = StringIO.StringIO() wb = xlwt.Workbook() worksheet = wb.add_sheet('Sheet 1') for col in range(len(params.fields2)): worksheet.write(0, col, ustr(params.fields2[col])) col+1 heading_xf = ezxf('align: wrap yes') for data in range(len(result)): for d in range(len(result[data])): try: result[data][d] = ustr(result[data][d]) except: pass result[data][d] = re.sub("\r", " ", result[data][d]) worksheet.write(data+1, d, result[data][d], heading_xf) worksheet.col(d).width = 8000 d+1 wb.save(fp) fp.seek(0) data = fp.read() return data
def do_create(self, password, dbname, admin_password, confirm_password, demo_data=False, language=None, **kw): if not re.match('^[a-zA-Z][a-zA-Z0-9_]+$', dbname): raise common.warning(_('The database name must contain only normal characters or "_".\nYou must avoid all accents, space or special characters.'), _('Bad database name!')) ok = False try: res = rpc.session.execute_db('create', password, dbname, demo_data, language, admin_password) while True: try: progress, users = rpc.session.execute_db('get_progress', password, res) if progress == 1.0: for x in users: if x['login'] == 'admin': rpc.session.login(dbname, 'admin', password) ok = True break else: time.sleep(1) except: raise Exception('DbFailed') except Exception, e: if e.args == ('DbExist',): raise common.warning(_("Could not create database."), _('Database already exists!')) elif e.args == ('DbFailed'): raise common.warning(_("The server crashed during installation.\nWe suggest you to drop this database."), _("Error during database creation!")) elif getattr(e, 'faultCode', False) == 'AccessDenied': raise common.warning(_('Bad database administrator password!'), _("Could not create database.")) else: raise common.warning(_("Could not create database."))
def do_password(self, old_password, new_password, confirm_password, **kw): try: res = rpc.session.execute_db('change_admin_password', old_password, new_password) except Exception,e: if getattr(e, 'faultCode', False) == 'AccessDenied': raise common.warning(_("Could not change super admin password."), _('Bad password provided!')) else: raise common.warning(_("Error, password not changed."))
def do_drop(self, dbname, password, **kw): try: rpc.session.execute_db('drop', password, dbname) except Exception, e: if getattr(e, 'faultCode', False) == 'AccessDenied': raise common.warning(_('Bad database administrator password!'), _("Could not drop database.")) else: raise common.warning(_("Couldn't drop database"))
def do_restore(self, filename, password, dbname, **kw): try: data = base64.encodestring(filename.file.read()) res = rpc.session.execute_db('restore', password, dbname, data) except Exception, e: if getattr(e, 'faultCode', False) == 'AccessDenied': raise common.warning(_('Bad database administrator password!'), _("Could not restore database.")) else: raise common.warning(_("Couldn't restore database"))
def do_password(self, old_password, new_password, confirm_password, **kw): try: res = rpc.session.execute_db('change_admin_password', old_password, new_password) except Exception, e: if getattr(e, 'faultCode', False) == 'AccessDenied': raise common.warning( _("Could not change super admin password."), _('Bad password provided!')) else: raise common.warning(_("Error, password not changed."))
def import_data(self, csvfile, csvsep, csvdel, csvcode, csvskip, fields=[], **kw): params, data = TinyDict.split(kw) content = csvfile.file.read() input = StringIO.StringIO(content) data = list( csv.reader(input, quotechar=str(csvdel), delimiter=str(csvsep)))[int(csvskip):] datas = [] #if csv_data['combo']: if not isinstance(fields, list): fields = [fields] for line in data: try: datas.append( map(lambda x: x.decode(csvcode).encode('utf-8'), line)) except: datas.append( map(lambda x: x.decode('latin').encode('utf-8'), line)) try: res = rpc.session.execute('object', 'execute', params.model, 'import_data', fields, datas) except Exception, e: raise common.warning(ustr(e), _('XML-RPC error!'))
def user_action(self, id='action_id'): """Perform default user action. @param id: `action_id` or `menu_id` """ proxy = rpc.RPCProxy("res.users") act_id = proxy.read([rpc.session.uid], [id, 'name'], rpc.session.context) if not act_id[0][id]: common.warning(_('You can not log into the system!\nAsk the administrator to verify\nyou have an action defined for your user.'), _('Access Denied!')) rpc.session.logout() raise redirect('/'); act_id = act_id[0][id][0] return controllers.actions.execute_by_id(act_id)
def do_create(self, password, dbname, admin_password, confirm_password, demo_data=False, language=None, **kw): if not re.match('^[a-zA-Z][a-zA-Z0-9_]+$', dbname): raise common.warning( _('The database name must contain only normal characters or "_".\nYou must avoid all accents, space or special characters.' ), _('Bad database name!')) ok = False try: res = rpc.session.execute_db('create', password, dbname, demo_data, language, admin_password) while True: try: progress, users = rpc.session.execute_db( 'get_progress', password, res) if progress == 1.0: for x in users: if x['login'] == 'admin': rpc.session.login(dbname, 'admin', password) ok = True break else: time.sleep(1) except: raise Exception('DbFailed') except Exception, e: if e.args == ('DbExist', ): raise common.warning(_("Could not create database."), _('Database already exists!')) elif e.args == ('DbFailed'): raise common.warning( _("The server crashed during installation.\nWe suggest you to drop this database." ), _("Error during database creation!")) elif getattr(e, 'faultCode', False) == 'AccessDenied': raise common.warning(_('Bad database administrator password!'), _("Could not create database.")) else: raise common.warning(_("Could not create database."))
def do_backup(self, dbname, password, **kw): try: res = rpc.session.execute_db('dump', password, dbname) if res: cherrypy.response.headers['Content-Type'] = "application/data" cherrypy.response.headers['Content-Disposition'] = 'filename="' + dbname + '.dump"'; return base64.decodestring(res) except Exception, e: raise common.warning(_("Could not create backup."))
def do_backup(self, dbname, password, **kw): try: res = rpc.session.execute_db('dump', password, dbname) if res: cherrypy.response.headers['Content-Type'] = "application/data" cherrypy.response.headers[ 'Content-Disposition'] = 'filename="' + dbname + '.dump"' return base64.decodestring(res) except Exception, e: raise common.warning(_("Could not create backup."))
def import_data(self, csvfile, csvsep, csvdel, csvcode, csvskip, fields=[], **kw): params, data = TinyDict.split(kw) content = csvfile.file.read() input=StringIO.StringIO(content) data = list(csv.reader(input, quotechar=str(csvdel), delimiter=str(csvsep)))[int(csvskip):] datas = [] #if csv_data['combo']: if not isinstance(fields, list): fields = [fields] for line in data: try: datas.append(map(lambda x:x.decode(csvcode).encode('utf-8'), line)) except: datas.append(map(lambda x:x.decode('latin').encode('utf-8'), line)) try: res = rpc.session.execute('object', 'execute', params.model, 'import_data', fields, datas) except Exception, e: raise common.warning(ustr(e), _('XML-RPC error!'))
def button_action(self, params): button = params.button name = ustr(button.name) name = name.rsplit('/', 1)[-1] btype = button.btype model = button.model id = button.id or params.id id = (id or False) and int(id) ids = (id or []) and [id] ctx = (params.context or {}).copy() ctx.update(rpc.session.context.copy()) ctx.update(button.context or {}) if btype == 'cancel': if name: button.btype = "object" params.id = False res = self.button_action(params) if res: return res return """<html> <head> <script type="text/javascript"> window.onload = function(evt){ if (window.opener) { window.opener.setTimeout("window.location.reload()", 0); window.close(); } else { window.location.href = '/'; } } </script> </head> <body></body> </html>""" elif btype == 'save': params.id = False elif btype == 'workflow': res = rpc.session.execute('object', 'exec_workflow', model, name, id) if isinstance(res, dict): from openerp.controllers import actions return actions.execute(res, ids=[id]) elif btype == 'object': res = rpc.session.execute('object', 'execute', model, name, ids, ctx) if isinstance(res, dict): from openerp.controllers import actions return actions.execute(res, ids=[id]) elif btype == 'action': from openerp.controllers import actions action_id = int(name) action_type = actions.get_action_type(action_id) if action_type == 'ir.actions.wizard': cherrypy.session['wizard_parent_form'] = self.path cherrypy.session['wizard_parent_params'] = params.parent_params or params res = actions.execute_by_id(action_id, type=action_type, model=model, id=id, ids=ids, context=ctx or {}) if res: return res else: raise common.warning(_('Invalid button type')) params.button = None
def button_action(self, params): button = params.button name = ustr(button.name) name = name.rsplit('/', 1)[-1] btype = button.btype model = button.model id = button.id or params.id id = (id or False) and int(id) ids = (id or []) and [id] ctx = (params.context or {}).copy() ctx.update(rpc.session.context.copy()) ctx.update(button.context or {}) if btype == 'cancel': if name: button.btype = "object" params.id = False res = self.button_action(params) if res: return res return """<html> <head> <script type="text/javascript"> window.onload = function(evt){ if (window.opener) { window.opener.setTimeout("window.location.reload()", 0); window.close(); } else { window.location.href = '/'; } } </script> </head> <body></body> </html>""" elif btype == 'save': params.id = False elif btype == 'workflow': res = rpc.session.execute('object', 'exec_workflow', model, name, id) if isinstance(res, dict): from openerp.controllers import actions return actions.execute(res, ids=[id]) elif btype == 'object': res = rpc.session.execute('object', 'execute', model, name, ids, ctx) if isinstance(res, dict): from openerp.controllers import actions result = actions.execute(res, ids=[id]) if result is None or type(result) == type({}): return """<html> <head> <script type="text/javascript"> window.onload = function(evt){ if (window.opener) { window.opener.setTimeout("window.location.reload()", 0); window.close(); } else { window.location.href = '/'; } } </script> </head> <body></body> </html>""" else: return result elif btype == 'action': from openerp.controllers import actions action_id = int(name) action_type = actions.get_action_type(action_id) if action_type == 'ir.actions.wizard': cherrypy.session['wizard_parent_form'] = self.path cherrypy.session[ 'wizard_parent_params'] = params.parent_params or params res = actions.execute_by_id(action_id, type=action_type, model=model, id=id, ids=ids, context=ctx or {}) if res: return res else: raise common.warning(_('Invalid button type')) params.button = None
def detect_data(self, csvfile, csvsep, csvdel, csvcode, csvskip, **kw): params, data = TinyDict.split(kw) _fields = {} _fields_invert = {} proxy = rpc.RPCProxy(params.model) fields = proxy.fields_get(False, rpc.session.context) def model_populate(fields, prefix_node='', prefix=None, prefix_value='', level=2): def str_comp(x,y): if x<y: return 1 elif x>y: return -1 else: return 0 fields_order = fields.keys() fields_order.sort(lambda x,y: str_comp(fields[x].get('string', ''), fields[y].get('string', ''))) for field in fields_order: if (fields[field].get('type','') not in ('reference',))\ and (not fields[field].get('readonly', False)\ or not dict(fields[field].get('states', {}).get( 'draft', [('readonly', True)])).get('readonly',True)): st_name = prefix_value+fields[field]['string'] or field _fields[prefix_node+field] = st_name _fields_invert[st_name] = prefix_node+field if fields[field].get('type','')=='one2many' and level>0: fields2 = rpc.session.execute('object', 'execute', fields[field]['relation'], 'fields_get', False, rpc.session.context) fields2.update({'id': {'type': 'char', 'string': 'ID'}, 'db_id':{'type': 'char', 'string': 'Database ID'}}) model_populate(fields2, prefix_node+field+'/', None, st_name+'/', level-1) if fields[field].get('type','') in ('many2one', 'many2many' ) and level>0: # _fields[field+':id'] = fields[field]['string'] same in GTK # _fields_invert[fields[field]['string']] = field+':id' same in GTK model_populate({'id': {'type': 'char', 'string': 'ID'}, 'db_id': {'type': 'char', 'string': 'Database ID'}}, prefix_node+field+':', None, st_name+'/', level-1) fields.update({'id': {'type': 'char', 'string': 'ID'}, 'db_id': {'type': 'char', 'string': 'Database ID'}}) model_populate(fields) try: data = csv.reader(csvfile.file, quotechar=str(csvdel), delimiter=str(csvsep)) except: raise common.warning(_('Error opening .CSV file'), _('Input Error.')) fields = [] word='' try: for line in data: for word in line: word = ustr(word.decode(csvcode)) if word in _fields: fields += [(word, _fields[word])] elif word in _fields_invert.keys(): fields += [(_fields_invert[word], word)] else: raise common.warning(_("You cannot import this field %s, because we cannot auto-detect it" % (word,))) break except: raise common.warning(_('Error processing your first line of the file.\nField %s is unknown!') % (word,), _('Import Error.')) kw['fields'] = fields return self.imp(**kw)
def export_data(self, fname, fields, export_as="csv", add_names=False, import_compat=False, **kw): params, data = TinyDict.split(kw) proxy = rpc.RPCProxy(params.model) if isinstance(fields, basestring): fields = [fields] ctx = params.context or {} ctx.update(rpc.session.context.copy()) ctx['import_comp'] = import_compat domain = params.seach_domain or [] ids = params.ids or proxy.search(domain, 0, 0, 0, ctx) result = datas_read(ids, params.model, fields, context=ctx) if result.get('warning', False): common.warning(unicode(result.get('warning', False)), _('Export Error!')) return False result = result.get('datas', []) if import_compat: params.fields2 = fields if export_as == 'xls': try: import xlwt except Exception, e: raise common.warning( _('Please Install xlwt Library.\nTo create spreadsheet files compatible with MS Excel.' ), _('Import Error.')) ezxf = xlwt.easyxf fp = StringIO.StringIO() wb = xlwt.Workbook() worksheet = wb.add_sheet('Sheet 1') for col in range(len(params.fields2)): worksheet.write(0, col, ustr(params.fields2[col])) col + 1 heading_xf = ezxf('align: wrap yes') for data in range(len(result)): for d in range(len(result[data])): try: result[data][d] = ustr(result[data][d]) except: pass result[data][d] = re.sub("\r", " ", result[data][d]) worksheet.write(data + 1, d, result[data][d], heading_xf) worksheet.col(d).width = 8000 d + 1 wb.save(fp) fp.seek(0) data = fp.read() return data
def detect_data(self, csvfile, csvsep, csvdel, csvcode, csvskip, **kw): params, data = TinyDict.split(kw) _fields = {} _fields_invert = {} proxy = rpc.RPCProxy(params.model) fields = proxy.fields_get(False, rpc.session.context) def model_populate(fields, prefix_node='', prefix=None, prefix_value='', level=2): def str_comp(x, y): if x < y: return 1 elif x > y: return -1 else: return 0 fields_order = fields.keys() fields_order.sort(lambda x, y: str_comp( fields[x].get('string', ''), fields[y].get('string', ''))) for field in fields_order: if (fields[field].get('type','') not in ('reference',))\ and (not fields[field].get('readonly', False)\ or not dict(fields[field].get('states', {}).get( 'draft', [('readonly', True)])).get('readonly',True)): st_name = prefix_value + fields[field]['string'] or field _fields[prefix_node + field] = st_name _fields_invert[st_name] = prefix_node + field if fields[field].get('type', '') == 'one2many' and level > 0: fields2 = rpc.session.execute( 'object', 'execute', fields[field]['relation'], 'fields_get', False, rpc.session.context) fields2.update({ 'id': { 'type': 'char', 'string': 'ID' }, 'db_id': { 'type': 'char', 'string': 'Database ID' } }) model_populate(fields2, prefix_node + field + '/', None, st_name + '/', level - 1) if fields[field].get( 'type', '') in ('many2one', 'many2many') and level > 0: # _fields[field+':id'] = fields[field]['string'] same in GTK # _fields_invert[fields[field]['string']] = field+':id' same in GTK model_populate( { 'id': { 'type': 'char', 'string': 'ID' }, 'db_id': { 'type': 'char', 'string': 'Database ID' } }, prefix_node + field + ':', None, st_name + '/', level - 1) fields.update({ 'id': { 'type': 'char', 'string': 'ID' }, 'db_id': { 'type': 'char', 'string': 'Database ID' } }) model_populate(fields) try: data = csv.reader(csvfile.file, quotechar=str(csvdel), delimiter=str(csvsep)) except: raise common.warning(_('Error opening .CSV file'), _('Input Error.')) fields = [] word = '' try: for line in data: for word in line: word = ustr(word.decode(csvcode)) if word in _fields: fields += [(word, _fields[word])] elif word in _fields_invert.keys(): fields += [(_fields_invert[word], word)] else: raise common.warning( _("You cannot import this field %s, because we cannot auto-detect it" % (word, ))) break except: raise common.warning( _('Error processing your first line of the file.\nField %s is unknown!' ) % (word, ), _('Import Error.')) kw['fields'] = fields return self.imp(**kw)