1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
23 # OSV: Objects Services
33 from psycopg2 import IntegrityError
34 from tools.func import wraps
38 module_class_list = {}
41 class except_osv(Exception):
42 def __init__(self, name, value, exc_type='warning'):
44 self.exc_type = exc_type
46 self.args = (exc_type, name)
49 class osv_pool(netsvc.Service):
53 def wrapper(self, dbname, *args, **kwargs):
55 if not pooler.get_pool(dbname)._ready:
56 raise except_osv('Database not ready', 'Currently, this database is not fully loaded and can not be used.')
57 return f(self, dbname, *args, **kwargs)
58 except orm.except_orm, inst:
59 if inst.name == 'AccessError':
60 self.logger.debug("AccessError", exc_info=True)
61 self.abortResponse(1, inst.name, 'warning', inst.value)
62 except except_osv, inst:
63 self.abortResponse(1, inst.name, inst.exc_type, inst.value)
64 except IntegrityError, inst:
65 for key in self._sql_error.keys():
67 self.abortResponse(1, 'Constraint Error', 'warning', self._sql_error[key])
68 self.abortResponse(1, 'Integrity Error', 'warning', inst[0])
70 self.logger.exception("Uncaught exception")
79 self.module_object_list = {}
82 self._store_function = {}
84 self._init_parent = {}
85 self.logger = logging.getLogger("web-services")
86 netsvc.Service.__init__(self, 'object_proxy', audience='')
87 self.exportMethod(self.obj_list)
88 self.exportMethod(self.exec_workflow)
89 self.exportMethod(self.execute)
91 def init_set(self, cr, mode):
92 different = mode != self._init
95 self._init_parent = {}
97 for o in self._init_parent:
98 self.get(o)._parent_store_compute(cr)
104 def execute_cr(self, cr, uid, obj, method, *args, **kw):
105 object = pooler.get_pool(cr.dbname).get(obj)
107 raise except_osv('Object Error', 'Object %s doesn\'t exist' % str(obj))
108 return getattr(object, method)(cr, uid, *args, **kw)
111 def execute(self, db, uid, obj, method, *args, **kw):
112 db, pool = pooler.get_db_and_pool(db)
116 if method.startswith('_'):
117 raise except_osv('Access Denied', 'Private methods (such as %s) cannot be called remotely.' % (method,))
118 res = pool.execute_cr(cr, uid, obj, method, *args, **kw)
120 self.logger.warning('RPC methods cannot return `None` at the moment!')
129 def exec_workflow_cr(self, cr, uid, obj, method, *args):
130 wf_service = netsvc.LocalService("workflow")
131 return wf_service.trg_validate(uid, obj, args[0], method, cr)
134 def exec_workflow(self, db, uid, obj, method, *args):
135 cr = pooler.get_db(db).cursor()
138 res = self.exec_workflow_cr(cr, uid, obj, method, *args)
148 return self.obj_pool.keys()
150 # adds a new object instance to the object pool.
151 # if it already existed, the instance is replaced
152 def add(self, name, obj_inst):
153 if name in self.obj_pool:
154 del self.obj_pool[name]
155 self.obj_pool[name] = obj_inst
157 module = str(obj_inst.__class__)[6:]
158 module = module[:len(module)-1]
159 module = module.split('.')[0][2:]
160 self.module_object_list.setdefault(module, []).append(obj_inst)
162 # Return None if object does not exist
164 obj = self.obj_pool.get(name, None)
167 #TODO: pass a list of modules to load
168 def instanciate(self, module, cr):
170 class_list = module_class_list.get(module, [])
171 for klass in class_list:
172 res.append(klass.createInstance(self, module, cr))
175 class osv_base(object):
176 def __init__(self, pool, cr):
177 pool.add(self._name, self)
179 super(osv_base, self).__init__(cr)
182 module = str(cls)[6:]
183 module = module[:len(module)-1]
184 module = module.split('.')[0][2:]
185 if not hasattr(cls, '_module'):
187 module_class_list.setdefault(cls._module, []).append(cls)
188 class_pool[cls._name] = cls
189 if module not in module_list:
190 module_list.append(cls._module)
193 class osv_memory(osv_base, orm.orm_memory):
195 # Goal: try to apply inheritancy at the instanciation level and
196 # put objects in the pool var
198 def createInstance(cls, pool, module, cr):
199 parent_names = getattr(cls, '_inherit', None)
201 if isinstance(parent_names, (str, unicode)):
202 name = cls._name or parent_names
203 parent_names = [parent_names]
207 raise TypeError('_name is mandatory in case of multiple inheritance')
209 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
210 parent_class = pool.get(parent_name).__class__
211 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
213 for s in ('_columns', '_defaults'):
214 new = copy.copy(getattr(pool.get(parent_name), s))
215 if hasattr(new, 'update'):
216 new.update(cls.__dict__.get(s, {}))
218 new.extend(cls.__dict__.get(s, []))
220 cls = type(name, (cls, parent_class), nattr)
222 obj = object.__new__(cls)
223 obj.__init__(pool, cr)
225 createInstance = classmethod(createInstance)
227 class osv(osv_base, orm.orm):
229 # Goal: try to apply inheritancy at the instanciation level and
230 # put objects in the pool var
232 def createInstance(cls, pool, module, cr):
233 parent_names = getattr(cls, '_inherit', None)
235 if isinstance(parent_names, (str, unicode)):
236 name = cls._name or parent_names
237 parent_names = [parent_names]
241 raise TypeError('_name is mandatory in case of multiple inheritance')
243 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
244 parent_class = pool.get(parent_name).__class__
245 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
247 for s in ('_columns', '_defaults', '_inherits', '_constraints', '_sql_constraints'):
248 new = copy.copy(getattr(pool.get(parent_name), s))
249 if hasattr(new, 'update'):
250 new.update(cls.__dict__.get(s, {}))
252 if s=='_constraints':
253 for c in cls.__dict__.get(s, []):
255 for c2 in range(len(new)):
256 #For _constraints, we should check field and methods as well
257 if new[c2][2]==c[2] and new[c2][0]==c[0]:
264 new.extend(cls.__dict__.get(s, []))
266 cls = type(name, (cls, parent_class), nattr)
267 obj = object.__new__(cls)
268 obj.__init__(pool, cr)
270 createInstance = classmethod(createInstance)
272 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: