Exemplo n.º 1
0
def doccli(argv):
    """doccli [-h?] [-D] [<filename>]
    Create and interactively edit an XHTML document.
    """
    filename = None
    try:
        optlist, longopts, args = getopt.getopt(argv[1:], "?hD")
    except getopt.GetoptError:
        print doccli.__doc__
        return
    for opt, optarg in optlist:
        if opt in ("-?", "-h"):
            print doccli.__doc__
            return
        elif opt == "-D":
            from pycopia import autodebug
    if args:
        filename = args[0]

    io = CLI.ConsoleIO()
    ui = CLI.UserInterface(io)
    cmd = TopLevel(ui)
    cmd._environ["filename"] = filename
    if filename:
        doc = XHTML.get_document(filename)
    else:
        doc = XHTML.new_document()
    cmd._setup(doc, "doc> ")
    parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_doccli"))
    parser.interact()
Exemplo n.º 2
0
 def handle_decl(self, decl):
     if decl.startswith("DOCTYPE"):
         if decl.find("Strict") > 1:
             self.doc = XHTML.new_document(dtds.XHTML1_STRICT, encoding=self._encoding)
         elif decl.find("Frameset") > 1:
             self.doc = XHTML.new_document(dtds.XHTML1_FRAMESET, encoding=self._encoding)
         elif decl.find("Transitional") > 1:
             self.doc = XHTML.new_document(dtds.XHTML1_TRANSITIONAL, encoding=self._encoding)
         else:
             self.doc = XHTML.new_document(dtds.XHTML1_TRANSITIONAL, encoding=self._encoding)
     else:
         print >>sys.stderr, "!!! Unhandled decl: %r" % (decl,)
Exemplo n.º 3
0
 def initialize(self):
     dtd = self.dtd
     root = XHTML.get_container(dtd, "Html", {"class_": FEATURE_CLASS})
     self.set_root(root)
     head = XHTML.get_container(dtd, "Head", {})
     body = XHTML.get_container(dtd, "Body", {})
     head.append(dtd.Meta(charset="utf-8"))
     head.append(
         dtd.Meta(http_equiv="X-UA-Compatible", content="IE=edge,chrome=1"))
     root.append(head)
     root.append(body)
     root.head = head
     root.body = body
Exemplo n.º 4
0
 def handle_decl(self, decl):
     if decl.startswith("DOCTYPE"):
         if decl.find("Strict") > 1:
             self.doc = XHTML.new_document(dtds.XHTML1_STRICT,
                                           encoding=self._encoding)
         elif decl.find("Frameset") > 1:
             self.doc = XHTML.new_document(dtds.XHTML1_FRAMESET,
                                           encoding=self._encoding)
         elif decl.find("Transitional") > 1:
             self.doc = XHTML.new_document(dtds.XHTML1_TRANSITIONAL,
                                           encoding=self._encoding)
         else:
             self.doc = XHTML.new_document(dtds.XHTML1_TRANSITIONAL,
                                           encoding=self._encoding)
     else:
         print >> sys.stderr, "!!! Unhandled decl: %r" % (decl, )
Exemplo n.º 5
0
def emailrequest(request):
    """Send HTTP request headers to provided email address."""
    resp = framework.ResponseDocument(request, doc_constructor, title="Web Responder")
    recipients = request.GET.getlist("recipient")+request.GET.getlist("rcpt") or resp.config.ADMINS
    # some basic validation. Mailer shuould validate the rest.
    recipients = filter(lambda name: "@" in name, recipients)
    recipients = filter(lambda name: "." in name, recipients)

    if recipients:
        rpt = XHTML.new_document()
        get_header_table(rpt.body, request.environ)

        body = ezmail.AutoMessage(EMAILBODY)
        body["Content-Disposition"] = 'inline'
        msg = ezmail.AutoMessage(str(rpt), mimetype=rpt.MIMETYPE, charset=rpt.encoding)
        msg["Content-Disposition"] = 'attachment; filename=headers.html'
        ezmail.mail([body, msg], To=recipients,
                  subject="Webtool header request from %s." % (request.environ.get("REMOTE_ADDR", "<unknown>"),))

    get_header_table(resp.doc.content, request.environ)

    if recipients:
        resp.doc.content.new_para("Header data emailed to %s." % (", ".join(recipients),))
    else:
        resp.doc.content.new_para("No valid email recipients.")
    return resp.finalize()
