SmartGridready / SGrPython

Development of SGr PyPi package
Other
1 stars 1 forks source link

Improvements / fixes #3

Closed marco92 closed 10 months ago

marco92 commented 1 year ago

"More" generic way in replacing config variables

Currently, the Python Library replaces the following variables after reading the XML file: https://github.com/SmartgridReady/SGrPython/blob/master/sgr_library/restapi_client_async.py

        user = parser.get('AUTHENTICATION', 'username', fallback=None)
        password = parser.get('AUTHENTICATION', 'password', fallback=None)
        self.sensor_id = parser.get('RESSOURCE', 'sensor_id', fallback=None)
        #TODO this one can be formulated more elegantly with a format() method.
        request_body = str(self.root.rest_apiinterface_desc.rest_apibearer.service_call.request_body)
        data = json.loads(request_body)
        data['email'] = user
        data['password'] = password
        self.data = json.dumps(data)
marco92 commented 1 year ago

In comparison, the string regex replacement in the node.js code:

      for(const xmlVar of options.xmlVariables) {
        const re = new RegExp('{{' + xmlVar.name + '}}', 'g');
        xmlString = xmlString.replace(re, String(xmlVar.value));
      }
options.xmlVariables =  [
    {name: 'edgeid', value: process.env.EDGEID},
    {name: 'username', value: process.env.RESTAPIUSERNAME},
    {name: 'password', value: process.env.RESTAPIPASSWORD},
  ]
marco92 commented 1 year ago

@Zupeuc I changed the way the variables from the .ini file are being used. I first read the xml file and save it's content in a string variable. Then I do a regex replace with the config variables from the ini file: https://github.com/SmartgridReady/SGrPython/blob/aa61c8a0aca60830a43bde881531f999d4702236/sgr_library/auxiliary_functions.py#L13

In all other places, the xml should be parsed as string (this hasn't been done everywhere yet):

marco92 commented 1 year ago

Python Example (already implemented in branch 3-improvements-fixes):

# Read XML file, replace variables form config file and return xml as string
def xml_to_string(xml_file:str, config_file:str):
    xml_string = ""
    with open(xml_file, 'r') as file:
        xml_string = file.read()

    parser = configparser.ConfigParser()
    parser.read(config_file)
    for section in parser.sections():
        for(key, val) in parser.items(section):
            pattern = re.compile(r'\{\{\s*' + re.escape(key) + r'\s*\}\}', re.IGNORECASE)
            xml_string = re.sub(pattern, val, xml_string)

    return xml_string
marco92 commented 10 months ago

closing issue. a new one will be created to provide a solution for the XML variable replacement