本文整理汇总了Python中xml.parsers.expat.ExpatError方法的典型用法代码示例。如果您正苦于以下问题:Python expat.ExpatError方法的具体用法?Python expat.ExpatError怎么用?Python expat.ExpatError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.parsers.expat
的用法示例。
在下文中一共展示了expat.ExpatError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _handle_result
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [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
示例2: __init__
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def __init__(self, response, _message=None):
status = response.status
reason = response.reason
body = response.body.read()
try:
detail = XML(body).findtext("./messages/msg")
except ParseError as err:
detail = body
message = "HTTP %d %s%s" % (
status, reason, "" if detail is None else " -- %s" % detail)
Exception.__init__(self, _message or message)
self.status = status
self.reason = reason
self.headers = response.headers
self.body = body
self._response = response
示例3: __init__
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def __init__(self, response, _message=None):
status = response.status
reason = response.reason
body = (response.body.read()).decode()
try:
detail = XML(body).findtext("./messages/msg")
except ParseError as err:
detail = body
message = "HTTP %d %s%s" % (
status, reason, "" if detail is None else " -- %s" % detail)
Exception.__init__(self, _message or message)
self.status = status
self.reason = reason
self.headers = response.headers
self.body = body
self._response = response
示例4: send
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def send(self, command, *args, **kwargs):
"""Generic method for executing an XML-RPC *command*. *args* and
*kwargs* are the arguments and parameters needed by the command.
"""
args = list(args)
if kwargs:
args.append(kwargs)
method = self.proxy
for elt in command.split('.'):
method = getattr(method, elt)
try:
return method(*args)
except Fault as err:
if err.faultCode == 121:
return {}
elif err.faultCode == 321:
return []
raise DokuWikiError(err)
except ExpatError as err:
if str(err) != ERR:
raise DokuWikiError(err)
示例5: set
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def set(self, page, content, **options):
"""Set/replace the *content* of *page*.
Valid *options* are:
* *sum*: (str) change summary
* *minor*: (bool) whether this is a minor change
"""
try:
return self._dokuwiki.send('wiki.putPage', page, content, options)
except ExpatError as err:
# Sometime the first line of the XML response is blank which raise
# the 'ExpatError' exception although the change has been done. This
# allow to ignore the error.
if str(err) != ERR:
raise DokuWikiError(err)
示例6: _upload_instances
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def _upload_instances(self, path):
instances_count = 0
dirs, not_in_use = default_storage.listdir(path)
for instance_dir in dirs:
instance_dir_path = os.path.join(path, instance_dir)
i_dirs, files = default_storage.listdir(instance_dir_path)
xml_file = None
if 'submission.xml' in files:
file_obj = default_storage.open(
os.path.join(instance_dir_path, 'submission.xml'))
xml_file = file_obj
if xml_file:
try:
self._upload_instance(xml_file, instance_dir_path, files)
except ExpatError:
continue
except Exception:
pass
else:
instances_count += 1
return instances_count
示例7: CallFunction
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def CallFunction(self):
"""Calls the function via RPC."""
if self._xmlrpc_proxy is None:
return None
rpc_call = getattr(self._xmlrpc_proxy, self._RPC_FUNCTION_NAME, None)
if rpc_call is None:
return None
try:
return rpc_call() # pylint: disable=not-callable
except (
expat.ExpatError, SocketServer.socket.error,
xmlrpclib.Fault) as exception:
logger.warning('Unable to make RPC call with error: {0!s}'.format(
exception))
return None
示例8: _from_xml
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def _from_xml(self, datastring):
if datastring is None:
return None
plurals = set(self.metadata.get('plurals', {}))
try:
node = etree.fromstring(datastring)
root_tag = self._get_key(node.tag)
links = self._get_links(root_tag, node)
result = self._from_xml_node(node, plurals)
if root_tag == constants.VIRTUAL_ROOT_KEY:
return result
return dict({root_tag: result}, **links)
except Exception as e:
parseError = False
if (hasattr(etree, 'ParseError') and
isinstance(e, getattr(etree, 'ParseError'))):
parseError = True
elif isinstance(e, expat.ExpatError):
parseError = True
if parseError:
msg = _("Cannot understand XML")
raise exception.MalformedResponseBody(reason=msg)
else:
raise
示例9: setOutputFile
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def setOutputFile(self):
'''
Initiates the xml file from the configuration.
'''
if (conf.xmlFile):
try:
self._outputFile = conf.xmlFile
self.__root = None
if os.path.exists(self._outputFile):
try:
self.__doc = xml.dom.minidom.parse(self._outputFile)
self.__root = self.__doc.childNodes[0]
except ExpatError:
self.__doc = Document()
self._outputFP = codecs.open(self._outputFile, "w+", UNICODE_ENCODING)
if self.__root is None:
self.__root = self.__doc.createElementNS(NAME_SPACE_ATTR, RESULTS_ELEM_NAME)
self.__root.setAttributeNode(self._createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR))
self.__root.setAttributeNode(self._createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME))
self.__doc.appendChild(self.__root)
except IOError:
raise SqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile)
示例10: read_nfofile
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def read_nfofile(filename):
if not xbmcvfs.exists(filename):
return None
with closing(xbmcvfs.File(filename)) as nfofile:
try:
return ET.parse(nfofile).getroot()
except ParseError:
pass
# maybe it's all XML except the last line, like the wiki suggests for XML + URL
nfofile.seek(0, 0)
lines = nfofile.read().split('\n')
while lines and not lines[-1].strip():
del lines[-1] # Remove final blank lines
if lines: # Remove the line that possibly contains the URL
del lines[-1]
if lines:
try:
return ET.XML('\n'.join(lines))
except ParseError:
pass
示例11: make_sparse_image
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def make_sparse_image(volume_name, output_path):
'''Make a sparse disk image we can install a product to'''
cmd = ['/usr/bin/hdiutil', 'create', '-size', '16g', '-fs', 'HFS+',
'-volname', volume_name, '-type', 'SPARSE', '-plist', output_path]
try:
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError as err:
print(err, file=sys.stderr)
exit(-1)
try:
return read_plist_from_string(output)[0]
except IndexError as err:
print('Unexpected output from hdiutil: %s' % output, file=sys.stderr)
exit(-1)
except ExpatError as err:
print('Malformed output from hdiutil: %s' % output, file=sys.stderr)
print(err, file=sys.stderr)
exit(-1)
示例12: parse_server_metadata
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def parse_server_metadata(filename):
'''Parses a softwareupdate server metadata file, looking for information
of interest.
Returns a dictionary containing title, version, and description.'''
title = ''
vers = ''
try:
md_plist = read_plist(filename)
except (OSError, IOError, ExpatError) as err:
print('Error reading %s: %s' % (filename, err), file=sys.stderr)
return {}
vers = md_plist.get('CFBundleShortVersionString', '')
localization = md_plist.get('localization', {})
preferred_localization = (localization.get('English') or
localization.get('en'))
if preferred_localization:
title = preferred_localization.get('title', '')
metadata = {}
metadata['title'] = title
metadata['version'] = vers
return metadata
示例13: readXML
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def readXML(xmlfile, expectedRootTag=None):
"""
Read in XML data from a file and parse into ElementTree. Optionally verify
the root node is what we expect.
@param xmlfile: file to read from
@type xmlfile: C{File}
@param expectedRootTag: root tag (qname) to test or C{None}
@type expectedRootTag: C{str}
@return: C{tuple} of C{ElementTree}, C{Element}
"""
# Read in XML
try:
etree = XML.ElementTree(file=xmlfile)
except XMLParseError, e:
raise ValueError("Unable to parse file '%s' because: %s" % (xmlfile, e,))
示例14: convert_result
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def convert_result(self, result):
if self.conversion_method == "none" or "result" not in result:
return result
try:
if self.conversion_method == "text":
result["result"] = str(result["result"])
elif self.conversion_method == "json":
result["result"] = loads(result["result"])
elif self.conversion_method == "xml":
result["result"] = parse(result["result"])
except (ExpatError, JSONDecodeError) as exc:
result = {
"success": False,
"text_response": result,
"error": f"Conversion to {self.conversion_method} failed",
"exception": str(exc),
}
return result
示例15: _get_properties
# 需要导入模块: from xml.parsers import expat [as 别名]
# 或者: from xml.parsers.expat import ExpatError [as 别名]
def _get_properties(self):
"""Get the properties of the download center."""
request_xml = """
<App_DCGetDataToCreatePackageReq getListOfUsers="1"
getListOfGroups="1" getCategories="1" getSubCategories="1"
getPlatforms="1" getDownloadTypes="1" getProductVersions="1"
getRecutNumbers="1" getVendors="1" getDownloadedPackageUsers="1"
packageId="1" getServerTypes="1"/>
"""
flag, response = self._cvpysdk_object.make_request(
'POST', self._services['GET_DC_DATA'], request_xml
)
if flag:
try:
self._response = response.json()
except ExpatError:
raise SDKException('DownloadCenter', '101', response.text)
else:
response_string = self._update_response_(response.text)
raise SDKException('Response', '101', response_string)