Esempio n. 1
0
def test_load_template_with_entity_map():
    xml = '<html>&nbsp;</html>'
    s = load_template(xml).serialize(encoding='ascii')
    assert s.endswith('<html>&#160;</html>')
    xml = '<html>&codswallop;</html>'
    try:
        e = load_template(xml).serialize(encoding='ascii')
    except Exception, e:
        e = str(e)
Esempio n. 2
0
def test_load_template_with_entity_map():
    xml = '<html>&nbsp;</html>'
    s = load_template(xml).serialize(encoding='ascii')
    assert s.endswith('<html>&#160;</html>')
    xml = '<html>&codswallop;</html>'
    try:
        e = load_template(xml).serialize(encoding='ascii')
    except Exception, e:
        e = str(e)
Esempio n. 3
0
def test_load_template_func_with_ns():
    t = kid.load_template(joinpath(template_dir, 'templates.kid'),
    	name='', cache=False)
    s = """
    <docelement xmlns:py="http://purl.org/kid/ns#" py:extends="t">
    <element py:content="template1()" />
    </docelement>
    """
    t2 = kid.load_template(s, cache=False, ns={'t': t})
    xml = t2.serialize()
    assert "This is a test" in xml
Esempio n. 4
0
def test_load_template_func():
    t = kid.load_template(joinpath(template_dir, 'test_if.kid'),
    	name='', cache=False)
    assert_template_interface(t)
    t2 = kid.load_template(joinpath(template_dir, 'test_if.kid'),
                           name=template_package + 'test_if',
                           cache=True)
    assert not t is t2
    t3 = kid.load_template(joinpath(template_dir, 'test_if.kid'),
                           name=template_package + 'test_if',
                           cache=True)
    assert t3 is t2
Esempio n. 5
0
def test_load_template_func_with_ns():
    t = kid.load_template(joinpath(template_dir, 'templates.kid'),
                          name='',
                          cache=False)
    s = """
    <docelement xmlns:py="http://purl.org/kid/ns#" py:extends="t">
    <element py:content="template1()" />
    </docelement>
    """
    t2 = kid.load_template(s, cache=False, ns={'t': t})
    xml = t2.serialize()
    assert "This is a test" in xml
Esempio n. 6
0
def test_load_template_with_exec_module():
    s = """<?python Mickey = 'Mouse' ?>
    <html>Hello, World!</html>"""
    t= kid.load_template(s)
    assert t.Mickey == 'Mouse'
    assert not hasattr(t, 'Donald')
    def exec_module(mod, code):
        exec code in mod.__dict__
        mod.Donald = 'Duck'
    t = kid.load_template(s, exec_module=exec_module)
    assert t.Mickey == 'Mouse'
    assert t.Donald == 'Duck'
Esempio n. 7
0
def test_load_template_func():
    t = kid.load_template(joinpath(template_dir, 'test_if.kid'),
                          name='',
                          cache=False)
    assert_template_interface(t)
    t2 = kid.load_template(joinpath(template_dir, 'test_if.kid'),
                           name=template_package + 'test_if',
                           cache=True)
    assert not t is t2
    t3 = kid.load_template(joinpath(template_dir, 'test_if.kid'),
                           name=template_package + 'test_if',
                           cache=True)
    assert t3 is t2
Esempio n. 8
0
def test_load_template_with_exec_module():
    s = """<?python Mickey = 'Mouse' ?>
    <html>Hello, World!</html>"""
    t = kid.load_template(s)
    assert t.Mickey == 'Mouse'
    assert not hasattr(t, 'Donald')

    def exec_module(mod, code):
        exec code in mod.__dict__
        mod.Donald = 'Duck'

    t = kid.load_template(s, exec_module=exec_module)
    assert t.Mickey == 'Mouse'
    assert t.Donald == 'Duck'
Esempio n. 9
0
  def get_template(self, name):
    controller = self.__class__.__name__.lower()
    if controller.endswith('controller'):
      controller = controller[:-10]
      
    template = self.templates.get((controller, name))
    if template:
      return template
    else:
      try:
        resources = pkg_resources.resource_listdir(self.__class__.__module__, './views/%s/' % controller)
        for resource in resources:
          if resource.startswith(name):
            resource_name = resource
            break

        stream = pkg_resources.resource_stream(self.__class__.__module__, 
                                           './views/%s/%s' % (controller,resource_name))
        # Todo: Cache these templates
        if resource_name.endswith('kid'):
          t = kid.load_template(stream, ns={'template': self.get_template})
        else:
          t = erbtemplate.ERBTemplate()
          t.loadFromFile(stream)
        self.templates[(controller,name)] = t
        return t
      except IOError:
        return None
