Search code examples
pythoncherrypyjinja2

CherryPy + Jinja, where to initialize Environment


I'm writing an application in python using CherryPy and Jinja as the template system. May be needed to say that i'm a beginner with these tools. The problem I'm facing now is I cannot figure where to initialize Jinja's Environment class.

Currently I have

  • application.py (entry point, sets up Environment and starts server)
  • root.py (root page class for cherrypy, must be imported from 'application.py', and must import 'application.py' to retrieve instantiated Enviroment)
  • pages.py (other page classes for cherry.py, must import 'application.py', and must be imported from root to build the tree)

Trying to run that ends up in what seems to be a circular reference and fails (application > root > pages > application).

Should I stick to only one Environment instance or is it okay to have an instance at root.py and another in pages.py?

Which is the correct pattern for this?


Solution

  • You shouldn't really repeat yourself. If I were you I would create a new python module templates.py and put all the jinja environment configuration / creation there. Afterwards you can simply import that environment wherever you need it (e.g. from templates import jinjaenv). In this case you keep things simple and extensible for future use.