Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8979073
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T19:45:44+00:00 2026-06-15T19:45:44+00:00

I’am using Python 2.5 on App Engine and tried to get the Jinja2 ModuleLoader

  • 0

I’am using Python 2.5 on App Engine and tried to get the Jinja2 ModuleLoader to work.

To initialize the environment I use :

@staticmethod                                                   # get Jinja environment (global)
def get_new():                                                   # and initialize Jinja environment
    if  myEnv._my_env == None :
        path = os.path.join(os.path.dirname(__file__), 'compiled')
        myEnv._my_env = Environment(loader = ModuleLoader(path))     

    return myEnv._my_env

‘compiled’ is a directory in my GAE project.
But I receive TemplateNotFound exceptions all the time??

I compiled the templates using :

    env = Environment(extensions=['jinja2.ext.i18n'])

    env.filters['euros'] = Euros

    db_runtimes = Runtimes.all()                                                       # the html templates saved in a db.Blob
    for each in db_runtimes.fetch(999) :
        key = each.key().name()
        source =  db.Blob(each.content).decode('utf-8')
        name = key.split('.')[0]
        raw = env.compile(source, name=name, filename=name + '.py', raw=True)
        each.compiled = db.Blob(raw.encode('utf-8'))                           # compile and save the .py
        each.put()

The resulting code looks fine. Any ideas?
I hope you can help me. This article from Rodrigo Moraes shows that loading templates from python modules is very fast. But in this 2009 proof of concept he “hacked” the Jinja code to be able to run the code. I think the ModuleLoader should do the same job.
https://groups.google.com/group/pocoo-libs/browse_thread/thread/748b0d2024f88f64


The testmod.py looks like this :

from __future__ import division
from jinja2.runtime import LoopContext, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join, to_string, identity, TemplateNotFound
name = u'testmod.py'

def root(context, environment=environment):
    if 0: yield None
    yield u'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0      Transitional//EN"\n"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n<meta http-equiv="Content-Type" content="text/html;   charset=utf-8" />\n<title>TEST</title>\n</head>\n<body>\n\t<p>test template</p>\n</body>\n</html>'

blocks = {}
debug_info = ''

And the page handler :

def get(self):

    my_env = myEnv.get() 
    page = 'testmod.py' 
    template = my_env.get_template(page)  
    self.response.out.write(template.render({}))

I’have also tried to get the template without the .py extension.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T19:45:45+00:00Added an answer on June 15, 2026 at 7:45 pm

    Update: See this Gist with the code I use for a CMS:

    https://gist.github.com/voscausa/9154936

    Update : Now I am using Python 27 and was able to create a module loader, which can load jinja compiled templates (python code) from a package or from the database (package = None).

    To initialize the loader, you can use:

    from jinja2 import Environment
    Environment(auto_reload=False, loader = moduleloader.FileSystemModuleLoader(package))
    
    class ModuleLoader(object):
        """Base mixin class for loaders that use pre-parsed Jinja2 templates stored
        as Python code.
        """
        def get_module(self, environment, template):
            raise TemplateNotFound(template)
    
        def load(self, environment, filename, j_globals=None):
            """Loads a pre-compiled template, stored as Python code in a template
            module.
            """
            if j_globals is None: j_globals = {'environment' : environment}
    
            t = object.__new__(environment.template_class)
    
            module = self.get_module(environment, filename)
            name, blocks, root, debug_info = module.run(environment, t)   # module run function      
    
            t.environment = environment
            t.globals = j_globals
            t.name = name
            t.filename = filename
            t.blocks = blocks
            # render function and module
            t.root_render_func = root
            t._module = None
    
            # debug and loader helpers
            t._debug_info = debug_info
            t._uptodate = lambda: True
            return t
    
    class FileSystemModuleLoader(ModuleLoader):
    
        def __init__(self, package = None):   # load module from package or datastore
            self.package = package            # package = "compiled" or package = None
    
        def get_module(self, environment, template):
            # Convert the path to a module name
            name = template.replace('.html', '').replace('.txt','').replace('/', '.')   # NO extensions   
            module = None
    
            if self.package == None :
                if name in sys.modules : return sys.modules[name]
                logging.info('load module : ' + name)      # load module from runtimes db
                try :
                    runtime = models.Runtimes.get_by_key_name(template)
                    module_code = db.Text(runtime.compiled)                                 
                    module = imp.new_module(name)
                    exec module_code in module.__dict__                                         
                    sys.modules[name] = module             # add to sys modules, so no import
                    return module
                except (ImportError, AttributeError):
                    logging.error('load failed : ' + name)
    
            else :                                         # load module from package
                logging.info('load module : ' + name + ' from package : ' + self.package)
                try: 
                    mod_import = __import__(self.package, globals(), None, [str(name)])
                    module = getattr(mod_import, name)
                    return module
                except (ImportError, AttributeError):
                    logging.error('load failed : ' + name)
    
            raise TemplateNotFound(template)   
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We're building an app, our first using Rails 3, and we're having to build
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I am using Paperclip to handle profile photo uploads in my app. They upload
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.