from mod_python import apache from pysqlite2 import dbapi2 as sqlite from xml.dom.minidom import getDOMImplementation, parse, parseString import os import urllib def handler(req): req.content_type = "text/xml" impl = getDOMImplementation() # createDocument(nimiavaruus, juurielementti, dokumenttityyppi) # doc = impl.createDocument(None, "table", None) doc = impl.createDocument("http://www.w3.org/1999/xhtml", "table", None) # pakko laittaa seuraava, koska jostakin syystä edellinen ei pelkästään riitä doc.documentElement.setAttribute("xmlns", "http://www.w3.org/1999/xhtml") if req.uri == "/~tjlahton/python/luento15/esim1.py": con = sqlite.connect( os.path.join(os.path.dirname(req.filename), 'kanta')) con.text_factory = str con.row_factory = sqlite.Row cur = con.cursor() try: cur.execute(""" SELECT Elokuvanimi, Lajinimi FROM Lajityyppi LEFT OUTER JOIN Elokuva ON Elokuva.Lajityyppi_LajiID = Lajityyppi.LajiID ORDER BY Lajinimi ASC """) except: req.write("nyt tuli virhe: %s" % sys.exc_info()[0]) for rivi in cur: tr = doc.createElement("tr") td = doc.createElement("td") tr.appendChild(td) td.appendChild( doc.createTextNode( rivi['Elokuvanimi'].decode("ISO-8859-1") ) ); td = doc.createElement("td") tr.appendChild(td) td.appendChild( doc.createTextNode( rivi['Lajinimi'].decode("ISO-8859-1") ) ) doc.documentElement.appendChild(tr) req.write( doc.toxml("ISO-8859-1") ) # req.write( doc.toxml() ) if req.uri == "/~tjlahton/python/luento15/esim2.py": doc2 = parse( urllib.urlopen("http://www.hs.fi/uutiset/rss/")) for node in doc2.getElementsByTagName("item"): tr = doc.createElement("tr"); td = doc.createElement("td"); tr.appendChild(td); td.appendChild( doc.importNode( node.getElementsByTagName("title").item(0).firstChild,1)); td = doc.createElement("td"); tr.appendChild(td); td.appendChild( doc.importNode( node.getElementsByTagName("link").item(0).firstChild,1)); td = doc.createElement("td"); tr.appendChild(td); td.appendChild( doc.importNode( node.getElementsByTagName("category").item(0).firstChild,1)); doc.documentElement.appendChild(tr); req.write( doc.toxml('UTF-8') ) if req.uri == "/~tjlahton/python/luento15/esim3.py": # seuraava ei toimi... # doc2 = parse( urllib.urlopen("http://www.fmi.fi/")) # tämä toimii eli ajetaan tidyn kautta # tehokkaampaa olisi jos ajaisi tidya suoraan python-kirjastona # mutta ei löydy valmiiksi asennettuna doc2 = parse( urllib.urlopen("http://cgi.w3.org/cgi-bin/tidy?docAddr=http%3A%2F%2Fwww.fmi.fi%2F&forceXML=on")) for node in doc2.getElementsByTagName("a"): # if node.getAttribute("class") == "index_link": if node.getAttribute("class") == "ignore_ext_link": tr = doc.createElement("tr"); td = doc.createElement("td"); tr.appendChild(td); td.appendChild( doc.importNode( node.firstChild,1) ); doc.documentElement.appendChild(tr) req.write( doc.toxml("ISO-8859-1") ) return apache.OK