User Tools

Site Tools


userspace:json-rpc_python_requests

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
userspace:json-rpc_python_requests [2018/03/16 16:55]
schuhj created
userspace:json-rpc_python_requests [2021/08/23 08:37] (current)
Line 8: Line 8:
 **More error handling and concern for security is needed before use in production environments! **  **More error handling and concern for security is needed before use in production environments! ** 
  
-===== The Module =====+===== The Module (opsirpc.py) =====
  
 <code python> <code python>
Line 16: Line 16:
 import base64 import base64
 import os.path import os.path
-# ignore warnings about missing ssl cert field+ 
 +# ignore warnings about missing ssl cert field subjectAltName (you may remove this and ln 102)
 from requests.packages.urllib3.exceptions import SubjectAltNameWarning from requests.packages.urllib3.exceptions import SubjectAltNameWarning
  
Line 23: Line 24:
  
 class OpsiError(Exception): class OpsiError(Exception):
-    """Exception raised for remote RPC errors 
- 
-    Attributes: 
-        expression -- the RPC Call 
-        class -- the Error class 
-        message -- the Error message 
-    """ 
  
     def __init__(self, expression, opsierrorclass, message):     def __init__(self, expression, opsierrorclass, message):
 +        """
 +
 +        :param expression: the RPC Call
 +        :param opsierrorclass: the Error class
 +        :param message: the Error message
 +        """
         self.expression = expression         self.expression = expression
         self.opsierrorclass = opsierrorclass         self.opsierrorclass = opsierrorclass
Line 38: Line 38:
  
 class OpsiConnection: class OpsiConnection:
 +
     def __init__(self, url, authfile=None, auth=None, certfile=None, legal_methods_path=None):     def __init__(self, url, authfile=None, auth=None, certfile=None, legal_methods_path=None):
         # 0 is not a valid id         # 0 is not a valid id
 +        """
 +
 +        :param url: Opsiserver URL
 +        :param authfile: base64 encoded UTF-8 String containing username password
 +        :param auth: username password as tuple
 +        :param certfile: Opsiserver SSL Certificate
 +        :param legal_methods_path: Textfile containing one method name per line 
 +        """
         self.id = 0         self.id = 0
         self.server = url         self.server = url
Line 49: Line 58:
         elif not auth:         elif not auth:
             # get auth from file             # get auth from file
-            # authfile expected to contain base64 encoded UTF-8 String (username password) 
             # The authfile has to be kept in an secure environment!             # The authfile has to be kept in an secure environment!
             with open(authfile, 'rb') as f:             with open(authfile, 'rb') as f:
Line 64: Line 72:
                 raise FileNotFoundError(legal_methods_path)                 raise FileNotFoundError(legal_methods_path)
         else:         else:
-            # getPossibleMethods_listOfHashes does not always deliver a comprehensive list of methods!+            # getPossibleMethods_listOfHashes lacks the modern _getObjects methods!
             opsicon_logger.debug("Get Methods from Server...")             opsicon_logger.debug("Get Methods from Server...")
             self.id += 1             self.id += 1
Line 79: Line 87:
  
     def raw_request(self, payload):     def raw_request(self, payload):
 +        """
 +
 +        :param payload: json string to send to the server
 +        """
         self.__rpc_request(self.session, payload)         self.__rpc_request(self.session, payload)
  
Line 99: Line 111:
         # avoid proxy issues         # avoid proxy issues
         session.trust_env = False         session.trust_env = False
-        # ignore warnings about missing ssl cert field +        # ignore warnings about missing ssl cert field subjectAltName
         requests.packages.urllib3.disable_warnings(SubjectAltNameWarning)         requests.packages.urllib3.disable_warnings(SubjectAltNameWarning)
         # supply cert file         # supply cert file
Line 113: Line 125:
             r.raise_for_status()             r.raise_for_status()
         except requests.exceptions.Timeout as e:         except requests.exceptions.Timeout as e:
-            # TODO: Maybe set up retry loop 
             raise e             raise e
         except requests.exceptions.RequestException as e:         except requests.exceptions.RequestException as e:
-            # TODO: Maybe think about better handling 
             raise e             raise e
         if r.json()["error"]:         if r.json()["error"]:
             raise OpsiError(payload, r.json()['error']['class'], r.json()['error']['message'])             raise OpsiError(payload, r.json()['error']['class'], r.json()['error']['message'])
-        return r+        return r.json()['result']
 </code> </code>
 ===== Example ===== ===== Example =====
 <code python> <code python>
 +import json
 +
 from opsirpc import OpsiConnection as OpsiServerCon from opsirpc import OpsiConnection as OpsiServerCon
-from opsirpc import OpsiError+
  
 def print_name_example(response): def print_name_example(response):
-    for o in response.json()['result']:+    for o in response:
         print(o['name'])         print(o['name'])
 +
  
 server_connection = OpsiServerCon(url = 'https://my.opsiserver.dom:4447', server_connection = OpsiServerCon(url = 'https://my.opsiserver.dom:4447',
                                   authfile = "myPasswordBase64.txt",                                   authfile = "myPasswordBase64.txt",
-                                  certfile = "myCert.crt") +                                  certfile = "myCert.crt" 
-                                  +                                  legal_methods_path='rpc_methods.txt')
  
-r = server_connection.product_getObjects(licenseRequired = True+r = server_connection.product_getObjects(licenseRequired=True)
-print_name_example(r) +
-r = server_connection.product_getObjects('name', id = 'flashplayer')+
 print_name_example(r) print_name_example(r)
 +
 +print(server_connection.product_getObjects('description', id='flashplayer')[0]['description'])
 +print('\n'.join([json.dumps(d, indent=4, sort_keys=True) for d
 +                 in server_connection.getPossibleMethods_listOfHashes()]))
 </code> </code>
 +
 +[[https://pastebin.com/raw/2AMSkiTA|rpc_methods.txt]]
 +
userspace/json-rpc_python_requests.1521219350.txt.gz · Last modified: 2021/08/23 08:37 (external edit)