Python xml.sax.saxutils.unescape() Examples

The following are 30 code examples of xml.sax.saxutils.unescape(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.sax.saxutils , or try the search function .
Example #1
Source File: ui.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: xmlclass.py    From OpenPLC_Editor with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: flowables.py    From rst2pdf with MIT License 6 votes vote down vote up
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 "&amp;" 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) 
Example #4
Source File: flowables.py    From rst2pdf with MIT License 6 votes vote down vote up
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 "&amp;" 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) 
Example #5
Source File: oxcSERVER_storage.py    From openxenmanager with GNU General Public License v2.0 6 votes vote down vote up
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("&quot;", '"')
            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 
Example #6
Source File: oxcSERVER_storage.py    From openxenmanager with GNU General Public License v2.0 6 votes vote down vote up
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("&quot;", '"')
        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 
Example #7
Source File: report_generator.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
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) 
Example #8
Source File: ui.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 
Example #9
Source File: ui.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: ui.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 
Example #11
Source File: ui.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: util.py    From SalesforceXyTools with Apache License 2.0 6 votes vote down vote up
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) 
Example #13
Source File: tag.py    From gtg with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #14
Source File: util.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
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 = ')&#124; &amp; &lt; &gt; &apos; &quot; &#93; &#91;'
        >>> 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"&apos;": r"'",
            r"&quot;": r'"',
            r"&#124;": r"|",
            r"&#91;": r"[",
            r"&#93;": r"]",
        },
    ) 
