def tal_template(self, filename, data={}): from simpletal import simpleTAL, simpleTALES import cStringIO context = simpleTALES.Context(allowPythonPath=1) for k in self.__globals__.keys(): context.addGlobal(k,self.__globals__[k]) for k in data.keys(): context.addGlobal(k,data[k]) try: # if there's a macros.pt file, we load that macrosfile = open("%s/macros.pt" % self.template_dir) macros = simpleTAL.compileXMLTemplate(macrosfile) macrosfile.close() context.addGlobal("sitemacros",macros) except: pass templatefile = open("%s/%s" % (self.template_dir,filename),'r') template = simpleTAL.compileXMLTemplate(templatefile) templatefile.close() fakeout = cStringIO.StringIO() template.expand(context,fakeout) fakeout.seek(0) return fakeout.read()
def _runMacroTest_(self, macros, page, result, errMsg="Error"): macroTemplate = simpleTAL.compileXMLTemplate(macros) pageTemplate = simpleTAL.compileXMLTemplate(page) self.context.addGlobal("site", macroTemplate) self.context.addGlobal("here", pageTemplate) file = io.StringIO() pageTemplate.expand(self.context, file) realResult = file.getvalue() try: expectedChecksum = getXMLChecksum(result) except Exception as e: self.fail("Exception (%s) thrown parsing XML expected result: %s" % (str(e), result)) try: realChecksum = getXMLChecksum(realResult) except Exception as e: self.fail( "Exception (%s) thrown parsing XML actual result: %s\nPage Template: %s\nMacro Template: %s" % (str(e), realResult, str(pageTemplate), str(macroTemplate))) self.failUnless( expectedChecksum == realChecksum, "%s - \npassed in macro: %s \n and page: %s\ngot back %s \nexpected %s\n\nPage Template: %s" % (errMsg, macros, page, realResult, result, pageTemplate))
def _runTest_ (self, macros, page, result, errMsg="Error"): macroTemplate = simpleTAL.compileXMLTemplate (macros) #print "Macro template: " + str (macroTemplate) pageTemplate = simpleTAL.compileXMLTemplate (page) self.context.addGlobal ("site", macroTemplate) self.context.addGlobal ("here", pageTemplate) file = io.StringIO () pageTemplate.expand (self.context, file, outputEncoding="iso-8859-1") realResult = file.getvalue() self.assertEqual (realResult,result, "%s - \npassed in macro: %s \npage: %s\ngot back %s \nexpected %s\n" % (errMsg, macros, page, realResult, result))
def _runTest_(self, macros, page, result, errMsg="Error"): macroTemplate = simpleTAL.compileXMLTemplate(macros) #print "Macro template: " + str (macroTemplate) pageTemplate = simpleTAL.compileXMLTemplate(page) self.context.addGlobal("site", macroTemplate) self.context.addGlobal("here", pageTemplate) file = io.StringIO() pageTemplate.expand(self.context, file, outputEncoding="iso-8859-1") realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in macro: %s \npage: %s\ngot back %s \nexpected %s\n" % (errMsg, macros, page, realResult, result))
def _runCompileTest_ (self, txt, result, errMsg="Error"): try: macroTemplate = simpleTAL.compileXMLTemplate (txt) except simpleTAL.TemplateParseException as e: self.failUnless (str (e) == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, str(e), result, pageTemplate)) return self.fail ("Expected exception '%s' during compile - but got no exception" % result)
def testXMLMacroExpansionSlots(self): txt = '<?xml version="1.0" encoding="utf-8"?>\n<html><div metal:use-macro="mac/macros/one">Hello<b metal:fill-slot="blue">Blue</b></div></html>' template = simpleTAL.compileXMLTemplate(txt) self._runTest_( template, txt, '<?xml version="1.0"?>\n<html><body metal:use-macro="mac/macros/one">World is <b metal:fill-slot="blue">Blue</b></body></html>', 'Expasion with slots failed.')
def testXMLMacroExpansionSlots (self): txt = '<?xml version="1.0" encoding="utf-8"?>\n<html><div metal:use-macro="mac/macros/one">Hello<b metal:fill-slot="blue">Blue</b></div></html>' template = simpleTAL.compileXMLTemplate (txt) self._runTest_ (template ,txt ,'<?xml version="1.0"?>\n<html><body metal:use-macro="mac/macros/one">World is <b metal:fill-slot="blue">Blue</b></body></html>' ,'Expasion with slots failed.')
def testCompileTemplateText (self): """ Test creating an XML template directly from a file that was text opened. Write output to a text file, letting the caller do the encoding. """ # Create a temporary file manually try: fileName = tempfile.mktemp () with open (fileName, mode='t+w', encoding = "utf-8") as templateFile: # Write out the XML in UTF-8 txt = '<?xml version="1.0" encoding="utf-8"?>\n<html><p>Somethings cost £3</p><p tal:content="one">Two</p></html>' expectedOutput = '<?xml version="1.0"?>\n<html><p>Somethings cost £3</p><p>1</p></html>' templateFile.write (txt) templateFile.seek (0) template = simpleTAL.compileXMLTemplate (templateFile) finally: # Delete the temporary file we created os.remove (fileName) try: fileName = tempfile.mktemp () with open (fileName, mode="t+w") as outputFile: # Now expand the template into a destination file that is binary template.expand (self.context,outputFile) # Read it back in and compare with what we expected outputFile.seek(0) outputValue = outputFile.read () finally: # Delete the temporary file we created os.remove (fileName) self.assertTrue (outputValue == expectedOutput, "passed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, outputValue, expectedOutput, template))
def _runTest_ (self, txt, result, errMsg="Error"): macroTemplate = simpleTAL.compileXMLTemplate (txt) self.context.addGlobal ("site", macroTemplate) file = io.StringIO () pageTemplate.expand (self.context, file, outputEncoding="iso-8859-1") realResult = file.getvalue() self.assertTrue (realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, pageTemplate))
def testUTF8ToISO (self): template = simpleTAL.compileXMLTemplate (b'<?xml version="1.0"?>\n<html>\xc2\xa33.12? <b tal:replace="HighBC"></b></html>') file = io.StringIO() template.expand (self.context, file, 'iso-8859-1') result = file.getvalue().encode ('iso-8859-1') expectedResult = '<?xml version="1.0" encoding="iso-8859-1"?>\n<html>�12? This cost nothing, yep �</html>'.encode ('iso-8859-1') self.failUnless (result == expectedResult, "UTF8 -> ISO Encoding failed. \nResult was: " + str (result) + "\nExpected result: " + str (expectedResult))
def apply_to(view, obj, refpkg=None): f = view.content_as_file html = view.content_mimetype.startswith("text/html") if html: t = simpleTAL.compileHTMLTemplate(f, "utf-8") kw = {} else: t = simpleTAL.compileXMLTemplate(f) kw = { "suppressXMLDeclaration": 1 } # It is a bit ugly to suppress XML declaration, but necessary when XML # views are used inside other XML views. # Furthermore, this does not seem to serious a ugliness, since we use # UTF-8 # encoding, which appears to be the default (at least for # simpleTAL generator), and since the XML spec allows well-formed # documents to have no XML declaration. f.close() # should we cache the compiled template for future uses, # and recompile it only when the content is modified? # the problem is that external contents may be modified without notification # (or rely on f.headers['date'], but that would require to hack content.py # to make that field *always* present - might be a good idea...) c = AdveneContext(here=obj) c.addGlobal("view", view) if refpkg is None: if hasattr(obj, "ADVENE_TYPE"): refpkg = obj.owner else: refpkg = obj c.addGlobal("package", refpkg) out = StringIO() t.expand(c, out, outputEncoding="utf-8", **kw) return out.getvalue()
def _runErrTest_ (self, txt, result, errMsg="Error"): try: template = simpleTAL.compileXMLTemplate (txt) except simpleTAL.TemplateParseException as e: realResult = str (e) self.assertTrue (realResult == result, "%s - \npassed in: %s \ngot back exception %s \nexpected exception %s\n" % (errMsg, txt, realResult, result)) return self.fail ("No exception thrown!")
def testXMLDeclarationSuppressionWithDocType (self): txt = """<?xml version="1.0" encoding="iso-8859-1"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html><p>Test</p></html>""" template = simpleTAL.compileXMLTemplate (txt) fh = io.StringIO () template.expand (self.context, fh, docType="""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">""", suppressXMLDeclaration=1) realResult = fh.getvalue() expectedResult = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html><p>Test</p></html>""" self.failUnless (realResult == expectedResult, "Doctype failed - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, realResult, expectedResult, str(template)))
def testXMLDeclarationSuppressionWithNoDocType (self): txt = """<?xml version="1.0" encoding="iso-8859-1"?>\n<html><p>Test</p></html>""" template = simpleTAL.compileXMLTemplate (txt) fh = io.StringIO () template.expand (self.context, fh, suppressXMLDeclaration=1) realResult = fh.getvalue() expectedResult = """<html><p>Test</p></html>""" self.failUnless (realResult == expectedResult, "Doctype failed - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, realResult, expectedResult, str(template)))
def testXMLDeclarationSuppressionWithDocType (self): txt = """<?xml version="1.0" encoding="iso-8859-1"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html><p>Test</p></html>""" template = simpleTAL.compileXMLTemplate (txt) fh = io.StringIO () template.expand (self.context, fh, docType="""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">""", suppressXMLDeclaration=1) realResult = fh.getvalue() expectedResult = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html><p>Test</p></html>""" self.assertTrue (realResult == expectedResult, "Doctype failed - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, realResult, expectedResult, str(template)))
def testISOToUTF8 (self): utf8Pound = b"\xc2\xa3" template = simpleTAL.compileXMLTemplate ('<?xml version="1.0" encoding="iso-8859-1"?>\n<html>�12? <b tal:replace="HighBC"></b></html>'.encode ('iso-8859-1')) file = io.StringIO() template.expand (self.context, file, 'utf-8') result = file.getvalue().encode ('utf-8') expectedResult = b'<?xml version="1.0"?>\n<html>' + utf8Pound + b"3.12? This cost nothing, yep " + utf8Pound + b"0!</html>" self.failUnless (result == expectedResult, "UTF8 Encoding failed. \nResult was: " + str(result) + "\nExpected result: " + str(expectedResult))
def testXMLDeclarationSuppressionWithNoDocType (self): txt = """<?xml version="1.0" encoding="iso-8859-1"?>\n<html><p>Test</p></html>""" template = simpleTAL.compileXMLTemplate (txt) fh = io.StringIO () template.expand (self.context, fh, suppressXMLDeclaration=1) realResult = fh.getvalue() expectedResult = """<html><p>Test</p></html>""" self.assertTrue (realResult == expectedResult, "Doctype failed - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, realResult, expectedResult, str(template)))
def macros_from(self, view, context): """Fetch macros from a view and injects them into a context.""" source = open(self.path_for(view), 'r') macros = simpleTAL.compileXMLTemplate(source) source.close() context.addGlobal("sitemacros", macros) return context
def _runTest_(self, txt, result, errMsg="Error", allowTALInStructure=1): template = simpleTAL.compileXMLTemplate(txt) file = io.StringIO() template.expand(self.context, file, outputEncoding="iso-8859-1") realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
def testContentStructure (self): # This test has specific needs - i.e. wrap the weblog/entry in a template... entry = """<insertedData>Some structure: <b tal:content="weblog/subject"></b></insertedData>""" weblog = {'subject': 'Test subject', 'entry': simpleTAL.compileXMLTemplate(entry)} self.context.addGlobal ('weblog', weblog) self._runTest_ ('<html><p tal:content="structure weblog/entry">Original</p></html>' ,'<?xml version="1.0" encoding="iso-8859-1"?>\n<html><p><insertedData>Some structure: <b>Test subject</b></insertedData></p></html>' ,'Content of Structure did not evaluate to expected result')
def _runBasicTest_ (self, text, result, errMsg = "Error"): """ Runs a basic test - i.e. does full string compare rather than checksum. """ template = simpleTAL.compileXMLTemplate (text) file = io.StringIO () template.expand (self.context, file, outputEncoding="iso-8859-1") realResult = file.getvalue().encode ('iso-8859-1') self.assertTrue (result == realResult, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, text, realResult, result, template))
def _runMacroTest_ (self, macros, page, result, errMsg="Error"): macroTemplate = simpleTAL.compileXMLTemplate (macros) pageTemplate = simpleTAL.compileXMLTemplate (page) self.context.addGlobal ("site", macroTemplate) self.context.addGlobal ("here", pageTemplate) file = io.StringIO () pageTemplate.expand (self.context, file) realResult = file.getvalue() try: expectedChecksum = getXMLChecksum (result) except Exception as e: self.fail ("Exception (%s) thrown parsing XML expected result: %s" % (str (e), result)) try: realChecksum = getXMLChecksum (realResult) except Exception as e: self.fail ("Exception (%s) thrown parsing XML actual result: %s\nPage Template: %s\nMacro Template: %s" % (str (e), realResult, str (pageTemplate), str (macroTemplate))) self.assertTrue (expectedChecksum == realChecksum, "%s - \npassed in macro: %s \n and page: %s\ngot back %s \nexpected %s\n\nPage Template: %s" % (errMsg, macros,page, realResult, result, pageTemplate))
def zpt(tfile): tinstance = _zpt_cache.get(tfile) stat = os.stat(tfile) if tinstance is None or tinstance.stat != stat: text = open(tfile).read() text = re.sub(r'\s*\n\s*', '\n', text) text = re.sub(r'[ \t]+', ' ', text) tinstance = _zpt_cache[tfile] = TemplateWrapper( simpleTAL.compileXMLTemplate(text), tfile, stat) return tinstance
def _runTest_(self, txt, result, errMsg="Error"): macroTemplate = simpleTAL.compileXMLTemplate(txt) self.context.addGlobal("site", macroTemplate) file = io.StringIO() pageTemplate.expand(self.context, file, outputEncoding="iso-8859-1") realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, pageTemplate))
def _runErrTest_(self, txt, result, errMsg="Error"): try: template = simpleTAL.compileXMLTemplate(txt) except simpleTAL.TemplateParseException as e: realResult = str(e) self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back exception %s \nexpected exception %s\n" % (errMsg, txt, realResult, result)) return self.fail("No exception thrown!")
def testNBSPparsing (self): txt = """<?xml version="1.0" encoding="iso-8859-1"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html><p>Test Space</p></html>""".encode ("iso-8859-1") template = simpleTAL.compileXMLTemplate (txt) fh = io.BytesIO () template.expand (self.context, fh) realResult = fh.getvalue() if not use_lexical_handler: expectedResult = """<?xml version="1.0"?>\n<html><p>Test\xa0Space</p></html>""".encode ("utf-8") else: expectedResult = """<?xml version="1.0"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html><p>Test\xa0Space</p></html>""".encode ("utf-8") self.assertTrue (realResult == expectedResult, "NBSP expansion failed - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, realResult, expectedResult, template))
def testNBSPparsing (self): txt = """<?xml version="1.0" encoding="iso-8859-1"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html><p>Test Space</p></html>""".encode ("iso-8859-1") template = simpleTAL.compileXMLTemplate (txt) fh = io.BytesIO () template.expand (self.context, fh) realResult = fh.getvalue() if not use_lexical_handler: expectedResult = """<?xml version="1.0"?>\n<html><p>Test\xa0Space</p></html>""".encode ("utf-8") else: expectedResult = """<?xml version="1.0"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html><p>Test\xa0Space</p></html>""".encode ("utf-8") self.failUnless (realResult == expectedResult, "NBSP expansion failed - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, realResult, expectedResult, template))
def __init__(self, credentials=None): if credentials: self.username, self.password = credentials else: if not os.path.exists(authfile): raise CredentialsNotFound(authfile) auth = open(authfile) self.username = auth.readline()[:-1] self.password = auth.readline()[:-1] self.retrieve_endpoint = retrieve_endpoint_tmpl % self.username self.template = simpleTAL.compileXMLTemplate(mytemplate)
def _runTest_ (self, txt, result, errMsg="Error"): template = simpleTAL.compileXMLTemplate (txt) fh = io.StringIO () template.expand (self.context, fh, outputEncoding="iso-8859-1") realResult = fh.getvalue() expectedChecksum = getXMLChecksum (result) try: realChecksum = getXMLChecksum (realResult) except Exception as e: self.fail ("Exception (%s) thrown parsing XML actual result: %s\nPage Template: %s" % (str (e), realResult, str (template))) self.assertTrue (expectedChecksum == realChecksum, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
def _runCompileTest_(self, txt, result, errMsg="Error"): try: macroTemplate = simpleTAL.compileXMLTemplate(txt) except simpleTAL.TemplateParseException as e: self.failUnless( str(e) == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, str(e), result, pageTemplate)) return self.fail( "Expected exception '%s' during compile - but got no exception" % result)
def render_html(self, view, context): """Renderes the TAL view using the context into HTML.""" source = open(self.path_for(view), 'r') template = simpleTAL.compileXMLTemplate(source) source.close() html = StringIO.StringIO() docType = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"' + "\n" docType += '"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' template.expand(context, html, outputEncoding='utf-8', docType=docType) return unicode(html.getvalue(), 'utf-8')
def _runTest_ (self, txt, result, errMsg="Error"): template = simpleTAL.compileXMLTemplate (txt) fh = io.StringIO () template.expand (self.context, fh, outputEncoding="iso-8859-1") realResult = fh.getvalue() expectedChecksum = getXMLChecksum (result) try: realChecksum = getXMLChecksum (realResult) except Exception as e: self.fail ("Exception (%s) thrown parsing XML actual result: %s\nPage Template: %s" % (str (e), realResult, str (template))) self.failUnless (expectedChecksum == realChecksum, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
def expand_template_with_jurisdictions(templatefilename, juridict): # Create the context that is used by the template context = simpleTALES.Context() context.addGlobal("jurisdictions", juridict) templateFile = open('template.html') template = simpleTAL.compileXMLTemplate(templateFile) templateFile.close() output_buffer = StringIO.StringIO() template.expand(context, output_buffer, 'utf-8') return output_buffer.getvalue()
def testContentStructure(self): # This test has specific needs - i.e. wrap the weblog/entry in a template... entry = """<insertedData>Some structure: <b tal:content="weblog/subject"></b></insertedData>""" weblog = { 'subject': 'Test subject', 'entry': simpleTAL.compileXMLTemplate(entry) } self.context.addGlobal('weblog', weblog) self._runTest_( '<html><p tal:content="structure weblog/entry">Original</p></html>', '<?xml version="1.0" encoding="iso-8859-1"?>\n<html><p><insertedData>Some structure: <b>Test subject</b></insertedData></p></html>', 'Content of Structure did not evaluate to expected result')
def _runBasicTest_(self, text, result, errMsg="Error"): """ Runs a basic test - i.e. does full string compare rather than checksum. """ template = simpleTAL.compileXMLTemplate(text) file = io.StringIO() template.expand(self.context, file, outputEncoding="iso-8859-1") realResult = file.getvalue().encode('iso-8859-1') self.failUnless( result == realResult, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, text, realResult, result, template))
def testCompileTemplateBinary(self): """ Test creating an XML template directly from a file that was binary opened. Write output to a binary file, letting simpleTAL do the encoding. NOTE: Can not use tempfile.TemporaryFile as this sets the 'name' attribute to an integer, which then breaks Expat. """ # Create a temporary file manually try: fileHandle, fileName = tempfile.mkstemp() with open(fileName, mode='b+w') as templateFile: # Write out the XML in UTF-8 txt = '<?xml version="1.0" encoding="utf-8"?>\n<html><p>Somethings cost £3</p><p tal:content="one">Two</p></html>' expectedOutput = '<?xml version="1.0"?>\n<html><p>Somethings cost £3</p><p>1</p></html>'.encode( 'utf-8') templateFile.write(txt.encode('utf-8')) templateFile.seek(0) template = simpleTAL.compileXMLTemplate(templateFile) finally: # Delete the temporary file we created os.remove(fileName) try: fileHandle, fileName = tempfile.mkstemp() with open(fileName, mode="b+w") as outputFile: # Now expand the template into a destination file that is binary template.expand(self.context, outputFile) # Read it back in and compare with what we expected outputFile.seek(0) outputValue = outputFile.read() finally: # Delete the temporary file we created os.remove(fileName) self.failUnless( outputValue == expectedOutput, "passed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, outputValue, expectedOutput, template))
def testCompileTemplateText(self): """ Test creating an XML template directly from a file that was text opened. Write output to a text file, letting the caller do the encoding. """ # Create a temporary file manually try: fileHandle, fileName = tempfile.mkstemp() with open(fileName, mode='t+w', encoding="utf-8") as templateFile: # Write out the XML in UTF-8 txt = '<?xml version="1.0" encoding="utf-8"?>\n<html><p>Somethings cost £3</p><p tal:content="one">Two</p></html>' expectedOutput = '<?xml version="1.0"?>\n<html><p>Somethings cost £3</p><p>1</p></html>' templateFile.write(txt) templateFile.seek(0) template = simpleTAL.compileXMLTemplate(templateFile) finally: # Delete the temporary file we created os.remove(fileName) try: fileHandle, fileName = tempfile.mkstemp() with open(fileName, mode="t+w", encoding="utf-8") as outputFile: # Now expand the template into a destination file that is binary template.expand(self.context, outputFile) # Read it back in and compare with what we expected outputFile.seek(0) outputValue = outputFile.read() finally: # Delete the temporary file we created os.remove(fileName) self.failUnless( outputValue == expectedOutput, "passed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, outputValue, expectedOutput, template))
def testCompileTemplateBinary (self): """ Test creating an XML template directly from a file that was binary opened. Write output to a binary file, letting simpleTAL do the encoding. NOTE: Can not use tempfile.TemporaryFile as this sets the 'name' attribute to an integer, which then breaks Expat. """ # Create a temporary file manually try: fileName = tempfile.mktemp () with open (fileName, mode='b+w') as templateFile: # Write out the XML in UTF-8 txt = '<?xml version="1.0" encoding="utf-8"?>\n<html><p>Somethings cost £3</p><p tal:content="one">Two</p></html>' expectedOutput = '<?xml version="1.0"?>\n<html><p>Somethings cost £3</p><p>1</p></html>'.encode ('utf-8') templateFile.write (txt.encode ('utf-8')) templateFile.seek (0) template = simpleTAL.compileXMLTemplate (templateFile) finally: # Delete the temporary file we created os.remove (fileName) try: fileName = tempfile.mktemp () with open (fileName, mode="b+w") as outputFile: # Now expand the template into a destination file that is binary template.expand (self.context,outputFile) # Read it back in and compare with what we expected outputFile.seek(0) outputValue = outputFile.read () finally: # Delete the temporary file we created os.remove (fileName) self.assertTrue (outputValue == expectedOutput, "passed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, outputValue, expectedOutput, template))
def prepareProxyArtifacts(self,context): ## Improvement Extract common method outof it # Prepare proxies default.xml proxyTemplateFile = open ("./templates/proxies/default.xml", 'rt', encoding = 'utf-8') proxyDirectoryPath = "./apiproxy/proxies" self.createFolder(proxyDirectoryPath) proxyWriteFile = open(proxyDirectoryPath+"/default.xml",'w') template = simpleTAL.compileXMLTemplate (proxyTemplateFile) template.expand(context, proxyWriteFile) proxyTemplateFile.close() proxyWriteFile.close() print("Proxies....SUCCESSS!!!!!!!!!!!!!!!!!") # Prepare targets default.xml templateFile = open ("./templates/targets/default.xml", 'rt', encoding = 'utf-8') targetProxyDirectoryPath = "./apiproxy/targets" self.createFolder(targetProxyDirectoryPath) testWriteFile = open(targetProxyDirectoryPath+"/default.xml",'w') template = simpleTAL.compileXMLTemplate (templateFile) template.expand(context, testWriteFile) templateFile.close() testWriteFile.close() print("Proxies--Target....SUCCESSS!!!!!!!!!!!!!!!!!") # prepare hash for proxy default.xml __objecthashgenerator = HashGenerator.hashgenerator() _proxyHashValue = __objecthashgenerator.calculatehashfromfile("./apiproxy/proxies/default.xml") context.addGlobal("proxyResourceName", "default") _proxyHashValue = "SHA-512:"+_proxyHashValue context.addGlobal("proxyHash", _proxyHashValue) _targetHashValue = __objecthashgenerator.calculatehashfromfile("./apiproxy/targets/default.xml") _targetHashValue = "SHA-512:"+_targetHashValue context.addGlobal("targetResourceName", "default") context.addGlobal("targetHash", _targetHashValue) # prepare Manifest File i.e. manifest.xml templateFile = open ("./templates/manifests/manifest.xml", 'rt', encoding = 'utf-8') targetProxyDirectoryPath = "./apiproxy/manifests" self.createFolder(targetProxyDirectoryPath) testWriteFile = open(targetProxyDirectoryPath+"/manifest.xml",'w') template = simpleTAL.compileXMLTemplate (templateFile) template.expand(context, testWriteFile) templateFile.close() testWriteFile.close() print("Manifest....SUCCESSS!!!!!!!!!!!!!!!!!") # prepare Hash for Manifest file _proxyHashValue = __objecthashgenerator.calculatehashfromfile("./apiproxy/manifests/manifest.xml") _proxyHashValue = "SHA-512:"+_proxyHashValue context.addGlobal("manifestHash", _proxyHashValue) # Prepare proxy info file templateFile = open ("./templates/template-info-v1.xml", 'rt', encoding = 'utf-8') testWriteFile = open("./apiproxy/"+context.__getattribute__("proxyName")+".xml",'w') template = simpleTAL.compileXMLTemplate (templateFile) template.expand(context, testWriteFile) templateFile.close() testWriteFile.close() print("SUCCESSS!!!!!!!!!!!!!!!!!")
#!/usr/bin/python # -*- coding: utf-8 -*- from simpletal import simpleTAL, simpleTALES, simpleTALUtils import psycopg2 import locale import time encoding = "UTF-8" conn = psycopg2.connect("dbname=dnsdelve-ip") cursor = conn.cursor() html_page = open("ipv6.tmpl.xhtml") template = simpleTAL.compileXMLTemplate(html_page) context = simpleTALES.Context() # TODO: ignored, decimal numbers are formatted with a dot :-( locale.setlocale(locale.LC_NUMERIC, "fr_FR.%s" % encoding) # But month names are OK locale.setlocale(locale.LC_TIME, "fr_FR.%s" % encoding) last_uuid = None first_uuid = None num_exec = 0 cursor.execute("SELECT uuid,date,samplingrate FROM Runs ORDER BY date DESC;") for tuple in cursor.fetchall(): num_exec += 1 if last_uuid is None: # TODO: create a cache of answers, Cache.Counts and use it cursor.execute("SELECT count(*) FROM Broker WHERE uuid=%(last_uuid)s;",
def _runTest_ (self, txt, result, errMsg="Error", allowTALInStructure=1): template = simpleTAL.compileXMLTemplate (txt) file = io.StringIO () template.expand (self.context, file, outputEncoding="iso-8859-1") realResult = file.getvalue() self.assertTrue (realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
try: # Is PyXML's LexicalHandler available? from xml.sax.saxlib import LexicalHandler use_lexical_handler = 1 except ImportError: use_lexical_handler = 0 if (os.path.exists ("logging.ini")): logging.config.fileConfig ("logging.ini") else: logging.basicConfig() pageTemplate = simpleTAL.compileXMLTemplate ("""<html> <body metal:use-macro="site/macros/one"> <h1 metal:fill-slot="title">Expansion of macro one</h1> </body> <br/> </html>""") class DefineMacroTests (unittest.TestCase): def setUp (self): self.context = simpleTALES.Context() self.context.addGlobal ('test', 'testing') self.context.addGlobal ('link', 'www.owlfish.com') self.context.addGlobal ('needsQuoting', """Does "this" work?""") def _runTest_ (self, txt, result, errMsg="Error"): macroTemplate = simpleTAL.compileXMLTemplate (txt) self.context.addGlobal ("site", macroTemplate) file = io.StringIO () pageTemplate.expand (self.context, file, outputEncoding="iso-8859-1")
def main(): config = { "basedir": "/home/kms/web/la9pma.org/la-hams", "cachedir": "/home/kms/url-watcher/pages-la-hams", "proxy": "home.tmvs.vgs.no:3128", } pagesToWatch = [ ("Personal", "LAØBY", "http://www.qsl.net/la0by/", None, 1.0), ("Group", "LA2T Trondheimsgruppen", "http://www.la2t.org/", None, 1.0), ( "Group", "LA7G Gudbrandsdalgsgruppen", "http://www.hamradio.no/la7g/", "http://www.hamradio.no/la7g/start00.htm", 1.0, ), ("Group", "LA2D Drammensgruppen", "http://www.la2d.com/", None, 1.0), ("Misc", "JX7SIX", "http://www.qsl.net/la7dfa/jx7six.htm", None, 1.0), ("Group", "LA2K Kirkenesgruppen", "http://www.arcticnet.no/la5xx/la2k.htm", None, 1.0), ("Misc", "Norwegain Repeaters, 2m", "http://www.nrrl.no/4_fakta/rep_la144.htm", None, 1.0), ("Misc", "Norwegian Repeaters, 6m", "http://www.nrrl.no/4_fakta/rep_la50.htm", None, 1.0), ("Misc", "Norwegian Repeaters, 70cm", "http://www.nrrl.no/4_fakta/rep_la432.htm", None, 1.0), ("Misc", "Norwegian Repeaters, links", "http://www.nrrl.no/4_fakta/rep_lafmlinks.htm", None, 1.0), ("Misc", "Samband Mjøsa", "http://www.qsl.net/la3r/sm/sm.html", None, 1.0), ( "Misc", "List of Norwegian hams", "http://www.npt.no/pt_internet/ressursforvaltning/frekvenser/radioamatoer/radioamatoerer.html", None, 1.0, ), ("Group", "LA1G Grenlandgruppen", "http://www.qsl.net/la1g/main.htm", None, 1.0), ("News", "NRRL Nyheter", "http://www.nrrl.no/start/start00.htm", "http://www.nrrl.no/", 1.0), ("Personal", "LA3LNA", "http://www.la3lna.net/", None, 1.0), ("Group", "LA6LI Listagruppen", "http://www.qsl.net/la6li/main.htm", "http://www.qsl.net/la6li/", 1.0), ("Personal", "LA8OKA", "http://www.arcticpeak.com/index.htm", None, 1.0), ("Personal", "LA8OKA (Radio)", "http://www.arcticpeak.com/radio.htm", None, 1.0), ("Misc", "APRS Norge", "http://aprs.dahltech.no/", None, 0.999), ("Commercial", "Permo", "http://www.permo.no/main.htm", None, 1.0), ("Commercial", "Permo (Auksjon)", "http://www.permo.no/Auksjon.htm", None, 1.0), ("Commercial", "Permo (Nyheter)", "http://www.permo.no/A/Nyheter.htm", None, 1.0), ("News", "AMSAT", "http://www.amsat.org/", None, 1.0), ("News", "AMSAT What's New", "http://www.amsat.org/amsat/whatsnew.html", None, 1.0), ("News", "AMSAT WSR", "http://www.amsat.org/amsat/news/wsr.html", None, 1.0), ("Personal", "LA8IMA", "http://www.rolvs.org/index2.php", None, 1.0), ("DX/Contest", "3B9C Rodrigues Island", "http://www.fsdxa.com/3b9c/", None, 1.0), ( "DX/Contest", "T33C Banaba", "http://www.dx-pedition.de/banaba2004/home.htm", "http://www.dx-pedition.de/banaba2004/", 1.0, ), ("News", "AMSAT OSCAR E", "http://www.amsat.org/amsat/sats/echo/index.html", None, 1.0), ("News", "findU News", "http://www.findu.com/new.html", None, 1.0), ("Misc", "Solar Terrestrial Activity Report", "http://www.dxlc.com/solar/", None, 1.0), ("Misc", "W1AW Propagation Bulletins", "http://www.arrl.org/w1aw/prop/", None, 0.99), ("DX/Contest", "Contests this week", "http://www.hornucopia.com/contestcal/weeklycont.php", None, 1.0), ("Personal", "LA1BNA", "http://www.la1bna.net/main.html", "http://www.la1bna.net/", 1.0), ("Personal", "LA9PMA", "http://la9pma.org/", None, 1.0), ("Group", "LA1T Tønsberggruppen", "http://la1t.tsoft.no/files/nyheter.asp", "http://la1t.tsoft.no/", 1.0), ( "Personal", "LA5UNA", "http://www.qsl.net/la5una/hei_og_velkommen_til_min_hjemmes.htm", "http://www.qsl.net/la5una/", 1.0, ), ("Personal", "LA3YNA", "http://home.online.no/~arvjakob/index2.htm", "http://www.la3yna.tk/", 1.0), ("Misc", "Norwegian Beacon List", "http://www.qsl.net/la0by/LA-beac.htm", None, 1.0), ( "Group", "LA3T Tromsøgruppen", "http://www.hamradio.no/la3t/hovedside.htm", "http://www.hamradio.no/la3t/", 1.0, ), ("Group", "LA4O Oslogruppen", "http://www.qsl.net/la4o/", None, 1.0), ("Group", "LA3F Follogruppen", "http://www.la3f.no/main.htm", "http://www.la3f.no/", 1.0), ("Personal", "LA5NCA", "http://www.laud.no/la6nca/", None, 1.0), ("Personal", "LA9UX", "http://www.qsl.net/la9ux/", None, 1.0), ("Personal", "LAØFX", "http://www.qsl.net/la0fx/", None, 1.0), ("Personal", "LAØFA", "http://www.qsl.net/la0fa/index.html", None, 1.0), ("Personal", "LAØFD", "http://www.qsl.net/la0fd/index.html", None, 1.0), ("Personal", "LAØHV", "http://www.qsl.net/la0hv/index.html", None, 1.0), ("Personal", "LA1AEA", "http://www.qsl.net/la1aea/index.html", None, 1.0), ("Group", "LA ARDF", "http://www.ardf.no/", None, 1.0), ("Personal", "LA1CNA", "http://www.qsl.net/la1cna/index.html", None, 1.0), ("Personal", "LA1DGA", "http://www.qsl.net/la1aea/main.html", "http://www.qsl.net/la1aea/index.html", 1.0), ( "Misc", "PACKET-radio nettet i Nord-Norge", "http://www.qsl.net/la1h/nodenett/hoyre.htm", "http://www.qsl.net/la1h/nodenett/index.htm", 1.0, ), ("Group", "LA1JAM", "http://www.qsl.net/la1jam/index.htm", None, 1.0), ("Personal", "LA1KHA", "http://www.qsl.net/la1kha/index.html", None, 1.0), ("Personal", "LA1KKA", "http://www.qsl.net/la1kka/index.html", None, 1.0), ("DX/Contest", "VHF aktivitets-tester (NRAU NAC)", "http://www.qsl.net/la1kka/vhf/index.html", None, 1.0), ("Personal", "LA1KP", "http://www.qsl.net/la1kp/index.html", None, 1.0), ( "Group", "LA8D Sandnes og Jærengruppen", "http://www.lug.no/la8d/main.php?LA8D=1", "http://www.lug.no/la8d/", 1.0, ), ("Personal", "LA3ZA", "http://www.qsl.net/la3za/hoved.html", "http://www.qsl.net/la3za/", 1.0), ("Group", "LA1NRK", "http://home.eunet.no/~aosteren/index0.htm", None, 1.0), ("Group", "LA1NSF", "http://www.qsl.net/la1nsf/index.htm", None, 1.0), ("Personal", "LA1PHA", "http://www.qsl.net/la1pha/index.htm", None, 1.0), ("Personal", "LA1PNA", "http://www.qsl.net/la1pna/index.htm", None, 1.0), ("Personal", "LA1SNA", "http://www.qsl.net/la1sna/right.html", "http://www.qsl.net/la1sna/index.html", 1.0), ("Group", "LA1SS Nettverk for radiospeidere", "http://www.qsl.net/la1ss/index.html", None, 1.0), ( "Group", "LA1TUR Radioklubben ut på tur", "http://www.qsl.net/la1tur/index.html", "http://www.qsl.net/la1tur/hoved.html", 1.0, ), ("Personal", "LA1UW", "http://www.qsl.net/la1uw/index.html", None, 1.0), ("Personal", "LA1VNA", "http://www.qsl.net/la1vna/index.htm", None, 1.0), ("Personal", "LA1ONA", "http://www.qsl.net/la1ona/index.htm", None, 1.0), ("Personal", "LA3FY", "http://k-j.skontorp.net/", None, 1.0), ( "Group", "LA1B Bergensgruppen", "http://www.qsl.net/la1b/frame1.htm", "http://www.qsl.net/la1b/index.htm", 1.0, ), ] exportData = [] startTime = int(mktime(gmtime())) for (category, title, watchURL, linkURL, tresholdRatio) in pagesToWatch: page = {} page["title"] = unicode(title, "iso-8859-1") page["category"] = category page["watchURL"] = watchURL page["cacheFilename"] = md5.new(watchURL).hexdigest() if linkURL: page["linkURL"] = linkURL else: page["linkURL"] = watchURL page["tresholdRatio"] = tresholdRatio try: request = urllib2.Request(watchURL) if config.has_key("proxy"): request.set_proxy(config["proxy"], None) if (len(sys.argv) == 2) and (sys.argv[1] == "--no-cache"): request.add_header("Pragma", "no-cache") response = urllib2.urlopen(request) lastModifiedHeader = response.info().getheader("Last-Modified") page["proxyStatus"] = response.info().getheader("X-Cache") if lastModifiedHeader: page["lastModified"] = int(mktime(strptime(lastModifiedHeader, "%a, %d %b %Y %H:%M:%S %Z"))) page["lastModifiedFromHeader"] = "true" else: page["lastModified"] = int(mktime(gmtime())) page["lastModifiedFromHeader"] = "false" webpageNow = response.read() except urllib2.HTTPError: continue try: file = open(config["cachedir"] + "/" + page["cacheFilename"], "r") webpageOld = file.read() file.close() except IOError: webpageOld = "" s = SequenceMatcher(None, webpageNow, webpageOld) webpageRatio = s.ratio() s = None if webpageRatio < page["tresholdRatio"]: try: file = open(config["cachedir"] + "/" + page["cacheFilename"], "w") file.write(webpageNow) file.close() os.utime(config["cachedir"] + "/" + page["cacheFilename"], (page["lastModified"], page["lastModified"])) except IOError: print "Unable to save cache..." secs = os.stat(config["cachedir"] + "/" + page["cacheFilename"]).st_mtime class utc(tzinfo): def utcoffset(self, dt): return timedelta() def dst(selft, dt): return timedelta() page["lastModified"] = datetime.fromtimestamp(secs, tz=utc()).isoformat(sep="T") page["lastModifiedDate"] = datetime.fromtimestamp(secs, tz=utc()).strftime("%A %d. %B, %Y") page["lastModifiedTime"] = datetime.fromtimestamp(secs, tz=utc()).strftime("%H:%M") page["lastModifiedUnix"] = secs exportData.append(page) endTime = int(mktime(gmtime())) context = simpleTALES.Context() if (len(sys.argv) == 2) and (sys.argv[1] == "--no-cache"): context.addGlobal("noCache", "true") else: context.addGlobal("noCache", "false") context.addGlobal("runtime", str(endTime - startTime)) context.addGlobal("pages", exportData) context.addGlobal("generated", datetime.utcnow().isoformat(sep="T")) templateFile = open(config["basedir"] + "/" + "uw-template.xml", "r") template = simpleTAL.compileXMLTemplate(templateFile) templateFile.close() template.expand(context, sys.stdout, "iso-8859-1")
def main(): global LOCALES # parse command line parameters and check for sanity (opts, args) = loadOpts() if (getattr(opts, 'podir', None) is None): print >> sys.stderr, "You must specify --podir." sys.exit(1) # load the catalogs and jurisdiction list LOCALES = loadCatalogs(opts.podir) # determine our output directory output_dir = getattr(opts, 'outputDir', None) # set up our TAL context context = simpleTALES.Context(allowPythonPath=1) context.addGlobal ("locales", LOCALES.keys()) context.addGlobal ("jurisdictions", loadJurisdictions()) context.addGlobal ("lookupString", lookupString) # iterate over the specified for in_fn in args: if output_dir is None: # just output to the same directory out_fn = in_fn[:-3] else: out_fn = os.path.join(output_dir, os.path.basename(in_fn)[:-3]) # generate a temporary intermediary file to validate the XML temp_fn = "%s.tmp" % out_fn # compile the template and write it to the temporary file template = simpleTAL.compileXMLTemplate (open (in_fn, 'r')) output = file(temp_fn, 'w') print 'writing to %s..' % temp_fn template.expand (context, output, 'utf-8') output.close() # try to clear the error log before checking validity try: et.clearErrorLog() except AttributeError: # lxml < 1.1 pass # re-read the temp file and parse it for well-formed-ness try: print 'validating XML structure of %s...' % temp_fn tree = et.parse(temp_fn) except Exception, e: print print "An error exists in %s: " % temp_fn print e sys.exit(1) # the file was either read correctly or elementtree is not available print 'moving %s to %s...' % (temp_fn, out_fn) shutil.move(temp_fn, out_fn)
def testHasFrame(self): file_ = open('root/__/frame.pt', 'r') expected = simpleTAL.compileXMLTemplate(file_).macros['frame'] actual = self.handler._getframe() self.assertEqual(type(expected), type(actual)) self.assertEqual(str(expected), str(actual))
As simple as it gets: 1 - Create a context 2 - Compile a template 3 - Expand the template Module Dependencies: simpleTAL, simpleTALES """ from simpletal import simpleTAL, simpleTALES, simpleElementTree import sys, logging logging.basicConfig() xmlTree = simpleElementTree.parseFile(file="input.xml") # Create the context that is used by the template context = simpleTALES.Context(allowPythonPath=1) # Add the XML element tree to the context context.addGlobal("input", xmlTree) # Open the template file templateFile = open("basic.xml", 'rb') # Compile a template template = simpleTAL.compileXMLTemplate(templateFile) # Close the template file templateFile.close() # Expand the template as HTML using this context template.expand(context, sys.stdout, "utf-8")
<summary tal:condition="entry/summary" tal:content="entry/summary"/> <content tal:condition="entry/content" tal:content="python: entry.content[0]['value']"/> <!-- TODO: metadata and the other items in content --> <id tal:condition="entry/id" tal:content="entry/id"/> <author tal:condition="entry/author"> <name tal:content="python: entry.authors[0]['name']"/> <email tal:content="python: entry.authors[0]['email']"/> <!-- <uri tal:content="python: entry.authors[0]['uri']"/> TODO: not available with FeedParser :-( --> </author> <published tal:condition="entry/published" tal:content="entry/published"/> <updated tal:condition="entry/updated" tal:content="entry/updated"/> <!-- TODO other entry fields? <link>? --> </entry> </feed> """ context = simpleTALES.Context(allowPythonPath=True) template = simpleTAL.compileXMLTemplate (mytemplate) class FeedParserPlus(feedparser.FeedParserDict): def serialize(self): context.addGlobal ("feed", self.feed) context.addGlobal ("entries", self.entries) result = simpleTALUtils.FastStringOutput() template.expand (context, result) return result.getvalue() @classmethod def parse(klass, text): result = feedparser.parse(text) return FeedParserPlus(result)
def get_template(name): dirpath = os.path.dirname(__file__) with file(os.path.join(dirpath, "%s.html" % name)) as templateFile: return simpleTAL.compileXMLTemplate(templateFile.read())
1 - Create a context 2 - Compile a template 3 - Expand the template Module Dependencies: simpleTAL, simpleTALES """ from simpletal import simpleTAL, simpleTALES, simpleElementTree import sys, logging logging.basicConfig() xmlTree = simpleElementTree.parseFile (file="input.xml") # Create the context that is used by the template context = simpleTALES.Context(allowPythonPath=1) # Add the XML element tree to the context context.addGlobal ("input", xmlTree) # Open the template file templateFile = open ("basic.xml", 'rb') # Compile a template template = simpleTAL.compileXMLTemplate (templateFile) # Close the template file templateFile.close() # Expand the template as HTML using this context template.expand (context, sys.stdout, "utf-8")
try: # Is PyXML's LexicalHandler available? from xml.sax.saxlib import LexicalHandler use_lexical_handler = 1 except ImportError: use_lexical_handler = 0 if (os.path.exists("logging.ini")): logging.config.fileConfig("logging.ini") else: logging.basicConfig() pageTemplate = simpleTAL.compileXMLTemplate("""<html> <body metal:use-macro="site/macros/one"> <h1 metal:fill-slot="title">Expansion of macro one</h1> </body> <br/> </html>""") class DefineMacroTests(unittest.TestCase): def setUp(self): self.context = simpleTALES.Context() self.context.addGlobal('test', 'testing') self.context.addGlobal('link', 'www.owlfish.com') self.context.addGlobal('needsQuoting', """Does "this" work?""") def _runTest_(self, txt, result, errMsg="Error"): macroTemplate = simpleTAL.compileXMLTemplate(txt) self.context.addGlobal("site", macroTemplate) file = io.StringIO()
# -*- coding: utf-8 -*- from simpletal import simpleTAL, simpleTALES, simpleTALUtils import psycopg2 import locale import time import Utils encoding = "UTF-8" sniffer = "jezabel" conn = psycopg2.connect("dbname=dnsmezzo3") cursor = conn.cursor() html_page = open("respsize.tmpl.xhtml") template = simpleTAL.compileXMLTemplate(html_page) context = simpleTALES.Context() # TODO: ignored, decimal numbers are formatted with a dot :-( locale.setlocale(locale.LC_NUMERIC, "fr_FR.%s" % encoding) # But month names are OK locale.setlocale(locale.LC_TIME, "fr_FR.%s" % encoding) (last_sunday_id, last_tuesday_id, last_tuesday_date) = Utils.get_set_days(cursor, sniffer, 1).next() cursor.execute( "SELECT count(id) FROM DNS_packets WHERE query AND (file=%(sunday)s OR file=%(tuesday)s);", { 'sunday': last_sunday_id, 'tuesday': last_tuesday_id })
def main(): global LOCALES # parse command line parameters and check for sanity (opts, args) = loadOpts() if (getattr(opts, "podir", None) is None): print >> sys.stderr, "You must specify --podir." sys.exit(1) # load the catalogs and jurisdiction list LOCALES = loadCatalogs(opts.podir) # determine our output directory output_dir = getattr(opts, "outputDir", None) # set up our TAL context context = simpleTALES.Context(allowPythonPath=1) context.addGlobal("locales", LOCALES.keys()) context.addGlobal("jurisdictions", loadJurisdictions()) context.addGlobal("lookupString", lookupString) # iterate over the specified for in_fn in args: if output_dir is None: # just output to the same directory out_fn = in_fn[:-3] else: out_fn = os.path.join(output_dir, os.path.basename(in_fn)[:-3]) # generate a temporary intermediary file to validate the XML temp_fn = "{}.tmp".format(out_fn) # compile the template and write it to the temporary file template = simpleTAL.compileXMLTemplate(open(in_fn, "r")) output = file(temp_fn, "w") print "writing to {}..".format(temp_fn) template.expand(context, output, "utf-8") output.close() # try to clear the error log before checking validity try: et.clearErrorLog() except AttributeError: # lxml < 1.1 pass # re-read the temp file and parse it for well-formed-ness try: print "validating XML structure of {}...".format(temp_fn) tree = et.parse(temp_fn) # noqa: F841 except Exception, e: print print "An error exists in {}: ".format(temp_fn) print e sys.exit(1) # the file was either read correctly or elementtree is not available print "moving {} to {}...".format(temp_fn, out_fn) shutil.move(temp_fn, out_fn)