Exemplo n.º 6
0
    def parse_docstring(self, text):
        renderer = rst.get_renderer()
        doc = XHTML.new_document()
        parser = doc.get_parser()
        text = textwrap.dedent(text)

        # If not in section format, just add it to Purpose section.
        if text.find("+++") < 0:
            self.__setitem__("purpose", " ".join(text.split())) # normalized text.
            return

        # Convert RST docstring to XHTML/POM object model.
        xhtml = renderer(text)
        parser.feed(xhtml)
        parser.close()
        del parser
        if _DEBUG:
            print ("=== parse_docstring: Original text ===:")
            print (text)
            print ("--- parse_docstring: document text ---:")
            print (doc)

        if not doc.root.id:
            for div in doc.root.find_elements("div"):
                self._do_div(div)            # more than one section
        else:
                self._do_div(doc.root) # one section
Exemplo n.º 7
0
def emailrequest(request):
    """Send HTTP request headers to provided email address."""
    resp = framework.ResponseDocument(request,
                                      doc_constructor,
                                      title="Web Responder")
    recipients = request.GET.getlist("recipient") + request.GET.getlist(
        "rcpt") or resp.config.ADMINS
    # some basic validation. Mailer shuould validate the rest.
    recipients = filter(lambda name: "@" in name, recipients)
    recipients = filter(lambda name: "." in name, recipients)

    if recipients:
        rpt = XHTML.new_document()
        get_header_table(rpt.body, request.environ)

        body = ezmail.AutoMessage(EMAILBODY)
        body["Content-Disposition"] = 'inline'
        msg = ezmail.AutoMessage(str(rpt),
                                 mimetype=rpt.MIMETYPE,
                                 charset=rpt.encoding)
        msg["Content-Disposition"] = 'attachment; filename=headers.html'
        ezmail.mail([body, msg],
                    To=recipients,
                    subject="Webtool header request from %s." %
                    (request.environ.get("REMOTE_ADDR", "<unknown>"), ))

    get_header_table(resp.doc.content, request.environ)

    if recipients:
        resp.doc.content.new_para("Header data emailed to %s." %
                                  (", ".join(recipients), ))
    else:
        resp.doc.content.new_para("No valid email recipients.")
    return resp.finalize()
Exemplo n.º 8
0
def RSTtoXHTML(rsttext):
    from pycopia.WWW import XHTML
    tempdoc = XHTML.new_document()
    renderer = get_renderer()
    parser = tempdoc.get_parser()
    xhtml = renderer(rsttext)
    parser.feed(xhtml)
    parser.close()
    return tempdoc.root
Exemplo n.º 9
0
def RSTtoXHTML(rsttext):
    from pycopia.WWW import XHTML
    tempdoc = XHTML.new_document()
    renderer = get_renderer()
    parser = tempdoc.get_parser()
    xhtml = renderer(rsttext)
    parser.feed(xhtml)
    parser.close()
    return tempdoc.root
Exemplo n.º 10
0
def get_acceptable_document(request):
    accept = request.headers["accept"]
    preferred = accept.select(SUPPORTED)
    if preferred:
        if preferred == "text/plain":
            return Plaintext.new_document()
        else:
            return XHTML.new_document(doctype=None, mimetype=preferred)
    else:
        raise HTTPError(415, "Unsupported Media Type")
Exemplo n.º 11
0
def get_acceptable_document(request):
    accept = request.headers["accept"]
    preferred = accept.select(SUPPORTED)
    if preferred:
        if preferred == "text/plain":
            return Plaintext.new_document()
        else:
            return XHTML.new_document(doctype=None, mimetype=preferred)
    else:
        raise HTTPError(415, "Unsupported Media Type")
Exemplo n.º 12
0
def get_parser(document=None, namespaces=0, validate=0, mimetype=None,
        logfile=None):
    if mimetype == XHTML.MIME_HTML:
        if not document:
            document = XHTML.new_document(dtds.XHTML1_TRANSITIONAL, encoding=POM.DEFAULT_ENCODING)
        return _HTMLParser(document)
    else: # assume some kind of XML
        from pycopia.XML import POMparse
        return POMparse.get_parser(document, namespaces=namespaces, validate=validate, 
            external_ges=1, logfile=logfile, doc_factory=XHTML.xhtml_factory)
