当前位置: 首页>>代码示例>>Python>>正文


Python xmltodict.parse方法代码示例

本文整理汇总了Python中xmltodict.parse方法的典型用法代码示例。如果您正苦于以下问题:Python xmltodict.parse方法的具体用法?Python xmltodict.parse怎么用?Python xmltodict.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在xmltodict的用法示例。


在下文中一共展示了xmltodict.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _handle_result

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def _handle_result(self, res):
        res.encoding = "utf-8-sig"
        xml = res.text
        logger.debug("Response from WeChat API \n %s", xml)
        try:
            data = xmltodict.parse(xml)["xml"]
        except (xmltodict.ParsingInterrupted, ExpatError):
            # 解析 XML 失败
            logger.debug("WeChat payment result xml parsing error", exc_info=True)
            return xml

        return_code = data["return_code"]
        return_msg = data.get("return_msg", data.get("retmsg"))
        result_code = data.get("result_code", data.get("retcode"))
        errcode = data.get("err_code")
        errmsg = data.get("err_code_des")
        if return_code != "SUCCESS" or result_code != "SUCCESS":
            # 返回状态码不为成功
            raise WeChatPayException(
                return_code, result_code, return_msg, errcode, errmsg, client=self, request=res.request, response=res,
            )
        return data 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:24,代码来源:__init__.py

示例2: parse_message

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def parse_message(self, msg, msg_signature, timestamp, nonce):
        """
        处理 wechat server 推送消息

        :params msg: 加密内容
        :params msg_signature: 消息签名
        :params timestamp: 时间戳
        :params nonce: 随机数
        """
        content = self.crypto.decrypt_message(msg, msg_signature, timestamp, nonce)
        message = xmltodict.parse(to_text(content))["xml"]
        message_type = message["InfoType"].lower()
        message_class = COMPONENT_MESSAGE_TYPES.get(message_type, ComponentUnknownMessage)
        msg = message_class(message)
        if msg.type == "component_verify_ticket":
            self.session.set(msg.type, msg.verify_ticket)
        elif msg.type in ("authorized", "updateauthorized"):
            msg.query_auth_result = self.query_auth(msg.authorization_code)
        return msg 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:21,代码来源:component.py

示例3: get_timestamp_from_date_string

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def get_timestamp_from_date_string(date_string):
    """ parse a date string into unix epoch (ms) """
    if 'strip_tz' in agent_config_vars and agent_config_vars['strip_tz']:
        date_string = ''.join(agent_config_vars['strip_tz_fmt'].split(date_string))

    if 'timestamp_format' in agent_config_vars:
        if agent_config_vars['timestamp_format'] == 'epoch':
            timestamp_datetime = get_datetime_from_unix_epoch(date_string)
        else:
            timestamp_datetime = datetime.strptime(date_string, agent_config_vars['timestamp_format'])
    else:
        try:
            timestamp_datetime = dateutil.parse.parse(date_string)
        except:
            timestamp_datetime = get_datetime_from_unix_epoch(date_string)
            agent_config_vars['timestamp_format'] = 'epoch'

    return get_timestamp_from_datetime(timestamp_datetime) 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:20,代码来源:getlogs_evtx.py

示例4: _add_batch

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def _add_batch(self, catalog_entry, job_id, start_date, order_by_clause=True):
        endpoint = "job/{}/batch".format(job_id)
        url = self.bulk_url.format(self.sf.instance_url, endpoint)

        body = self.sf._build_query_string(catalog_entry, start_date, order_by_clause=order_by_clause)

        headers = self._get_bulk_headers()
        headers['Content-Type'] = 'text/csv'

        with metrics.http_request_timer("add_batch") as timer:
            timer.tags['sobject'] = catalog_entry['stream']
            resp = self.sf._make_request('POST', url, headers=headers, body=body)

        batch = xmltodict.parse(resp.text)

        return batch['batchInfo']['id'] 
开发者ID:singer-io,项目名称:tap-salesforce,代码行数:18,代码来源:bulk.py

示例5: _url_status

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def _url_status(url):
    parse_obj = urllib.parse.urlparse(url)

    timer = 1
    for i in range(6):
        try:
            connection = http.client.HTTPConnection(parse_obj.netloc)
            connection.request('HEAD', parse_obj.path)
            break
        except Exception as e:
            print(url, e, 'sleep', timer)
            time.sleep(timer)
            timer *= 2
    else:
        return e

    response = connection.getresponse()
    connection.close()
    return response.status 
开发者ID:airware,项目名称:buzzard,代码行数:21,代码来源:example_tools.py