Esempio n. 10
0
	def loadClass(self, transaction, path):
		"""Load servlet class for the given Kid template."""
		classname = self.computeClassName(path)
		if self._cacheTemplates and self._useCache:
			# Cache the compiled templates separately:
			mtime = os.path.getmtime(path)
			classfile = os.path.join(self._cacheDir, classname + ".py")
			if not self._cacheSource:
				classfile += __debug__ and 'c' or 'o'
			if not os.path.exists(classfile) \
					or os.path.getmtime(classfile) != mtime:
				kidFile = KidFile(path)
				if self._cacheSource:
					kidFile.dump_source(classfile)
				else:
					kidFile.dump_code(classfile)
				# Set the modification time of the compiled file
				# to be the same as the source file;
				# that's how we'll know if it needs to be recompiled:
				os.utime(classfile, (os.path.getatime(classfile), mtime))
			module = self.importAsPackage(transaction, classfile)
		else:
			# Let Kid care about the caching:
			module = load_template(path, cache=self._cacheTemplates)
		# Setting __orig_file__ here is already too late,
		module.__orig_file__ = path
		# so we need to tell ImportSpy explicitely about the file:
		self._imp.watchFile(path)
		theClass = kidClass(module)
		theClass._orig_file = path
		theClass.__name__ = self.computeClassName(path)
		return theClass
Esempio n. 11
0
    def _write(self, templateName, templatePath = None, **values):
        if not templatePath:
            templatePath = self.cfg.templatePath

        path = os.path.join(templatePath, templateName + ".kid")

        template = kid.load_template(path)

        # pass along the context (overridden by values passed in as
        # kwargs to _write)
        context = dict(self.__dict__.iteritems())
        context.update(values)
        context.update({'cacheFakeoutVersion': helperfuncs.getVersionForCacheFakeout()})

        # Check for a bulletin file
        if os.path.exists(self.cfg.bulletinPath):
            bulletin = open(self.cfg.bulletinPath).read()
        else:
            bulletin = ''
        context.update({'bulletin': bulletin})

        # write out the template
        t = template.Template(**context)

        lang = self.cfg.language
        if lang != 'en':
            xlator = make_i18n_filter(self.cfg.localeDir, lang)
            t._filters.append(xlator)

        t.assume_encoding = 'latin1'
        returner = t.serialize(encoding = "utf-8", output = self.output)

        return returner
Esempio n. 12
0
def test_write_func():
    class FO:
        def write(self, text):
            pass
    kid.Template(name=template_package+'test_if').write(file=FO())
    m = kid.load_template(joinpath(template_dir, 'test_if.kid'))
    m.write(file=FO())
Esempio n. 13
0
 def loadClass(self, transaction, path):
     """Load servlet class for the given Kid template."""
     classname = self.computeClassName(path)
     if self._cacheTemplates and self._useCache:
         # Cache the compiled templates separately:
         mtime = os.path.getmtime(path)
         classfile = os.path.join(self._cacheDir, classname + ".py")
         if not self._cacheSource:
             classfile += 'c' if __debug__ else 'o'
         if (not os.path.exists(classfile)
                 or os.path.getmtime(classfile) != mtime):
             kidFile = KidFile(path)
             if self._cacheSource:
                 kidFile.dump_source(classfile)
             else:
                 kidFile.dump_code(classfile)
             # Set the modification time of the compiled file
             # to be the same as the source file;
             # that's how we'll know if it needs to be recompiled:
             os.utime(classfile, (os.path.getatime(classfile), mtime))
         module = self.importAsPackage(transaction, classfile)
     else:
         # Let Kid care about the caching:
         module = load_template(path, cache=self._cacheTemplates)
     # Setting __orig_file__ here is already too late,
     module.__orig_file__ = path
     # so we need to tell ImportSpy explicitely about the file:
     self._imp.watchFile(path)
     theClass = kidClass(module)
     theClass._orig_file = path
     theClass.__name__ = self.computeClassName(path)
     return theClass
Esempio n. 14
0
def test_generate_func():
    def run_test(o):
        for s in o.generate(encoding='ascii'):
            assert s is not None and len(s) > 0

    run_test(kid.Template(name=template_package + 'test_if'))
    run_test(kid.load_template(joinpath(template_dir, 'test_if.kid')))
Esempio n. 15
0
def test_write_func():
    class FO:
        def write(self, text):
            pass

    kid.Template(name=template_package + 'test_if').write(file=FO())
    m = kid.load_template(joinpath(template_dir, 'test_if.kid'))
    m.write(file=FO())