Exemplo n.º 13
0
 def test_Zfetch(self):
     doc = XHTML.get_document("http://www.pycopia.net/")
     self.assertEqual(doc.title.get_text(), "Python Application Frameworks")
     # write it out for inspection
     # Note that the document was parsed, and regenerated.
     fo = open("/tmp/pycopia_net.html", "w")
     try:
         doc.emit(fo)
     finally:
         fo.close()
     print "Fetched document found here: /tmp/pycopia_net.html"
Exemplo n.º 14
0
 def test_Zfetch(self):
     doc = XHTML.get_document("http://www.pycopia.net/")
     self.assertEqual(doc.title.get_text(), "Python Application Frameworks")
     # write it out for inspection
     # Note that the document was parsed, and regenerated.
     fo = open("/tmp/pycopia_net.html", "w")
     try:
         doc.emit(fo)
     finally:
         fo.close()
     print "Fetched document found here: /tmp/pycopia_net.html"
Exemplo n.º 15
0
 def test_Zfetchmobile(self):
     doc = XHTML.get_document(
     "http://www.google.com/gwt/n?u=http://www.pynms.net",
     mimetype=WML,
     useragent=MOBILEAGENT2)
     print "Mobile doctype:", doc.DOCTYPE
     # write it out for inspection
     # Note that the document was parsed, and regenerated.
     fo = open("/tmp/test_WWW_mobile.html", "w")
     try:
         doc.emit(fo)
     finally:
         fo.close()
     print "Fetched document found here: /tmp/test_WWW_mobile.html"
Exemplo n.º 16
0
 def test_Zfetchmobile(self):
     doc = XHTML.get_document(
         "http://www.google.com/gwt/n?u=http://www.pynms.net",
         mimetype=WML,
         useragent=MOBILEAGENT2)
     print "Mobile doctype:", doc.DOCTYPE
     # write it out for inspection
     # Note that the document was parsed, and regenerated.
     fo = open("/tmp/test_WWW_mobile.html", "w")
     try:
         doc.emit(fo)
     finally:
         fo.close()
     print "Fetched document found here: /tmp/test_WWW_mobile.html"
Exemplo n.º 17
0
def get_parser(document=None,
               namespaces=0,
               validate=0,
               mimetype=None,
               logfile=None):
    if mimetype == XHTML.MIME_HTML:
        if not document:
            document = XHTML.new_document(dtds.XHTML1_TRANSITIONAL,
                                          encoding=POM.DEFAULT_ENCODING)
        return _HTMLParser(document)
    else:  # assume some kind of XML
        from pycopia.XML import POMparse
        return POMparse.get_parser(document,
                                   namespaces=namespaces,
                                   validate=validate,
                                   external_ges=1,
                                   logfile=logfile,
                                   doc_factory=XHTML.xhtml_factory)
Exemplo n.º 18
0
def get_base_document(request, **kwargs):
    doc = XHTML.new_document()
    ss = kwargs.pop("stylesheet", DEFAULTSTYLE)
    js = kwargs.pop("javascriptlink", None)
    for name, val in kwargs.items():
        setattr(doc, name, val)
    doc.stylesheet = request.get_url("css", name=ss)
    doc.javascriptlink = request.get_url("js", name=JSKIT)
    doc.javascriptlink = request.get_url("js", name=UILIB)
    if js:
        doc.javascriptlink = request.get_url("js", name=js)
    container = doc.add_section("container")
    header = container.add_section("container", id="header")
    wrapper = container.add_section("container", id="wrapper")
    content = wrapper.add_section("container", id="content")
    navigation = container.add_section("container", id="navigation")
    extra = container.add_section("container", id="extra")
    footer = container.add_section("container", id="footer")
    doc.header = header
    doc.content = content
    doc.nav = navigation
    doc.extra = extra
    doc.footer = footer
    return doc
Exemplo n.º 19
0
def get_base_document(request, **kwargs):
    doc = XHTML.new_document()
    ss = kwargs.pop("stylesheet", DEFAULTSTYLE)
    js = kwargs.pop("javascriptlink", None)
    for name, val in kwargs.items():
        setattr(doc, name, val)
    doc.stylesheet = request.get_url("css", name=ss)
    doc.javascriptlink = request.get_url("js", name=JSKIT)
    doc.javascriptlink = request.get_url("js", name=UILIB)
    if js:
        doc.javascriptlink = request.get_url("js", name=js)
    container = doc.add_section("container")
    header = container.add_section("container", id="header")
    wrapper = container.add_section("container", id="wrapper")
    content = wrapper.add_section("container", id="content")
    navigation = container.add_section("container", id="navigation")
    extra = container.add_section("container", id="extra")
    footer = container.add_section("container", id="footer")
    doc.header = header
    doc.content = content
    doc.nav = navigation
    doc.extra = extra
    doc.footer = footer
    return doc
