本文整理匯總了Python中xml.sax.saxutils.unescape方法的典型用法代碼示例。如果您正苦於以下問題:Python saxutils.unescape方法的具體用法?Python saxutils.unescape怎麽用?Python saxutils.unescape使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類xml.sax.saxutils
的用法示例。
在下文中一共展示了saxutils.unescape方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: getUniqueElementValueFromXmlString
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def getUniqueElementValueFromXmlString(xmlString, elementName):
"""
Extracts an element value from an XML string.
For example, invoking
getUniqueElementValueFromXmlString(
'<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>', 'foo')
should return the value 'bar'.
"""
xmlStringAsDom = xml.dom.minidom.parseString(xmlString)
elementsByName = xmlStringAsDom.getElementsByTagName(elementName)
elementValue = None
if len(elementsByName) > 0:
elementValue = elementsByName[0].toxml().replace(
'<' + elementName + '>', '').replace('</' + elementName + '>', '')
return unescape(elementValue)
示例2: __init__
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def __init__(self, name, req, attributes={}):
"""Construct a tag.
@param name: The name of the tag. Should be a string, generally
a short one.
@param attributes: Allow having initial set of attributes without
calling _save callback
"""
super().__init__(name)
self._name = saxutils.unescape(str(name))
self.req = req
self._save = None
self._attributes = {'name': self._name}
for key, value in attributes.items():
self.set_attribute(key, value)
self.viewcount = None
示例3: _email_html
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def _email_html(to, subject, body):
"""Sends an email including a textual representation of the HTML body.
The body must not contain <html> or <body> tags.
"""
mail_args = {
'body': saxutils.unescape(re.sub(r'<[^>]+>', r'', body)),
'html': '<html><body>%s</body></html>' % body,
'sender': 'no_reply@%s.appspotmail.com' % app_identity.get_application_id(),
'subject': subject,
}
try:
if to:
mail_args['to'] = to
mail.send_mail(**mail_args)
else:
mail.send_mail_to_admins(**mail_args)
return True
except mail_errors.BadRequestError:
return False
示例4: SendReport
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def SendReport(self, report):
"""Emails an exception report.
Args:
report: A string containing the report to send.
"""
subject = ('Daily exception report for app "%s", major version "%s"'
% (self.app_id, self.major_version))
report_text = saxutils.unescape(re.sub('<[^>]+>', '', report))
mail_args = {
'sender': self.sender,
'subject': subject,
'body': report_text,
'html': report,
}
if self.to:
mail_args['to'] = self.to
self.send_mail(**mail_args)
else:
self.send_mail_to_admins(**mail_args)
示例5: check_iscsi
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def check_iscsi(self, ref, name, host, port, scsiid, targetiqn, user, password):
sr = {"port": port,
"target": host,
"SCSIid": scsiid,
"targetIQN": targetiqn}
if user:
sr["chapuser"] = user
if password:
sr["chappassword"] = password
value = self.connection.Async.SR.probe(self.session_uuid, ref, sr, "lvmoiscsi", {})['Value']
task = self.connection.task.get_record(self.session_uuid, value)['Value']
while task["status"] == "pending":
task = self.connection.task.get_record(self.session_uuid, value)['Value']
result = saxutils.unescape(task['result']).replace("<value>", "").replace("</value>", "").replace(""", '"')
print result
dom = xml.dom.minidom.parseString(result)
nodes = dom.getElementsByTagName("UUID")
if len(nodes):
return nodes[0].childNodes[0].data.strip()
else:
return None
示例6: scan_nfs_vhd
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def scan_nfs_vhd(self, ref, list, host, path, options):
sr = {"serverpath": path,
"server": host,
"options": options}
value = self.connection.Async.SR.probe(self.session_uuid, ref, sr, "nfs", {})['Value']
task = self.connection.task.get_record(self.session_uuid, value)['Value']
while task["status"] == "pending":
task = self.connection.task.get_record(self.session_uuid, value)['Value']
if task['result'].count("<value>"):
result = saxutils.unescape(task['result']).replace("<value>", "").replace("</value>", "").replace(""", '"')
dom = xml.dom.minidom.parseString(result)
nodes = dom.getElementsByTagName("SRlist")
if len(nodes[0].childNodes):
for i in range(1, len(nodes[0].childNodes), 2):
ref = nodes[0].childNodes[i].childNodes[1].childNodes[0].data.strip()
if not self.search_storage_uuid(ref):
list.append([ref, ref])
if list.__len__() > 0:
return 2
else:
return 1
else:
self.wine.show_error_dlg(task["error_info"][2])
self.connection.task.destroy(self.session_uuid, value)
return 0
示例7: __init__
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def __init__(
self,
text,
style,
bulletText=None,
caseSensitive=1,
level=0,
snum=None,
parent_id=None,
node=None,
section_header_depth=2,
):
# Issue 114: need to convert "&" to "&" and such.
# Issue 140: need to make it plain text
self.stext = re.sub(r'<[^>]*?>', '', unescape(text))
self.stext = self.stext.strip()
self.level = int(level)
self.snum = snum
self.parent_id = parent_id
self.node = node
self.section_header_depth = section_header_depth
Paragraph.__init__(self, text, style, bulletText)
示例8: GetAttributeValue
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def GetAttributeValue(attr, extract=True):
"""
Function that extracts data from a tree node
@param attr: tree node containing data to extract
@param extract: attr is a tree node or not
@return: data extracted as string
"""
if not extract:
return attr
if len(attr.childNodes) == 1:
return text(unescape(attr.childNodes[0].data))
else:
# content is a CDATA
txt = u''
for node in attr.childNodes:
if not (node.nodeName == "#text" and node.data.strip() == u''):
txt += text(unescape(node.data))
return text
示例9: _formalize
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def _formalize(self, html):
html = html.replace("\r\n", " ").replace("\n", " ")
html = re.sub(r"[ \t]+", " ", html)
html = re.sub(r"[ ]*>[ ]*", ">", html)
html = re.sub(r"[ ]*<[ ]*", "<", html)
return unescape(html)
示例10: xml_unescape
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def xml_unescape(text):
"""
This function transforms the "escaped" version suitable
for well-formed XML formatting into humanly-readable string.
Note that the default xml.sax.saxutils.unescape() function don't unescape
some characters that Moses does so we have to manually add them to the
entities dictionary.
>>> from xml.sax.saxutils import unescape
>>> s = ')| & < > ' " ] ['
>>> expected = ''')| & < > \' " ] ['''
>>> xml_unescape(s) == expected
True
:param text: The text that needs to be unescaped.
:type text: str
:rtype: str
"""
return unescape(
text,
entities={
r"'": r"'",
r""": r'"',
r"|": r"|",
r"[": r"[",
r"]": r"]",
},
)
示例11: unescape
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def unescape(string):
"""
>>> unescape("one <![CDATA[two ]]>three")
'one two three'
"""
result = list()
for index, data in enumerate(cdata.split(string)):
if index % 3 != 2:
data = _unescape(data, {" ": " "})
result.append(data)
return "".join(result)
示例12: xml_unescape
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def xml_unescape(string):
if string is None:
return
return _xml_unescape(string)
示例13: anime
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def anime(self, ctx, *, name:str):
"""Searches MyAnimeList for the specified anime"""
await ctx.channel.trigger_typing()
r = requests.get("https://myanimelist.net/api/anime/search.xml?q={}".format(name), auth=requests.auth.HTTPBasicAuth(config._malUsername, config._malPassword))
if r.status_code == 401:
log.critical("The MyAnimeList credinals are incorrect, please check your MyAnimeList login information in the config.")
await ctx.send(Language.get("myanimelist.incorrect_creds", ctx))
return
try:
xmldoc = minidom.parseString(r.text)
except XmlParserErrors.ExpatError:
await ctx.send(Language.get("myanimelist.no_anime_found", ctx).format(name))
return
# pls no flame
anime = xmldoc.getElementsByTagName("entry")[0]
id = anime.getElementsByTagName("id")[0].firstChild.nodeValue
title = anime.getElementsByTagName("title")[0].firstChild.nodeValue
try:
english = anime.getElementsByTagName("english")[0].firstChild.nodeValue
except:
english = title
episodes = anime.getElementsByTagName("episodes")[0].firstChild.nodeValue
score = anime.getElementsByTagName("score")[0].firstChild.nodeValue
type = anime.getElementsByTagName("type")[0].firstChild.nodeValue
status = anime.getElementsByTagName("status")[0].firstChild.nodeValue
start_date = anime.getElementsByTagName("start_date")[0].firstChild.nodeValue
end_date = anime.getElementsByTagName("end_date")[0].firstChild.nodeValue
image = anime.getElementsByTagName("image")[0].firstChild.nodeValue
synopsis = saxutils.unescape(anime.getElementsByTagName("synopsis")[0].firstChild.nodeValue)
synopsis = remove_html(synopsis)
if len(synopsis) > 300:
synopsis = synopsis[:300] + "..."
url = "https://myanimelist.net/anime/{}".format(id)
fields = {Language.get("myanimelist.english_title", ctx):english, Language.get("myanimelist.episodes", ctx):episodes, Language.get("myanimelist.mal_line", ctx):score, Language.get("myanimelist.type", ctx):type, Language.get("myanimelist.status", ctx):status, Language.get("myanimelist.start_date", ctx):start_date, Language.get("myanimelist.end_date", ctx):end_date}
embed = make_list_embed(fields)
embed.title = title
embed.description = synopsis
embed.url = url
embed.color = 0xFF0000
embed.set_thumbnail(url=image)
await ctx.send(embed=embed)
示例14: render_resource
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def render_resource(path, **context):
"""
Render static resource using provided context.
Returns: django.utils.safestring.SafeText
"""
html = Template(resource_string(path))
return html_parser.unescape(
html.render(Context(context))
)
示例15: render_template
# 需要導入模塊: from xml.sax import saxutils [as 別名]
# 或者: from xml.sax.saxutils import unescape [as 別名]
def render_template(template_name, **context):
"""
Render static resource using provided context.
Returns: django.utils.safestring.SafeText
"""
template_dirs = [os.path.join(os.path.dirname(__file__), 'static/html')]
engine = Engine(dirs=template_dirs, debug=True)
html = engine.get_template(template_name)
return html_parser.unescape(
html.render(Context(context))
)