changeset 6bc3cc2d62e1 in proteus:default
details: https://hg.tryton.org/proteus?cmd=changeset&node=6bc3cc2d62e1
description:
        Support session with XML-RPC

        issue7783
        review350521003
diffstat:

 CHANGELOG         |   1 +
 doc/index.rst     |   4 ++++
 proteus/config.py |  27 +++++++++++++++++++++++++++
 3 files changed, 32 insertions(+), 0 deletions(-)

diffs (71 lines):

diff -r 7eec360324a9 -r 6bc3cc2d62e1 CHANGELOG
--- a/CHANGELOG Thu Sep 23 23:09:16 2021 +0200
+++ b/CHANGELOG Thu Sep 23 23:16:31 2021 +0200
@@ -1,3 +1,4 @@
+* Support session with XML-RPC
 * Use bigdecimal tag for XML-RPC
 
 Version 6.0.0 - 2021-05-03
diff -r 7eec360324a9 -r 6bc3cc2d62e1 doc/index.rst
--- a/doc/index.rst     Thu Sep 23 23:09:16 2021 +0200
+++ b/doc/index.rst     Thu Sep 23 23:16:31 2021 +0200
@@ -16,6 +16,10 @@
 
     >>> config = config.set_trytond('sqlite:///:memory:')
 
+There is also the `config.set_xmlrpc` method which can be used to connect using
+a URL, and the `config.set_xmlrpc_session` method (when used as a context
+manager) which connects for a session.
+
 Activating a module
 ~~~~~~~~~~~~~~~~~~~
 
diff -r 7eec360324a9 -r 6bc3cc2d62e1 proteus/config.py
--- a/proteus/config.py Thu Sep 23 23:09:16 2021 +0200
+++ b/proteus/config.py Thu Sep 23 23:16:31 2021 +0200
@@ -4,12 +4,14 @@
 Configuration functions for the proteus package for Tryton.
 """
 
+import base64
 import datetime
 import os
 import threading
 import urllib.parse
 import xmlrpc.client
 from decimal import Decimal
+from contextlib import contextmanager
 
 __all__ = ['set_trytond', 'set_xmlrpc', 'get_config']
 
@@ -369,5 +371,30 @@
     return _CONFIG.current
 
 
+@contextmanager
+def set_xmlrpc_session(
+        url, username, password=None, parameters=None, **kwargs):
+    """
+    Set XML-RPC as backend using session.
+    """
+    if parameters is None:
+        parameters = {}
+    else:
+        parameters = parameters.copy()
+    if password:
+        parameters['password'] = password
+    server = xmlrpc.client.ServerProxy(
+        url, allow_none=True, use_builtin_types=True, **kwargs)
+    session = server.common.db.login(username, parameters)
+    session = ':'.join(map(str, [username] + session))
+    auth = base64.encodebytes(session.encode('utf-8')).decode('ascii')
+    auth = ''.join(auth.split())  # get rid of whitespace
+    kwargs.setdefault('headers', []).append(
+        ('Authorization', 'Session ' + auth))
+    config = set_xmlrpc(url, **kwargs)
+    yield config
+    config.server.common.db.logout()
+
+
 def get_config():
     return _CONFIG.current

Reply via email to