Exemplo n.º 20
0
    def test_XHTML(self):
        """Construct an XHTML page. Verify visually."""
        htd = XHTML.new_document(dtds.XHTML)
        htd.title = "This is the title."
        htd.add_header(1, 'Main document & "stuff"')
        htd.new_para("This is a test. This is text.")
        htd.add_unordered_list(["List line one.", "list line two."])
        BR = htd.get_new_element("Br")
        A = htd.get_new_element("A", href="somelink.html")
        A.add_text("some link")
        p = htd.get_para()
        p.append(A)
        p.add_text(" This is ")
        b = p.bold("bold")
        p.add_text(" text. using ")
        stb = htd.get_new_element("B")
        stb.add_text("bold tags")
        p.text(stb)
        p.add_text(" Dynamic Date: ")
        p.append(XHTML.DynamicNode(thedate))
        rp = str(p)
        htd.append(POM.ASIS(rp))
        # table methods
        t = htd.add_table(border=1)
        t.summary = "This is a test table."
        t.caption("table caption")
        h = t.set_heading(2, "heading col 2")
        h.set_attribute("class", "headerclass")
        t.set_heading(1, "heading col 1")
        t.set_cell(1, 1, "row 1, col 1")
        t.set_cell(1, 2, "row 2, col 1")
        t.set_cell(2, 1, "row 1, col 2")
        t.set_cell(2, 2, "row 2, col 2")
        # sections
        div = htd.get_section("section1")
        div.add_header(1, "Div heading.")
        div.new_para("First div para.")
        htd.append(div)
        div2 = div.get_section("section2")
        div2.new_para("Second div para")
        div.append(div2)

        dl = div.add_definition_list()
        dl.add_definitions({
            "def1": "The definition of 1",
            "def2": "The definition of 2"
        })

        # using the nodemaker object
        NM = htd.nodemaker
        ul = NM(
            "Ul",
            None,
            NM("Li", None, "line 1"),
            NM("Li", None, "line 2"),
            NM("Li", None, "Date: ",
               NM("code", None, thedate)),  # another way to add dynamic node
        )
        htd.append(ul)
        htd.append(NM("JS", None, 'var a = new Array(8);'))
        # using the creator object.
        creator = htd.creator
        parts = creator([("Just", "just/"), "How will this turn out?",
                         ["It is hard to tell.", "Well, not too hard."]])

        htd.add_comment(
            "the name attribute is required for all but submit & reset")
        htd.append(parts)
        f = htd.add_form(action="http://localhost:4001/cgi-bin/testing.py",
                         method="post")

        f.add_textarea("mytextarea", """Default text in the textarea.""")
        f.append(BR)
        f.add_input(type="text", name="mytext", value="mytext text")
        f.append(BR)
        f.add_input(type="button",
                    name="button1",
                    src="button.png",
                    value="Button")
        f.append(BR)
        f.add_input(type="submit",
                    name="submit1",
                    src="submit.png",
                    value="Ok")
        f.append(BR)
        f.add_radiobuttons("radlist", ["one", "two", "three", "four"],
                           vertical=False)
        f.append(BR)
        f.add_checkboxes("checks", ["one", "two", "three", "four"],
                         vertical=True)
        f.append(BR)
        f.add_fileinput(name="myfile", default="/etc/hosts")
        f.append(BR)
        f.add_textinput(name="mytext", label="Enter text")
        f.append(BR)
        f.yes_no("What's it gonna be?")
        f.add_select([
            "one", "two", ("three", True), "four", {
                "agroup": ["group1", "group2"]
            }
        ],
                     name="myselect")
        f.append(BR)

        f.add_select(
            {
                "Group1":
                Enums("g1one", "g1two", "g1three") + [("g1four", True)],
                "Group2": Enums("g2one", "g2two", "g2three"),
                "Group3": Enums("g3one", "g3two", "g3three"),
            },
            name="useenums")
        f.append(BR)

        f.add_select(["mone", "mtwo", ("mthree", True), ("mfour", True)],
                     name="multiselect",
                     multiple=True)
        f.append(BR)

        set = f.add_fieldset("afieldset")
        set.add_textinput(name="settext", label="Enter set text")
        set.add_textinput(name="settext2",
                          label="Enter set text 2",
                          default="Default text.")
        set.append(BR)
        tbl = htd.new_table([1, 2, 3, 4, 5], [NULL, NULL, NULL],
                            ["col1", "col2", "col3"],
                            width="100%",
                            summary="autogenerated")

        gentable = table.GenericTable(["heading1", "heading2", "heading3"],
                                      title="Sample generic table")
        gentable.append([1, 2, 3])
        gentable.append([4, 5, 6])
        tbl2 = htd.new_table_from_GenericTable(gentable)
        # object
        subdoc = XHTML.new_document(dtds.XHTML)
        parts = subdoc.creator(
            ("Add a document object.", ["Some data.", "some more data.."]))
        subdoc.append(parts)
        sdfo = open("/tmp/subdoc.html", "w")
        subdoc.emit(sdfo)
        sdfo.close()
        htd.add_object(data="subdoc.html",
                       type=subdoc.MIMETYPE,
                       width="400px",
                       height="600px")
        htd.emit(sys.stdout)
        print "-----"
        fo = open(XHTMLFILENAME, "w")
        bw = POM.BeautifulWriter(fo, XHTML.INLINE)
        htd.emit(bw)
        fo.close()
        print "----- Form values:"
        print f.fetch_form_values()
        print "----- Form elements:"
        felems = f.fetch_form_elements()
        for name, elemlist in felems.items():
            print repr(name), ": ", repr(elemlist)
            print
        # visually verify the page.
        webbrowser.open("file://%s" % (XHTMLFILENAME, ))