Example #15
Source File: oxcSERVER_storage.py    From openxenmanager with GNU General Public License v2.0 5 votes vote down vote up
def reattach_and_introduce_hardware_hba(self, ref, uuid, name, path):
        res = self.connection.SR.introduce(self.session_uuid, self.stg_uuid, name, "Hardware HBA SR [%s]" % path, "lvmohba", "", False, {})
        pbd = {"uuid": "",
               "host": ref,
               "SR": res['Value'],
               "device_config": {"SCSIid": uuid},
               "currentyle_attached": False,
               "other_config": {}}

        res = self.connection.Async.PBD.create(self.session_uuid, pbd)
        if "Value" in res:
            self.track_tasks[res['Value']] = self.host_vm[ref][0]
            value = res['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("&quot;", '"')
            res = self.connection.Async.PBD.plug(self.session_uuid, result)
            value = res['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["status"] == "success":
                return 0
            else:
                self.wine.show_error_dlg(str(task["error_info"]))
                return 1
        else:
            print res 
Example #16
Source File: oxcSERVER_storage.py    From openxenmanager with GNU General Public License v2.0 5 votes vote down vote up
def reattach_hardware_hba(self, ref, uuid, name, path):
        ref = self.all['host'].keys()[0]
        pbd = {"uuid": "",
               "host": ref,
               "SR": self.stg_ref,
               "device_config": {"SCSIid": uuid},
               "currentyle_attached": False,
               "other_config": {}}
        self.connection.SR.set_name_label(self.session_uuid, self.stg_ref, name)
        self.connection.SR.set_name_description(self.session_uuid, self.stg_ref, "Hardware HBA SR [%s]" % path)
        res = self.connection.Async.PBD.create(self.session_uuid, pbd)
        if "Value" in res:
            self.track_tasks[res['Value']] = self.host_vm[ref][0]
            value = res['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("&quot;", '"')
            res = self.connection.Async.PBD.plug(self.session_uuid, result)
            value = res['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["status"] == "success":
                return 0
            else:
                self.wine.show_error_dlg(str(task["error_info"]))
                return 1
        else:
            print res 
Example #17
Source File: myanimelist.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
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) 
Example #18
Source File: pencil.py    From quiver with Apache License 2.0 5 votes vote down vote up
def xml_unescape(string):
    if string is None:
        return

    return _xml_unescape(string) 
Example #19
Source File: template.py    From wxGlade with MIT License 5 votes vote down vote up
def __init__(self, filename=None):
        self.author = ''
        self.description = ''
        self.instructions = ''
        self.filename = filename

        if filename is not None:
            filexml = minidom.parse(filename)
            # we have no use for all the xml data in the file. We only care
            # about what is between the "description" tags
            templatedata = filexml.getElementsByTagName('templatedata')
            if len(templatedata):
                desc_xml = templatedata[0]
                try:
                    self.author = saxutils.unescape( desc_xml.getElementsByTagName('author')[0].firstChild.data )
                except (IndexError, AttributeError): self.author = ''
                try:
                    self.description = saxutils.unescape(
                        desc_xml.getElementsByTagName('description')[0].firstChild.data )
                except (IndexError, AttributeError): self.description = ''
                try:
                    self.instructions = saxutils.unescape(
                        desc_xml.getElementsByTagName( 'instructions')[0].firstChild.data)
                except (IndexError, AttributeError): self.instructions = ''
            else:
                self.author = ''
                self.description=''
                self.instructions='' 
Example #20
Source File: unescaper.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unescape_all(url):
    """Recursively unescape a given URL.

    .. note:: '&amp;&amp;' becomes a single '&'.

    Parameters
    ----------
    url : str or bytes
        URL to unescape.

    Returns
    -------
    clean_url : str or bytes
        Unescaped URL.

    """
    if isinstance(url, bytes):
        func2use = _unescape_bytes
        keys2use = _bytes_keys
    else:
        func2use = _unescape_str
        keys2use = _str_keys
    clean_url = func2use(url)
    not_done = [clean_url.count(key) > 0 for key in keys2use]
    if True in not_done:
        return unescape_all(clean_url)
    else:
        return clean_url 
Example #21
Source File: unescaper.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _unescape_str(url):
    return saxutils.unescape(url, _str_entities) 
Example #22
Source File: oxcSERVER_storage.py    From openxenmanager with GNU General Public License v2.0 5 votes vote down vote up
def reattach_cifs_iso(self, sr, name, share, options, user="", password=""):
        ref = self.all['host'].keys()[0]
        pbd = {"uuid": "",
               "host": ref,
               "SR": sr,
               "device_config": {"location": share, "type": "cifs",
                                 "options": options},
               "currentyle_attached": False,
               "other_config": {}}
        self.connection.SR.set_name_label(self.session_uuid, sr, name)
        self.connection.SR.set_name_description(self.session_uuid, sr, "CIFS ISO Library [%s]" % share)
        res = self.connection.Async.PBD.create(self.session_uuid, pbd)
        if "Value" in res:
            self.track_tasks[res['Value']] = ref
            value = res['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("&quot;", '"')
            res = self.connection.Async.PBD.plug(self.session_uuid, result)
            value = res['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["status"] == "success":
                return 0
            else:
                self.wine.show_error_dlg(str(task["error_info"]))
                return 1
        else:
            print res 
Example #23
Source File: render.py    From pycbc with GNU General Public License v3.0 5 votes vote down vote up
def render_text(path, cp):
    """ Render a file as text.
    """

    # define filename and slug from path
    filename = os.path.basename(path)
    slug = filename.replace('.', '_')

    # initializations
    content = None

    # read file as a string
    with codecs.open(path, 'r', encoding='utf-8', errors='replace') as fp:
        content = fp.read()

    # replace all the escaped characters
    content = unescape(content, unescape_table)

    # render template
    template_dir = pycbc.results.__path__[0] + '/templates/files'
    env = Environment(loader=FileSystemLoader(template_dir))
    env.globals.update(abs=abs)
    env.globals.update(path_exists=os.path.exists)
    template = env.get_template('file_pre.html')
    context = {'filename' : filename,
               'slug'     : slug,
               'cp'       : cp,
               'content'  : content}
    output = template.render(context)

    return output 
Example #24
Source File: render.py    From pycbc with GNU General Public License v3.0 5 votes vote down vote up
def render_tmplt(path, cp):
    """ Render a file as text.
    """

    # define filename and slug from path
    filename = os.path.basename(path)
    slug = filename.replace('.', '_')

    # initializations
    content = None

    # read file as a string
    with open(path, 'r') as fp:
        content = fp.read()

    # replace all the escaped characters
    content = unescape(content, unescape_table)

    # render template
    template_dir = '/'.join(path.split('/')[:-1])
    env = Environment(loader=FileSystemLoader(template_dir))
    env.globals.update(setup_template_render=setup_template_render)
    env.globals.update(get_embedded_config=get_embedded_config)
    env.globals.update(path_exists=os.path.exists)
    template = env.get_template(filename)
    context = {'filename' : filename,
               'slug'     : slug,
               'cp'       : cp,
               'content'  : content}
    output = template.render(context)

    return output 
Example #25
Source File: metadata.py    From pycbc with GNU General Public License v3.0 5 votes vote down vote up
def handle_starttag(self, tag, attrs):
        attr= {}
        for key, value in attrs:
            attr[key] = value
        if tag == 'div' and 'class' in attr and attr['class'] == 'pycbc-meta':
            self.metadata[attr['key']] = unescape(attr['value'], unescape_table) 
Example #26
Source File: cleanmxbot.py    From abusehelper with MIT License 5 votes vote down vote up
def unescape(string):
    """
    >>> unescape("one&nbsp;<![CDATA[two&nbsp;]]>three")
    'one two&nbsp;three'
    """

    result = list()

    for index, data in enumerate(cdata.split(string)):
        if index % 3 != 2:
            data = _unescape(data, {"&nbsp;": " "})
        result.append(data)

    return "".join(result) 
Example #27
Source File: fancytitles.py    From rst2pdf with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        # The inicialization is taken from rst2pdf.flowables.Heading
        hstyle = kwargs.pop('hstyle')
        level = 0
        text = kwargs.pop('text')
        self.snum = kwargs.pop('snum')
        self.parent_id = kwargs.pop('parent_id')
        # self.stext =
        Heading.__init__(self, text, hstyle, level=level, parent_id=self.parent_id)
        # Cleanup title text
        # self.stext = re.sub(r'<[^>]*?>', '', unescape(self.stext))
        # self.stext = self.stext.strip()

        # Stuff needed for the outline entry
        MyImage.__init__(self, *args, **kwargs) 
Example #28
Source File: util.py    From sacremoses with MIT License 5 votes vote down vote up
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 = ')&#124; &amp; &lt; &gt; &apos; &quot; &#93; &#91;'
        >>> 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"&apos;": r"'",
            r"&quot;": r'"',
            r"&#124;": r"|",
            r"&#91;": r"[",
            r"&#93;": r"]",
        },
    ) 
Example #29
Source File: tableofcontents.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def unquote(txt):
    from xml.sax.saxutils import unescape
    return unescape(txt, {"&apos;": "'", "&quot;": '"'}) 
Example #30
Source File: oxcSERVER_storage.py    From openxenmanager with GNU General Public License v2.0 5 votes vote down vote up
def reattach_nfs_iso(self, sr, name, share, options):
        # FIXME
        ref = self.all['host'].keys()[0]
        pbd = {"uuid": "",
               "host": ref,
               "SR": sr,
               "device_config": {"location": share, "options": options},
               "currentyle_attached": False,
               "other_config": {}}
        self.connection.SR.set_name_label(self.session_uuid, sr, name)
        self.connection.SR.set_name_description(self.session_uuid, sr, "NFS ISO Library [%s]" % share)
        res = self.connection.Async.PBD.create(self.session_uuid, pbd)
        if "Value" in res:
            self.track_tasks[res['Value']] = ref
            value = res['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("&quot;", '"')
            res = self.connection.Async.PBD.plug(self.session_uuid, result)
            value = res['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["status"] == "success":
                return 0
            else:
                self.wine.show_error_dlg(str(task["error_info"]))
                return 1
        else:
            print res