Git Product home page Git Product logo

cheetah3's Introduction

Cheetah Template 3.3.4a4

Cheetah3 is a free and open source (MIT) Python template engine. It's a fork of the original CheetahTemplate library.

Python 2.7 or 3.4+ is required.

Where is CheetahTemplate3

Site: https://cheetahtemplate.org/

Download: https://pypi.org/project/CT3/

News and changes: https://cheetahtemplate.org/news.html

StackOverflow: https://stackoverflow.com/questions/tagged/cheetah

Mailing lists: https://sourceforge.net/p/cheetahtemplate/mailman/

Development: https://github.com/CheetahTemplate3

Developer Guide: https://cheetahtemplate.org/dev_guide/

Example

Install:

$ pip install CT3 # (or even "ct3")

Below is a simple example of some Cheetah code, as you can see it's practically Python. You can import, inherit and define methods just like in a regular Python module, since that's what your Cheetah templates are compiled to :)

#from Cheetah.Template import Template
#extends Template

#set $people = [{'name' : 'Tom', 'mood' : 'Happy'}, {'name' : 'Dick',
                        'mood' : 'Sad'}, {'name' : 'Harry', 'mood' : 'Hairy'}]

<strong>How are you feeling?</strong>
<ul>
    #for $person in $people
        <li>
            $person['name'] is $person['mood']
        </li>
    #end for
</ul>

cheetah3's People

Contributors

abbeyj avatar blkkkbvsik avatar cendioossman avatar dareonion avatar hexaclock avatar huangxiaodui avatar ianb avatar jbq avatar jjinux avatar js-cfl avatar karmix avatar kyrios123 avatar melor avatar mgorny avatar mikebonnet avatar mikeorr avatar mikola avatar msabramo avatar navilan avatar nsoranzo avatar odidev avatar phdru avatar redbeard0531 avatar saiprasad16 avatar schwehr avatar swamper78 avatar tavisrudd avatar vstinner avatar wedebe avatar yegorich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cheetah3's Issues

'file' type in Python2

hi

an opened file in Python2 is not of type io.IOBase

I have distilled this much code from Cheetah/Template.py , as you see it fails

test.txt

the following patch fixes the problem

diff.txt

bye, a.

Add support to release aarch64 wheels

Problem

On aarch64, pip install cheetah3 builds the wheels from source code and then install it. It requires user to have development environment installed on his system. also, it take some time to build the wheels than downloading and extracting the wheels from pypi.

Resolution

On aarch64, pip install cheetah3 should download the wheels from pypi

@phdru, please let me know your interest on releasing aarch64 wheels. I can help in this.

Dealing with missing values

I need to implement a templating system with missing values, since the final template string is processed in multiple steps. I have 2 questions, with one of them possibly being a bug.

  1. I've tried using a different error catcher do suppress the NotFound exception, but it appears to not work:
>>> str(Cheetah.Template.Template("My test $string string.", searchList=[{}], errorCatcher=Cheetah.ErrorCatchers.Echo))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jlorieau/Code/Python/VirtualEnvironments/Disseminate/lib/python3.6/site-packages/Cheetah/Template.py", line 1053, in __unicode__
    return getattr(self, mainMethName)()
  File "DynamicallyCompiledCheetahTemplate.py", line 87, in respond
NameMapper.NotFound: cannot find 'string'

I've also tried passing the 'Echo' string for the errorCatcher parameter, but I can't get this error catcher to work. My aim is to get the string My test $string string. returned unchanged.

  1. Apparently there is a (significant?) cost in suppressing this exception, according to the documentation. Is there a better and more efficient way to suppress missed variables?

Thanks,

Justin

run command “cheetah test” failed

version:3.3.1

I am using the latest version of 3.3.1. After the compilation is complete, run command "cheetah test" to run test cases. The system displays failure information "Wrong argument or wrong number of arguments".
image

The error code is

if args_l == 1:
    pass
elif args_l == 2 and sys.argv[1] == '--namemapper-pure':
    try:
        from Cheetah import _namemapper  # noqa
    except ImportError:
        # _namemapper hasn't been compiled so Tests/NameMapper.py
        # tests pure-python NameMapper.py; no need to duplicate these tests.
        print('Ok')
        sys.exit(0)
    sys.modules['Cheetah._namemapper'] = None
    sys._cheetah_namemapper_pure = True
else:
    sys.exit('Wrong argument or wrong number of arguments')

Please confirm whether the code needs to be modified, thank you.

Python 3.10 support?

Since there appear to be no release notes connected with the tagged versions, can someone shed some light on Python version requirements? My specific question is which stable release (if any) will work on Python 3.10.

What's the level of compatibility between Cheetah and Cheetah3?

Hi,

When building a port using Cheetah 3 as a dependency, I noticed that Cheetah 3 uses the same package directory (Cheetah). Other ports still declare a dependency on Cheetah 2, so a question arises: how compatible are Cheetah 3 and Cheetah 2? Can Cheetah 3 be considered a drop-in replacement?

Thanks.

Tests fail when TMPDIR contains hyphens

We've noticed that the test suite fails on Gentoo because the TMPDIR used while building packages contains hyphens. It seems that sometimes substitutes all hyphens in path with underscores.

To reproduce:

export TMPDIR=/tmp/cheetah3-3.3.1/temp
mkdir -p "${TMPDIR}"
tox
Error output
.pkg: _optional_hooks> python /usr/lib/python3.11/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
.pkg: get_requires_for_build_sdist> python /usr/lib/python3.11/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
.pkg: prepare_metadata_for_build_wheel> python /usr/lib/python3.11/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
.pkg: build_sdist> python /usr/lib/python3.11/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
py310: install_package> python -I -m pip install --force-reinstall --no-deps /tmp/cheetah3-3.3.1/.tox/.tmp/package/2/CT3-3.3.1.tar.gz
py310: commands[0]> .tox/py310/bin/python --version
Python 3.10.10
py310: commands[1]> .tox/py310/bin/python -c 'import struct; print(struct.calcsize('"'"'P'"'"') * 8)'
64
py310: commands[2]> .tox/py310/bin/python /tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Test.py
.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................E.EEEE.FF...................................................
======================================================================
ERROR: runTest (Cheetah.Tests.Unicode.JBQ_UTF8_Test7)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 131, in runTest
    template = self.createAndCompile(source)
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 24, in createAndCompile
    fd = open('%s.tmpl' % sourcefile, 'w', encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/cheetah3_3.3.1/temp/tmplre8dnao.tmpl'

======================================================================
ERROR: testStaticCompile (Cheetah.Tests.Unicode.JBQ_UTF8_Test8)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 143, in testStaticCompile
    template = self.createAndCompile(source)()
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 24, in createAndCompile
    fd = open('%s.tmpl' % sourcefile, 'w', encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/cheetah3_3.3.1/temp/tmpcnzh_309.tmpl'

======================================================================
ERROR: test_BasicASCII (Cheetah.Tests.Unicode.Unicode_in_SearchList_Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 185, in test_BasicASCII
    template = self.createAndCompile(source)
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 24, in createAndCompile
    fd = open('%s.tmpl' % sourcefile, 'w', encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/cheetah3_3.3.1/temp/tmplkrv57du.tmpl'

======================================================================
ERROR: test_Thai (Cheetah.Tests.Unicode.Unicode_in_SearchList_Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 193, in test_Thai
    template = self.createAndCompile(source)
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 24, in createAndCompile
    fd = open('%s.tmpl' % sourcefile, 'w', encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/cheetah3_3.3.1/temp/tmp3z63xypm.tmpl'

======================================================================
ERROR: test_Thai_utf8 (Cheetah.Tests.Unicode.Unicode_in_SearchList_Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 210, in test_Thai_utf8
    template = self.createAndCompile(source)
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Unicode.py", line 24, in createAndCompile
    fd = open('%s.tmpl' % sourcefile, 'w', encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/cheetah3_3.3.1/temp/tmpufwexe2x.tmpl'

======================================================================
FAIL: testFill (Cheetah.Tests.CheetahWrapper.FileDataFill)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/CheetahWrapper.py", line 628, in testFill
    self.go('cheetah fill --json {jsonfile} json.tmpl'
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/CheetahWrapper.py", line 237, in go
    output = self.assertSubprocess(cmd)
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/CheetahWrapper.py", line 217, in assertSubprocess
    self.assertEqual(status, 0,
AssertionError: 1 != 0 : Subprocess exited with a non-zero status (1)
                             b'Traceback (most recent call last):\n  File "/tmp/cheetah3-3.3.1/.tox/py310/bin/cheetah", line 3, in <module>\n    _cheetah()\n  File "/tmp/cheetah3-3.3.1/Cheetah/CheetahWrapper.py", line 664, in _cheetah\n    CheetahWrapper().main()\n  File "/tmp/cheetah3-3.3.1/Cheetah/CheetahWrapper.py", line 132, in main\n    self.parseOpts(argv[2:])\n  File "/tmp/cheetah3-3.3.1/Cheetah/CheetahWrapper.py", line 257, in parseOpts\n    f = open(opts.json, \'r\')\nFileNotFoundError: [Errno 2] No such file or directory: \'/tmp//tmp/cheetah3-3.3.1/.tox/py310/bin/cheetah3-3.3.1/temp/tmp51ab6_bf\'\n'

======================================================================
FAIL: testText (Cheetah.Tests.CheetahWrapper.FileDataFill)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/CheetahWrapper.py", line 636, in testText
    self.go('cheetah fill --json {jsonfile} --oext txt json.tmpl'
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/CheetahWrapper.py", line 237, in go
    output = self.assertSubprocess(cmd)
  File "/tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/CheetahWrapper.py", line 217, in assertSubprocess
    self.assertEqual(status, 0,
AssertionError: 1 != 0 : Subprocess exited with a non-zero status (1)
                             b'Traceback (most recent call last):\n  File "/tmp/cheetah3-3.3.1/.tox/py310/bin/cheetah", line 3, in <module>\n    _cheetah()\n  File "/tmp/cheetah3-3.3.1/Cheetah/CheetahWrapper.py", line 664, in _cheetah\n    CheetahWrapper().main()\n  File "/tmp/cheetah3-3.3.1/Cheetah/CheetahWrapper.py", line 132, in main\n    self.parseOpts(argv[2:])\n  File "/tmp/cheetah3-3.3.1/Cheetah/CheetahWrapper.py", line 257, in parseOpts\n    f = open(opts.json, \'r\')\nFileNotFoundError: [Errno 2] No such file or directory: \'/tmp//tmp/cheetah3-3.3.1/.tox/py310/bin/cheetah3-3.3.1/temp/tmp_5ukkv4z\'\n'

----------------------------------------------------------------------
Ran 2181 tests in 10.025s

FAILED (failures=2, errors=5)
py310: exit 1 (10.37 seconds) /tmp/cheetah3-3.3.1> .tox/py310/bin/python /tmp/cheetah3-3.3.1/.tox/py310/lib/python3.10/site-packages/Cheetah/Tests/Test.py pid=2004668
.pkg: _exit> python /usr/lib/python3.11/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
  py310: FAIL code 1 (17.91=setup[7.52]+cmd[0.00,0.02,10.37] seconds)
  evaluation failed :( (18.00 seconds)

#extend mistake in python3

Hi cheetah developers, I'm facing an issue when using Cheetah3.2.6.post1!
When I try to import a module in the same directory by using: #extend MyModule. Cheetah generate the code to: from MyModule import MyModule. As you can see, the generated code is in Python2, the correct code in Python3 should be: from .MyModule import MyModule. I tried to change the code in tmpl file to: #extend .MyModule, but Cheetah throw me an error about Syntax Error at the dot before MyModule.
I took a look about your document from https://cheetahtemplate.org/users_guide/inheritanceEtc.html but your document still mention about the Python2 syntax at:

2.  Site.tmpl/py  (template containing the general site framework;
                   this is the template that controls the output,
                   the one that contains "<HTML><HEAD>...", the one
                   that contains text outside any #def/#block.)
        #from SiteLogic import SiteLogic
        #extends SiteLogic
        #implements respond

I don't know is it a mistake or my gap in knowledge about your open source!
Appreciate for your help!

Cheetah Test Error: Cheetah.CheetahWrapper

Hello!

I am working with the JPL F Prime software and am having a hard time getting Cheetah to work properly. When I run the command "Cheetah Test", this is the error I'm getting:

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/bin/cheetah", line 2, in
from Cheetah.CheetahWrapper import _cheetah
ImportError: No module named Cheetah.CheetahWrapper

When I go to the referenced file, it has this:
#!/usr/bin/env python
from Cheetah.CheetahWrapper import _cheetah
_cheetah()

There is a file called Cheetah.CheetahWrapper in the folder with these files and I can't figure out why the code isn't seeing.

I have little to no experience with this, so any help would be greatly appreciated.

Thank you!

markdown dependency

markdown will be imported in Cheetah/Filters.py but it is missing as install_requires in setup.py. Is this intentional?

Calling Template.getVar() with a string beginning with "$" crashes

The compiled C version of NameMapper does not handle names beginning with "$" correctly. Specifically on CentOS 6.10, this command results in a Segmentation fault:
python -c "from Cheetah.Template import Template; print(Template(source='blah').getVar('$'))"

I get the same result from both Cheetah 3.1.0 and 3.2.5 on Python 2.7.

After deleting _namemapper.so, the same command produces a traceback:

You don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with compiled C version of NameMapper.
  "\nYou don't have the C version of NameMapper installed! "
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/sscadmin/.local/share/virtualenvs/python2.7/lib64/python2.7/site-packages/Cheetah/Template.py", line 1446, in getVar
    self.searchList(), varName.replace('$', ''), autoCall)
  File "/home/sscadmin/.local/share/virtualenvs/python2.7/lib64/python2.7/site-packages/Cheetah/NameMapper.py", line 289, in valueFromSearchList
    _raiseNotFoundException(key, searchList)
  File "/home/sscadmin/.local/share/virtualenvs/python2.7/lib64/python2.7/site-packages/Cheetah/NameMapper.py", line 174, in _raiseNotFoundException
    raise NotFound(excString)
Cheetah.NameMapper.NotFound: cannot find ''

Cheetah.Tests.SyntaxAndOutput.*.test4 filure with Python 3.13.0b2

I tried to test cheetah3-3.3.3 with recent release of Python 3.13.0b2 and two tests fail for me:

======================================================================
ERROR: test4 (Cheetah.Tests.SyntaxAndOutput.CGI.test4)
A CGI script with a GET variable.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/var/tmp/portage/dev-python/cheetah3-3.3.3/work/cheetah3-3.3.3-python3_13/install/usr/lib/python3.13/site-packages/Cheetah/Tests/SyntaxAndOutput.py", line 3141, in test4
    self.verify(source,
    ~~~~~~~~~~~^^^^^^^^
                "Content-type: text/html\n\nHello, world!")
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/tmp/portage/dev-python/cheetah3-3.3.3/work/cheetah3-3.3.3-python3_13/install/usr/lib/python3.13/site-packages/Cheetah/Tests/SyntaxAndOutput.py", line 179, in verify
    output = templateObj.respond()
  File "cheetah_DynamicallyCompiledCheetahTemplate_1718569711_7594848_70780.py", line 89, in respond
  File "/var/tmp/portage/dev-python/cheetah3-3.3.3/work/cheetah3-3.3.3-python3_13/install/usr/lib/python3.13/site-packages/Cheetah/Template.py", line 1937, in webInput
    source, func = 'field', self.request().field
                            ~~~~~~~~~~~~^^
TypeError: 'NoneType' object is not callable

======================================================================
ERROR: test4 (Cheetah.Tests.SyntaxAndOutput.CGI_DiffBaseClass.test4)
A CGI script with a GET variable.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/var/tmp/portage/dev-python/cheetah3-3.3.3/work/cheetah3-3.3.3-python3_13/install/usr/lib/python3.13/site-packages/Cheetah/Tests/SyntaxAndOutput.py", line 3141, in test4
    self.verify(source,
    ~~~~~~~~~~~^^^^^^^^
                "Content-type: text/html\n\nHello, world!")
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/tmp/portage/dev-python/cheetah3-3.3.3/work/cheetah3-3.3.3-python3_13/install/usr/lib/python3.13/site-packages/Cheetah/Tests/SyntaxAndOutput.py", line 179, in verify
    output = templateObj.respond()
  File "cheetah_DynamicallyCompiledCheetahTemplate_1718569711_7689054_24344.py", line 89, in respond
  File "/var/tmp/portage/dev-python/cheetah3-3.3.3/work/cheetah3-3.3.3-python3_13/install/usr/lib/python3.13/site-packages/Cheetah/Template.py", line 1937, in webInput
    source, func = 'field', self.request().field
                            ~~~~~~~~~~~~^^
TypeError: 'NoneType' object is not callable

----------------------------------------------------------------------
Ran 2181 tests in 15.273s

FAILED (errors=2)

There is also lots of following, similarly looking lines in the test log:

Exception ignored in PyMapping_HasKeyString(); consider using PyMapping_HasKeyStringWithError(), PyMapping_GetOptionalItemString() or PyMapping_GetItemString():
Traceback (most recent call last):
  File "cheetah_DynamicallyCompiledCheetahTemplate_1718569711_8529928_92881.py", line 90, in meth
TypeError: string indices must be integers, not 'str'

RecursionError: maximum recursion depth exceeded while calling a Python object

When running the tests under Python 3.8 (3.8.0b3 in a Fedora Rawhide chroot) I'm getting recursion errors in the CheetahWrapper tests. It's reproduceable outside the tests with a simple cheetah fill command:

[mockbuild@eb00021cc65144128240dd7e5148c7fd tmpztxspttp]$ cat a.tmpl 
Hello, world!
[mockbuild@eb00021cc65144128240dd7e5148c7fd tmpztxspttp]$ cheetah fill a.tmpl 
Filling a.tmpl -> a.html
Traceback (most recent call last):
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/bin/cheetah", line 3, in <module>
    _cheetah()
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/CheetahWrapper.py", line 655, in _cheetah
    CheetahWrapper().main()
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/CheetahWrapper.py", line 147, in main
    meth()
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/CheetahWrapper.py", line 263, in fill
    self._compileOrFill()
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/CheetahWrapper.py", line 409, in _compileOrFill
    self._compileOrFillBundle(b)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/CheetahWrapper.py", line 622, in _compileOrFillBundle
    tclass = TemplateClass.compile(file=src,
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/Template.py", line 767, in compile
    compiler = compilerClass(source, file,
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/Compiler.py", line 1659, in __init__
    f = open(file, 'r')
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 462, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 523, in doimport
    mod = director.getmod(nm)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 363, in getmod
    mod = owner.getmod(nm)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 462, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 523, in doimport
    mod = director.getmod(nm)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 363, in getmod
    mod = owner.getmod(nm)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
...
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 462, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 523, in doimport
    mod = director.getmod(nm)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 363, in getmod
    mod = owner.getmod(nm)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 441, in importHook
    pkgnm = packageName(importernm)
  File "/builddir/build/BUILDROOT/python-cheetah-3.2.3-1.fc32.x86_64/usr/lib64/python3.8/site-packages/Cheetah/ImportManager.py", line 108, in packageName
    for i in range(len(s) - 1, -1, -1):
RecursionError: maximum recursion depth exceeded while calling a Python object

This is using the 3.2.3 release of Cheetah from pypi.

A bunch of DeprecationWarnings when running in development mode

We try to use Python's development mode to get early warnings about stuff in our code. However we're also getting these DeprecationWarnings from Cheetah:

/opt/thinlinc/modules/Cheetah/Template.py:142: DeprecationWarning: invalid escape sequence \*
  '''
/opt/thinlinc/modules/Cheetah/Template.py:1617: DeprecationWarning: invalid escape sequence \*
  """Compile the template. This method is automatically called by
/opt/thinlinc/modules/Cheetah/Template.py:1728: DeprecationWarning: invalid escape sequence \*
  """Method for importing web transaction variables in bulk.
/opt/thinlinc/modules/Cheetah/Template.py:1984: DeprecationWarning: invalid escape sequence \d
  re.search('[ \t]*File.*line (\d+)', formatedExc).group(1))
/opt/thinlinc/modules/Cheetah/Template.py:2025: DeprecationWarning: invalid escape sequence \d
  cheetahPosMatch = re.search('line (\d+), col (\d+)', formatedExc)
/opt/thinlinc/modules/Cheetah/Template.py:2035: DeprecationWarning: invalid escape sequence \d
  cheetahPosMatch = re.search('line (\d+), col (\d+)',
/opt/thinlinc/modules/Cheetah/SettingsManager.py:19: DeprecationWarning: invalid escape sequence \(
  '[\(]*' + Number + r'[ \t]*\+[ \t]*' + Number + '[\)]*')
/opt/thinlinc/modules/Cheetah/SettingsManager.py:19: DeprecationWarning: invalid escape sequence \)
  '[\(]*' + Number + r'[ \t]*\+[ \t]*' + Number + '[\)]*')
/opt/thinlinc/modules/Cheetah/Parser.py:464: DeprecationWarning: invalid escape sequence \*
  + r'(?P<REFRESH_CACHE>\*' + interval + '\*)'
/opt/thinlinc/modules/Cheetah/Parser.py:557: DeprecationWarning: invalid escape sequence \$
  """Unescape any escaped Cheetah \$vars in the string.
/opt/thinlinc/modules/Cheetah/SourceReader.py:8: DeprecationWarning: invalid escape sequence \s
  ENCODINGsearch = re.compile("coding[=:]\s*([-\w.]+)").search

Not sure if they indicate a real issue, but it would be nice to get rid of them to make development mode easier to use.

Failing to catch an Exception

Hello,

The following except line is expected to be reached as the file expect_exception_catch doesn't exist. Instead, an indentation error is raised which was not happening at some point, but even then the ImportError was not catching either. I think this whole area has been broken since 2, so a legacy issue.

#try
    #from lib.expect_exception_catch import as_should_be_ImportError
#except ImportError
    #pass
#end try

As a test, the above code is at the top of the template file, and the error is...

except ImportError: # generated from line 3, col 1
^
IndentationError: expected an indented block 

Thanks for picking up Cheetah

p.s. please keep pypi release build binaries in sync with the git master branch for the best feedback loop

C++ code generation example

Is there any C++ code generation example?

Basically, I want to render a template that looks like this:

#pragma once

#include <cstdint>
#include <cstring>
#include <cassert>

class ${base_name}_view_t
{
public:
    static constexpr std::size_t expected_size_in_bytes = ${expected_size};

    ${base_name}_view_t( const void * ptr, std::size_t size_in_bytes )
    {
        assert( expected_size_in_bytes == size_in_bytes );
    }

    //#for $field in $fields
    ${field.type} ${field.name}() const noexcept
    {
        ${field.type} result;
        const char * location_ptr = static_cast<char*>(m_ptr) + ${field.offset};
        std::memcpy( &result, location_ptr, sizeof(${field.type}) );
        return result;
    }
    //#end for

private:
    const void * const m_ptr;
};

I try to compile it with:

cheetah compile ./templates/x_data_viewer.tmpl \
--settings="directiveStartToken='//#',directiveEndToken='//#',commentStartToken='//##'"

And can't succeed.

Unfortunately, I didn't find any tutorial for using Cheetah for code generation (C++ specifically). Any help would be great.

Question on decision to switch to CT3 on PyPI

I saw your announcement on python-announce for Cheetah 3.3.0 (congrats), but was confused by the following statement:

  • PyPI has wrongfully classified project Cheetah3 as "critical".
    This puts a burden to use 2FA to manage the project at PyPI. To
    avoid the burden the project is renamed to CT3 at PyPI.
    There will be no updates for Cheetah3.
    Sorry for the inconvenience!

What kind of burden is 2FA causing you? It looks like you are already using a secret username and password in your CI to upload to PyPI. Switching to a user-generated token to do the upload should remove any need to perform 2FA during an upload. Any light you can shed on the issues you ran into would be very appreciated.

I'm the maintainer of many packages that upload to PyPI with tokens like this so if you need any help setting it up let me know.

Memory Leak - Included Files

This issue is thoroughly discussed at:

https://groups.google.com/g/weewx-user/c/mZ_uDL7cX1k/m/3w_U9iu6BwAJ

Use: WeeWX weather system with Belchertown skin extension - both projects on GitHub. The Belchertown skin allows a user to include HTML via a set of "hook include files."

Issue: If the hook include files are recreated periodically (say every 5 minutes when index.html is re-created), memory usage by WeeWX increases over time until memory is exhausted. If the hook files are static, memory usage is stable.

Belchertown's template (for index.html) includes the hook include files using Cheetah's '#include' directive without a 'raw' argument. If the 'raw' argument is specified, memory usage is stable.

An additional workaround that does not require modifying the template file was identified: If the hook include file contains:

#include raw "name of re-created content file"

memory usage is stable.

This problem was replicated on Raspberry Pi OS and Ubuntu on a Raspberry Pi 4 with 8 GB, and verified by others. The conversation above includes a Python script to demonstrate the problem within WeeWX/Belchetown. I believe others have replicated the problem independent of WeeWX/Belchertown.

Regards,

Garry

AttributeError: module 'types' has no attribute 'ListType'

Getting this error when trying to create a template

.../Cheetah/Template.py", line 1053, in __unicode__
return getattr(self, mainMethName)()
File "DynamicallyCompiledCheetahTemplate.py", line 100, in respond
AttributeError: module 'types' has no attribute 'ListType

Dependency cgi module is being removed in Python 3.13

I noticed that Cheetah has support for CGI scripts through Python's cgi module. This module is scheduled for removal in 3.13, meaning that Cheetah's current CGI implementation won't work in 3.13 or later.

Python does not have a perfect replacement for the module, but recommends the following in PEP 594:

Replacements for the various parts of cgi which are not directly related to executing code are:

  • parse with urllib.parse.parse_qs (parse is just a wrapper)
  • parse_header with email.message.Message (see example below)
  • parse_multipart with email.message.Message (same MIME RFCs) FieldStorage/MiniFieldStorage has no direct replacement, but can typically be replaced by using multipart (for POST and PUT requests) or
  • urllib.parse.parse_qsl (for GET and HEAD requests)
  • valid_boundary (undocumented) with re.compile("^[ -]{0,200}[!-]$")

If CGI scripts in Cheetah are not a central functionality, another possible option could also be to remove CGI script support.

You don't have the C version of NameMapper installed!

When I run the cheetah version command, the version information of cheetah is successfully displayed, but when I run the cheetah test command, the error is as follows:
`D:\FACE\MTF\etc\scripts\Cheetah\Compiler.py:1509: UserWarning:
You don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with the compiled C version of NameMapper.
"\nYou don't have the C version of NameMapper installed! "
............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF

FAIL: testCompile (Cheetah.Tests.CheetahWrapper.OneFileNoExtension)

Traceback (most recent call last):
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 258, in testCompile
self.go("cheetah compile a")
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 222, in go
output = self.assertSubprocess(cmd)
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 205, in assertSubprocess
%s''' % (status, output))
AssertionError: Subprocess exited with a non-zero status (1)
Traceback (most recent call last):
File "D:\Python27\lib\site.py", line 539, in
main()
File "D:\Python27\lib\site.py", line 518, in main
known_paths = removeduppaths()
File "D:\Python27\lib\site.py", line 110, in removeduppaths
dir, dircase = makepath(dir)
File "D:\Python27\lib\site.py", line 82, in makepath
dir = os.path.abspath(dir)
File "D:\Python27\lib\ntpath.py", line 488, in abspath
path = _getfullpathname(path)
TypeError: encoded string too long (529, maximum length 519)

======================================================================
FAIL: testFill (Cheetah.Tests.CheetahWrapper.OneFileNoExtension)

Traceback (most recent call last):
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 262, in testFill
self.go("cheetah fill a")
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 222, in go
output = self.assertSubprocess(cmd)
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 205, in assertSubprocess
%s''' % (status, output))
AssertionError: Subprocess exited with a non-zero status (1)
Traceback (most recent call last):
File "D:\Python27\lib\site.py", line 539, in
main()
File "D:\Python27\lib\site.py", line 518, in main
known_paths = removeduppaths()
File "D:\Python27\lib\site.py", line 110, in removeduppaths
dir, dircase = makepath(dir)
File "D:\Python27\lib\site.py", line 82, in makepath
dir = os.path.abspath(dir)
File "D:\Python27\lib\ntpath.py", line 488, in abspath
path = _getfullpathname(path)
TypeError: encoded string too long (552, maximum length 519)

======================================================================
FAIL: testText (Cheetah.Tests.CheetahWrapper.OneFileNoExtension)

Traceback (most recent call last):
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 266, in testText
self.go("cheetah fill --oext txt a")
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 222, in go
output = self.assertSubprocess(cmd)
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 205, in assertSubprocess
%s''' % (status, output))
AssertionError: Subprocess exited with a non-zero status (1)
Traceback (most recent call last):
File "D:\Python27\lib\site.py", line 539, in
main()
File "D:\Python27\lib\site.py", line 518, in main
known_paths = removeduppaths()
File "D:\Python27\lib\site.py", line 110, in removeduppaths
dir, dircase = makepath(dir)
File "D:\Python27\lib\site.py", line 82, in makepath
dir = os.path.abspath(dir)
File "D:\Python27\lib\ntpath.py", line 488, in abspath
path = _getfullpathname(path)
TypeError: encoded string too long (575, maximum length 519)

======================================================================
FAIL: testCompile (Cheetah.Tests.CheetahWrapper.OneFileWithOdir)

Traceback (most recent call last):
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 345, in testCompile
self.go("cheetah compile --odir DEST a.tmpl")
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 222, in go
output = self.assertSubprocess(cmd)
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 205, in assertSubprocess
%s''' % (status, output))
AssertionError: Subprocess exited with a non-zero status (1)
Traceback (most recent call last):
File "D:\Python27\lib\site.py", line 539, in
main()
File "D:\Python27\lib\site.py", line 518, in main
known_paths = removeduppaths()
File "D:\Python27\lib\site.py", line 110, in removeduppaths
dir, dircase = makepath(dir)
File "D:\Python27\lib\site.py", line 82, in makepath
dir = os.path.abspath(dir)
File "D:\Python27\lib\ntpath.py", line 488, in abspath
path = _getfullpathname(path)
TypeError: encoded string too long (598, maximum length 519)

======================================================================
FAIL: testFill (Cheetah.Tests.CheetahWrapper.OneFileWithOdir)

Traceback (most recent call last):
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 350, in testFill
self.go("cheetah fill --odir DEST a.tmpl")
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 222, in go
output = self.assertSubprocess(cmd)
File "D:\FACE\MTF\etc\scripts\Cheetah\Tests\CheetahWrapper.py", line 205, in assertSubprocess
%s''' % (status, output))
AssertionError: Subprocess exited with a non-zero status (1)
Traceback (most recent call last):
File "D:\Python27\lib\site.py", line 539, in
main()
File "D:\Python27\lib\site.py", line 518, in main
known_paths = removeduppaths()
File "D:\Python27\lib\site.py", line 110, in removeduppaths
dir, dircase = makepath(dir)
File "D:\Python27\lib\site.py", line 82, in makepath
dir = os.path.abspath(dir)
File "D:\Python27\lib\ntpath.py", line 488, in abspath
path = _getfullpathname(path)
TypeError: encoded string too long (621, maximum length 519)
`
I want to know what should I do?

Missing OSX wheels

Last platform missing wheels is macOS. I think that now it should not be too complicated to add this to .travis.yml .

Missing manylinux1_x86_64 wheels

On https://pypi.org/project/Cheetah3/#files there are already manylinux wheels for i686, but the ones for x86_64 are missing.

In fact, when installing it on my Ubuntu 16.04 on x86_64 architecture, cheetah3 is built from the source .tar.gz:

$ virtualenv -p /usr/bin/python3.5 cheetah3
Running virtualenv with interpreter /usr/bin/python3.5
Using base prefix '/usr'
New python executable in /tmp/cheetah3/bin/python3.5
Also creating executable in /tmp/cheetah3/bin/python
Installing setuptools, pip, wheel...done.
$ . cheetah3/bin/activate
(cheetah3) $ pip install cheetah3
Collecting cheetah3
  Downloading https://files.pythonhosted.org/packages/54/86/ea50bb5baf1daa8ca1a56774d48150a69376679d27c4130848702efc378c/Cheetah3-3.1.0.tar.gz (872kB)
    100% |████████████████████████████████| 880kB 8.5MB/s 
Building wheels for collected packages: cheetah3
  Running setup.py bdist_wheel for cheetah3 ... done
  Stored in directory: /usr/users/ga002/soranzon/.cache/pip/wheels/f4/d4/c9/0f3e385c5c1966e7877cd46a8f722b47cdef71ab51e3c179f0
Successfully built cheetah3
Installing collected packages: cheetah3
Successfully installed cheetah3-3.1.0

can't install cheetah update

recently I worked on a project of a 2d game with arcade library in python, so when I tried to some dependencies whose cheetah included I used this commands :

$ pip install -r requirement.txt

I got this error :

Collecting Cheetah==2.4.4
  Using cached Cheetah-2.4.4.tar.gz (190 kB)
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-a6yheyby/cheetah/setup.py'"'"'; __file__='"'"'/tmp/pip-install-a6yheyby/cheetah/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-ldbnk8sq
         cwd: /tmp/pip-install-a6yheyby/cheetah/
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-a6yheyby/cheetah/setup.py", line 10, in <module>
        import SetupTools
      File "/tmp/pip-install-a6yheyby/cheetah/SetupTools.py", line 50
        except DistutilsPlatformError, x:
                                     ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

how to fix it please !?

child template not output when using #extends

Hello,

I have 2 templates, a parent template and a child template, in which the child template uses #extends to inherit from the base template as follows:

Parent template (device.tmpl)

{
#try
	#set $snapshot = $metadata.snapshot
	"snapshot": $snapshot,
#except
	#pass
#end try
#try
	#set $snapshot_count = $metadata.snapshot_count
	"snapshot_count": $snapshot_count,
#except
	#pass
#end try
#try
	#set $thing_ref = $thing
	"thing": $thing_ref,
#except
	#pass
#end try
##try
	#set $formatted_timestamp = time.strftime("%Y/%m/%d %H:%M:%S", time.gmtime($payload.timestamp))
	"timestamp": $formatted_timestamp,
##except
	##pass
##end try
#try
	#set $version = $payload.version
	"version": $version,
#except
	#pass
#end try
}

Child Template (thermostat.tmpl)

#extends device
{
#try
	#set $temperature = $payload.state.reported.telemetry.temperature
	"temperature": $temperature,
#except
	#pass
#end try
#try
	#set $humidity = $payload.state.reported.telemetry.humidity
	"humidity": $humidity,
#except
	#pass
#end try
#try
	#set $occupancy = $payload.state.reported.telemetry.occupancy
	"occupancy": $occupancy,
#except
	#pass
#end try
#try
	#set $lux = $payload.state.reported.telemetry.lux
	"lux": $lux
#except
	#pass
#end try
}

I am pre-compiling the parent template as instructed. When I run cheetah against the child template I only see the contents from the parent template.

I am using this script to execute the template:

import json
from Cheetah.Template import Template
with open('thermostat.tmpl', 'r') as myfile:
	print('-------------------TEMPLATE-------------------------')
	data=myfile.read()
	print(data)
	with open('Thermostat1-1537990300536.json', 'r') as myfile2:
		print('-------------------DATA -------------------------')
		data2=myfile2.read()
		data2=json.loads(data2)
		print(data2)
		t=Template(data, searchList=[data2])
		print('-------------------OUTPUT-------------------------')
		print(t)

Here is the sample input I am using:

{
	"payload": {
		"state": {
			"reported": {
				"telemetry": {
					"temperature": 81,
					"humidity": 59,
					"occupancy": 97
				},
				"version": "1.0.0",
				"enabled": true
			}
		},
		"metadata": {
			"reported": {
				"telemetry": {
					"temperature": {
						"timestamp": 1537990300
					},
					"humidity": {
						"timestamp": 1537990300
					},
					"occupancy": {
						"timestamp": 1537990300
					}
				},
				"version": {
					"timestamp": 1537990300
				},
				"enabled": {
					"timestamp": 1537990300
				}
			}
		},
		"version": 3838,
		"timestamp": 1537990300
	},
	"thing": "Thermostat1",
	"metadata": {
		"stream": "Thermostat1Stream"
	}
}

Here is the output I am seeing:

{
        "thing": Thermostat1,
        "timestamp": 2018/09/26 19:31:40,
        "version": 3838,
}

I would expect to see the combination of both the parent and child templates output, but that is not happening. The documentation is not clear on this topic so I cannot understand what I am doing wrong.

Thanks!

Failure running cheetah test on a new installation on a mac

I am attempting to install and test Cheetah3 on a mac with Python2.7 installed with Brew. The first time I tried this the cheetah test complained about missing Pygments and Markdown, so I installed them and then the test got farther, but still failed. I uninstalled Cheetah, then wrote and ran the following bash script:

sw_vers
python --version
pip --version
pip install Cheetah3
cheetah test

and below is the result. Any thoughts on why this failed?

$ source test.bash 
ProductName:	Mac OS X
ProductVersion:	10.14.2
BuildVersion:	18C54
Python 2.7.15
pip 18.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)
Collecting Cheetah3
Installing collected packages: Cheetah3
Successfully installed Cheetah3-3.1.0
...................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
----------------------------------------------------------------------
Ran 2163 tests in 11.945s

OK
.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE.E.......FF.................................................................................................
======================================================================
ERROR: test1 (Cheetah.Tests.NameMapper.VFF)
string in dict lookup
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 138, in test1
    self.check('aStr')
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 123, in check
    got = self.get(name)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 487, in get
    return valueFromFrame(name, autocall)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/NameMapper.py", line 297, in valueFromFrame
    frame = inspect.stack()[1][0]
AttributeError: 'NoneType' object has no attribute 'stack'

======================================================================
ERROR: test10 (Cheetah.Tests.NameMapper.VFF)
aFunc in dict lookup in a loop
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 179, in test10
    self.check('aFunc')
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 123, in check
    got = self.get(name)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 487, in get
    return valueFromFrame(name, autocall)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/NameMapper.py", line 297, in valueFromFrame
    frame = inspect.stack()[1][0]
AttributeError: 'NoneType' object has no attribute 'stack'

======================================================================
ERROR: test11 (Cheetah.Tests.NameMapper.VFF)
aMeth in dict lookup
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 183, in test11
    self.check('aMeth')
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 123, in check
    got = self.get(name)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 487, in get
    return valueFromFrame(name, autocall)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/NameMapper.py", line 297, in valueFromFrame
    frame = inspect.stack()[1][0]
AttributeError: 'NoneType' object has no attribute 'stack'

this goes on for hundreds of lines ending with:

======================================================================
ERROR: test9 (Cheetah.Tests.NameMapper.VFS_4namespaces)
aFunc in dict lookup
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 174, in test9
    self.check('aFunc')
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 123, in check
    got = self.get(name)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 466, in get
    return self.VFS(self.searchList(), name, autocall)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper.py", line 117, in VFS
    return valueFromSearchList(searchList, name, autocall)
  File "/usr/local/lib/python2.7/site-packages/Cheetah/NameMapper.py", line 286, in valueFromSearchList
    if hasKey(namespace, key):
TypeError: 'NoneType' object is not callable

======================================================================
ERROR: tearDownModule (Cheetah.Tests.NameMapper_pure)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/NameMapper_pure.py", line 32, in tearDownModule
    del sys.modules['Cheetah.Tests.NameMapper']
KeyError: 'Cheetah.Tests.NameMapper'

======================================================================
FAIL: test_compilationCache (Cheetah.Tests.Template.ClassMethods_compile)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/Template.py", line 147, in test_compilationCache
    assert not klass._CHEETAH_isInCompilationCache
AssertionError

======================================================================
FAIL: test_keepRefToGeneratedCodeArg (Cheetah.Tests.Template.ClassMethods_compile)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/Cheetah/Tests/Template.py", line 124, in test_keepRefToGeneratedCodeArg
    assert not t.generatedModuleCode()
AssertionError

----------------------------------------------------------------------
Ran 2163 tests in 8.066s

FAILED (failures=2, errors=592)

NameError: name 'basestring' is not defined when use Cheetah.Template

version:3.3.1
I'm using Cheetah.Template to generate a string type of data, the test code is :

if __name__ == "__main__":
    templ_output = Template(template_str, searchList=[{'data': excel_data}])
    print("output:", templ_output)

The template_str is correct when use it in a Python2 project.
The excel_data is a dict.
And then I have a error :

Traceback (most recent call last):
  File "/Users/playcrab/loggers/tester.py", line 414, in <module>
    print("output:", templ_output)
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Cheetah/Template.py", line 1053, in __unicode__
    return getattr(self, mainMethName)()
  File "DynamicallyCompiledCheetahTemplate.py", line 276, in respond
NameError: name 'basestring' is not defined
output: 
Process finished with exit code 1

I just have no idea to fix it.
(I have updated the template and excel_data as attached)
excel_data.txt
template_file.txt

Standard Input / output does not work on LinuxMint 21.1 (Ubuntu 22.04)

Test case via command line:
echo "print('Hello World')" | cheetah-compile3 -

Error:

Traceback (most recent call last):
  File "/usr/bin/cheetah-compile3", line 3, in <module>
    _cheetah_compile()
  File "/usr/lib/python3/dist-packages/Cheetah/CheetahWrapper.py", line 662, in _cheetah_compile
    CheetahWrapper().main()
  File "/usr/lib/python3/dist-packages/Cheetah/CheetahWrapper.py", line 147, in main
    meth()
  File "/usr/lib/python3/dist-packages/Cheetah/CheetahWrapper.py", line 258, in compile
    self._compileOrFill()
  File "/usr/lib/python3/dist-packages/Cheetah/CheetahWrapper.py", line 344, in _compileOrFill
    self._compileOrFillStdin()
  File "/usr/lib/python3/dist-packages/Cheetah/CheetahWrapper.py", line 590, in _compileOrFillStdin
    sys.stdout.write(output)
TypeError: write() argument must be str, not bytes

Cause:

  • Trying to print unicode string (binary) with sys.sdtout.write()
  • This this is binary, sys.stdout.buffer.write() is needed

Solution:

  • Change source as follows:
  • File: /usr/lib/python3/dist-packages/Cheetah/CheetahWrapper.py
  • Line 582 to 590
        if self.isCompile:
            pysrc = TemplateClass.compile(file=sys.stdin, compilerSettings=compilerSettings, returnAClass=False)
            sys.stdout.buffer.write(pysrc)
        else:
            output = str(TemplateClass(file=sys.stdin, compilerSettings=compilerSettings)) 
            sys.stdout.write(output)

Namemapper Issues with python3.7

Hi,
I'm trying to use Cheetah with Python3.7
I installed Cheetah using the command 'pip3 install Cheetah3'
I could see the '_namemapper.cpython-37m-x86_64-linux-gnu.so' file in /usr/local/lib/python3.7/dist-packages/Cheetah
I got the below error. Any ideas on how to get over this?

/usr/local/lib/python3.7/dist-packages/Cheetah/Compiler.py:1630: UserWarning:
You don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with compiled C version of NameMapper.
"\nYou don't have the C version of NameMapper installed! "
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/Cheetah/NameMapper.py", line 231, in _valueForName
nextObj = getattr(obj, key)
AttributeError: 'dict' object has no attribute 'iteritems'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/scripts/py_script/generate_validation_report.py", line 174, in
ReportGenerator().generate(in_file, out_fn)
File "/scripts/py_script/generate_validation_report.py", line 153, in generate
html = str(t)
File "/usr/local/lib/python3.7/dist-packages/Cheetah/Template.py", line 1053, in unicode
return getattr(self, mainMethName)()
File "_scripts_py_script_view_template_report_html.py", line 170, in respond
File "/usr/local/lib/python3.7/dist-packages/Cheetah/NameMapper.py", line 285, in valueForName
_wrapNotFoundException(e, fullName=name, namespace=obj)
File "/usr/local/lib/python3.7/dist-packages/Cheetah/NameMapper.py", line 283, in valueForName
return _valueForName(obj, name, executeCallables)
File "/usr/local/lib/python3.7/dist-packages/Cheetah/NameMapper.py", line 233, in _valueForName
_raiseNotFoundException(key, obj)
File "/usr/local/lib/python3.7/dist-packages/Cheetah/NameMapper.py", line 178, in _raiseNotFoundException
raise NotFound(excString)
Cheetah.NameMapper.NotFound: cannot find 'iteritems' while searching for 'iteritems'

An ideomatic way to add generation process meta

What is considered a standard way to add meta info to generated text. For example, I would like to add date, hash of template and hash of parameters. I can do it by adding necessary fields to parameters, but m.b. there is a better way?

License BSD or MIT ?

The description of the project says it's a BSD style license, but the license file is actually an old style MIT license. This should be sorted out to allow distributions to include cheetah3 in their repository (most of the are still shipping cheetah version 2 although it is not supported anymore)

PS: It would be nice to use a SPDX license identifier.

Endless recursion in ImportManager (Python 3)

Hi, I'm running Cheetah on Ubuntu. The following problems arises with the the official Ubuntu packages and with the latest version from here, but only with Python 3.

I have the following example template (test.tmpl):

Test

and the following program (driver.py):

from __future__ import print_function
from Cheetah.Template import Template
from Cheetah import ImportHooks
ImportHooks.install()

t = Template(file='test.tmpl')
print(t)

Running it with Python 2 works (almost) fine, except for the warning mentioned in #7:

$> /usr/bin/python2 driver.py
[...]/cheetah3/Cheetah/Compiler.py:1630: UserWarning: 
You don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with compiled C version of NameMapper.
  "\nYou don't have the C version of NameMapper installed! "
Test

But running with Python 3 gives the following error (I removed the repeating parts and the full path of the cheetah library.):

$> /usr/bin/python3 driver.py
[...]/cheetah3/Cheetah/Compiler.py:1630: UserWarning: 
You don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with compiled C version of NameMapper.
  "\nYou don't have the C version of NameMapper installed! "
Traceback (most recent call last):
  File "driver.py", line 6, in <module>
    t = Template(file='test.tmpl')
  File "[...]/cheetah3/Cheetah/Template.py", line 1337, in __init__
    self._compile(source, file, compilerSettings=compilerSettings)
  File "[...]/cheetah3/Cheetah/Template.py", line 1638, in _compile
    keepRefToGeneratedCode=True)
  File "[...]/cheetah3/Cheetah/Template.py", line 772, in compile
    settings=(compilerSettings or {}))
  File "[...]/cheetah3/Cheetah/Compiler.py", line 1659, in __init__
    f = open(file, 'r')
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 459, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 520, in doimport
    mod = director.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 360, in getmod
    mod = owner.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
[...]
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 459, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 520, in doimport
    mod = director.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 360, in getmod
    mod = owner.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 438, in importHook
    pkgnm = packageName(importernm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 104, in packageName
    for i in range(len(s) - 1, -1, -1):
RecursionError: maximum recursion depth exceeded while calling a Python object
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 53, in apport_excepthook
    if not enabled():
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 26, in enabled
    with open(CONFIG) as f:
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 459, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 520, in doimport
    mod = director.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 360, in getmod
    mod = owner.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
[...]
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 459, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 520, in doimport
    mod = director.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 360, in getmod
    mod = owner.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 438, in importHook
    pkgnm = packageName(importernm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 104, in packageName
    for i in range(len(s) - 1, -1, -1):
RecursionError: maximum recursion depth exceeded while calling a Python object

Original exception was:
Traceback (most recent call last):
  File "driver.py", line 6, in <module>
    t = Template(file='test.tmpl')
  File "[...]/cheetah3/Cheetah/Template.py", line 1337, in __init__
    self._compile(source, file, compilerSettings=compilerSettings)
  File "[...]/cheetah3/Cheetah/Template.py", line 1638, in _compile
    keepRefToGeneratedCode=True)
  File "[...]/cheetah3/Cheetah/Template.py", line 772, in compile
    settings=(compilerSettings or {}))
  File "[...]/cheetah3/Cheetah/Compiler.py", line 1659, in __init__
    f = open(file, 'r')
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 459, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 520, in doimport
    mod = director.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 360, in getmod
    mod = owner.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
[...]
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 459, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 520, in doimport
    mod = director.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 360, in getmod
    mod = owner.getmod(nm)
  File "[...]/cheetah3/Cheetah/ImportHooks.py", line 57, in getmod
    mod = DirOwner.getmod(self, name)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 213, in getmod
    with open(py[0], 'r') as py_code_file:
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 438, in importHook
    pkgnm = packageName(importernm)
  File "[...]/cheetah3/Cheetah/ImportManager.py", line 104, in packageName
    for i in range(len(s) - 1, -1, -1):
RecursionError: maximum recursion depth exceeded while calling a Python object

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.