Exemplo n.º 21
0
def build_testplans(argv):
    py_matcher = re.compile(r"(^[a-zA-Z]+)\.py$", re.M)
    HOME = fix_path()
    home_len = len(HOME) + 1
    if len(argv) > 1:
        DOCDIR = os.path.expanduser(os.path.expandvars(argv[1]))
    else:
        DOCDIR = "/var/www/localhost/htdocs/testplans"
    os.chdir(DOCDIR)
    index = XHTML.new_document()
    NM = index.nodemaker
    index.add_title("Package Index")
    index.stylesheet = INDEX_STYLESHEET
    index.add_header(1, "Package Index")
    index.new_para("""Here are the available packages.""")
    UL = index.get_unordered_list()
    index.append(UL)

    for dirname, dirs, files in os.walk(HOME):
        if "__init__.py" in files:
            pkgname = ".".join(dirname[home_len:].split("/"))
            if not pkgname:
                continue
            rstname = pkgname.replace(".", "_") + ".rst"
            htmlname = pkgname.replace(".", "_") + ".html"

            A = NM("A", {"href": htmlname})
            A.add_text(pkgname)
            UL.add_item(A)

            fo = file(rstname, "w")
            extract_package(fo, pkgname)
            fo.close()
            publish_file(source_path=rstname,
                         parser_name='restructuredtext',
                         writer_name='html',
                         destination_path=htmlname,
                         settings_overrides={
                             "link_stylesheet": True,
                             "embed_stylesheet": False,
                             "stylesheet_path": None,
                             "stylesheet": STYLESHEET
                         })
            for fname in files:  # copy any included files to destination
                if fname[-3:] in ("jpg", "png", "gif", "rst"):
                    shutil.copy(os.path.join(dirname, fname), DOCDIR)
        else:
            for fname in files:
                mo = py_matcher.match(fname)
                if mo:
                    modname = mo.group(1)
                    rstname = modname.replace(".", "_") + ".rst"
                    htmlname = modname.replace(".", "_") + ".html"

                    A = NM("A", {"href": htmlname})
                    A.add_text(modname)
                    UL.add_item(A)

                    fo = file(rstname, "w")
                    extract_module(fo, modname)
                    fo.close()
                    publish_file(
                        source_path=rstname,
                        parser_name='restructuredtext',
                        writer_name='html',
                        destination_path=htmlname,
                        settings_overrides={
                            "link_stylesheet": True,
                            "embed_stylesheet": False,
                            "stylesheet_path": None,
                            "stylesheet": STYLESHEET
                        },
                    )

    indexfile = file("testplan_index.html", "w")
    index.emit(indexfile)
    indexfile.close()
