mnot (owner)

Revisions

gist: 221417 Download_button fork
public
Description:
use XSLT on the "normal" Web
Public Clone URL: git://gist.github.com/221417.git
Embed All Files: show embed
libxslt_web.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python2.4
 
"""
libxslt_web - XSLT Extension Functions for the HTML Web
 
This is a set of XSLT extension functions that give access to HTTP mechanisms and HTML
documents (even those that are invalid) on the Web.
 
In particular, it offers;
- GET and POST support, with control over the POST body and content-type
- Automatic HTTP cookie and redirect handling
- SSL (when supported by urllib2)
 
The functions exposed are:
get(uri) - GET the uri; returns a string of the response representation.
post(uri, body, [content-type]) - post the body to the URI; returns a string of
the response representation.
tidy_parse(instr) - parse html and return a nodeset.
to_string(node) - return the node serialised as a string.
form_encode(node) - return the arguments serialised as a urlencoded form.
 
Responses to HTTP methods return a nodeset with an arbitrary number of 'header' elements,
one for each HTTP response header, and a single 'body' element. The header element
has a single attribute, 'name', which contains the lowercased header field-name. For example;
 
<header name="cache-control">Private</header>
<header name="date">Tue, 18 Oct 2005 22:38:52 GMT</header>
<body>... body content here...</body>
 
Forms are similarly handled;
<arg name="username">my_username</arg>
<arg name="password">my_password</arg>
and passed to form_encode.
 
See the test() function for a demonstration.
 
Requires Python 2.4, libxml2, libxslt and mxTidy.
 
TODO:
- return respnose status
- PUT and DELETE
- authentication support (basic, digest)
- base64 of binary content (?)
"""
 
__license__ = """
Copyright (c) 2005 Mark Nottingham <mnot@pobox.com>
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
 
__version__ = "0.2"
 
import string, urllib, urllib2, tempfile, cookielib
import libxml2, libxslt # http://xmlsoft.org/
from mx import Tidy # http://www.egenix.com/files/python/mxTidy.html
 
EXT_NS = "http://mnot.net/libxslt_web/1.0"
parse_options = libxml2.HTML_PARSE_RECOVER + libxml2.HTML_PARSE_NOERROR + libxml2.HTML_PARSE_NOWARNING
 
# set up cookie handling
cookie_policy = cookielib.DefaultCookiePolicy(rfc2965=True)
cookie_jar = cookielib.CookieJar(cookie_policy)
cookie_handler = urllib2.HTTPCookieProcessor(cookie_jar)
opener = urllib2.build_opener(cookie_handler)
urllib2.install_opener(opener)
 
def get(ctx, uri):
    """ Extension function to perform a HTTP GET. """
    if type(uri) == type([]):
        node = libxml2.xmlNode(_obj=uri[0])
        uri = node.getContent()
    res = urllib2.urlopen(uri)
    root = libxml2.newNode('response')
    for name, value in res.headers.dict.items():
        hdr = root.newTextChild(None, 'header', value)
        hdr.setProp('name', name.lower())
    root.newTextChild(None, 'body', res.read())
    return [root]
 
def post(ctx, uri, body, content_type='application/x-www-form-urlencoded'):
    """ Extension function to perform a HTTP POST. """
    if type(uri) == type([]):
        node = libxml2.xmlNode(_obj=uri[0])
        uri = node.getContent()
    if type(body) == type([]):
        node = libxml2.xmlNode(_obj=body[0])
        body = node.getContent()
    headers = {'Content-Type': content_type}
    req = urllib2.Request(uri, body, headers)
    res = urllib2.urlopen(req).read()
    root = libxml2.newNode('response')
    for name, value in res.headers.dict.items():
        hdr = root.newTextChild(None, 'header', value)
        hdr.setProp('name', name.lower())
    root.newTextChild(None, 'body', res.read())
    return [root]
    
def tidy_parse(ctx, content):
    """ Extension function to Tidy a string into a tree of XML nodes. """
    if type(content) == type([]):
        node = libxml2.xmlNode(_obj=content[0])
        content = node.getContent()
    tmp = tempfile.NamedTemporaryFile()
    try:
        content.replace("&nbsp;", " ")
        content.replace("&nbsp", " ")
        result = Tidy.tidy(content, output=tmp.file, output_xhtml=1, quote_ampersand=0, numeric_entities=0, output_error=0)
        tmp.flush()
        doc = libxml2.htmlReadFile(tmp.name, None, parse_options)
        root = doc.getRootElement()
        root.unlinkNode()
        return [root]
    finally:
        tmp.close()
 
def to_string(ctx, content):
    """ Extension function to serialise an XML node into a string. """
    if type(content) == type([]):
        node = libxml2.xmlNode(_obj=content[0])
        content = node.getContent()
    node = libxml2.xmlNode(_obj=content[0])
    return str(node)
 
def form_encode(ctx, content):
    """ Extension function to form-encode a string. """
    args = []
    if type(content) == type([]):
        node = libxml2.xmlNode(_obj=content[0])
        content = node.getContent()
    for node in content:
        arg = libxml2.xmlNode(_obj=node)
        print "*", arg.name, arg.prop('name'), arg.getContent()
        if arg.name != 'arg': continue
        args.append((arg.prop('name'), arg.getContent()))
    return urllib.urlencode(args)
 
libxslt.registerExtModuleFunction("tidy_parse", EXT_NS, tidy_parse)
libxslt.registerExtModuleFunction("to_string", EXT_NS, to_string)
libxslt.registerExtModuleFunction("get", EXT_NS, get)
libxslt.registerExtModuleFunction("post", EXT_NS, post)
libxslt.registerExtModuleFunction("form_encode", EXT_NS, form_encode)
 
def test():
    styledoc = libxml2.parseDoc("""
<xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:web='http://mnot.net/libxslt_web/1.0'
xsl:exclude-result-prefixes='web'>
 
<xsl:template match='/'>
<xsl:variable name="form">
<arg name="a">1</arg>
<arg name="b">2</arg>
<arg name="c">3</arg>
</xsl:variable>
<xsl:variable name="raw" select="web:get('http://www.google.com/')"/>
<xsl:variable name="doc" select="web:tidy_parse($raw/body)"/>
<xsl:variable name="test" select="web:tidy_parse(web:to_string($doc))"/>
<a><xsl:value-of select="$doc/head/title"/></a>
<b><xsl:value-of select="$raw/header[@name='date']"/></b>
<c><xsl:value-of select="web:to_string($doc/head)"/></c>
<d><xsl:value-of select="$test/head/title"/></d>
<e><xsl:value-of select="web:form_encode($form)"/></e>
</xsl:template>
</xsl:stylesheet>
""")
    
    style = libxslt.parseStylesheetDoc(styledoc)
    doc = libxml2.parseDoc("<doc/>")
    result = style.applyStylesheet(doc, {})
    style.freeStylesheet()
    doc.freeDoc()
    print result
 
def run(instance, stylesheet, params={}):
    style = libxslt.parseStylesheetFile(stylesheet)
    doc = libxml2.parseFile(instance)
    result = style.applyStylesheet(doc, params)
    doc.freeDoc()
    return result
 
def usage():
    import sys
    sys.stderr.write("%s instance stylesheet [param=value...]\n" % sys.argv[0])
    sys.exit(1)
 
if __name__ == "__main__":
    import sys
# test(); sys.exit(0) # uncomment to run test()
    try:
        instance, stylesheet = sys.argv[1:3]
    except:
        usage()
    params = {}
    for param in sys.argv[3:]:
        try:
            key, value = param.split('=', 1)
            params[key] = value
        except:
            usage()
    print run(instance, stylesheet, params)