[Python-modules-commits] [dominate] 01/15: import dominate_2.1.5.orig.tar.gz

Ross Gammon ross-guest at moszumanska.debian.org
Thu Mar 16 18:33:04 UTC 2017


This is an automated email from the git hooks/post-receive script.

ross-guest pushed a commit to branch master
in repository dominate.

commit edaaeca4c48f16cbb9307f2d799e06d237d83fc9
Author: Ross Gammon <rossgammon at mail.dk>
Date:   Mon Aug 24 19:38:16 2015 +0200

    import dominate_2.1.5.orig.tar.gz
---
 .gitignore              |   38 ++
 LICENSE.txt             |  165 ++++++++
 MANIFEST.in             |    1 +
 README.md               |  341 ++++++++++++++++
 dominate/__init__.py    |    3 +
 dominate/document.py    |   75 ++++
 dominate/dom1core.py    |   68 ++++
 dominate/dom_tag.py     |  423 +++++++++++++++++++
 dominate/tags.py        | 1032 +++++++++++++++++++++++++++++++++++++++++++++++
 dominate/util.py        |  158 ++++++++
 setup.py                |   48 +++
 tests/old/__init__.py   |   25 ++
 tests/old/attributes.py |   42 ++
 tests/old/rendering.py  |   61 +++
 tests/test_document.py  |   76 ++++
 tests/test_dom1core.py  |   16 +
 tests/test_html.py      |  150 +++++++
 17 files changed, 2722 insertions(+)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..15cc315
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,38 @@
+*.py[cod]
+
+# C extensions
+*.so
+
+# Packages
+*.egg
+*.egg-info
+dist
+build
+eggs
+parts
+bin
+var
+sdist
+develop-eggs
+.installed.cfg
+lib
+lib64
+__pycache__
+
+# Installer logs
+pip-log.txt
+
+# Unit test / coverage reports
+.coverage
+.tox
+nosetests.xml
+
+# Translations
+*.mo
+
+# Mr Developer
+.mr.developer.cfg
+.project
+.pydevproject
+*.sublime-workspace
+*.sublime-project
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..cca7fc2
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,165 @@
+		   GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..bb3ec5f
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1 @@
+include README.md
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e86d7b1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,341 @@
+Dominate
+========
+
+`Dominate` is a Python library for creating and manipulating HTML documents using an elegant DOM API.
+It allows you to write HTML pages in pure Python very concisely, which eliminate the need to learn another template language, and to take advantage of the more powerful features of Python.
+
+
+Compatability
+-------------
+
+`Dominate` is compatable with both Python 2.7 and Python 3.3. There are known issues with Python 3.2 and below.
+
+Installation
+------------
+
+The recommended way to install `dominate` is with
+[`pip`](http://pypi.python.org/pypi/pip/):
+
+    sudo pip install dominate
+
+
+Developed By
+------------
+
+* Tom Flanagan - <tom at zkpq.ca>
+* Jake Wharton - <jakewharton at gmail.com>
+* [Brad Janke](//github.com/bradj)
+
+Git repository located at
+[github.com/Knio/dominate](//github.com/Knio/dominate)
+
+
+Examples
+========
+
+All examples assume you have imported the appropriate tags or entire tag set (i.e. `from dominate.tags import *`).
+
+
+Hello, World!
+-------------
+
+The most basic feature of `dominate` exposes a class for each HTML element, where the constructor
+accepts child elements, text, or keyword attributes. `dominate` nodes return their HTML representation
+from the `__str__`, `__unicode__`, and `render()` methods.
+
+    >>> print html(body(h1('Hello, World!')))
+    <html>
+      <body>
+        <h1>Hello, World!</h1>
+      </body>
+    </html>
+
+
+Attributes
+----------
+
+`Dominate` can also use keyword arguments to append attributes onto your tags. Most of the attributes are a direct copy from the HTML spec with a few variations.
+
+Use `cls` for class names and `fr` for `for` in label elements. `cls` and `fr` are used because `class` and `for` in python are [reserved keyword](http://docs.python.org/2/reference/lexical_analysis.html#keywords "Reserved Keywords").
+
+    >>> test = label(cls='classname anothername', fr='someinput')
+    >>> print test
+    <label class="classname anothername" for="someinput">
+    </label>
+
+Use `data_*` for [custom HTML5 data attributes](http://www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes "HTML5 Data Attributes").
+
+    >>> test = div(data_employee='101011')
+    >>> print test
+    <div data-employee="101011">
+    </div>
+
+You can also modify the attributes of tags through a dictionary-like interface:
+
+    >>> header = div()
+    >>> header['id'] = 'header'
+    >>> print header
+    <div id="header"></div>
+
+
+Complex Structures
+------------------
+
+Through the use of the `+=` operator and the `.add()` method you can easily create more advanced structures.
+
+Create a simple list:
+
+    >>> list = ul()
+    >>> for item in range(4):
+    ...   list += li('Item #', item)
+    ...
+    >>> print list
+    <ul>
+      <li>Item #0</li>
+      <li>Item #1</li>
+      <li>Item #2</li>
+      <li>Item #3</li>
+    </ul>
+
+If you are using a database or other backend to fetch data, `dominate` supports iterables to help streamline your code:
+
+    >>> print ul(li(a(name, href=link), __inline=True) for name, link in menu_items)
+    <ul>
+      <li><a href="/home/">Home</a></li>
+      <li><a href="/about/">About</a></li>
+      <li><a href="/downloads/">Downloads</a></li>
+      <li><a href="/links/">Links</a></li>
+    </ul>
+
+A simple document tree:
+
+    >>> _html = html()
+    >>> _body = _html.add(body())
+    >>> header  = _body.add(div(id='header'))
+    >>> content = _body.add(div(id='content'))
+    >>> footer  = _body.add(div(id='footer'))
+    >>> print _html
+    <html>
+      <body>
+        <div id="header"></div>
+        <div id="content"></div>
+        <div id="footer"></div>
+      </body>
+    </html>
+
+For clean code, the `.add()` method returns children in tuples. The above example can be cleaned up and expanded like this:
+
+    >>> _html = html()
+    >>> _head, _body = _html.add(head(title('Simple Document Tree')), body())
+    >>> names = ['header', 'content', 'footer']
+    >>> header, content, footer = _body.add(div(id=name) for name in names)
+    >>> print _html
+    <html>
+      <head>
+        <title>Simple Document Tree</title>
+      </head>
+      <body>
+        <div id="header"></div>
+        <div id="content"></div>
+        <div id="footer"></div>
+      </body>
+    </html>
+
+You can modify the attributes of tags through a dictionary-like interface:
+
+    >>> header = div()
+    >>> header['id'] = 'header'
+    >>> print header
+    <div id="header"></div>
+
+Or the children of a tag though an array-line interface:
+
+    >>> header = div('Test')
+    >>> header[0] = 'Hello World'
+    >>> print header
+    <div>Hello World</div>
+
+
+Comments can be created using objects too!
+
+    >>> print comment('BEGIN HEADER')
+    <!--BEGIN HEADER-->
+    >>> print comment(p('Upgrade to newer IE!'), condition='lt IE9')
+    <!--[if lt IE9]>
+    <p>Upgrade to newer IE!</p>
+    <![endif]-->
+
+
+Context Managers
+----------------
+
+You can also add child elements using Python's `with` statement:
+
+    >>> h = ul()
+    >>> with h:
+    ...   li('One')
+    ...   li('Two')
+    ...   li('Three')
+    ...
+    >>>
+    >>> print h
+    <ul>
+      <li>One</li>
+      <li>Two</li>
+      <li>Three</li>
+    </ul>
+
+
+You can use this along with the other mechanisms of adding children elements, including nesting `with` statements, and it works as expected:
+
+    >>> h = html()
+    >>> with h.add(body()).add(div(id='content')):
+    ...   h1('Hello World!')
+    ...   p('Lorem ipsum ...')
+    ...   with table().add(tbody()):
+    ...     l = tr()
+    ...     l += td('One')
+    ...     l.add(td('Two'))
+    ...     with l:
+    ...       td('Three')
+    ...
+    >>>
+    >>> print h
+    <html>
+      <body>
+        <div id="content">
+          <h1>Hello World!</h1>
+          <p>Lorem ipsum ...</p>
+          <table>
+            <tbody>
+              <tr>
+                <td>One</td>
+                <td>Two</td>
+                <td>Three</td>
+              </tr>
+            </tbody>
+          </table>
+        </div>
+      </body>
+    </html>
+
+
+When the context is closed, any nodes that were not already added to something get added to the current context.
+
+Attributes can be added to the current context with the `attr` function:
+
+    >>> d = div()
+    >>> with d:
+    ...   attr(id='header')
+    ...
+    >>>
+    >>> print d
+    <div id="header"></div>
+
+
+Decorators
+----------
+
+`Dominate` is great for creating reusable widgets for parts of your page. Consider this example:
+
+    >>> def greeting(name):
+    ...     with div() as d:
+    ...         p('Hello, %s' % name)
+    ...     return d
+    ...
+    ...
+    >>> print greeting('Bob')
+    <div>
+      <p>Hello, Bob</p>
+    </div>
+    >>>
+
+You can see the following pattern being repeated here:
+
+    def widget(parameters):
+      with tag() as t:
+          ...
+      return t
+
+This boilerplate can be avoided by using tags (objects and instances) as decorators
+
+    >>> @div
+    ... def greeting(name):
+    ...     p('Hello %s' % name)
+    ...
+    ...
+    >>> print greeting('Bob')
+    <div>
+      <p>Hello Bob</p>
+    </div>
+    >>>
+
+The decorated function will return a new instance of the tag used to decorate it, and execute in a `with` context which will collect all the nodes created inside it.
+
+You can also use instances of tags as decorators, if you need to add attributes or other data to the root node of the widget.
+Each call to the decorated function will return a copy of the node used to decorate it.
+
+    >>> @div(h2('Welcome'), cls='greeting')
+    ... def greeting(name):
+    ...     p('Hello %s' % name)
+    ...
+    ...
+    >>> print greeting('Bob')
+    <div class="greeting">
+      <h2>Welcome</h2>
+      <p>Hello Bob</p>
+    </div>
+    >>>
+
+
+
+Creating Documents
+------------------
+
+Since creating the common structure of an HTML document everytime would be excessively tedious dominate provides a class to create an manage them for you, `document`.
+
+When you create a new document, the basic HTML tag structure is created for you.
+
+    >>> d = document()
+    >>> print d
+    <!DOCTYPE html>
+    <html>
+      <head>
+        <title>Dominate</title>
+      </head>
+      <body></body>
+    </html>
+
+The `document` class accepts `title`, `doctype`, and `request` keyword arguments.
+The default values for these arguments are `Dominate`, `<!DOCTYPE html>`, and `None` respectively.
+
+The `document` class also provides helpers to allow you to access the `html`, `head`, and `body` nodes directly.
+
+    >>> d = document()
+    >>> d.html
+    <dominate.tags.html: 0 attributes, 2 children>
+    >>> d.head
+    <dominate.tags.head: 0 attributes, 0 children>
+    >>> d.body
+    <dominate.tags.body: 0 attributes, 0 children>
+
+You should notice that here the `head` tag contains zero children.
+This is because the default `title` tag is only added when the document is rendered and the `head` element already does not explicitly contain one.
+
+The `document` class also provides helpers to allow you to directly add nodes to the `body` tag.
+
+    >>> d = document()
+    >>> d += h1('Hello, World!')
+    >>> d += p('This is a paragraph.')
+    >>> print d
+    <!DOCTYPE html>
+    <html>
+      <head>
+        <title>Dominate</title>
+      </head>
+      <body>
+        <h1>Hello, World!</h1>
+        <p>This is a paragraph.</p>
+      </body>
+    </html>
+
diff --git a/dominate/__init__.py b/dominate/__init__.py
new file mode 100644
index 0000000..d32fd3e
--- /dev/null
+++ b/dominate/__init__.py
@@ -0,0 +1,3 @@
+version = __version__ = '2.1.5'
+
+from .document import document
diff --git a/dominate/document.py b/dominate/document.py
new file mode 100644
index 0000000..22dc81c
--- /dev/null
+++ b/dominate/document.py
@@ -0,0 +1,75 @@
+__license__ = '''
+This file is part of Dominate.
+
+Dominate is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as
+published by the Free Software Foundation, either version 3 of
+the License, or (at your option) any later version.
+
+Dominate 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 Dominate.  If not, see
+<http://www.gnu.org/licenses/>.
+'''
+
+from . import tags
+
+try:
+  basestring = basestring
+except NameError: # py3
+  basestring = str
+  unicode = str
+
+class document(tags.html):
+  tagname = 'html'
+  def __init__(self, title='Dominate', doctype='<!DOCTYPE html>', request=None):
+    '''
+    Creates a new document instance. Accepts `title`, `doctype`, and `request` keyword arguments.
+    '''
+    super(document, self).__init__()
+    self.doctype    = doctype
+    self.head       = super(document, self).add(tags.head())
+    self.body       = super(document, self).add(tags.body())
+    self.title_node = self.head.add(tags.title(title))
+    self._entry     = self.body
+
+  def get_title(self):
+    return self.title_node.text
+
+  def set_title(self, title):
+    if isinstance(title, basestring):
+      self.title_node.text = title
+    else:
+      self.head.remove(self.title_node)
+      self.head.add(title)
+      self.title_node = title
+
+  title = property(get_title, set_title)
+
+  def add(self, *args):
+    '''
+    Adding tags to a document appends them to the <body>.
+    '''
+    return self._entry.add(*args)
+
+  def render(self, *args, **kwargs):
+    '''
+    Creates a <title> tag if not present and renders the DOCTYPE and tag tree.
+    '''
+    r = []
+
+    #Validates the tag tree and adds the doctype if one was set
+    if self.doctype:
+      r.append(self.doctype)
+      r.append('\n')
+    r.append(super(document, self).render(*args, **kwargs))
+
+    return u''.join(r)
+  __str__ = __unicode__ = render
+
+  def __repr__(self):
+    return '<dominate.document "%s">' % self.title
diff --git a/dominate/dom1core.py b/dominate/dom1core.py
new file mode 100644
index 0000000..5045784
--- /dev/null
+++ b/dominate/dom1core.py
@@ -0,0 +1,68 @@
+__license__ = '''
+This file is part of Dominate.
+
+Dominate is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as
+published by the Free Software Foundation, either version 3 of
+the License, or (at your option) any later version.
+
+Dominate 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 Dominate.  If not, see
+<http://www.gnu.org/licenses/>.
+'''
+
+try:
+  basestring = basestring
+except NameError: # py3
+  basestring = str
+  unicode = str
+
+
+class dom1core(object):
+  '''
+  Implements the Document Object Model (Core) Level 1
+
+  http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/
+  http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html
+  '''
+  @property
+  def parentNode(self):
+    '''
+    DOM API: Returns the parent tag of the current element.
+    '''
+    return self.parent
+
+  def getElementById(self, id):
+    '''
+    DOM API: Returns single element with matching id value.
+    '''
+    results = self.get(id=id)
+    if len(results) > 1:
+      raise ValueError('Multiple tags with id "%s".' % id)
+    elif results:
+      return results[0]
+    else:
+      return None
+
+  def getElementsByTagName(self, name):
+    '''
+    DOM API: Returns all tags that match name.
+    '''
+    if isinstance(name, basestring):
+      return self.get(name.lower())
+    else:
+      return None
+
+  def appendChild(self, obj):
+    '''
+    DOM API: Add an item to the end of the children list.
+    '''
+    self.add(obj)
+    return self
+
+
diff --git a/dominate/dom_tag.py b/dominate/dom_tag.py
new file mode 100644
index 0000000..f3be8b7
--- /dev/null
+++ b/dominate/dom_tag.py
@@ -0,0 +1,423 @@
+__license__ = '''
+This file is part of Dominate.
+
+Dominate is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as
+published by the Free Software Foundation, either version 3 of
+the License, or (at your option) any later version.
+
+Dominate 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 Dominate.  If not, see
+<http://www.gnu.org/licenses/>.
+'''
+
+import copy
+import numbers
+from collections import defaultdict, namedtuple, Callable
+from functools import wraps
+import threading
+
+try:
+  basestring = basestring
+except NameError: # py3
+  basestring = str
+  unicode = str
+
+def _get_thread_context():
+  context = [threading.current_thread()]
+  try:
+    import greenlet
+    context.append(greenlet.getcurrent())
+  except:
+    pass
+  return hash(tuple(context))
+
+
+class dom_tag(object):
+  TAB = '  '  # TODO make this a parameter to render(), and a tag.
+
+  is_single = False  # Tag does not require matching end tag (ex. <hr/>)
+  is_pretty = True   # Text inside the tag should be left as-is (ex. <pre>)
+                     # otherwise, text will be escaped() and whitespace may be
+                     # modified
+
+  frame = namedtuple('frame', ['tag', 'items', 'used'])
+
+  def __new__(_cls, *args, **kwargs):
+    '''
+    Check if bare tag is being used a a decorator.
+    decorate the function and return
+    '''
+    if len(args) == 1 and isinstance(args[0], Callable) \
+        and not isinstance(args[0], dom_tag) and not kwargs:
+      wrapped = args[0]
+
+      @wraps(wrapped)
+      def f(*args, **kwargs):
+        with _cls() as _tag:
+          return wrapped(*args, **kwargs) or _tag
+      return f
+    return object.__new__(_cls)
+
+  def __init__(self, *args, **kwargs):
+    '''
+    Creates a new tag. Child tags should be passed as aruguments and attributes
+    should be passed as keyword arguments.
+
+    There is a non-rendering attribute which controls how the tag renders:
+
+    * `__inline` - Boolean value. If True renders all children tags on the same
+                   line.
+    '''
+
+    self.attributes = {}
+    self.children   = []
+    self.parent     = None
+    self.document   = None
+
+    # Does not insert newlines on all children if True (recursive attribute)
+    self.do_inline = kwargs.pop('__inline', False)
+
+    #Add child elements
+    if args:
+      self.add(*args)
+
+    for attr, value in kwargs.items():
+      self.set_attribute(*dom_tag.clean_pair(attr, value))
+
+    self._ctx = None
+    self._add_to_ctx()
+
+  def _add_to_ctx(self):
+    ctx = dom_tag._with_contexts[_get_thread_context()]
+    if ctx and ctx[-1]:
+      self._ctx = ctx[-1]
+      ctx[-1].items.append(self)
+
+  # stack of (root_tag, [new_tags], set(used_tags))
+  _with_contexts = defaultdict(list)
+
+  def __enter__(self):
+    ctx = dom_tag._with_contexts[_get_thread_context()]
+    ctx.append(dom_tag.frame(self, [], set()))
+    return self
+
+  def __exit__(self, type, value, traceback):
+    ctx = dom_tag._with_contexts[_get_thread_context()]
+    slf, items, used = ctx[-1]
+    ctx[-1] = None
+    for item in items:
+      if item in used: continue
+      self.add(item)
+    ctx.pop()
+
+  def __call__(self, func):
+    '''
+    tag instance is being used as a decorator.
+    wrap func to make a copy of this tag
+    '''
+    # remove decorator from its context so it doesn't
+    # get added in where it was defined
+    if self._ctx:
+      assert False, self._ctx
+      self._ctx.used.add(self)
+
+    @wraps(func)
+    def f(*args, **kwargs):
+      tag = copy.deepcopy(self)
+      tag._add_to_ctx()
+      with tag:
+        return func(*args, **kwargs) or tag
+    return f
+
+  def set_attribute(self, key, value):
+    '''
+    Add or update the value of an attribute.
+    '''
+    if isinstance(key, int):
+      self.children[key] = value
+    elif isinstance(key, basestring):
+      self.attributes[key] = value
+    else:
+      raise TypeError('Only integer and string types are valid for assigning '
+          'child tags and attributes, respectively.')
+  __setitem__ = set_attribute
+
+  def setdocument(self, doc):
+    '''
+    Creates a reference to the parent document to allow for partial-tree
+    validation.
+    '''
+    # assume that a document is correct in the subtree
+    if self.document != doc:
+      self.document = doc
+      for i in self.children:
+        if not isinstance(i, dom_tag): return
+        i.setdocument(doc)
+
+  def add(self, *args):
+    '''
+    Add new child tags.
+    '''
+    for obj in args:
+      if isinstance(obj, numbers.Number):
+        # Convert to string so we fall into next if block
+        obj = str(obj)
+
+      if isinstance(obj, basestring):
+        if self.is_pretty:
+          obj = escape(obj)
+        self.children.append(obj)
+
+      elif isinstance(obj, dom_tag):
+        ctx = dom_tag._with_contexts[_get_thread_context()]
+        if ctx and ctx[-1]:
+          ctx[-1].used.add(obj)
+        self.children.append(obj)
+        obj.parent = self
+        obj.setdocument(self.document)
+
+      elif isinstance(obj, dict):
+        for attr, value in obj.items():
+          self.set_attribute(*dom_tag.clean_pair(attr, value))
+
+      elif hasattr(obj, '__iter__'):
+        for subobj in obj:
+          self.add(subobj)
+
+      else:  # wtf is it?
+        raise ValueError('%r not a tag or string.' % obj)
+
+    if len(args) == 1:
+      return args[0]
+
+    return args
+
+  def add_raw_string(self, s):
+    self.children.append(s)
+
+  def remove(self, obj):
+    self.children.remove(obj)
+
+  def clear(self):
+    for i in self.children:
+      if isinstance(i, dom_tag) and i.parent is self:
+        i.parent = None
+    self.children = []
+
+  def get(self, tag=None, **kwargs):
+    '''
+    Recursively searches children for tags of a certain
+    type with matching attributes.
+    '''
+    # Stupid workaround since we can not use dom_tag in the method declaration
+    if tag is None: tag = dom_tag
+
+    attrs = [(dom_tag.clean_attribute(attr), value)
+        for attr, value in kwargs.items()]
+
+    results = []
+    for child in self.children:
+      if (isinstance(tag, basestring) and type(child).__name__ == tag) or \
+        (not isinstance(tag, basestring) and isinstance(child, tag)):
+
+        if all(child.attributes.get(attribute) == value
+            for attribute, value in attrs):
+          # If the child is of correct type and has all attributes and values
+          # in kwargs add as a result
+          results.append(child)
+      if isinstance(child, dom_tag):
+        # If the child is a dom_tag extend the search down through its children
+        results.extend(child.get(tag, **kwargs))
... 1849 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/dominate.git



More information about the Python-modules-commits mailing list