Exemplo n.º 22
0
def build_testplans(argv):
    from pycopia.WWW import XHTML
    py_matcher = re.compile(r"(^[a-zA-Z]+)\.py$", re.M)
    HOME = fix_path()
    STYLESHEET = "/stylesheets/qa_tp.css"
    hl = len(HOME) + 1
    if len(argv) > 1:
        DOCDIR = os.path.expanduser(os.path.expandvars(argv[1]))
    else:
        DOCDIR = "/var/www/localhost/htdocs/testplans"
    os.chdir(DOCDIR)
    index = XHTML.new_document(XHTML.STRICT)
    index.add_title("Test Plan Index")
    index.add_to_head("Link",
                      rel="stylesheet",
                      href=STYLESHEET,
                      type="text/css")
    index.add_header(1, "Test Plan Index")
    index.add_para("""Below is a list of test packages. Each test module
located in the package is documented inside the package document.  """)
    UL = index.get_unordered_list()
    index.append(UL)

    for dirname, dirs, files in os.walk(HOME):
        if "__init__.py" in files:
            pkgname = ".".join(dirname[hl:].split("/"))
            rstname = pkgname.replace(".", "_") + ".rst"
            htmlname = pkgname.replace(".", "_") + ".html"

            A = index.get_element("A", href=htmlname)
            A.add_text(pkgname)
            UL.add_item(A)

            fo = file(rstname, "w")
            extract_package(fo, pkgname)
            fo.close()
            publish_file(source_path=rstname,
                         parser_name='restructuredtext',
                         writer_name='html',
                         destination_path=htmlname,
                         settings_overrides={"stylesheet": STYLESHEET})
            for fname in files:  # copy any included files to destination
                if fname[-3:] in ("jpg", "png", "gif", "rst"):
                    shutil.copy(os.path.join(dirname, fname), DOCDIR)
        else:
            for fname in files:
                mo = py_matcher.match(fname)
                if mo:
                    modname = mo.group(1)
                    rstname = modname.replace(".", "_") + ".rst"
                    htmlname = modname.replace(".", "_") + ".html"

                    A = index.get_element("A", href=htmlname)
                    A.add_text(modname)
                    UL.add_item(A)

                    fo = file(rstname, "w")
                    extract_module(fo, modname)
                    fo.close()
                    publish_file(source_path=rstname,
                                 parser_name='restructuredtext',
                                 writer_name='html',
                                 destination_path=htmlname,
                                 settings_overrides={"stylesheet": STYLESHEET})

    indexfile = file("testplan_index.html", "w")
    index.emit(indexfile)
    indexfile.close()
