Debian Codegraph @

odoorpc/rpc/__init__.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright 2014 Sébastien Alix
3 # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl)
4 """This module provides `Connector` classes to communicate with an `Odoo`
5 server with the `JSON-RPC` protocol or through simple HTTP requests.
6
7 Web controllers of `Odoo` expose two kinds of methods: `json` and `http`.
8 These methods can be accessed from the connectors of this module.
9 """
10 import sys
11
12 from odoorpc.rpc import error, jsonrpclib
13
14 # Python 2
15 if sys.version_info[0] < 3:
16 from cookielib import CookieJar
17 from urllib2 import HTTPCookieProcessor, build_opener
18 # Python >= 3
19 else:
20 from http.cookiejar import CookieJar
21 from urllib.request import HTTPCookieProcessor, build_opener
22
23
24 class Connector(object):
25 """Connector base class defining the interface used
26 to interact with a server.
27 """
28
29 def __init__(self, host, port=8069, timeout=120, version=None):
30 self.host = host
31 try:
32 int(port)
33 except (ValueError, TypeError):
34 txt = "The port '{0}' is invalid. An integer is required."
35 txt = txt.format(port)
36 raise error.ConnectorError(txt)
37 else:
38 self.port = int(port)
39 self._timeout = timeout
40 self.version = version
41
42 @property
43 def ssl(self):
44 """Return `True` if SSL is activated."""
45 return False
46
47 @property
48 def timeout(self):
49 """Return the timeout."""
50 return self._timeout
51
52 @timeout.setter
53 def timeout(self, timeout):
54 """Set the timeout."""
55 self._timeout = timeout
56
57
58 class ConnectorJSONRPC(Connector):
59 """Connector class using the `JSON-RPC` protocol.
60
61 .. doctest::
62 :options: +SKIP
63
64 >>> from odoorpc import rpc
65 >>> cnt = rpc.ConnectorJSONRPC('localhost', port=8069)
66
67 .. doctest::
68 :hide:
69
70 >>> from odoorpc import rpc
71 >>> cnt = rpc.ConnectorJSONRPC(HOST, port=PORT)
72
73 Open a user session:
74
75 .. doctest::
76 :options: +SKIP
77
78 >>> cnt.proxy_json.web.session.authenticate(db='db_name', login='admin', password='password')
79 {'id': 51373612,
80 'jsonrpc': '2.0',
81 'result': {'company_id': 1,
82 'currencies': {'1': {'digits': [69, 2],
83 'position': 'after',
84 'symbol': '\u20ac'},
85 '3': {'digits': [69, 2],
86 'position': 'before',
87 'symbol': '$'}},
88 'db': 'db_name',
89 'is_admin': True,
90 'is_system': True,
91 'name': 'Mitchell Admin',
92 'partner_display_name': 'YourCompany, Mitchell Admin',
93 'partner_id': 3,
94 'server_version': '12.0',
95 'server_version_info': [12, 0, 0, 'final', 0, ''],
96 'session_id': '6dd7a34f16c1c67b38bfec413cca4962d5c01d53',
97 'show_effect': True,
98 'uid': 2,
99 'user_companies': False,
100 'user_context': {'lang': 'en_US',
101 'tz': 'Europe/Brussels',
102 'uid': 2},
103 'username': 'admin',
104 'web.base.url': 'http://localhost:8069',
105 'web_tours': []}}
106
107 .. doctest::
108 :hide:
109 :options: +NORMALIZE_WHITESPACE
110
111 >>> from odoorpc.tools import v
112 >>> data = cnt.proxy_json.web.session.authenticate(db=DB, login=USER, password=PWD)
113 >>> keys = ['company_id', 'db', 'session_id', 'uid', 'user_context', 'username']
114 >>> if v(VERSION) >= v('10.0'):
115 ... keys.extend([
116 ... 'currencies', 'is_admin', 'is_superuser', 'name',
117 ... 'partner_id', 'server_version', 'server_version_info',
118 ... 'user_companies', 'web.base.url', 'web_tours',
119 ... ])
120 >>> if v(VERSION) >= v('11.0'):
121 ... keys.extend([
122 ... 'is_system',
123 ... ])
124 ... keys.remove('is_admin')
125 >>> if v(VERSION) >= v('12.0'):
126 ... keys.extend([
127 ... 'is_admin',
128 ... 'partner_display_name',
129 ... 'show_effect',
130 ... ])
131 ... keys.remove('is_superuser')
132 >>> if v(VERSION) >= v('13.0'):
133 ... keys.extend([
134 ... 'display_switch_company_menu',
135 ... 'cache_hashes',
136 ... ])
137 ... keys.remove('session_id')
138 >>> if v(VERSION) >= v('14.0'):
139 ... keys.extend([
140 ... 'active_ids_limit',
141 ... ])
142 >>> all([key in data['result'] for key in keys])
143 True
144
145 Read data of a partner:
146
147 .. doctest::
148 :options: +SKIP
149
150 >>> cnt.proxy_json.web.dataset.call(model='res.partner', method='read', args=[[1]])
151 {'jsonrpc': '2.0', 'id': 454236230,
152 'result': [{'id': 1, 'comment': False, 'ean13': False, 'property_account_position': False, ...}]}
153
154 .. doctest::
155 :hide:
156
157 >>> data = cnt.proxy_json.web.dataset.call(model='res.partner', method='read', args=[[1]])
158 >>> 'jsonrpc' in data and 'id' in data and 'result' in data
159 True
160
161 You can send requests this way too:
162
163 .. doctest::
164 :options: +SKIP
165
166 >>> cnt.proxy_json['/web/dataset/call'](model='res.partner', method='read', args=[[1]])
167 {'jsonrpc': '2.0', 'id': 328686288,
168 'result': [{'id': 1, 'comment': False, 'ean13': False, 'property_account_position': False, ...}]}
169
170 .. doctest::
171 :hide:
172
173 >>> data = cnt.proxy_json['/web/dataset/call'](model='res.partner', method='read', args=[[1]])
174 >>> 'jsonrpc' in data and 'id' in data and 'result' in data
175 True
176
177 Or like this:
178
179 .. doctest::
180 :options: +SKIP
181
182 >>> cnt.proxy_json['web']['dataset']['call'](model='res.partner', method='read', args=[[1]])
183 {'jsonrpc': '2.0', 'id': 102320639,
184 'result': [{'id': 1, 'comment': False, 'ean13': False, 'property_account_position': False, ...}]}
185
186 .. doctest::
187 :hide:
188
189 >>> data = cnt.proxy_json['web']['dataset']['call'](model='res.partner', method='read', args=[[1]])
190 >>> 'jsonrpc' in data and 'id' in data and 'result' in data
191 True
192 """
193
194 def __init__(
195 self,
196 host,
197 port=8069,
198 timeout=120,
199 version=None,
200 deserialize=True,
201 opener=None,
202 ):
203 super(ConnectorJSONRPC, self).__init__(host, port, timeout, version)
204 self.deserialize = deserialize
205 # One URL opener (with cookies handling) shared between
206 # JSON and HTTP requests
207 if opener is None:
208 cookie_jar = CookieJar()
209 opener = build_opener(HTTPCookieProcessor(cookie_jar))
210 self._opener = opener
211 self._proxy_json, self._proxy_http = self._get_proxies()
212
213 def _get_proxies(self):
214 """Returns the :class:`ProxyJSON <odoorpc.rpc.jsonrpclib.ProxyJSON>`
215 and :class:`ProxyHTTP <odoorpc.rpc.jsonrpclib.ProxyHTTP>` instances
216 corresponding to the server version used.
217 """
218 proxy_json = jsonrpclib.ProxyJSON(
219 self.host,
220 self.port,
221 self._timeout,
222 ssl=self.ssl,
223 deserialize=self.deserialize,
224 opener=self._opener,
225 )
226 proxy_http = jsonrpclib.ProxyHTTP(
227 self.host,
228 self.port,
229 self._timeout,
230 ssl=self.ssl,
231 opener=self._opener,
232 )
233 # Detect the server version
234 if self.version is None:
235 result = proxy_json('/web/webclient/version_info')['result']
236 if 'server_version' in result:
237 self.version = result['server_version']
238 return proxy_json, proxy_http
239
240 @property
241 def proxy_json(self):
242 """Return the JSON proxy."""
243 return self._proxy_json
244
245 @property
246 def proxy_http(self):
247 """Return the HTTP proxy."""
248 return self._proxy_http
249
250 @property
251 def timeout(self):
252 """Return the timeout."""
253 return self._proxy_json._timeout
254
255 @timeout.setter
256 def timeout(self, timeout):
257 """Set the timeout."""
258 self._proxy_json._timeout = timeout
259 self._proxy_http._timeout = timeout
260
261
262 class ConnectorJSONRPCSSL(ConnectorJSONRPC):
263 """Connector class using the `JSON-RPC` protocol over `SSL`.
264
265 .. doctest::
266 :options: +SKIP
267
268 >>> from odoorpc import rpc
269 >>> cnt = rpc.ConnectorJSONRPCSSL('localhost', port=8069)
270
271 .. doctest::
272 :hide:
273
274 >>> if 'ssl' in PROTOCOL:
275 ... from odoorpc import rpc
276 ... cnt = rpc.ConnectorJSONRPCSSL(HOST, port=PORT)
277 """
278
279 def __init__(
280 self,
281 host,
282 port=8069,
283 timeout=120,
284 version=None,
285 deserialize=True,
286 opener=None,
287 ):
288 super(ConnectorJSONRPCSSL, self).__init__(
289 host, port, timeout, version, opener=opener
290 )
291 self._proxy_json, self._proxy_http = self._get_proxies()
292
293 @property
294 def ssl(self):
295 return True
296
297
298 PROTOCOLS = {'jsonrpc': ConnectorJSONRPC, 'jsonrpc+ssl': ConnectorJSONRPCSSL}