Esempio n. 16
0
def test_encoding():
    s = ('<?xml version="1.0" encoding="iso-8859-2"?>\n'
        '<e a="\xb5\xb9\xe8\xbb\xbe">'
        '\xb5\xb9\xe8\xbb\xbe\xfd\xe1\xed</e>')
    r = load_template(s).serialize(encoding='utf-8')
    s = s.decode('iso-8859-2').replace('iso-8859-2', 'utf-8')
    r = r.decode('utf-8')
    assert r == s
Esempio n. 17
0
def test_encoding():
    s = ('<?xml version="1.0" encoding="iso-8859-2"?>\n'
         '<e a="\xb5\xb9\xe8\xbb\xbe">'
         '\xb5\xb9\xe8\xbb\xbe\xfd\xe1\xed</e>')
    r = load_template(s).serialize(encoding='utf-8')
    s = s.decode('iso-8859-2').replace('iso-8859-2', 'utf-8')
    r = r.decode('utf-8')
    assert r == s
Esempio n. 18
0
 def load_template_string(self, template_string):
     assert isinstance(template_string, basestring)
     tempclass = kid.load_template(
         template_string, 
         name = "KidTemplateFromString-%d" % self.string_template_serial.next()
         ).Template
     tempclass.serializer = self.serializer
     return tempclass
Esempio n. 19
0
def test_serialize_func():
    def run_test(o):
        out = o.serialize(encoding='utf-8')
        assert out is not None and len(out) > 0
        out = o.serialize(encoding='ascii')
        assert out is not None and len(out) > 0
    run_test(kid.Template(name=template_package + 'test_if'))
    run_test(kid.load_template(joinpath(template_dir, 'test_if.kid')))
Esempio n. 20
0
def test_serialize_func():
    def run_test(o):
        out = o.serialize(encoding='utf-8')
        assert out is not None and len(out) > 0
        out = o.serialize(encoding='ascii')
        assert out is not None and len(out) > 0

    run_test(kid.Template(name=template_package + 'test_if'))
    run_test(kid.load_template(joinpath(template_dir, 'test_if.kid')))
Esempio n. 21
0
def kidTemplate(rq, o, bfn=None, **kw):
  fn=rq.webapp._getTemplateFile(bfn, default="root.kid")
  try: tmp=kid.load_template(file=fn)
  except kid.template_util.TemplateNotFound: raise fileNotFoundException()
  except:
    rq.webapp._logger.debug('template error fn=[%s]' % fn)
    raise
  # FIXME: check for valid template
  o.update(kw)
  s=tmp.Template(**o).serialize()
  return s
Esempio n. 22
0
def load_kid_template(t, modname=None):
    """
    Loads the given template into the given module name, if modname is None,
    an unique one will be generated.
    Returns a tuple (compiled_tmpl, template_text (or modulepath)
    """
    if isinstance(t, basestring) and "<" in t:
        if not modname:
            modname = 'instance_template_%d' % widget_instance_serial.next()
        return (kid.load_template(t, name=modname).Template, t)
    else:
        return (t, None)
def get_base_class(thing, from_file=None, arg=None):
    """Get template base class for thing, raising an exception on error."""
    if thing is None:
        return kid.BaseTemplate
    if isinstance(thing, TypeType):
        return thing
    elif isinstance(thing, ModuleType):
        try:
            cls = thing.Template
        except AttributeError:
            cls = None
        if (isinstance(cls, TypeType)
                and issubclass(cls, kid.BaseTemplate)
                and cls != kid.Template):
            return cls
        thing = repr(thing)
        if arg:
            thing = arg
        else:
            try:
                thing = thing.__name__
            except AttributeError:
                thing = repr(thing)
        raise TemplateNotFound(
            '%s is a module without Template class' % thing)
    elif isinstance(thing, basestring):
        try:
            path = kid.path.find(thing, from_file)
        except Exception:
            path = None
        if not path:
            if arg:
                thing = arg
            raise TemplateNotFound('Template file %r not found' % thing)
        try:
            mod = kid.load_template(path)
        except Exception:
            mod = None
        if not mod:
            raise TemplateNotFound('Could not open %r' % path)
        try:
            cls = mod.Template
        except AttributeError:
            cls = None
        if (isinstance(cls, TypeType)
                and issubclass(cls, kid.BaseTemplate)
                and cls != kid.Template):
            return cls
        raise TemplateNotFound('%r does not contain a template class' % path)
    thing = repr(thing)
    if arg:
        thing = '%s (%s)' % (arg, thing)
    raise TemplateNotFound('%s is not a Template class' % thing)
Esempio n. 24
0
def load_kid_template(t, modname=None):
    """Load the given template into the given module name.

    If modname is None, an unique one will be generated.
    Returns a tuple (compiled_tmpl, template_text (or modulepath).

    """
    if isinstance(t, basestring) and "<" in t:
        if not modname:
            modname = 'instance_template_%d' % widget_instance_serial.next()
        return (kid.load_template(t, name=modname).Template, t)
    else:
        return (t, None)