Exemplo n.º 23
0
    def test_XHTML(self):
        """Construct an XHTML page. Verify visually."""
        htd = XHTML.new_document(dtds.XHTML)
        htd.title = "This is the title."
        htd.add_header(1, 'Main document & "stuff"')
        htd.new_para("This is a test. This is text.")
        htd.add_unordered_list(["List line one.", "list line two."])
        BR = htd.get_new_element("Br")
        A = htd.get_new_element("A", href="somelink.html")
        A.add_text("some link")
        p = htd.get_para()
        p.append(A)
        p.add_text(" This is ")
        b = p.bold("bold")
        p.add_text(" text. using ")
        stb = htd.get_new_element("B")
        stb.add_text("bold tags")
        p.text(stb)
        rp = str(p)
        htd.append(POM.ASIS(rp))
        # table methods
        t = htd.add_table(border=1)
        t.summary = "This is a test table."
        t.caption("table caption")
        h = t.set_heading(2, "heading col 2")
        h.set_attribute("class", "headerclass")
        t.set_heading(1, "heading col 1")
        t.set_cell(1,1,"row 1, col 1")
        t.set_cell(1,2,"row 2, col 1")
        t.set_cell(2,1,"row 1, col 2")
        t.set_cell(2,2,"row 2, col 2")
        # sections
        div = htd.get_section("section1")
        div.add_header(1, "Div heading.")
        div.new_para("First div para.")
        htd.append(div)
        div2 = div.get_section("section2")
        div2.new_para("Second div para")
        div.append(div2)

        dl = div.add_definition_list()
        dl.add_definitions({"def1":"The definition of 1", 
                        "def2": "The definition of 2"})

        # using the nodemaker object
        NM = htd.nodemaker
        ul = NM("Ul", None, 
                NM("Li", None, "line 1"), 
                NM("Li", None, "line 2")
                )
        htd.append(ul)
        # using the creator object.
        creator = htd.creator
        parts = creator([("Just", "just/"), "How will this turn out?", ["It is hard to tell.", "Well, not too hard."]])

        htd.add_comment("the name attribute is required for all but submit & reset")
        htd.append(parts)
        f = htd.add_form(action="http://localhost:4001/cgi-bin/testing.py", method="post")

        f.add_textarea("mytextarea", """Default text in the textarea.""") ; f.append(BR)
        f.add_input(type="text", name="mytext", value="mytext text") ; f.append(BR)
        f.add_input(type="button", name="button1", src="button.png", value="Button") ; f.append(BR)
        f.add_input(type="submit", name="submit1", src="submit.png", value="Ok") ; f.append(BR)
        f.add_radiobuttons("radlist", ["one", "two", "three", "four"], vertical=False) ; f.append(BR)
        f.add_checkboxes("checks", ["one", "two", "three", "four"], vertical=True) ; f.append(BR)
        f.add_fileinput(name="myfile", default="/etc/hosts") ; f.append(BR)
        f.add_textinput(name="mytext", label="Enter text") ; f.append(BR)
        f.yes_no("What's it gonna be?")
        f.add_select(["one", "two", ("three", True), "four", 
                       {"agroup": ["group1", "group2"]}], 
                       name="myselect") ; f.append(BR)

        f.add_select({"Group1": Enums("g1one", "g1two", "g1three")+[("g1four", True)],
                      "Group2": Enums("g2one", "g2two", "g2three"),
                      "Group3": Enums("g3one", "g3two", "g3three"),
                    }, name="useenums") ; f.append(BR)

        f.add_select(["mone", "mtwo", ("mthree", True), ("mfour", True)], name="multiselect", multiple=True) ; f.append(BR)

        set = f.add_fieldset("afieldset")
        set.add_textinput(name="settext", label="Enter set text")
        set.add_textinput(name="settext2", label="Enter set text 2", default="Default text.")
        set.append(BR)
        tbl = htd.new_table([1,2,3,4,5], 
                            [NULL, NULL, NULL], 
                            ["col1", "col2", "col3"], width="100%", summary="autogenerated")

        gentable = table.GenericTable(["heading1", "heading2", "heading3"], 
                    title="Sample generic table")
        gentable.append([1,2,3])
        gentable.append([4,5,6])
        tbl2 = htd.new_table_from_GenericTable(gentable)
        # object 
        subdoc = XHTML.new_document(dtds.XHTML)
        parts = subdoc.creator(("Add a document object.", ["Some data.", "some more data.."]))
        subdoc.append(parts)
        sdfo = open("/tmp/subdoc.html", "w")
        subdoc.emit(sdfo)
        sdfo.close()
        htd.add_object(data="subdoc.html", type=subdoc.MIMETYPE,
                                    width="400px", height="600px")
        htd.emit(sys.stdout)
        print "-----"
        fo = open(XHTMLFILENAME, "w")
        bw = POM.BeautifulWriter(fo, XHTML.INLINE)
        htd.emit(bw)
        fo.close()
        print "----- Form values:"
        print f.fetch_form_values()
        print "----- Form elements:"
        felems = f.fetch_form_elements()
        for name, elemlist in felems.items():
            print repr(name), ": ", repr(elemlist)
            print
        # visually verify the page.
        webbrowser.open("file://%s" % (XHTMLFILENAME,))