示例6: generate_references

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def generate_references(self):
        self.zip_file = zipfile.ZipFile(
            self.book_filename, mode='r', allowZip64=True)
        self.file_list = self.zip_file.namelist()

        # Book structure relies on parsing the .opf file
        # in the book. Now that might be the usual content.opf
        # or package.opf or it might be named after your favorite
        # eldritch abomination. The point is we have to check
        # the container.xml
        container = self.find_file('container.xml')
        if container:
            container_xml = self.zip_file.read(container)
            container_dict = xmltodict.parse(container_xml)
            packagefile = container_dict['container']['rootfiles']['rootfile']['@full-path']
        else:
            presumptive_names = ('content.opf', 'package.opf', 'volume.opf')
            for i in presumptive_names:
                packagefile = self.find_file(i)
                if packagefile:
                    logger.info('Using presumptive package file: ' + self.book_filename)
                    break

        packagefile_data = self.zip_file.read(packagefile)
        self.opf_dict = xmltodict.parse(packagefile_data) 
开发者ID:BasioMeusPuga,项目名称:Lector,代码行数:27,代码来源:read_epub.py

示例7: get_chapter_content

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def get_chapter_content(self, chapter_file):
        this_file = self.find_file(chapter_file)
        if this_file:
            chapter_content = self.zip_file.read(this_file).decode()

            # Generate a None return for a blank chapter
            # These will be removed from the contents later
            contentDocument = QtGui.QTextDocument(None)
            contentDocument.setHtml(chapter_content)
            contentText = contentDocument.toPlainText().replace('\n', '')
            if contentText == '':
                chapter_content = None

            return chapter_content
        else:
            return 'Possible parse error: ' + chapter_file 
开发者ID:BasioMeusPuga,项目名称:Lector,代码行数:18,代码来源:read_epub.py

示例8: _createWorkitem

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def _createWorkitem(self, url_post, workitem_raw):
        headers = copy.deepcopy(self.headers)
        headers['Content-Type'] = self.OSLC_CR_XML

        resp = self.post(url_post, verify=False,
                         headers=headers, proxies=self.proxies,
                         data=workitem_raw)

        raw_data = xmltodict.parse(resp.content)
        workitem_raw = raw_data["oslc_cm:ChangeRequest"]
        workitem_id = workitem_raw["dc:identifier"]
        workitem_url = "/".join([self.url,
                                 "oslc/workitems/%s" % workitem_id])
        new_wi = Workitem(workitem_url,
                          self,
                          workitem_id=workitem_id,
                          raw_data=raw_data["oslc_cm:ChangeRequest"])

        self.log.info("Successfully create <Workitem %s>" % new_wi)
        return new_wi 
开发者ID:dixudx,项目名称:rtcclient,代码行数:22,代码来源:client.py

示例9: get_qos_class_map

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def get_qos_class_map(netconf_handler):
    '''
    This procedure takes in the netconf handler for the switch and read what is the QoS Softmax Multiplier
    Procedure returns True if configuration successful, else returns False
    '''

    netconf_reply = netconf_handler.get_config( source='running', filter=('xpath', "/native/policy/class-map"))

    data = xmltodict.parse(netconf_reply.xml)
    #print (data)
   
    class_map_names = [] 
    for cmap in (data["rpc-reply"]["data"]["native"]["policy"]["class-map"]):
        class_map_names.append(cmap["name"])


    return class_map_names 
开发者ID:CiscoDevNet,项目名称:catalyst9k-network-automation,代码行数:19,代码来源:QoS.py

示例10: get_qos_policy_map

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def get_qos_policy_map(netconf_handler):
    '''
    This procedure takes in the netconf handler for the switch and read what is the QoS Softmax Multiplier
    Procedure returns True if configuration successful, else returns False
    '''

    netconf_reply = netconf_handler.get_config( source='running', filter=('xpath', "/native/policy/policy-map"))

    data = xmltodict.parse(netconf_reply.xml)

    policy_map_names = [] 
    for pmap in (data["rpc-reply"]["data"]["native"]["policy"]["policy-map"]):
        if (pmap["name"]) != "system-cpp-policy":
            class_maps_in_policy = "  Contains Class maps: " 
            for cmap in (pmap["class"]):
                class_maps_in_policy = class_maps_in_policy + cmap["name"] + "  "
            policy_map_names.append("Policy map: " + pmap["name"] + class_maps_in_policy) 

    return policy_map_names 
开发者ID:CiscoDevNet,项目名称:catalyst9k-network-automation,代码行数:21,代码来源:QoS.py

