domhelpers.py :  » Network » Twisted » Twisted-1.0.3 » Twisted-1.0.3 » twisted » web » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Network » Twisted 
Twisted » Twisted 1.0.3 » Twisted 1.0.3 » twisted » web » domhelpers.py
# -*- test-case-name: twisted.test.test_woven -*-
# Twisted, the Framework of Your Internet
# Copyright (C) 2001-2002 Matthew W. Lefkowitz
# 
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
# 
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
# 
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# 

from twisted.web import microdom
import cStringIO

class NodeLookupError(Exception): pass

def substitute(request, node, subs):
    """
    Look through the given node's children for strings, and
    attempt to do string substitution with the given parameter.
    """
    for child in node.childNodes:
        if hasattr(child, 'nodeValue') and child.nodeValue:
            child.replaceData(0, len(child.nodeValue), child.nodeValue % subs)
        substitute(request, child, subs)

def _get(node, nodeId, nodeAttrs=('id','class','model','pattern')):
    """
    (internal) Get a node with the specified C{nodeId} as any of the C{class},
    C{id} or C{pattern} attributes.
    """
    
    if hasattr(node, 'hasAttributes') and node.hasAttributes():
        for nodeAttr in nodeAttrs:
            if (str (node.getAttribute(nodeAttr)) == nodeId):
                return node
    if node.hasChildNodes():
        if hasattr(node.childNodes, 'length'):
            length = node.childNodes.length
        else:
            length = len(node.childNodes)
        for childNum in range(length):
            result = _get(node.childNodes[childNum], nodeId)
            if result: return result

def get(node, nodeId):
    """
    Get a node with the specified C{nodeId} as any of the C{class},
    C{id} or C{pattern} attributes. If there is no such node, raise
    L{NodeLookupError}.
    """
    result = _get(node, nodeId)
    if result: return result
    raise NodeLookupError, nodeId

def getIfExists(node, nodeId):
    """
    Get a node with the specified C{nodeId} as any of the C{class},
    C{id} or C{pattern} attributes.  If there is no such node, return
    C{None}.
    """
    return _get(node, nodeId)

def getAndClear(node, nodeId):
    """Get a node with the specified C{nodeId} as any of the C{class},
    C{id} or C{pattern} attributes. If there is no such node, raise
    L{NodeLookupError}. Remove all child nodes before returning.
    """
    result = get(node, nodeId)
    if result:
        clearNode(result)
    return result

def clearNode(node):
    """
    Remove all children from the given node.
    """
    node.childNodes[:] = []

def locateNodes(nodeList, key, value, noNesting=1):
    """
    Find subnodes in the given node where the given attribute
    has the given value.
    """
    returnList = []
    if not isinstance(nodeList, type([])):
        return locateNodes(nodeList.childNodes, key, value, noNesting)
    for childNode in nodeList:
        if not hasattr(childNode, 'getAttribute'):
            continue
        if str(childNode.getAttribute(key)) == value:
            returnList.append(childNode)
            if noNesting:
                continue
        returnList.extend(locateNodes(childNode, key, value, noNesting))
    return returnList
    
def superSetAttribute(node, key, value):
    if not hasattr(node, 'setAttribute'): return
    node.setAttribute(key, value)
    if node.hasChildNodes():
        for child in node.childNodes:
            superSetAttribute(child, key, value)

def superPrependAttribute(node, key, value):
    if not hasattr(node, 'setAttribute'): return
    old = node.getAttribute(key)
    if old:
        node.setAttribute(key, value+'/'+old)
    else:
        node.setAttribute(key, value)
    if node.hasChildNodes():
        for child in node.childNodes:
            superPrependAttribute(child, key, value)

def superAppendAttribute(node, key, value):
    if not hasattr(node, 'setAttribute'): return
    old = node.getAttribute(key)
    if old:
        node.setAttribute(key, old + '/' + value)
    else:
        node.setAttribute(key, value)
    if node.hasChildNodes():
        for child in node.childNodes:
            superAppendAttribute(child, key, value)

def getElementsByTagName(iNode, name):
    childNodes = iNode.childNodes[:]
    gathered = []
    while childNodes:
        node = childNodes.pop(0)
        if node.childNodes:
            [childNodes.insert(0, ch_node) for ch_node in node.childNodes]
        if node.nodeName == name:
            gathered.append(node)
    gathered.reverse()
    return gathered

def gatherTextNodes(iNode):
    """Visit each child node and collect its text data, if any, into a string.
For example::
    >>> doc=microdom.parseString('<a>1<b>2<c>3</c>4</b></a>')
    >>> gatherTextNodes(doc.documentElement)
    '1234'
@return: the gathered nodes as a single string
@rtype: str
"""
    childNodes = iNode.childNodes[:]
    gathered = []
    while childNodes:
        node = childNodes.pop(0)
        if node.childNodes:
            [childNodes.insert(0, ch_node) for ch_node in node.childNodes]
        if hasattr(node, 'nodeValue') and node.nodeValue is not None:
            gathered.append(node.nodeValue)
    gathered.reverse()
    return ''.join(gathered)


class RawText(microdom.Text):
    """This is an evil and horrible speed hack. Basically, if you have a big
    chunk of XML that you want to insert into the DOM, but you don't want to
    incur the cost of parsing it, you can construct one of these and insert it
    into the DOM. This will most certainly only work with microdom as the API
    for converting nodes to xml is different in every DOM implementation.

    This could be improved by making this class a Lazy parser, so if you
    inserted this into the DOM and then later actually tried to mutate this
    node, it would be parsed then.
    """

    def writexml(self, writer, indent="", addindent="", newl="", strip=0):
        writer.write("%s%s%s" % (indent, self.data, newl))

def findNodes(parent, matcher, accum=None):
    if accum is None:
        accum = []
    if not parent.hasChildNodes():
        return accum
    for child in parent.childNodes:
        # print child, child.nodeType, child.nodeName
        if matcher(child):
            accum.append(child)
        findNodes(child, matcher, accum)
    return accum

def findElements(parent, matcher):
    return findNodes(
        parent,
        lambda n, matcher=matcher: isinstance(n, microdom.Element) and
                                   matcher(n))

def findElementsWithAttribute(parent, attribute, value=None):
    if value:
        return findElements(
            parent,
            lambda n, attribute=attribute, value=value:
              n.hasAttribute(attribute) and n.getAttribute(attribute) == value)
    else:
        return findElements(
            parent,
            lambda n, attribute=attribute: n.hasAttribute(attribute))


def findNodesNamed(parent, name):
    return findNodes(parent, lambda n, name=name: n.nodeName == name)


def writeNodeData(node, oldio):
    for subnode in node.childNodes:
        if hasattr(subnode, 'data'):
            oldio.write(str(subnode.data))
        else:
            writeNodeData(subnode, oldio)


def getNodeText(node):
    oldio = cStringIO.StringIO()
    writeNodeData(node, oldio)
    return oldio.getvalue()

def getParents(node):
    l = []
    while node:
        l.append(node)
        node = node.parentNode
    return l
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.