Exemplo n.º 24
0
def build_testplans(argv):
    from pycopia.WWW import XHTML
    py_matcher = re.compile(r"(^[a-zA-Z]+)\.py$", re.M)
    HOME = fix_path()
    STYLESHEET = "/stylesheets/qa_tp.css"
    hl = len(HOME)+1
    if len(argv) > 1:
        DOCDIR = os.path.expanduser(os.path.expandvars(argv[1]))
    else:
        DOCDIR = "/var/www/localhost/htdocs/testplans"
    os.chdir(DOCDIR)
    index = XHTML.new_document(XHTML.STRICT)
    index.add_title("Test Plan Index")
    index.add_to_head("Link", rel="stylesheet", href=STYLESHEET, type="text/css")
    index.add_header(1, "Test Plan Index")
    index.add_para("""Below is a list of test packages. Each test module
located in the package is documented inside the package document.  """)
    UL = index.get_unordered_list()
    index.append(UL)

    for dirname, dirs, files in os.walk(HOME):
        if "__init__.py" in files:
            pkgname = ".".join(dirname[hl:].split("/"))
            rstname = pkgname.replace(".", "_")+".rst"
            htmlname = pkgname.replace(".", "_")+".html"

            A = index.get_element("A", href=htmlname)
            A.add_text(pkgname)
            UL.add_item(A)

            fo = file(rstname, "w")
            extract_package(fo, pkgname)
            fo.close()
            publish_file(source_path=rstname, parser_name='restructuredtext', 
                        writer_name='html', destination_path=htmlname,
                        settings_overrides={"stylesheet":STYLESHEET})
            for fname in files: # copy any included files to destination
                if fname[-3:] in ("jpg", "png", "gif", "rst"):
                    shutil.copy(os.path.join(dirname, fname), DOCDIR)
        else:
            for fname in files:
                mo = py_matcher.match(fname)
                if mo:
                    modname = mo.group(1)
                    rstname = modname.replace(".", "_")+".rst"
                    htmlname = modname.replace(".", "_")+".html"

                    A = index.get_element("A", href=htmlname)
                    A.add_text(modname)
                    UL.add_item(A)

                    fo = file(rstname, "w")
                    extract_module(fo, modname)
                    fo.close()
                    publish_file(source_path=rstname, parser_name='restructuredtext', 
                                writer_name='html', destination_path=htmlname,
                                settings_overrides={"stylesheet":STYLESHEET})

    indexfile = file("testplan_index.html", "w")
    index.emit(indexfile)
    indexfile.close()
Exemplo n.º 25
0
def build_testplans(argv):
    py_matcher = re.compile(r"(^[a-zA-Z]+)\.py$", re.M)
    HOME = fix_path()
    home_len = len(HOME)+1
    if len(argv) > 1:
        DOCDIR = os.path.expanduser(os.path.expandvars(argv[1]))
    else:
        DOCDIR = "/var/www/localhost/htdocs/testplans"
    os.chdir(DOCDIR)
    index = XHTML.new_document()
    NM = index.nodemaker
    index.add_title("Package Index")
    index.stylesheet = INDEX_STYLESHEET
    index.add_header(1, "Package Index")
    index.new_para("""Here are the available packages.""")
    UL = index.get_unordered_list()
    index.append(UL)

    for dirname, dirs, files in os.walk(HOME):
        if "__init__.py" in files:
            pkgname = ".".join(dirname[home_len:].split("/"))
            if not pkgname:
                continue
            rstname = pkgname.replace(".", "_")+".rst"
            htmlname = pkgname.replace(".", "_")+".html"

            A = NM("A", {"href":htmlname})
            A.add_text(pkgname)
            UL.add_item(A)

            fo = file(rstname, "w")
            extract_package(fo, pkgname)
            fo.close()
            publish_file(source_path=rstname, parser_name='restructuredtext', 
                        writer_name='html', destination_path=htmlname,
                        settings_overrides={"link_stylesheet": True, "embed_stylesheet": False, "stylesheet_path": None, "stylesheet":STYLESHEET}
                        )
            for fname in files: # copy any included files to destination
                if fname[-3:] in ("jpg", "png", "gif", "rst"):
                    shutil.copy(os.path.join(dirname, fname), DOCDIR)
        else:
            for fname in files:
                mo = py_matcher.match(fname)
                if mo:
                    modname = mo.group(1)
                    rstname = modname.replace(".", "_")+".rst"
                    htmlname = modname.replace(".", "_")+".html"

                    A = NM("A", {"href":htmlname})
                    A.add_text(modname)
                    UL.add_item(A)

                    fo = file(rstname, "w")
                    extract_module(fo, modname)
                    fo.close()
                    publish_file(source_path=rstname, parser_name='restructuredtext', 
                                writer_name='html', destination_path=htmlname,
                                settings_overrides={"link_stylesheet": True, "embed_stylesheet": False, "stylesheet_path": None, "stylesheet":STYLESHEET},
                                )

    indexfile = file("testplan_index.html", "w")
    index.emit(indexfile)
    indexfile.close()