Best Python code snippet using ATX
upnp.py
Source:upnp.py  
...125        uri = hostName + controlURL126        response = self.fetch_url(uri, auth=None, username=None, password=None, timeout=2, method='POST', headers=headers, body=soapBody).decode()127        return response128    129    def _parse_xml_node(self, node):130        # spezielle anpassungen für das parsen der services, damit doppelte131        # key einträge im dicts vermieden werden132        tree = {}133        for child in node.getchildren():134            childTag = child.tag                135            if child.text is not None:136                childText = child.text.strip()137            else:138                childText = ''139            childTree = self._parse_xml_node(child)140            if not childTree:141                childDict = {childTag : childText}142            else:143                if child.tag == 'service':144                    # ebene 'service' text service durch serviceType ersetzen, da sonst im dict mehrfach gleiche keys145                    # da die namen in der referenz komplex, aber als parameter immer noch enthalten, daher146                    # für device und service eine verkürzung der namen.147                    childDict = {childTree['serviceType'].split(':')[3] : childTree}148                elif child.tag == 'action':149                    # ebene 'action' text action durch action.name ersetzen, da sonst im dict mehrfach gleiche keys150                    childDict = {childTree['name'] : childTree}151                elif child.tag == 'argument':152                    # ebene 'argument' text argument durch argument.name ersetzen, da sonst im dict mehrfach gleiche keys153                    childDict = {childTree['name'] : childTree}154                else: 155                    childDict = {childTag : childTree}156            if childTag not in tree:  # First time found157                tree.update(childDict)158        return tree159    160    def _extract_devices(self, xml):161        # rückgabewert ist ein dict über alle devices aus dem xml162        devicesDict = {}163        # erst einmal aus dem xml string ein etree machen164        rootNode = et.fromstring(xml)165        # jetzt suchen wir alle knoten mit dem eintrag device166        for node in rootNode.iter('device'):167            # die machen wir zu einem dict168            device = self._parse_xml_node(node)169            # wenn sie noch nicht eingetragen sind, dann tun wir das170            if not device['deviceType'] in devicesDict:171                # allerdings machen wir die hierachie platt, d.h. wenn noch eine device list im dict hängt,172                # dann werfen wir die raus, denn die haben wir ja schon separat über die iteration über das173                # xml gemacht174                if 'deviceList' in device:175                    del device['deviceList']176                # jetzt wird sie zugewiesen177                # name device ist device type, da friendly name weniger auswertbar178                # da die namen in der referenz komplex, aber als aremeter immer noch enthalten, daher179                # für device und service eine verkürzung der namen.180                devicesDict[device['deviceType'].split(':')[3]] = device181        return devicesDict182    183    184    def upnp_discover_devices(self, hostIp = None, st = None):185        # erst einmal scannen, was es an upnp im lokalen netz gibt186        # da wir beliebig lange scannen können, die beschränkung auf 5 sekunden187        ssdpServices = self._ssdp_scan(st, ssdpTimeout=5)188        # jetzt das rückgabe dict189        upnpDevices = {}190        for host in ssdpServices:191            # jetzt noch die möglichkeit der einschränkung auf host ip's192            if host == hostIp or hostIp == None:193                # als nächste suchen wir über alle gefundenen hosteinträge194                for service in ssdpServices[host]:195                    # und es gibt mehrere einträge pro host und services nach den urls196                    response = self.fetch_url(ssdpServices[host][service]['LOCATION']).decode()197                    # um etwas übersichtlicher hinterher unterwegs im dict zu sein, nehme ich den standard heraus198                    # mehr geht leider nicht, sonst macht mit etree beim parsen des xml strings exceptions199                    # hier die devices200                    response = response.replace("xmlns='urn:schemas-upnp-org:device-1-0'", '')201                    response = response.replace('xmlns="urn:schemas-upnp-org:device-1-0"', '')202                    # für dslforum der fritzboxen203                    response = response.replace('xmlns="urn:dslforum-org:device-1-0"', '')204                    # jetzt noch den port heraussuchen205                    port = ssdpServices[host][service]['LOCATION'].split('/')[2].split(':')[1]206                    # und das dict anlegen aus der antwort207                    devicesDict = self._extract_devices(response)208                    # jetzt noch die richtuge url inkl. port dazu packen, die wird nämlich nur im ssdp scan ermittelt209                    for device in devicesDict:210                        devicesDict[device]['URL'] = 'http://' + host + ':' + port211                    # host anlegen212                    if not host in upnpDevices:213                        # erstanlage214                        upnpDevices[host] = devicesDict215                    else:216                        # jetzt müssen wir noch nachschauen, ob bei host die services schon da sind217                        # diese werden unter umständen mehrfach durch den ssdp scan angelegt und aufgerufen218                        # ich will diese aber nur einmal in der liste haben219                        for service in devicesDict:220                            if not service in upnpDevices[host]:221                                upnpDevices[host][service] = devicesDict[service]222        # jetzt suchen wir die zugehörigen actions pro service noch heraus223        for host in upnpDevices:224            for device in upnpDevices[host]:225                if 'serviceList' in upnpDevices[host][device]:226                    for service in upnpDevices[host][device]['serviceList']:227                        uri = upnpDevices[host][device]['URL'] + upnpDevices[host][device]['serviceList'][service]['SCPDURL']228                        response = self.fetch_url(uri).decode()229                        # um etwas übersichtlicher hinterher unterwegs im dict zu sein, nehme ich den standard heraus230                        # mehr geht leider nicht, sonst macht mit etree beim parsen des xml strings exceptions231                        # hier die services232                        response = response.replace("xmlns='urn:schemas-upnp-org:service-1-0'", '')233                        response = response.replace('xmlns="urn:schemas-upnp-org:service-1-0"', '')234                        # für dslforum router wie die fritzbox235                        response = response.replace('xmlns="urn:dslforum-org:service-1-0"', '')236                        rootNode = et.fromstring(response)237                        for node in rootNode.iter('action'):238                            # achtung ! hier wird nur das erste argument mit aufgenommen, das239                            action = self._parse_xml_node(node)240                            # eintragen in die Service liste241                            if not 'actionList' in upnpDevices[host][device]['serviceList'][service]:242                                upnpDevices[host][device]['serviceList'][service]['actionList'] = {}243                            if 'argumentList' in action:244                                upnpDevices[host][device]['serviceList'][service]['actionList'].update({action['name'] : action['argumentList']})245                            else:246                                upnpDevices[host][device]['serviceList'][service]['actionList'].update({action['name'] : ''})247        return upnpDevices248if __name__ == "__main__":249    # import sys;sys.argv = ['', 'Test.testName']250    upnp=UPNP()251    upnpDevices = upnp.upnp_discover_devices(hostIp='192.168.2.1', st = 'urn:dslforum-org:device:InternetGatewayDevice:1')252    for device in upnpDevices['192.168.2.1']:253        print(device)...xml_helper.py
Source:xml_helper.py  
...124    def _parse_xml_root(self):125        """126        starts processing, takes care of first level idiosyncrasies127        """128        child_dict = self._parse_xml_node(self._root)129        return {self._root.tag: child_dict["children"]}130    def _parse_xml_node(self, element):131        """132        rest of the processing133        """134        # process any tag attributes135        # if we have attributes then the child container is a Dict136        #   otherwise a List137        if element.items():138            child_container = {}139            child_container.update(dict(element.items()))140        else:141            child_container = []142        if isinstance(child_container, list) and element.text:143            # tag with no attributes and one that contains text144            child_container.append(element.text)145        else:146            # tag might have children, let's process them147            for child_elem in element.getchildren():148                child_dict = self._parse_xml_node(child_elem)149                # let's store our child based on container type150                #151                if isinstance(child_container, dict):152                    # these children are lone tag entities ( eg, 'copyright' )153                    child_container.update({child_dict["tag"]: child_dict["children"]})154                else:155                    # these children are repeated tag entities ( eg, 'format' )156                    child_container.append(child_dict["children"])...nexus.py
Source:nexus.py  
...30        self.fieldmap = dict()31        xmlroot = ElementTree.parse(32            os.path.join(os.path.dirname(__file__), "hdf5_cfg.xml")33        ).getroot()34        self._parse_xml_node(xmlroot, [])35    def _parse_xml_node(self, xmlnode, parents):36        """Add xmlnode to the ICAT field map recursively37        """38        if xmlnode.tag == "group":39            # HDF5 group40            if parents:41                parents[-1]["name"] = xmlnode.get("groupName")42                parents[-1]["nxdict"].update(self._iter_hdf5_attributes(xmlnode))43        elif xmlnode.tag == "link":44            # HDF5 link:45            if parents:46                linkname = xmlnode.get("groupName")47                linkdest = xmlnode.get("ref")48                parents[-1]["nxdict"][">" + linkname] = linkdest49        else:50            # HDF5 dataset51            m = self._ICAT_FIELD_REGEX.match(xmlnode.text)52            if m:53                dset_name = xmlnode.tag54                field_name = m.group(1)55                napitype = xmlnode.get("NAPItype")56                attrs = {57                    dset_name + k: v for k, v in self._iter_hdf5_attributes(xmlnode)58                }59                self.fieldmap[field_name] = {60                    "name": dset_name,61                    "nxdict": attrs,62                    "napitype": napitype,63                    "parents": parents,64                }65        # Recurse66        for xmlchildnode in xmlnode:67            if xmlchildnode.tag == "group":68                rparents = parents + [{"nxdict": {}}]69            else:70                rparents = parents71            self._parse_xml_node(xmlchildnode, rparents)72    @classmethod73    def _iter_hdf5_attributes(cls, xmlnode):74        """Get HDF5 attributes from an XML node75        """76        for aname, avalue in xmlnode.items():77            if aname in cls._NON_HDF5_ATTRIBUTES or aname.startswith("ESRF_"):78                continue79            yield "@" + aname, avalue80    @classmethod81    def _convert_nx_type(cls, value, napitype):82        """Nexus convert to the Nexus type as defined in the XML file83        """84        if napitype == "NX_CHAR" or napitype is None:85            return numpy.array(value, nxcharUnicode)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