Esempio n. 25
0
    def run(self):
        destdir = self.destdir
        log.info("generating website to %s" % destdir)

        if not os.path.exists(destdir):
            log.info("creating %s" % destdir)
            os.makedirs(destdir)

        for name in self.templates_order:
            filename = self.templates[name]
            log.info("template %s loaded as %s" % (filename, name))
            kid.load_template(filename, name=name)

        if self.eggdir:
            if not self.eggdir.endswith("/"):
                self.eggdir += "/"
            choplen = len(self.eggdir)
            self.eggs = [fn[choplen:] for fn in glob(self.eggdir + "*")]
            self.eggs.sort()

        self.currentfiles = set()

        self.serializer = kid.HTMLSerializer(encoding=self.encoding)

        for d in self.srcdirs:
            self.update_site_files(d)
        for dest, src in self.copydirs.items():
            if os.path.isdir(src):
                self.update_site_files(src,
                                       processTemplates=False,
                                       destroot=os.path.join(
                                           self.destdir, dest))
            else:
                destfile = os.path.join(self.destdir, os.path.normpath(dest))
                self.copy_if_newer(src, destfile)
                self.currentfiles.add(destfile)
        self.printable_tutorial()
        self.delete_excess_files()
Esempio n. 26
0
 def _write(self, templateName, **values):
     path = os.path.join(self.templatePath, templateName + ".kid")
     t = kid.load_template(path)
     return t.serialize(encoding="utf-8",
                        output='xhtml-strict',
                        cfg=self.cfg,
                        methodName=self.methodName,
                        hasWrite=self.hasWrite,
                        loggedIn=self.loggedIn,
                        isAdmin=self.isAdmin,
                        isAnonymous=not self.loggedIn,
                        hasEntitlements=True,
                        currentUser=self.authToken[0],
                        **values)
Esempio n. 27
0
def kidTemplate(rq, o, bfn=None, **kw):
  d=rq.webapp._templatesDir
  if not os.path.isdir(d): raise fileNotFoundException()
  if not bfn: bfn='root.kid'
  fn=os.path.join(d, bfn)
  try: tmp=kid.load_template(file=fn)
  except kid.template_util.TemplateNotFound: raise fileNotFoundException()
  except:
    rq.webapp._logger.debug('template error fn=[%s]' % fn)
    raise
  # FIXME: check for valid template
  o.update(kw)
  s=tmp.Template(**o).serialize()
  return s
Esempio n. 28
0
    def run(self):
        destdir = self.destdir
        log.info("generating website to %s" % destdir)

        if not os.path.exists(destdir):
            log.info("creating %s" % destdir)
            os.makedirs(destdir)
            
        for name in self.templates_order:
            filename = self.templates[name]
            log.info("template %s loaded as %s" % (filename, name))
            kid.load_template(filename, name=name)
        
        if self.eggdir:
            if not self.eggdir.endswith("/"):
                self.eggdir += "/"
            choplen = len(self.eggdir)
            self.eggs = [fn[choplen:] for fn in glob(self.eggdir + "*")]
            self.eggs.sort()

        self.currentfiles = set()

        self.serializer = kid.HTMLSerializer(encoding=self.encoding)

        for d in self.srcdirs:
            self.update_site_files(d)
        for dest, src in self.copydirs.items():
            if os.path.isdir(src):
                self.update_site_files(src, processTemplates=False, 
                                   destroot=os.path.join(self.destdir, dest))
            else:
                destfile = os.path.join(self.destdir, os.path.normpath(dest))
                self.copy_if_newer(src, destfile)
                self.currentfiles.add(destfile)
        self.printable_tutorial()
        self.delete_excess_files()
Esempio n. 29
0
    def _write(self, templateName, **values):
        path = os.path.join(self.templatePath, templateName + ".kid")
        t = kid.load_template(path)
        return t.serialize(encoding = "utf-8",
                           output = 'xhtml-strict',

                           cfg = self.cfg,
                           methodName = self.methodName,
                           hasWrite = self.hasWrite,
                           loggedIn = self.loggedIn,
                           isAdmin = self.isAdmin,
                           isAnonymous = not self.loggedIn,
                           hasEntitlements = True,
                           currentUser = self.authToken[0],
                           **values)
