3 import dateutil.relativedelta
12 _logger = logging.getLogger(__name__)
14 #----------------------------------------------------------
15 # OpenERPSession RPC openerp backend access
16 #----------------------------------------------------------
17 class AuthenticationError(Exception):
20 class SessionExpiredException(Exception):
23 class Service(object):
24 def __init__(self, session, service_name):
25 self.session = session
26 self.service_name = service_name
28 def __getattr__(self, method):
29 def proxy_method(*args):
30 result = self.session.send(self.service_name, method, *args)
35 def __init__(self, session, model):
36 self.session = session
38 self.proxy = self.session.proxy('object')
40 def __getattr__(self, method):
41 def proxy(*args, **kw):
42 result = self.proxy.execute_kw(self.session._db, self.session._uid, self.session._password, self.model, method, args, kw)
45 if isinstance(result, list) and len(result) > 0 and "id" in result[0]:
49 result = [index[x] for x in args[0] if x in index]
53 def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None, context=None):
54 record_ids = self.search(domain or [], offset, limit or False, order or False, context or {})
55 if not record_ids: return []
56 records = self.read(record_ids, fields or [], context or {})
59 class OpenERPSession(object):
61 An OpenERP RPC session, a given user can own multiple such sessions
64 .. attribute:: context
66 The session context, a ``dict``. Can be reloaded by calling
67 :meth:`openerpweb.openerpweb.OpenERPSession.get_context`
69 .. attribute:: domains_store
71 A ``dict`` matching domain keys to evaluable (but non-literal) domains.
73 Used to store references to non-literal domains which need to be
74 round-tripped to the client browser.
77 self._creation_time = time.time()
81 self._password = False
84 self.jsonp_requests = {} # FIXME use a LRU
86 def send(self, service_name, method, *args):
87 code_string = u"warning -- %s\n\n%s"
89 return openerp.netsvc.dispatch_rpc(service_name, method, args)
90 except openerp.osv.osv.except_osv, e:
91 raise xmlrpclib.Fault(code_string % (e.name, e.value), '')
92 except openerp.exceptions.Warning, e:
93 raise xmlrpclib.Fault(code_string % ("Warning", e), '')
94 except openerp.exceptions.AccessError, e:
95 raise xmlrpclib.Fault(code_string % ("AccessError", e), '')
96 except openerp.exceptions.AccessDenied, e:
97 raise xmlrpclib.Fault('AccessDenied', openerp.tools.ustr(e))
98 except openerp.exceptions.DeferredException, e:
99 formatted_info = "".join(traceback.format_exception(*e.traceback))
100 raise xmlrpclib.Fault(openerp.tools.ustr(e), formatted_info)
102 formatted_info = "".join(traceback.format_exception(*(sys.exc_info())))
103 raise xmlrpclib.Fault(openerp.tools.ustr(e), formatted_info)
105 def proxy(self, service):
106 return Service(self, service)
108 def bind(self, db, uid, login, password):
112 self._password = password
114 def authenticate(self, db, login, password, env=None):
115 uid = self.proxy('common').authenticate(db, login, password, env)
116 self.bind(db, uid, login, password)
118 if uid: self.get_context()
121 def assert_valid(self, force=False):
123 Ensures this session is valid (logged into the openerp server)
125 if self._uid and not force:
127 # TODO use authenticate instead of login
128 uid = self.proxy("common").login(self._db, self._login, self._password)
130 raise AuthenticationError("Authentication failure")
132 def ensure_valid(self):
135 self.assert_valid(True)
139 def execute(self, model, func, *l, **d):
141 model = self.model(model)
142 r = getattr(model, func)(*l, **d)
145 def exec_workflow(self, model, id, signal):
147 r = self.proxy('object').exec_workflow(self._db, self._uid, self._password, model, signal, id)
150 def model(self, model):
151 """ Get an RPC proxy for the object ``model``, bound to this session.
153 :param model: an OpenERP model name
155 :rtype: a model object
157 if self._db == False:
158 raise SessionExpiredException("Session expired")
160 return Model(self, model)
162 def get_context(self):
163 """ Re-initializes the current user's session context (based on
164 his preferences) by calling res.users.get_context() with the old
167 :returns: the new context
169 assert self._uid, "The user needs to be logged-in to initialize his context"
170 self.context = self.model('res.users').context_get() or {}
171 self.context['uid'] = self._uid
172 self._fix_lang(self.context)
175 def _fix_lang(self, context):
176 """ OpenERP provides languages which may not make sense and/or may not
177 be understood by the web client's libraries.
181 :param dict context: context to fix
183 lang = context['lang']
185 # inane OpenERP locale
189 # lang to lang_REGION (datejs only handles lang_REGION, no bare langs)
190 if lang in babel.core.LOCALE_ALIASES:
191 lang = babel.core.LOCALE_ALIASES[lang]
193 context['lang'] = lang or 'en_US'