示例11: get_pytornado_settings_from_CPACS

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def get_pytornado_settings_from_CPACS(cpacs_in_path):
    """ Try to read PyTornado settings from CPACS

    Note:
        * Returns None if PyTornado settings not found in CPACS

    Args:
        cpacs_in_path (str): Path to CPACS file

    Returns:
        cpacs_settings (dict): PyTornado settings dictionary read from CPACS
    """

    with open(cpacs_in_path, "r") as fp:
        cpacs_as_dict = xml.parse(fp.read())
    cpacs_settings = cpacs_as_dict.get('cpacs', {}).get('toolspecific', {}).get('pytornado', None)
    parse_pytornado_settings_dict(cpacs_settings)
    return cpacs_settings 
开发者ID:cfsengineering,项目名称:CEASIOMpy,代码行数:20,代码来源:runpytornado.py

示例12: get_external_ip

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def get_external_ip(soap_url) -> str:
    """get external ip address"""
    s_o_a_p = '<?xml version="1.0"?>\r\n'
    s_o_a_p += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle=' \
               '"http://schemas.xmlsoap.org/soap/encoding/">\r\n'
    s_o_a_p += '<s:Body>\r\n'
    s_o_a_p += '<u:GetExternalIPAddress xmlns:u="urn:schemas-upnp-org:service:WANPPPConnection:1">\r\n'
    s_o_a_p += '</u:GetExternalIPAddress>\r\n'
    s_o_a_p += '</s:Body>\r\n'
    s_o_a_p += '</s:Envelope>\r\n'

    try:
        req = Request(soap_url)
        req.add_header('Content-Type', 'text/xml; charset="utf-8"')
        req.add_header('SOAPACTION', '"urn:schemas-upnp-org:service:WANPPPConnection:1#GetExternalIPAddress"')
        req.data = s_o_a_p.encode('utf8')
        result = xmltodict.parse(urlopen(req).read().decode())
        return result['s:Envelope']['s:Body']['u:GetExternalIPAddressResponse']['NewExternalIPAddress']
    except Exception:
        log.debug("get_external_ip exception", exc_info=True) 
开发者ID:namuyan,项目名称:p2p-python,代码行数:22,代码来源:upnpc.py

示例13: __init__

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def __init__(self, file_name):
        self.data = []

        content = open(file_name, encoding="utf-8").read()

        is_test_file = file_name.split("/")[-1] == "testdata_with_lex.xml"

        structure = xmltodict.parse(content)
        for i, entry in enumerate(structure["benchmark"]["entries"]["entry"]):
            triplets = [tuple(map(str.strip, r.split("|"))) for r in
                        self.triplets_from_object(entry["modifiedtripleset"], "mtriple")]
            sentences = list(self.extract_sentences(entry["lex"]))

            for s in sentences:
                info = {
                    "id": i,
                    "seen": not is_test_file or i <= 970,
                    "manual": is_test_file and i + 1 in FOR_MANUAL_EVAL and i <= 970
                }
                self.data.append(Datum(rdfs=triplets, text=s, info=info)) 
开发者ID:AmitMY,项目名称:chimera,代码行数:22,代码来源:reader.py

示例14: parse_nmap_xml

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def parse_nmap_xml(nmap_output_file, protocol):
    targets = []

    with open(nmap_output_file, 'r') as file_handle:
        scan_output = xmltodict.parse(file_handle.read())

    for host in scan_output['nmaprun']['host']:
        if host['address'][0]['@addrtype'] != 'ipv4':
            continue

        ip = host['address'][0]['@addr']
        for port in host['ports']['port']:
            if port['state']['@state'] == 'open':
                if 'service' in port and (port['service']['@name'] in protocol_dict[protocol]['services']):
                    if ip not in targets:
                        targets.append(ip)
                elif port['@portid'] in protocol_dict[protocol]['ports']:
                    if ip not in targets:
                        targets.append(ip)

    return targets 
开发者ID:byt3bl33d3r,项目名称:CrackMapExec,代码行数:23,代码来源:nmap.py

示例15: _fetch_sandbox_api_key

# 需要导入模块: import xmltodict [as 别名]
# 或者: from xmltodict import parse [as 别名]
def _fetch_sandbox_api_key(self):
        nonce_str = random_string(32)
        sign = calculate_signature({"mch_id": self.mch_id, "nonce_str": nonce_str}, self.api_key)
        payload = dict_to_xml({"mch_id": self.mch_id, "nonce_str": nonce_str,}, sign=sign)
        headers = {"Content-Type": "text/xml"}
        api_url = f"{self.API_BASE_URL}sandboxnew/pay/getsignkey"
        response = self._http.post(api_url, data=payload, headers=headers)
        return xmltodict.parse(response.text)["xml"].get("sandbox_signkey") 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:10,代码来源:__init__.py


注:本文中的xmltodict.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。