Esempio n. 30
0
def kidTemplate(rq, o, bfn=None, **kw):
    d = rq.webapp._templatesDir
    if not os.path.isdir(d): raise fileNotFoundException()
    if not bfn: bfn = 'root.kid'
    fn = os.path.join(d, bfn)
    try:
        tmp = kid.load_template(file=fn)
    except kid.template_util.TemplateNotFound:
        raise fileNotFoundException()
    except:
        rq.webapp._logger.debug('template error fn=[%s]' % fn)
        raise
    # FIXME: check for valid template
    o.update(kw)
    s = tmp.Template(**o).serialize()
    return s
Esempio n. 31
0
def kid(dirname, verbose=False):
    try:
        import kid
    except ImportError:
        return lambda: None
    kid.path = kid.TemplatePath([dirname])
    template = kid.load_template('template.kid').Template
    def render():
        return template(
            title='Just a test', user='******',
            items=['Number %d' % num for num in range(1, 15)]
        ).serialize(output='xhtml')

    if verbose:
        print render()
    return render
Esempio n. 32
0
def load_kid_template(t, modname=None):
    """Load the given template into the given module name.

    If modname is None, an unique one will be generated.
    Returns a tuple (compiled_tmpl, template_text (or modulepath).

    """
    # this is a dummy-value-return-thingy, see above comment
    try:
        kid
    except NameError:
        return None, None

    if isinstance(t, basestring) and "<" in t:
        if not modname:
            modname = 'instance_template_%d' % widget_instance_serial.next()
        return (kid.load_template(t, name=modname).Template, t)
    else:
        return (t, None)
Esempio n. 33
0
def kid(dirname, verbose=False):
    try:
        import kid
    except ImportError:
        print("Kid not installed, skipping")
        return lambda: None
    kid.path = kid.TemplatePath([dirname])
    template = kid.load_template("template.kid").Template

    def render():
        return template(
            title="Just a test",
            user="******",
            items=["Number %d" % num for num in range(1, 15)],
        ).serialize(output="xhtml")

    if verbose:
        print(render())
    return render
Esempio n. 34
0
 def render_template(self, src, dest, depth):
     if not self.force and not self.check_if_newer(src, dest):
         return
     if not self.dry_run:
         log.info("rendering %s" % dest)
     else:
         log.info("skipping rendering %s" % dest)
         return
     
     template = kid.load_template(src, cache=False)
     template.Template.serializer = self.serializer
     toroot = "../" * depth
     destfile = dest[len(self.destdir)+1:]
     updated = time.strftime("%b %d, %Y", time.localtime(os.path.getmtime(src)))
     output = template.serialize(encoding=self.encoding, root=toroot, updated=updated,
         destfile=destfile, eggs=self.eggs)
     output = output.replace("$$", "$")
     destfile = open(dest, "w")
     destfile.write(output)
     destfile.close()
Esempio n. 35
0
    def render_template(self, src, dest, depth):
        if not self.force and not self.check_if_newer(src, dest):
            return
        if not self.dry_run:
            log.info("rendering %s" % dest)
        else:
            log.info("skipping rendering %s" % dest)
            return

        template = kid.load_template(src, cache=False)
        template.Template.serializer = self.serializer
        toroot = "../" * depth
        destfile = dest[len(self.destdir) + 1:]
        updated = time.strftime("%b %d, %Y",
                                time.localtime(os.path.getmtime(src)))
        output = template.serialize(encoding=self.encoding,
                                    root=toroot,
                                    updated=updated,
                                    destfile=destfile,
                                    eggs=self.eggs)
        output = output.replace("$$", "$")
        destfile = open(dest, "w")
        destfile.write(output)
        destfile.close()
Esempio n. 36
0
    def run_kid(self):
        """Execute a Kid template."""
        scriptname, query = self.cgi_info
        scriptfile = self.translate_path(scriptname)
        if not os.path.exists(scriptfile):
            self.send_error(404, "No such Kid template (%r)"
                % scriptname)
            return
        if not os.path.isfile(scriptfile):
            self.send_error(403, "Kid template is not a plain file (%r)"
                % scriptname)
            return

        env = {}
        env['SERVER_SOFTWARE'] = self.version_string()
        env['SERVER_NAME'] = self.server.server_name
        env['GATEWAY_INTERFACE'] = 'CGI/1.1'
        env['SERVER_PROTOCOL'] = self.protocol_version
        env['SERVER_PORT'] = str(self.server.server_port)
        env['REQUEST_METHOD'] = self.command
        uqpath = unquote(scriptname)
        env['PATH_INFO'] = uqpath
        env['PATH_TRANSLATED'] = self.translate_path(uqpath)
        env['SCRIPT_NAME'] = scriptname
        if query:
            env['QUERY_STRING'] = query
        host = self.address_string()
        if host != self.client_address[0]:
            env['REMOTE_HOST'] = host
        env['REMOTE_ADDR'] = self.client_address[0]
        authorization = self.headers.getheader("authorization")
        if authorization:
            authorization = authorization.split()
            if len(authorization) == 2:
                import base64, binascii
                env['AUTH_TYPE'] = authorization[0]
                if authorization[0].lower() == "basic":
                    try:
                        authorization = base64.decodestring(authorization[1])
                    except binascii.Error:
                        pass
                    else:
                        authorization = authorization.split(':')
                        if len(authorization) == 2:
                            env['REMOTE_USER'] = authorization[0]
        if self.headers.typeheader is None:
            env['CONTENT_TYPE'] = self.headers.type
        else:
            env['CONTENT_TYPE'] = self.headers.typeheader
        length = self.headers.getheader('content-length')
        if length:
            env['CONTENT_LENGTH'] = length
        accept = []
        for line in self.headers.getallmatchingheaders('accept'):
            if line[:1] in "\t\n\r ":
                accept.append(line.strip())
            else:
                accept = accept + line[7:].split(',')
        env['HTTP_ACCEPT'] = ','.join(accept)
        ua = self.headers.getheader('user-agent')
        if ua:
            env['HTTP_USER_AGENT'] = ua
        co = filter(None, self.headers.getheaders('cookie'))
        if co:
            env['HTTP_COOKIE'] = ', '.join(co)

        self.send_response(200, "Script output follows")

        # Execute template in this process
        try:
            template_module = load_template(scriptfile, cache=True)
            template = template_module.Template(
                request=self, environ=env,
                FieldStorage=FieldStorage(self.rfile, environ=env))
            s = str(template)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(s)))
            self.end_headers()
            self.wfile.write(s)
        except Exception, e:
            self.log_error("Kid template exception: %s", str(e))
Esempio n. 37
0
        filehandler = logging.FileHandler(filename = logfile)
        filehandler.setFormatter(formatter)
        logging.getLogger().addHandler(filehandler)
    
    if sys.stderr.isatty():
        streamhandler = logging.StreamHandler(sys.stderr)
        streamhandler.setFormatter(formatter)
        logging.getLogger().addHandler(streamhandler)
    
    logging.log_init_done = True

# Just initialize logs as soon as this module is imported.
if not hasattr(logging, 'log_init_done'):
    initialize_logging()

multistatus = kid.load_template('multistatus.kid')
dirindex = kid.load_template('dirindex.kid')
activelock = kid.load_template('activelock.kid')

def handle_options(reqinfo, start_response):
    '''Handle an OPTIONS request.'''
    reqinfo.assert_nobody()
    if reqinfo.lockmanager:
        start_response('200 OK', [('DAV', '1,2')])
    else:
        start_response('200 OK', [('DAV', '1')])
    return ""

def get_resourcetype(path):
    '''Return the contents for <DAV:resourcetype> property.'''
    if os.path.isdir(path):
Esempio n. 38
0
        filehandler.setFormatter(formatter)
        logging.getLogger().addHandler(filehandler)

    if sys.stderr.isatty():
        streamhandler = logging.StreamHandler(sys.stderr)
        streamhandler.setFormatter(formatter)
        logging.getLogger().addHandler(streamhandler)

    logging.log_init_done = True


# Just initialize logs as soon as this module is imported.
if not hasattr(logging, 'log_init_done'):
    initialize_logging()

multistatus = kid.load_template('multistatus.kid')
dirindex = kid.load_template('dirindex.kid')
activelock = kid.load_template('activelock.kid')


def handle_options(reqinfo, start_response):
    '''Handle an OPTIONS request.'''
    reqinfo.assert_nobody()
    if reqinfo.lockmanager:
        start_response('200 OK', [('DAV', '1,2')])
    else:
        start_response('200 OK', [('DAV', '1')])
    return ""


def get_resourcetype(path):
Esempio n. 39
0
def _compile_template(package, basename, tfile, classname):
    mod = kid.load_template(tfile, name=classname)
    setattr(sys.modules[package], basename, mod)
    return mod
Esempio n. 40
0
#!/usr/bin/env python

# A script used to rebuild the website. We use kid for templating,
# generate all the HTML statically, and upload the new version

import os
import string, re

import kid

module = kid.load_template("outline.kid", cache=1)


class Bag:
    def __init__(self, **kwds):
        self.__dict__["url_prefix"] = ""
        self.__dict__.update(kwds)


announce = [
    Bag(date="April 22, 2018",
        text="Version 4.0 released. This supports Python 3.x"),
    Bag(date="June 1st, 2015", text="Moved to GitHub"),
    Bag(date="February 2nd, 2013",
        text=
        "Version 3.14.1 released. This is a bug-fix release including fixes for the manual and build system"
        ),
    Bag(date="May 18th, 2011",
        text=
        "Version 3.14 released. This contains bug fixes for Mac vs Windows in the build system."
        )
Esempio n. 41
0
def test_generate_func():
    def run_test(o):
        for s in o.generate(encoding='ascii'):
            assert s is not None and len(s) > 0
    run_test(kid.Template(name=template_package + 'test_if'))
    run_test(kid.load_template(joinpath(template_dir, 'test_if.kid')))
Esempio n. 42
0
         else:
             f = sys.stdin.read()
         # get arguments for the template file
         kw = {}
         while args:
             a = args.pop(0).split('=', 1)
             if len(a) > 1:
                 kw[a[0]] = a[1]
             else:
                 sys.argv.append(a[0])
         # do not run as __main__ module
         sys.modules['__kid_main__'] = sys.modules['__main__']
         __name__ = '__kid_main__'
         del sys.modules['__main__']
         # load kid template as __main__ module
         module = kid.load_template(f, name='__main__', cache=False)
         # execute the template and write output
         if not outfile:
             outfile = sys.stdout
         module.write(outfile, encoding=enc, **kw)
     else:
         sys.stderr.write('kid: No template file specified.\n')
         sys.stderr.write("     Try 'kid --help' for usage information.\n")
         sys.exit(EX_USAGE)
 else:
     if len(args) < 2:
         if outfile:
             stderr = file(outfile, 'a', 1)
             sys.stderr = stderr
         sys.stdout.write('Starting HTTP server ...\n')
         if args:
Esempio n. 43
0
    assert list(XML(xml, entity_map=entity_map))[0][1] == u'Hello, World!'


def test_load_template_with_entity_map():
    xml = '<html>&nbsp;</html>'
    s = load_template(xml).serialize(encoding='ascii')
    assert s.endswith('<html>&#160;</html>')
    xml = '<html>&codswallop;</html>'
    try:
        e = load_template(xml).serialize(encoding='ascii')
    except Exception, e:
        e = str(e)
    assert 'undefined entity &codswallop;' in e
    xml = '<html>&nbsp;, &codswallop;!</html>'
    entity_map = {'nbsp': u'Hello', 'codswallop': u'World'}
    s = load_template(xml, entity_map=entity_map).serialize(encoding='ascii')
    assert s.endswith('<html>Hello, World!</html>')


def test_encoding():
    s = ('<?xml version="1.0" encoding="iso-8859-2"?>\n'
         '<e a="\xb5\xb9\xe8\xbb\xbe">'
         '\xb5\xb9\xe8\xbb\xbe\xfd\xe1\xed</e>')
    r = load_template(s).serialize(encoding='utf-8')
    s = s.decode('iso-8859-2').replace('iso-8859-2', 'utf-8')
    r = r.decode('utf-8')
    assert r == s


def test_expand_fragments():
    """Testcase for expanding XML fragments (ticket #145)."""
Esempio n. 44
0
    entity_map = {'nbsp': u'Hello', 'codswallop': u'World'}
    assert list(XML(xml, entity_map=entity_map))[0][1] == u'Hello, World!'

def test_load_template_with_entity_map():
    xml = '<html>&nbsp;</html>'
    s = load_template(xml).serialize(encoding='ascii')
    assert s.endswith('<html>&#160;</html>')
    xml = '<html>&codswallop;</html>'
    try:
        e = load_template(xml).serialize(encoding='ascii')
    except Exception, e:
        e = str(e)
    assert 'undefined entity &codswallop;' in e
    xml = '<html>&nbsp;, &codswallop;!</html>'
    entity_map = {'nbsp': u'Hello', 'codswallop': u'World'}
    s = load_template(xml, entity_map=entity_map).serialize(encoding='ascii')
    assert s.endswith('<html>Hello, World!</html>')

def test_encoding():
    s = ('<?xml version="1.0" encoding="iso-8859-2"?>\n'
        '<e a="\xb5\xb9\xe8\xbb\xbe">'
        '\xb5\xb9\xe8\xbb\xbe\xfd\xe1\xed</e>')
    r = load_template(s).serialize(encoding='utf-8')
    s = s.decode('iso-8859-2').replace('iso-8859-2', 'utf-8')
    r = r.decode('utf-8')
    assert r == s

def test_expand_fragments():
    """Testcase for expanding XML fragments (ticket #145)."""
    template = """<div xmlns:py="http://purl.org/kid/ns#"
        py:replace="stream" />"""
Esempio n. 45
0
         else:
             f = sys.stdin.read()
         # get arguments for the template file
         kw = {}
         while args:
             a = args.pop(0).split('=', 1)
             if len(a) > 1:
                 kw[a[0]] = a[1]
             else:
                 sys.argv.append(a[0])
         # do not run as __main__ module
         sys.modules['__kid_main__'] = sys.modules['__main__']
         __name__ = '__kid_main__'
         del sys.modules['__main__']
         # load kid template as __main__ module
         module = kid.load_template(f, name='__main__', cache=False)
         # execute the template and write output
         if not outfile:
             outfile = sys.stdout
         module.write(outfile, encoding=enc, **kw)
     else:
         sys.stderr.write('kid: No template file specified.\n')
         sys.stderr.write("     Try 'kid --help' for usage information.\n")
         sys.exit(EX_USAGE)
 else:
     if len(args) < 2:
         if outfile:
             stderr = file(outfile, 'a', 1)
             sys.stderr = stderr
         sys.stdout.write('Starting HTTP server ...\n')
         if args:
Esempio n. 46
0
#!/usr/bin/env python

# A script used to rebuild the website. We use kid for templating,
# generate all the HTML statically, and upload the new version

import os
import string, re

import kid

module = kid.load_template("outline.kid",cache=1)

class Bag:
    def __init__(self,**kwds):
        self.__dict__["url_prefix"]=""
        self.__dict__.update(kwds)
        
announce = [
        Bag(
            date="June 1st, 2015",
            text="Moved to GitHub"),            
	Bag(
            date="February 2nd, 2013",
            text="Version 3.14.1 released. This is a bug-fix release including fixes for the manual and build system"),
	Bag(
            date="May 18th, 2011",
            text="Version 3.14 released. This contains bug fixes for Mac vs Windows in the build system.")
	]

manual_pages = [
    Bag(name="Using Gnofract 4D",
Esempio n. 47
0
 def __init__(self, filename, kwargs):
     module = kid.load_template(filename)
     self.template = module.Template(assume_encoding='utf-8', **kwargs)
    def run_kid(self):
        """Execute a Kid template."""
        scriptname, query = self.cgi_info
        scriptfile = self.translate_path(scriptname)
        if not os.path.exists(scriptfile):
            self.send_error(404, "No such Kid template (%r)" % scriptname)
            return
        if not os.path.isfile(scriptfile):
            self.send_error(
                403, "Kid template is not a plain file (%r)" % scriptname)
            return

        env = {}
        env['SERVER_SOFTWARE'] = self.version_string()
        env['SERVER_NAME'] = self.server.server_name
        env['GATEWAY_INTERFACE'] = 'CGI/1.1'
        env['SERVER_PROTOCOL'] = self.protocol_version
        env['SERVER_PORT'] = str(self.server.server_port)
        env['REQUEST_METHOD'] = self.command
        uqpath = unquote(scriptname)
        env['PATH_INFO'] = uqpath
        env['PATH_TRANSLATED'] = self.translate_path(uqpath)
        env['SCRIPT_NAME'] = scriptname
        if query:
            env['QUERY_STRING'] = query
        host = self.address_string()
        if host != self.client_address[0]:
            env['REMOTE_HOST'] = host
        env['REMOTE_ADDR'] = self.client_address[0]
        authorization = self.headers.getheader("authorization")
        if authorization:
            authorization = authorization.split()
            if len(authorization) == 2:
                import base64, binascii
                env['AUTH_TYPE'] = authorization[0]
                if authorization[0].lower() == "basic":
                    try:
                        authorization = base64.decodestring(authorization[1])
                    except binascii.Error:
                        pass
                    else:
                        authorization = authorization.split(':')
                        if len(authorization) == 2:
                            env['REMOTE_USER'] = authorization[0]
        if self.headers.typeheader is None:
            env['CONTENT_TYPE'] = self.headers.type
        else:
            env['CONTENT_TYPE'] = self.headers.typeheader
        length = self.headers.getheader('content-length')
        if length:
            env['CONTENT_LENGTH'] = length
        accept = []
        for line in self.headers.getallmatchingheaders('accept'):
            if line[:1] in "\t\n\r ":
                accept.append(line.strip())
            else:
                accept = accept + line[7:].split(',')
        env['HTTP_ACCEPT'] = ','.join(accept)
        ua = self.headers.getheader('user-agent')
        if ua:
            env['HTTP_USER_AGENT'] = ua
        co = filter(None, self.headers.getheaders('cookie'))
        if co:
            env['HTTP_COOKIE'] = ', '.join(co)

        self.send_response(200, "Script output follows")

        # Execute template in this process
        try:
            template_module = load_template(scriptfile, cache=True)
            template = template_module.Template(request=self,
                                                environ=env,
                                                FieldStorage=FieldStorage(
                                                    self.rfile, environ=env))
            s = str(template)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(s)))
            self.end_headers()
            self.wfile.write(s)
        except Exception, e:
            self.log_error("Kid template exception: %s", str(e))