1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ##############################################################################
24 # OSV: Objects Services
33 from psycopg2 import IntegrityError
34 from netsvc import Logger, LOG_ERROR
35 from tools.misc import UpdateableDict
38 module_class_list = {}
42 class except_osv(Exception):
43 def __init__(self, name, value, exc_type='warning'):
45 self.exc_type = exc_type
47 self.args = (exc_type, name)
50 from tools.func import wraps
51 class osv_pool(netsvc.Service):
55 def wrapper(self, dbname, *args, **kwargs):
57 if not pooler.get_pool(dbname)._ready:
58 raise except_osv('Database not ready', 'Currently, this database is not fully loaded and can not be used.')
59 return f(self, dbname, *args, **kwargs)
60 except orm.except_orm, inst:
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])
71 tb_s = reduce(lambda x, y: x+y, traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback))
73 logger.notifyChannel('web-services', LOG_ERROR, tb_s)
82 self.module_object_list = {}
85 self._store_function = {}
87 self._init_parent = {}
88 netsvc.Service.__init__(self, 'object_proxy', audience='')
89 self.joinGroup('web-services')
90 self.exportMethod(self.obj_list)
91 self.exportMethod(self.exec_workflow)
92 self.exportMethod(self.execute)
94 def init_set(self, cr, mode):
95 different = mode != self._init
98 self._init_parent = {}
100 for o in self._init_parent:
101 self.get(o)._parent_store_compute(cr)
107 def execute_cr(self, cr, uid, obj, method, *args, **kw):
108 object = pooler.get_pool(cr.dbname).get(obj)
110 raise except_osv('Object Error', 'Object %s doesn\'t exist' % str(obj))
111 return getattr(object, method)(cr, uid, *args, **kw)
114 def execute(self, db, uid, obj, method, *args, **kw):
115 db, pool = pooler.get_db_and_pool(db)
119 res = pool.execute_cr(cr, uid, obj, method, *args, **kw)
128 def exec_workflow_cr(self, cr, uid, obj, method, *args):
129 wf_service = netsvc.LocalService("workflow")
130 return wf_service.trg_validate(uid, obj, args[0], method, cr)
133 def exec_workflow(self, db, uid, obj, method, *args):
134 cr = pooler.get_db(db).cursor()
137 res = self.exec_workflow_cr(cr, uid, obj, method, *args)
147 return self.obj_pool.keys()
149 # adds a new object instance to the object pool.
150 # if it already existed, the instance is replaced
151 def add(self, name, obj_inst):
152 if name in self.obj_pool:
153 del self.obj_pool[name]
154 self.obj_pool[name] = obj_inst
156 module = str(obj_inst.__class__)[6:]
157 module = module[:len(module)-1]
158 module = module.split('.')[0][2:]
159 self.module_object_list.setdefault(module, []).append(obj_inst)
161 # Return None if object does not exist
163 obj = self.obj_pool.get(name, None)
166 #TODO: pass a list of modules to load
167 def instanciate(self, module, cr):
169 class_list = module_class_list.get(module, [])
170 for klass in class_list:
171 res.append(klass.createInstance(self, module, cr))
175 class osv_memory(orm.orm_memory):
176 #__metaclass__ = inheritor
178 module = str(cls)[6:]
179 module = module[:len(module)-1]
180 module = module.split('.')[0][2:]
181 if not hasattr(cls, '_module'):
183 module_class_list.setdefault(cls._module, []).append(cls)
184 class_pool[cls._name] = cls
185 if module not in module_list:
186 module_list.append(cls._module)
190 # Goal: try to apply inheritancy at the instanciation level and
191 # put objects in the pool var
193 def createInstance(cls, pool, module, cr):
194 name = hasattr(cls, '_name') and cls._name or cls._inherit
195 parent_name = hasattr(cls, '_inherit') and cls._inherit
197 raise 'Inherit not supported in osv_memory object !'
198 obj = object.__new__(cls)
199 obj.__init__(pool, cr)
201 createInstance = classmethod(createInstance)
203 def __init__(self, pool, cr):
204 pool.add(self._name, self)
206 orm.orm_memory.__init__(self, cr)
211 #__metaclass__ = inheritor
213 module = str(cls)[6:]
214 module = module[:len(module)-1]
215 module = module.split('.')[0][2:]
216 if not hasattr(cls, '_module'):
218 module_class_list.setdefault(cls._module, []).append(cls)
219 class_pool[cls._name] = cls
220 if module not in module_list:
221 module_list.append(cls._module)
225 # Goal: try to apply inheritancy at the instanciation level and
226 # put objects in the pool var
228 def createInstance(cls, pool, module, cr):
229 parent_name = hasattr(cls, '_inherit') and cls._inherit
231 parent_class = pool.get(parent_name).__class__
232 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
234 for s in ('_columns', '_defaults', '_inherits', '_constraints', '_sql_constraints'):
235 new = copy.copy(getattr(pool.get(parent_name), s))
236 if hasattr(new, 'update'):
237 new.update(cls.__dict__.get(s, {}))
239 if s=='_constraints':
240 for c in cls.__dict__.get(s, []):
242 for c2 in range(len(new)):
250 new.extend(cls.__dict__.get(s, []))
252 name = hasattr(cls, '_name') and cls._name or cls._inherit
253 cls = type(name, (cls, parent_class), nattr)
254 obj = object.__new__(cls)
255 obj.__init__(pool, cr)
257 createInstance = classmethod(createInstance)
259 def __init__(self, pool, cr):
260 pool.add(self._name, self)
262 orm.orm.__init__(self, cr)
264 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: