jaxml-3.01.orig/ 0042755 0001750 0001750 00000000000 07676515073 012207 5 ustar doko doko jaxml-3.01.orig/test/ 0042755 0001750 0001750 00000000000 07676515073 013166 5 ustar doko doko jaxml-3.01.orig/test/template.htt 0100644 0001750 0001750 00000001242 07461742572 015512 0 ustar doko doko You can visit ##link_to_my_homepage## if you want.
This document shows how well work the
variables substitution method (the _template() method).
If you look at the source of this document, you will see that
the 'some_text' variable wasn't replaced ##some_text## with anything but instead,
put in a comment. That's because the calling program didn't pass this
variable to the _template() method.
Just below a variable is incuded in a comment but when it is replaced it will be put out
of the comment, just like in the Whiz package from Neale Pickett at the LANL:
Bye.
jaxml-3.01.orig/test/test.py 0100755 0001750 0001750 00000021777 07630643572 014527 0 ustar doko doko #! /usr/bin/env python
# Test program for jaxml
#
# (C) Jerome Alet 2000
# You're welcome to redistribute this software under the
# terms of the GNU General Public Licence version 2.0
# or, at your option, any higher version.
#
# You can read the complete GNU GPL in the file COPYING
# which should come along with this software, or visit
# the Free Software Foundation's WEB site http://www.fsf.org
#
# $Id: test.py,v 1.13 2003/02/13 14:36:13 jerome Exp $
#
import sys
# import the jaxml module from the parent directory
sys.path.insert(0, "..")
import jaxml
print "\n\n==== TESTING XML ====\n"
# now we create an instance
# we may optionally pass a version and an encoding arguments.
x = jaxml.XML_document()
# first tag, with different attributes
# numeric values are automatically quoted
x.sometag(yes = "NO", some = "a bit", value = 5)
# this one, and till the end will be inside the previous one
x.anothertag("this tag and till the end will be inside the <sometag> ... </sometag>")
# here we save the current position
x._push()
# here some nested tags
x.whatever()
x.ilikepython()
x._text("Here we are inside <whatever><ilikepython> ... </ilikepython></whatever>")
# the following tag has nothing but attributes, we must save and restore it's
# position because it is followed by another tag (we doesn't want to enclose the following tag)
x._push()
x.someattributetag(attr = "Hey ! I'm the attribute !")
x._pop()
x.justatest("This is just a test", dummy="YES")
# here we want to continue our document
# at the same indentation level than
x._pop()
x.dummytag("we have just escaped", value = "Fine !")
x.dummytwo("Since the previous tag and this one were called with an unnamed first parameter\nwe didn't need _push() nor _pop()")
# here we insert plain text
x._text("Near the end")
# here we insert some text just like:
# Some dummy text
x.mytag("Some dummy text, and no tag attributes")
# here some beautiful tag nesting
x.onetag(message="This is").anotherone("a beautiful").deeper(message = "tag nesting possibility")
# here the naming space notation for ...
x.namingspace.onetag("This is how to use the naming space notation Space:Tag", wonderful="YES")
# here just a tag with attributes, but nothing in it
# we don't need to _push() and _pop() because it isn't followed by anything
x.attributetag(content = "I've got nothing enclosed in me", index = 9)
# here we save to a file
x._output("sampleXML.xml")
# but we may as well output it to the screen
print x
# test the new templating facility
# I urge you to read the following lines and look carefully at the result
# to see how this beautiful thing works !
x._text("Now we will replace some content with the new possibility of using a document as a mapping.")
x._text("This may be useful for templating without a template file, or replacing some chars with their equivalent SGML entities for example:")
x._text("Here are three accented characters, two of them which will be replaced\nwith their equivalent SGML entities: àéè")
x["nothing enclosed"] = "something enclosed"
x["SGML"] = "XML"
x["attributetag"] = "modifiedattributename"
x["é"] = "é";
x["è"] = "è";
x["à"] = "à";
# this is also available as readable attributes
sys.stderr.write('x["è"] = %s\n' % x["è"])
# and we can also delete them
del x["è"]
# or use the str() or repr() builtin functions
mydoc = "With str() or repr(), my modified document looks like:\n" + str(x) + "And that's all folks !"
print mydoc
# Now we want to test the HTML output
print "\n\n==== TESTING HTML ====\n"
page = jaxml.HTML_document()
# here we begin our html document
page.html()
# we must do a push and a pop in order for the tags
# to not be enclosed between and
page._push()
# build the head of the document
page.head()
#
#
# Other meta tags should work fine
page._meta(name="GENERATOR", content="jaxml.py v2.24 from Jerome Alet - alet@librelogiciel.com")
page._meta(name="DESCRIPTION", content="A CGI document, to test jaxml.py")
page._meta(name="KEYWORDS", content="python, jaxml, linux")
page.title("A CGI test document")
# here we exit from the ...
page._pop()
# we begin the body
page.body(bgcolor="pink")
# here we insert a dumb text
page._text("A small text")
# we do a push to be able to exit from the
page._push()
page.form(action="/cgi-bin/jerome/ok.py", method="POST")
page.h1("Form's title")
# to be able to exit from
page._push()
page.select(name="choice", size="1", multiple="multiple")
page.option("Choice number 1")
page.option("Choice number 2", selected="selected")
page.option("Choice number 3")
# exit from
page._pop()
page.h3("Second part of the Form")
page._br()
page._textinput(name="dumbstring", size="50")
page._submit()
page._reset()
# here we exit from the
page._pop()
page._text("here we should be outside of the form")
page._text("and there we should be one the same line visually but on two different lines in the html file")
page.a("Click on Me", href="http://www.slashdot.org")
page.pre("Hello !!!\n\t\tBye Bye\n\n")
page._text("Here we should be outside of the PRE.../PRE tag")
# then we insert some text
page._text("Just below you will see some lines of text which are included from a template file, with variables substitution:")
page._br()
# then we include the template file
page._template("template.htt", font_color='red', link_to_my_homepage="My website", another_variable="
Thank you for trying
")
# then some separation
page.hr(width="33%", noshade="noshade")
# here we do the output to the screen
page._output()
# and here we do the output to a file
page._output("sampleHTML.html")
# Now we want to test the CGI/HTML output
print "\n\n==== TESTING CGI ====\n"
# just some dummy values
page = jaxml.CGI_document(encoding = "utf-8", content_type="text/html", version = "3.0")
# to do a redirection, just do
# page.set_redirect("http://www.librelogiciel.com/")
# then just call page.output("")
# here again we can do that whenever we want (before output)
# text/html is the default for _set_content_type()
#page._set_content_type("application/pdf")
# to define a pragma, just use:
# page._set_pragma("pragma_name")
# we can do that whenever we want, (before output)
# to define an expiration date, just use:
# page._set_expires("expiration_date")
# we can do that whenever we want, (before output)
# Maybe this should be done by the class's __init__ function
# but I don't think so in order for us to have more control
page._default_header(title = 'a CGI document')
# we begin the body
page.body(bgcolor="pink")
# here we insert a dumb text
page._text("A small text")
# we do a push to be able to exit from the
page._push()
page.form(action="/cgi-bin/jerome/ok.py", method="POST")
page.h1("Form's title")
# to be able to exit from
page._push()
page.select(name="choice", size="1")
page.option("Choice number 1")
page.option("Choice number 2")
page.option("Choice number 3", selected="selected")
# exit from
page._pop()
page.h3("Second part of the Form")
page._br()
page._textinput(name="dumbstring", size="50")
page._submit()
page._reset()
# here we exit from the
page._pop()
page._text("here we should be outside of the form")
page._text("and there we should be one the same line visually but on two different lines in the html file")
page.a("Click on Me", href="http://www.slashdot.org")
page.pre("Hello !!!\n\t\tBye Bye\n\n")
page._text("Here we should be outside of the PRE.../PRE tag")
# here we define a debug file which will receive the CGI output too
page._set_debug("CGI_debug.html")
# here we do the output
# for a CGI script, give an empty string (for stdout)
# or None, or nothing, unless you want to debug (give a filename) or a file object
page._output("")
# Now we want to test the arithmetic operations
print "\n\n==== TESTING ARITHMETIC ====\n"
print "page + page = %s" % (page + page)
print "page + 'string' = %s" % (page + 'string')
print "'string' + page = %s" % ('string' + page)
print "page * 2 = %s" % (page * 2)
print "2 * page = %s" % (2 * page)
# new name spaces support
x = jaxml.XML_document()
x.tag("hello", name="blah")
x.another("bloum",
{ "xmlns": { "tal" : "http://xml.zope.org/namespaces/tal",
"metal": "http://xml.zope.org/namespaces/metal"},
"metal": {"use-macro" : "here/StandardLookAndFeel/macros/master"},
"" : { "class" : "header"}
})
x._push("save")
x.otherone({ "xmlns": { "tal" : "http://xml.zope.org/namespaces/tal",
"metal": "http://xml.zope.org/namespaces/metal"},
"metal": {"use-macro" : "here/StandardLookAndFeel/macros/master"},
"" : { "class" : "header"}
})
x._push()
x.inside(name="inside")
x.atag()
x._text("blah")
x._pop("save")
x.outside(attrib="None")
print x
jaxml-3.01.orig/COPYING 0100644 0001750 0001750 00000043334 07461742571 013241 0 ustar doko doko GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307, USA.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
Appendix: How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C) 19yy
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.
jaxml-3.01.orig/CREDITS 0100644 0001750 0001750 00000000620 07630643572 013214 0 ustar doko doko # jaxml credits file.
Many thanks to Kragen Sitaker and is invaluable post on comp.lang.python,
which multiplied jaxml speed by approximately 2.2 on the test.py program
launched 5000 times. Speed gain is expected to be even more important on
big xml documents.
Thanks to Jean Jordaan who found a pretty elegant way to solve the namespace
and reserved words problem. See at the end of test/test.py
jaxml-3.01.orig/MANIFEST.in 0100644 0001750 0001750 00000000123 07461742572 013732 0 ustar doko doko include COPYING NEWS AUTHORS CREDITS MANIFEST.in
recursive-include test *.py *.htt
jaxml-3.01.orig/NEWS 0100644 0001750 0001750 00000012746 07676514731 012713 0 ustar doko doko # jaxml (c) 2000-2001 Jerome Alet & Free Software Foundation
#
# $Id: NEWS,v 1.31 2003/06/26 06:59:31 jerome Exp $
#
jaxml NEWS:
===========
3.01: - Small fix.
3.00: - Full support for XML namespaces added (see end of test program)
- Named indentation levels, for easier use.
2.24: - Copyright strings changed.
2.23: - a typo caused a bug when _do_nothign() was called
in CGI scripts
2.22: - nothing is output when there's no content to output.
2.21: - the _updatemapping() method now returns the new mapping's
content.
- a minor bug which prevented headers
to be kept correct when adding or multiplying documents
was corrected.
- the copy module is not needed anymore.
2.20: - basic arithmetic operations can now be made on XML_document
instances, these constructs are now accepted:
firstdoc + seconddoc
seconddoc + firstdoc
Where firstdoc is an instance of XML_document
or one of its subclasses, and seconddoc is
either an instance of XML_document or one of
its subclasses or a string of text.
Nota Bene: This will not exactly concatenate the
two documents, instead the second one will be inserted
as plain text at the current position in the new one.
This may cause the indentation of the resulting document
looks bad.
yourdoc * intvalue
intvalue * yourdoc
Will repeat your document just like the * operator
works with strings of text.
Nota Bene: Since a multiplication is a big addition, same
remark as above.
- an infinite loop problem occured when doing a dir(yourdoc),
it is now corrected, but as a consequences every method
name beginning with "__" can't be used as a tag name.
This shouldn't cause any problem, because tag names
beginning with "__" are probably a very bad idea, if allowed
at all.
- an _updatemapping method was added to allow you to initialise
or update the internal mapping used for the new templating
facility.
2.10: - Docstrings added to the _TAGGED_document.Tag class.
- The __repr__ method is now defined once for all.
- You can now use yourdoc["something"] = "anotherthing"
to do powerful templating. See the test/test.py program
for details, but beware: documents are not real mappings.
- Truth value can now be tested: returns false for empty
documents.
2.00beta1: - Now fully integrates the jahtml module's
functionnalities, providing access to
an HTML_document class and a CGI_document
class. WARNING: the API for what was in jahtml has
changed, you MUST modify your programs before removing
the old jahtml module.
- The jahtml module is now considered as being obsolete.
- includes templating facilities for the XML_document class
as well as for the HTML_document and CGI_document classes
1.29: - Rollback on certain "speed optimisations"
- Needs cStringIO again.
1.28: - Numerous speed optimisations
- Doesn't need the cStringIO module anymore
1.27: - Speed optimisation
1.26: - The notation for naming spaces was introduced:
doc.space.tag(...)
will produce:
...
1.25: - A new useful notation was introduced, you can now
do something like:
doc.onetag("...", attr="yes").othertag().adnauseam("easy tag nesting")
1.24: - Tags that enclose nothing are now handled correctly,
see test/test.py for examples.
- Calls to yourtag("Some text", dummy="DUMMY") will
now produce:
Some text
instead of :
Some text
- Some changes to the test program to reflect the
new behaviour.
1.23: - Now the license is set in setup.py
- Now the _output() method accepts None
as the file argument
- Minor changes to the documentation
1.22: - small problem in the documentation
1.21: - small bug correction with empty text
1.2 : - Large scale speed optimisations. The test
program launched 5000 times is now 2.5 times
faster than the 1.1
See the file CREDITS for details
1.1 : - Now uses distutils as the installation method.
- Documentation fixes, thanks to Kragen Sitaker.
jaxml-3.01.orig/README 0100600 0001750 0001750 00000017225 07676514633 013062 0 ustar doko doko jaxml v3.01 - June 26th 2003
(C) Jerome Alet 2000-2003
You're welcome to redistribute this software under the
terms of the GNU General Public Licence version 2.0
or, at your option, any higher version.
You can read the complete GNU GPL in the file COPYING
which should come along with this software, or visit
the Free Software Foundation's WEB site http://www.fsf.org
----------------------------------------------------------
I was recently asked if the GPL meant that if you just import this
module then you should license your software under the GPL, here's
the answer:
You've written a software which uses (import) my GPLed module.
- If you don't plan to redistribute your software (e.g. internal use only),
then you can do whatever you want, and hide your software's sources from
your co-workers if you want (but not my software's sources).
- BUT, if you want to redistribute your software to a third party,
then your software MUST be GPLed too, and distributed with all its sources.
Please consider this module just like a GPLed C library, not a LGPLed
one.
I hope this is clearer now. Just refer to the GPL (the file COPYING)
for details.
FYI I've choosen to GPL this module because I strongly believe
in the Free Software movement, and want to discourage the
creation of proprietary software.
----------------------------------------------------------
This python module defines a class named XML_document which will
allow you to generate XML documents (yeah !) more easily than
using print or similar functions.
Here's a list of available methods:
===================================
__init__(version, encoding)
The instance constructor, automatically called
when you create a new instance of XML_document.
you can optionnally pass a version and encoding
string, the defaults are "1.0" and "iso-8859-1".
_indentstring(istr)
istr is the new indentation string used
to nicely present your XML documents. By
default istr is equal to 4 space characters.
_output(filearg)
use it to save the XML document to a file.
The optionnal filearg argument may be:
None, "", or "-" which stands for sys.stdout.
a file name.
any file object.
_text(sometext)
use it to insert plain text at the current position
in the document.
_push()
saves the current position in the XML document.
use it if you're going to create a bunch of nested
XML tags and want to escape from them later to continue
your document at the same indentation level.
you can pass an optional 'name' argument, to mark
a position by its name.
_pop()
restores the latest saved position.
use it to escape from nested tags and continue
your XML document at the same indentation level than
the latest time you called _push().
you can pass an optional 'name' argument, to continue
at the same indentation level as when you called _push()
with the same 'name' argument.
_template(file, **vars)
loads a template file and insert it as plain text at the current
position in the document, replacing ##varname## variables
in the template file with their corresponding value passed
in vars[varname]
_updatemapping(newmap)
updates the internal mapping used for replacing some strings with
others when rendering. This can be used as an easy way to
do templating without the need of an external file.
Pass None or no argument to reset the mapping to an empty one.
This method returns the new mapping's content.
Some more methods are available but not meant to be used directly, they
are: __nonzero__, __getitem__, __setitem__, __delitem__, __coerce__, __add__,
__radd__, __mul__, __rmul__, and __copy__. They are used automatically when doing
special things, read the source for details.
ANY and ALL other method you may call will be treated as an XML
tag, unless it already exists as a method in XML_document or a subclass of it,
or its name begins with "__". I suggest you to only add methods whose names
begin with '_' to keep things simple and clear: "__" is reserved for future
use.
The file test/test.py is an example program which generates
some documents, just play with it (use and modify) and you'll
learn quickly how to use jaxml. Its source code is documented and
attempts at describing and trying all jaxml's possibilities, so reading
it is probably the best way to become powerful with jaxml in less than
10 minutes.
Really, PLEASE READ the file test/test.py to learn all possibilities,
newer possibilities are at the end of the file.
=========================================================================
Since version 2.00, jaxml integrates the full functionnalities of the
old jahtml module via the HTML_document and CGI_document classes, however
the API for these two classes has changed to be cleaner and don't use any
predefined set of tags.
The HTML_document() and CGI_document() classes both inherit from XML_document()
and all its methods (see above), but also feature some useful helper methods.
Please read the jaxml module sources and the test/test.py program to learn how
to use them.
=========================================================================
The only difficult things are:
------------------------------
* you have to use the _push() and _pop() methods if you need
to get out of a bunch of nested tags.
* if you call a method (tag) with a string as the first
unnamed parameter, you won't need _push() or _pop()
because your tag will be automatically closed immediately.
* if you call a method (tag) with a python mapping as the
first or second unamed parameter, this mapping is used
to correctly handle XML namespaces or attributes
which are python reserved words (e.g. class), please
look at test/test.py to see an example.
----------------------------------------------------------
INSTALLATION:
=============
If you don't have Distutils installed (e.g. python version <= 1.5.2)
then first download it from:
http://www.python.org/sigs/distutils-sig/
then follow the installation instructions for Distutils and install
it on your system.
Download the latest jaxml version from:
http://www.librelogiciel.com/software/
Extract it:
gzip -d jaxml-x.xx.tar.gz | tar -xf -
where x.xx is jaxml's latest version number.
Go to jaxml directory:
cd jaxml-x.xx
Just type:
python setup.py install
You may need to be logged in with sufficient privileges (e.g. root)
You can optionnaly go to the test subdirectory and run test.py,
this should produce some XML output both on the screen and in
a file named sampleXML.xml
If you've got the old jahtml module, then you can remove it from your
disk, after having modified your programs to use the new jaxml API.
Voilà !
----------------------------------------------------------
You're very welcome to send me any idea or patch about this module.
See the CREDITS file for credits.
Always remember that the test/test.py program and the jaxml.py
module's source code are your best friends.
I hope this will be helpful to someone else.
Feedback is very welcome.
Jerome Alet -
jaxml-3.01.orig/jaxml.py 0100644 0001750 0001750 00000140142 07676514732 013672 0 ustar doko doko # Module for XML, HTML and CGI output
# jaxml
# (C) Jerome Alet 2000-2002
# You're welcome to redistribute this software under the
# terms of the GNU General Public Licence version 2.0
# or, at your option, any higher version.
#
# You can read the complete GNU GPL in the file COPYING
# which should come along with this software, or visit
# the Free Software Foundation's WEB site http://www.fsf.org
#
# $Id: jaxml.py,v 1.43 2003/06/26 06:59:32 jerome Exp $
#
# $Log: jaxml.py,v $
# Revision 1.43 2003/06/26 06:59:32 jerome
# Small fix.
#
# Revision 1.42 2003/02/13 14:36:09 jerome
# Version 3.0
#
# Revision 1.41 2003/02/13 10:33:58 jerome
# Version number changed to 3.0beta
# Named _push() and _pop() possibility (untested)
# Complete namespaces support thanks to Jean Jordaan
#
# Revision 1.40 2002/04/25 09:08:34 jerome
# New copyright strings
#
# Revision 1.39 2002/03/02 09:19:36 jerome
# typo in _do_nothing() in CGI scripts
#
# Revision 1.38 2001/04/23 12:17:08 jerome
# Nothing is output when there's no content to output.
#
# Revision 1.37 2001/02/23 15:02:49 jerome
# Correction of a minor bug which prevented headers to be kept correct
# when adding or multiplying documents
#
# Revision 1.36 2001/02/22 08:27:07 jerome
# The copy module is not needed anymore.
#
# Revision 1.35 2001/02/21 16:26:15 jerome
# Version number changed to 2.21
# The _updatemapping() method now returns the new mapping's content.
#
# Revision 1.34 2001/02/21 11:54:56 jerome
# Typo
#
# Revision 1.33 2001/02/21 11:40:47 jerome
# - version number changed to 2.20
# - basic arithmetic operations can now be made on XML_document
# instances, these constructs are now accepted:
#
# firstdoc + seconddoc
# seconddoc + firstdoc
#
# Where firstdoc is an instance of XML_document
# or one of its subclasses, and seconddoc is
# either an instance of XML_document or one of
# its subclasses or a string of text.
#
# yourdoc * intvalue
# intvalue * yourdoc
#
# Will repeat your document just like the * operator
# works with strings of text.
#
# - an infinite loop problem occured when doing a dir(yourdoc),
# it is now corrected, but as a consequences every method
# name beginning with "__" can't be used as a tag name.
# This shouldn't cause any problem, because tag names
# beginning with "__" are probably a very bad idea, if allowed
# at all.
# - an _updatemapping method was added to allow you to initialise
# or update the internal mapping used for the new templating
# facility.
#
# Revision 1.32 2001/02/19 13:42:10 jerome
# Suppressed a remaining debugging test
#
# Revision 1.31 2001/02/19 13:38:38 jerome
# Version changed to 2.10
# Added a new templating method, using documents as pseudo mappings:
# mydoc["some text"] = "another text"
# will replace all occurences of "some text" with "another text" on
# rendition (only), i.e. when either str() or repr() are called.
# Truth value can now be tested: empty documents return false.
#
# Revision 1.30 2001/02/14 10:49:20 jerome
# Typo
#
# Revision 1.29 2001/02/14 10:48:44 jerome
# Version number changed to 2.10
# Docstrings added to the _TAGGED_document.Tag class
# __repr__ is defined once for all
#
# Revision 1.28 2001/02/06 09:50:30 jerome
# Added documentation for the _template() method
# Added some doc for the HTML_document() and CGI_document() classes
#
# Revision 1.27 2001/02/05 16:03:59 jerome
# The CGI_document() constructor now accepts version and encoding arguments
#
# Revision 1.26 2001/02/05 14:49:55 jerome
# Exit code when using the old Html_document class was set to -1 (unsuccessful) instead of 0 (successful)
#
# Revision 1.25 2001/02/05 14:43:10 jerome
# Version number changed to 2.00beta1
#
# Revision 1.24 2001/02/05 14:31:07 jerome
# Version number changed to 2.00
# jaxml now includes what was in the old jahtml module, and features two new
# classes: HTML_document() and CGI_document().
# jaxml's API hasn't changed.
# jahtml's old API was changed to better match jaxml's one.
#
# ========================================================================
# = You don't need the old jahtml module anymore, but before removing it =
# = you must modify your programs to take care of the new API. =
# ========================================================================
#
# Revision 1.23 2001/01/26 12:43:16 jerome
# Rollback on "speed optimisations"
#
# Revision 1.22 2001/01/26 11:01:44 jerome
# The reduce line is commented out because it is much more slower then string.join + map
#
# Revision 1.21 2001/01/26 10:44:07 jerome
# Another speed optimisation
#
# Revision 1.20 2001/01/26 10:08:29 jerome
# Large scale speed optimisations
#
# Revision 1.19 2001/01/25 15:09:34 jerome
# Another optimisation
#
# Revision 1.18 2001/01/25 15:01:57 jerome
# Small speed optimisation in the _pop() method
#
# Revision 1.17 2001/01/25 13:28:48 jerome
# Version number changed to 1.26
# The notation for naming spaces was introduced:
#
# doc.space.tag(...)
#
# will produce:
#
#
# ...
#
#
# Revision 1.16 2001/01/25 12:22:03 jerome
# A new useful notation was introduced, you can now
# do something like:
#
# doc.onetag("...", attr="yes").othertag().adnauseam("easy tag nesting")
#
# Revision 1.15 2001/01/25 11:25:50 jerome
# Version number changed to 1.24
# Tags which enclose nothing are now handled correctly
# Calls to yourtag("Some text", dummy="DUMMY") will
# now produce:
#
# Some text
#
# instead of :
#
#
# Some text
#
#
# Some changes to the test program to reflect the new behaviour
#
# Revision 1.14 2001/01/23 10:30:24 jerome
# The _output() method now accepts None as its file argument
# Minor changes to the documentation
# Copyright year changed to 2000-2001
#
# Revision 1.13 2000/10/04 11:50:30 jerome
# The license is correctly set to "GNU GPL" in setup.py
# Version number change to 1.23
#
# Revision 1.12 2000/09/29 13:49:36 jerome
# The documentation referenced a non existing file.
#
# Revision 1.11 2000/09/29 13:25:37 jerome
# Small but correction with empty text, use None instead
#
# Revision 1.10 2000/09/29 11:14:18 jerome
# The traceback module is not needed anymore
#
# Revision 1.9 2000/09/29 11:02:26 jerome
# With the help of Kragen Sitaker idea posted on comp.lang.python,
# the speed increase factor is now almost 2.5 compared to the 1.1 version.
# Test made on the test.py program launched 5000 times.
#
# Revision 1.8 2000/09/29 08:55:04 jerome
# Near 13% speed optimisation on the test program launched 5000 times.
#
# Revision 1.7 2000/09/29 08:43:30 jerome
# Optimisations
#
# Revision 1.6 2000/09/29 07:42:52 jerome
# Version number changed to 1.2
#
# Revision 1.5 2000/09/28 10:06:09 jerome
# The frenglish word "imbricated" was replaced by the correct english one "nested",
# thanks to Kragen Sitaker.
# Version number changed to 1.1 because seems stable and want more testers: the
# Freshmeat Version Number Effect ;-)
#
# Revision 1.4 2000/09/15 08:30:41 jerome
# Version string and Documentation string added.
#
# Revision 1.3 2000/09/15 08:27:10 jerome
# Clarification on the licensing issue.
# General documentation changes.
# No code changes but version set to 0.3
#
# Revision 1.2 2000/09/14 07:15:29 jerome
# All tag attributes values are now quoted correctly.
# Using attributes with no value at all is not allowed anymore.
# Now xmllib doesn't complain anymore on sampleXML.py output.
#
#
import sys
import os
import string
import cStringIO
import time
__version__ = "3.01"
__doc__ = """
This python module defines a class named XML_document which will
allow you to generate XML documents (yeah !) more easily than
using print or similar functions.
Here's a list of available methods:
===================================
__init__(version, encoding)
The instance constructor, automatically called
when you create a new instance of XML_document.
you can optionnally pass a version and encoding
string, the defaults are "1.0" and "iso-8859-1".
_indentstring(istr)
istr is the new indentation string used
to nicely present your XML documents. By
default istr is equal to 4 space characters.
_output(filearg)
use it to save the XML document to a file.
The optionnal filearg argument may be:
None, "", or "-" which stands for sys.stdout.
a file name.
any file object.
_text(sometext)
use it to insert plain text at the current position
in the document.
_push()
saves the current position in the XML document.
use it if you're going to create a bunch of nested
XML tags and want to escape from them later to continue
your document at the same indentation level.
you can pass an optional 'name' argument, to mark
a position by its name.
_pop()
restores the latest saved position.
use it to escape from nested tags and continue
your XML document at the same indentation level than
the latest time you called _push().
you can pass an optional 'name' argument, to continue
at the same indentation level as when you called _push()
with the same 'name' argument.
_template(file, **vars)
loads a template file and insert it as plain text at the current
position in the document, replacing ##varname## variables
in the template file with their corresponding value passed
in vars[varname]
_updatemapping(newmap)
updates the internal mapping used for replacing some strings with
others when rendering. This can be used as an easy way to
do templating without the need of an external file.
Pass None or no argument to reset the mapping to an empty one.
This method returns the new mapping's content.
Some more methods are available but not meant to be used directly, they
are: __nonzero__, __getitem__, __setitem__, __delitem__, __coerce__, __add__,
__radd__, __mul__, __rmul__, and __copy__. They are used automatically when doing
special things, read the source for details.
ANY and ALL other method you may call will be treated as an XML
tag, unless it already exists as a method in XML_document or a subclass of it,
or its name begins with "__". I suggest you to only add methods whose names
begin with '_' to keep things simple and clear: "__" is reserved for future
use.
The file test/test.py is an example program which generates
some documents, just play with it (use and modify) and you'll
learn quickly how to use jaxml. Its source code is documented and
attempts at describing and trying all jaxml's possibilities, so reading
it is probably the best way to become powerful with jaxml in less than
10 minutes.
Really, PLEASE READ the file test/test.py to learn all possibilities.
=========================================================================
Since version 2.00, jaxml integrates the full functionnalities of the
old jahtml module via the HTML_document and CGI_document classes, however
the API for these two classes has changed to be cleaner and don't use any
predefined set of tags.
The HTML_document() and CGI_document() classes both inherit from XML_document()
and all its methods (see above), but also feature some useful helper methods.
Please read the jaxml module sources and the test/test.py program to learn how
to use them.
=========================================================================
The only difficult things are:
------------------------------
* you have to use the _push() and _pop() methods if you need
to get out of a bunch of nested tags.
* if you call a method (tag) with a string as the first
unnamed parameter, you'll don't need _push() or _pop()
because your tag will be automatically closed immediately.
* if you call a method (tag) with a python mapping as the
first or second unamed parameter, this mapping is used
to correctly handle XML namespaces or attributes
which are python reserved words (e.g. class), please
look at test/test.py to see an example.
"""
class _TAGGED_document :
"""This class defines a tagged document"""
class Tag :
"""This class defines a tag
This is largely inspired from a post in comp.lang.python
by Kragen Sitaker at the end of September 2000. Many
thanks to him !!!
"""
def __init__(self, parent, tagname) :
"""Save a link to the parent and the name of the tag for future reference
parent
The parent object, probably a _TAGGED_document instance.
tagname
The name of this tag
"""
self.__parent = parent
self.__tagname = tagname
def __call__(self, _text_ = None, *nsattributes, **attributes) :
"""Inserts the tag and its attributes in the document
_text_
eventually a string to be enclosed in the tag. the
name _text_ was chosen to not conflict with a probable user's attribute
called 'text'
"""
#
# NameSpace idea from Jean Jordaan
if type(_text_) == type({}) :
nsattributes = (_text_, )
_text_ = None
nsargs = ""
lg = len(nsattributes)
if (lg > 1) :
raise ValueError, "jaxml: Invalid attributes %s" % str(nsattributes[0])
elif lg :
nsattr = nsattributes[0]
try :
for ns in nsattr.keys() :
tags = nsattr[ns]
try :
for tag in tags.keys() :
nsargs = nsargs + ' %s%s%s="%s"' % (ns, (ns and ':'), tag, str(tags[tag]))
except AttributeError :
nsargs = nsargs + ' %s="%s"' % (ns, str(tags))
except AttributeError :
raise ValueError, "jaxml: Invalid attributes %s" % str(nsattr)
# first, we compute the attributes string
# we vonluntarily do the test because of the speed optimisation
# it gives when there's no attribute
if attributes :
# interestingly the "reduce" line is much more slower than the "string.join + map" one
# arg = reduce(lambda s,x,a=attributes: '%s %s="%s"' % (s, x, str(a[x])), attributes.keys(), "")
arg = string.join(map(lambda x,a=attributes: ' %s="%s"' % (x, str(a[x])), attributes.keys()), "")
else :
arg = ""
# if a "first" argument was passed, enclose it in the tag
# and just get out of this tag
if _text_ is not None :
self.__parent._text("<%s%s>%s%s>" % (self.__tagname, arg + nsargs, str(_text_), self.__tagname))
else :
# future tags will be inserted inside this one
self.__parent._tag__(self.__tagname, arg + nsargs)
return self.__parent
def __getattr__(self, name) :
"""Handles naming spaces (Space:Tag)
name
The name of the (sub)tag part
The current tag's name becomes the naming space's name.
name becomes the new tag's name.
"""
return self.__parent.Tag(self.__parent, "%s:%s" % (self.__tagname, name))
def __init__(self) :
"""Initialize local datas"""
# the document itself
self.__page = []
self.__pushed = []
self.__pusheddict = {}
self.__position = 0
# Initialise a mapping to implement another templating
# facility for postprocessing
self._updatemapping()
# sets the default indentation string
self._indentstring()
def __copy__(self) :
"""Creates a copy of the current document"""
# create an instance of the same class
new = self.__class__()
# copy the "private" members
new.__page = self.__page[:]
new.__pushed = self.__pushed[:]
new.__pusheddict = self.__pusheddict.copy()
new.__position = self.__position
new.__indentstring = self.__indentstring
new.__mapping = self.__mapping.copy()
# copy the "public" ones which are not callable (shouldn't occur anyway)
for (key, value) in self.__dict__.items() :
if (key[:2] == "__") and (key[-2:] == "__") and not callable(getattr(self, key)) :
setattr(new, key, value)
return new
def __mul__(self, number) :
"""Allows a document to be repeated
number
The number of times to repeat the document
allows constructs like: mydoc * 3
"""
if type(number) != type(1) :
raise TypeError, "jaxml.py: __mul__ operation not permitted on these operands."
if number < 0 :
raise ValueError, "jaxml.py: can't repeat a document a negative number of times."
if number == 0 :
# returns an empty document
return self.__class__()
else :
# a multiplication is just a big addition...
new = self.__copy__()
for i in range(number - 1) :
new = new + self
return new
def __rmul__(self, number) :
"""Allows a document to be repeated
number
The number of times to repeat the document
allows construts like: 3 * mydoc
"""
return self * number
def __add__(self, other) :
"""Allows two documents to be concatenated
other
The document or string of text to concatenate to self
This is not a real concatenation: the second
document (other) is in fact inserted at the current
position in the first one (self).
Also allows constructs like: mydoc + "some text"
"""
if (not isinstance(other, _TAGGED_document)) and (type(other) != type("")) :
raise TypeError, "jaxml.py: __add__ operation not permitted on these operands."
# first we make a copy of the original
new = self.__copy__()
# we must also "concatenate" our two template mappings
new.__mapping.update(other.__mapping)
# then we insert other as a single string of text
# skipping the last new line character.
# we use the parent class __str__ method to skip
# all the leading garbage like XML or HTTP headers.
# we should insert it as tags + text instead of plain text...
new._text(_TAGGED_document.__str__(other)[:-1])
return new
def __radd__(self, other) :
"""Allows two documents to be concatenated
other
The document or string of text to which self will be concatenated
This is not a real concatenation: the first
document (self) is in fact inserted at the current
position in the second one (other).
Also allows constructs like: "some text" + mydoc
"""
return other + self
def __coerce__(self, other) :
"""Try to convert two documents to a common type"""
if isinstance(other, _TAGGED_document) :
# no problem, compatible types
return (self, other)
elif type(other) == type("") :
# a string of text must be converted
# to self's type
new = self.__class__()
new._text(other)
return (self, new)
elif type(other) == type(1) :
# probably a __mul__ operation
return (self, other)
else :
# conversion is impossible
return None
def __getattr__(self, name) :
"""Here's the magic: we create tags on demand
name
The name of the tag we want to create
"""
# don't accept __xxxxx names
# we reserve them for internal or/and future use
if (name[:2] != "__") :
return self.Tag(self, name)
def __nonzero__(self) :
"""For truth value testing, returns 1 when the document is not empty"""
if self.__page :
return 1
else :
return 0
def __getitem__(self, key) :
"""returns key's value in the internal mapping"""
return self.__mapping[key]
def __setitem__(self, key, value) :
"""sets key's value in the internal mapping"""
self.__mapping[key] = value
def __delitem__(self, key) :
"""deletes this key from the internal mapping"""
del self.__mapping[key]
def __str__(self) :
"""returns the document as a string of text"""
outstr = cStringIO.StringIO()
indentation = ""
lgindent = len(self.__indentstring)
lastopened = None
for (text, arg, offset) in self.__page :
if offset == -1 : # closing tag
indentation = indentation[: -lgindent]
if text != lastopened : # normal case
outstr.write("%s%s>\n" % (indentation, text))
else : # noting enclosed
outstr.seek(-2, 1)
outstr.write(" />\n")
lastopened = None
elif offset == 1 : # opening tag
outstr.write("%s<%s%s>\n" % (indentation, text, arg))
indentation = indentation + self.__indentstring
lastopened = text
else : # plain text
outstr.write("%s%s\n" % (indentation, text))
lastopened = None
outstr.flush()
retval = outstr.getvalue()
outstr.close()
# and now we use the internal mapping
# to postprocess the document.
# This may prove to be useful for replacing chars with their
# equivalent SGML entities for example, or for templating
# without a template file.
for (key, value) in self.__mapping.items() :
retval = string.replace(retval, key, value)
return retval
def __repr__(self) :
"""Returns a printable representation of the document, same as str() for now"""
# we define it with a 'def' instead of doing __repr__ = __str__ like the previous versions did
# because we may redefine __str__ in subclasses and don't want to
# have to redefine __repr__ too.
#
# This way it is done once for all:
return str(self)
def __adjust_stack(self, offset) :
"""Adjust the stack of pushed positions.
offset
offset by which adjust the stack
"""
if self.__pushed :
pos, oldoffset = self.__pushed.pop()
self.__pushed.append((pos, oldoffset + offset))
def _tag__(self, tag, arg) :
self.__page.insert(self.__position, (tag, arg, 1))
self.__position = self.__position + 1
self.__page.insert(self.__position, (tag, None, -1))
self.__adjust_stack(2)
#
# Callable interface starts here
def _push(self, name=None) :
"""Push the current tag's position.
useful before a block of nested tags
name : can be used to name the pushed position and pop it later directly
"""
if name :
self.__pusheddict[name] = len(self.__pushed)
self.__pushed.append((self.__position, 0))
def _pop(self, name=None) :
"""Restore the latest pushed position.
useful to get out of a block of nested tags
name : can be used to restore a named position, not necessarily the latest.
"""
if self.__pushed :
maxindex = len(self.__pushed) - 1
if name :
try :
index = self.__pusheddict[name]
del self.__pusheddict[name]
except KeyError :
raise KeyError, "jaxml named position %s doesn't exist" % name
else :
index = maxindex
while maxindex >= index :
pos, offset = self.__pushed.pop()
self.__position = pos + offset
self.__adjust_stack(offset) # we report the offset on previously saved tags
maxindex = maxindex - 1
def _text(self, text):
"""Insert plain text in the document
text
text to be inserted
"""
self.__page.insert(self.__position, (str(text), None, 0))
self.__position = self.__position + 1
self.__adjust_stack(1)
def _indentstring(self, newindentstring = " "):
"""Sets the indentation string for the output (default is 4 space characters)"""
self.__indentstring = newindentstring
def _updatemapping(self, newmap = None) :
"""Updates the internal mapping for the new templating facility,
and returns the new mapping's content
newmap
a Python mapping object to initialise or extend the
mapping. If None then the mapping is reset to an empty dictionnary
which is the default value.
"""
if newmap == None :
# clears the template mapping
self.__mapping = {}
return self.__mapping
elif type(newmap) == type({}) :
# update or extend the current mapping
self.__mapping.update(newmap)
return self.__mapping
else :
raise TypeError, "jaxml.py: _updatemapping's parameter must be a Python mapping object."
def _output(self, file = "-") :
"""Ouput the page, with indentation.
file
the optional file object or filename to output to
("-" or None or "" means sys.stdout)
"""
isopen = 0
if (type(file) == type("")) or (file is None) :
if file and (file != "-") :
outf = open(file, "w")
isopen = 1
else :
outf = sys.stdout
else :
outf = file # we assume it's a file object
outf.write("%s" % str(self))
outf.flush()
if isopen :
outf.close()
class XML_document(_TAGGED_document) :
"""This class defines an XML document"""
def __init__(self, version = "1.0", encoding = "iso-8859-1") :
"""Initialize local datas.
arguments:
version: xml version string
encoding: xml encoding language
"""
_TAGGED_document.__init__(self)
self.__version__ = version
self.__encoding__ = encoding
def __str__(self) :
"""returns the XML document as a string of text"""
tagdocstr = _TAGGED_document.__str__(self)
if tagdocstr :
return ("""\n""" % (self.__version__, self.__encoding__)) + tagdocstr
else :
return ""
def __subst_lines(self, lines, **vars):
"""Substitues var names with their values.
parts of this function come from the Whiz package
THANKS TO Neale Pickett ! Here follows the original license terms for Whiz:
## Author: Neale Pickett
## Time-stamp: <99/02/11 10:45:42 neale>
## This software and ancillary information (herein called "SOFTWARE")
## called html.py made avaiable under the terms described here. The
## SOFTWARE has been approved for release with associated LA-CC Number
## 89-47.
## Unless otherwise indicated, this SOFTWARE has been authored by an
## employee or employees of the University of California, operator of
## the Los Alamos National Laboratory under contract No. W-7405-ENG-36
## with the U.S. Department of Energy. The U.S. Government has rights
## to use, reproduce, and distribute this SOFTWARE. The public may
## copy, distribute, prepare derivative works and publicly display this
## SOFTWARE without charge, provided that this Notice and any statement
## of authorship are reproduced on all copies. Neither the Government
## nor the University makes any warranty, express or implied, or assumes
## any liability or responsibility for the use of this SOFTWARE.
## If SOFTWARE is modified to produce derivative works, such modified
## SOFTWARE should be clearly marked, so as not to confuse it with the
## version available from LANL.
"""
import regex
container = regex.compile('\(\)?')
for line in lines:
while container.search(line) != -1:
try:
replacement = str(vars[container.group(2)])
except KeyError:
replacement = str('')
pre = line[:container.regs[0][0]]
post = line[container.regs[0][1]:]
if string.strip(pre) == '':
# pre is just whitespace, so pad our replacement's lines with that space
lines = string.split(replacement, '\n')
new = [lines[0]]
for l in lines[1:]:
new.append(pre + l)
replacement = string.join(new, '\n')
line = "%s%s%s" % (pre, replacement, post)
self._text(line)
def _template(self, file = "-", **vars) :
"""Include an external file in the current doc
and replaces ##vars## with their values.
Parts of this function come from the Whiz package
THANKS TO Neale Pickett ! Here follows the original license terms for Whiz:
## Author: Neale Pickett
## Time-stamp: <99/02/11 10:45:42 neale>
## This software and ancillary information (herein called "SOFTWARE")
## called html.py made avaiable under the terms described here. The
## SOFTWARE has been approved for release with associated LA-CC Number
## 89-47.
## Unless otherwise indicated, this SOFTWARE has been authored by an
## employee or employees of the University of California, operator of
## the Los Alamos National Laboratory under contract No. W-7405-ENG-36
## with the U.S. Department of Energy. The U.S. Government has rights
## to use, reproduce, and distribute this SOFTWARE. The public may
## copy, distribute, prepare derivative works and publicly display this
## SOFTWARE without charge, provided that this Notice and any statement
## of authorship are reproduced on all copies. Neither the Government
## nor the University makes any warranty, express or implied, or assumes
## any liability or responsibility for the use of this SOFTWARE.
## If SOFTWARE is modified to produce derivative works, such modified
## SOFTWARE should be clearly marked, so as not to confuse it with the
## version available from LANL.
"""
if (file is None) or (type(file) == type("")) :
if file and (file != "-") :
inf = open(file, "r")
else :
inf = sys.stdin
else :
inf = file
lines = map(lambda l: l[:-1], inf.readlines())
if inf != sys.stdin :
inf.close()
apply(self.__subst_lines, (lines,), vars)
class HTML_document(XML_document) :
"""This class defines a useful method to output a default header,
as well as some methods defined for easying the use of this module and
keep porting from the old jahtml module easy too.
"""
def _default_header(self, title = "JAXML Default HTML Document", **modifiers) :
"""Begins a normal document.
title
the title of the document
modifiers
usual meta name= content= tags (keywords, description, etc...)
WARNING: doesn't work with other meta tags
"""
self.html()
self._push()
self.head()
self.title(title)
for mod in modifiers.keys() :
if modifiers[mod] != None :
self._push()
self.meta(name = string.upper(mod), content = modifiers[mod])
self._pop()
self._pop()
#
# Here we define some methods for easy porting from the old jahtml module
#
def __fake_input(self, _text_ = None, **args) :
self._push()
retcode = apply(self.input, (None, ), args)
self._pop()
return retcode
def _submit(self, **args) :
"""Submit button input type, beware of the leading underscore"""
args["type"] = "submit"
return apply(self.__fake_input, (None, ), args)
def _reset(self, **args) :
"""Reset button input type, beware of the leading underscore"""
args["type"] = "reset"
return apply(self.__fake_input, (None, ), args)
def _radio(self, **args) :
"""Radio button input type, beware of the leading underscore"""
args["type"] = "radio"
return apply(self.__fake_input, (None, ), args)
def _checkbox(self, **args) :
"""Checkbox input type, beware of the leading underscore"""
args["type"] = "checkbox"
return apply(self.__fake_input, (None, ), args)
def _password(self, **args) :
"""Password input type, beware of the leading underscore"""
args["type"] = "password"
return apply(self.__fake_input, (None, ), args)
def _hidden(self, **args) :
"""Hidden input type, beware of the leading underscore"""
args["type"] = "hidden"
return apply(self.__fake_input, (None, ), args)
def _textinput(self, **args) :
"""Text input type, beware of the leading underscore and the trailing 'input'"""
args["type"] = "text"
return apply(self.__fake_input, (None, ), args)
def _button(self, **args) :
"""Button input type, beware of the leading underscore"""
args["type"] = "button"
return apply(self.__fake_input, (None, ), args)
def _file(self, **args) :
"""File input type, beware of the leading underscore"""
args["type"] = "file"
return apply(self.__fake_input, (None, ), args)
def _image(self, **args) :
"""Image input type, beware of the leading underscore"""
args["type"] = "image"
return apply(self.__fake_input, (None, ), args)
def _meta(self, **args) :
"""The META tag, beware of the leading underscore"""
self._push()
retcode = apply(self.meta, (None, ), args)
self._pop()
return retcode
def _br(self, **args) :
"""The BR tag, beware of the leading underscore"""
self._push()
retcode = apply(self.br, (None, ), args)
self._pop()
return retcode
def _hr(self, **args) :
"""The HR tag, beware of the leading underscore"""
self._push()
retcode = apply(self.hr, (None, ), args)
self._pop()
return retcode
class CGI_document(HTML_document) :
"""
This class defines a CGI document.
it inherits from the HTML_document class, but more methods are present
"""
__possibleargs = {"version": "1.0", "encoding": "iso-8859-1", "content_type": "text/html", "content_disposition": "", "expires": "", "pragma": "", "redirect": "", "status": "", "statmes": "", "debug": None}
def __init__(self, **args) :
"""
Initialise local datas.
"""
HTML_document.__init__(self)
for key in self.__possibleargs.keys() :
if args.has_key(key) :
value = args[key]
else :
value = self.__possibleargs[key]
setattr(self, "__" + key + "__", value)
def __str__(self) :
"""Returns the CGI output as a string."""
if self.__redirect__ :
return "Location: %s\n\n" % self.__redirect__
else :
val = "Content-type: %s\n" % self.__content_type__
if self.__status__ :
val = val + "Status: %s %s\n" % (self.__status__, self.__statmes__)
if self.__pragma__ :
val = val + "Pragma: %s\n" % self.__pragma__
if self.__expires__ :
val = val + "Expires: %s\n" % self.__expires__
if self.__content_disposition__ :
val = val + "Content-Disposition: %s\n" % self.__content_disposition__
return val + "\n" + HTML_document.__str__(self)
def _set_debug(self, file) :
"""Sets the flag to send the output to a file too."""
self.__debug__ = file
def _set_pragma(self, pragma) :
"""Defines the pragma value.
pragma
The pragma's value
"""
self.__pragma__ = pragma
def _set_expires(self, expires) :
"""Defines the expiration date of the CGI output.
expires
The expiration date
"""
self.__expires__ = expires
def _set_redirect(self, url) :
"""Defines the redirection url.
url
The redirection url to send
"""
self.__redirect__ = url
def _set_content_type(self, content_type = "text/html") :
"""Defines the content type of the CGI output.
content_type
The new content type, default is text/html
"""
self.__content_type__ = content_type
def _set_content_disposition(self, content_disposition = "") :
"""Defines the content disposition of the CGI output.
content_disposition
The new disposition, default is ""
"""
self.__content_disposition__ = content_disposition
def _set_status(self, status, message="") :
"""Defines the status to return.
statsus
The status value
message
The message following the status value
"""
self.__status__ = status
self.__statmes__ = message
def _do_nothing(self, message = "No response") :
"""Set status to 204 (do nothing)."""
self._set_status("204", message)
def _envvar(self, varname) :
"""Returns the variable value or None."""
if os.environ.has_key(varname) :
return os.environ[varname]
def _server_software(self) :
"""Returns the SERVER_SOFTWARE environment variable value."""
return self._envvar('SERVER_SOFTWARE')
def _server_name(self) :
"""Returns the SERVER_NAME environment variable value."""
return self._envvar('SERVER_NAME')
def _gateway_interface(self) :
"""Returns the GATEWAY_INTERFACE environment variable value."""
return self._envvar('GATEWAY_INTERFACE')
def _server_protocol(self) :
"""Returns the SERVER_PROTOCOL environment variable value."""
return self._envvar('SERVER_PROTOCOL')
def _server_port(self) :
"""Returns the SERVER_PORT environment variable value."""
return self._envvar('SERVER_PORT')
def _request_method(self) :
"""Returns the REQUEST_METHOD environment variable value."""
return self._envvar('REQUEST_METHOD')
def _path_info(self) :
"""Returns the PATH_INFO environment variable value."""
return self._envvar('PATH_INFO')
def _path_translated(self) :
"""Returns the PATH_TRANSLATED environment variable value."""
return self._envvar('PATH_TRANSLATED')
def _document_root(self) :
"""Returns the DOCUMENT_ROOT environment variable value."""
return self._envvar('DOCUMENT_ROOT')
def _script_name(self) :
"""Returns the SCRIPT_NAME environment variable value."""
return self._envvar('SCRIPT_NAME')
def _query_string(self) :
"""Returns the QUERY_STRING environment variable value."""
return self._envvar('QUERY_STRING')
def _remote_host(self) :
"""Returns the REMOTE_HOST environment variable value."""
return self._envvar('REMOTE_HOST')
def _remote_addr(self) :
"""Returns the REMOTE_ADDR environment variable value."""
return self._envvar('REMOTE_ADDR')
def _auth_type(self) :
"""Returns the AUTH_TYPE environment variable value."""
return self._envvar('AUTH_TYPE')
def _remote_user(self) :
"""Returns the REMOTE_USER environment variable value."""
return self._envvar('REMOTE_USER')
def _remote_ident(self) :
"""Returns the REMOTE_IDENT environment variable value."""
return self._envvar('REMOTE_IDENT')
def _content_type(self) :
"""Returns the CONTENT_TYPE environment variable value."""
return self._envvar('CONTENT_TYPE')
def _content_length(self) :
"""Returns the CONTENT_LENGTH environment variable value."""
return self._envvar('CONTENT_LENGTH')
def _http_accept(self) :
"""Returns the HTTP_ACCEPT environment variable value."""
return self._envvar('HTTP_ACCEPT')
def _http_user_agent(self) :
"""Returns the HTTP_USER_AGENT environment variable value."""
return self._envvar('HTTP_USER_AGENT')
def _http_referer(self) :
"""Returns the HTTP_REFERER environment variable value."""
return self._envvar('HTTP_REFERER')
def _log_message(self, msg = "Error in a CGI Script made with jaxml", level = "error") :
"""Logs a message to the HTTP server's error log file (usually on stderr)."""
sys.stderr.write("[%s] [%s] %s\n" % (time.asctime(time.localtime(time.time())), level, msg))
def _log_message_and_exit(self, msg = "Fatal Error in a CGI Script made with jaxml", level = "error") :
"""Logs a message to the HTTP server's error log file (usually on stderr) and exits unsuccessfully."""
self.log_message(msg, level)
sys.exit(-1)
def _output(self, file = "-") :
"""Prints the CGI script output to stdout or file.
If self.__debug__ is defined it is used as a file
to which send the output to too.
"""
HTML_document._output(self, file)
if self.__debug__ :
HTML_document._output(self, self.__debug__)
class Html_document :
"""This class warns the programmer when used, and exits the program.
This is done to say that the jahtml module is now obsolete"""
def __init__(self) :
"""Warns and Exit"""
sys.stderr.write("EXITING: The jaxml.Html_document() class shouldn't be used anymore.\nUse jaxml.HTML_document() instead, and modify your programs according to the new API.\n")
sys.exit(-1)
jaxml-3.01.orig/setup.py 0100755 0001750 0001750 00000001467 07461743631 013722 0 ustar doko doko #! /usr/bin/env python
#
# jaxml
# (C) Jerome Alet 2000-2001
# You're welcome to redistribute this software under the
# terms of the GNU General Public Licence version 2.0
# or, at your option, any higher version.
#
# You can read the complete GNU GPL in the file COPYING
# which should come along with this software, or visit
# the Free Software Foundation's WEB site http://www.fsf.org
#
# $Id: setup.py,v 1.6 2002/04/25 09:08:35 jerome Exp $
from distutils.core import setup
import jaxml
setup(name = "jaxml", version = jaxml.__version__,
licence = "GNU GPL",
description = "a Python module to generate XML easily",
author = "Jerome Alet",
author_email = "alet@librelogiciel.com",
url = "http://www.librelogiciel.com/software/",
py_modules = [ "jaxml" ])
jaxml-3.01.orig/PKG-INFO 0100644 0001750 0001750 00000000403 07676515073 013274 0 ustar doko doko Metadata-Version: 1.0
Name: jaxml
Version: 3.01
Summary: a Python module to generate XML easily
Home-page: http://www.librelogiciel.com/software/
Author: Jerome Alet
Author-email: alet@librelogiciel.com
License: UNKNOWN
Description: UNKNOWN
Platform: UNKNOWN