views:

33

answers:

1

Using webpy, what's the proper way to reference the templates directory for web.template.render() so that it works on both the webpy development web server and on Apache?

The following code works using the development server but not when running on my Apache server.

import web

urls = (
  '/', 'index',
  )

class index:
  def GET(self):
    render = web.template.render('templates/')
    return render.index(self)

I know the problem is that web.template.render('templates/') is the problem, because the relative path is no longer valid when Apache runs from C:\Program Files\Apache Software Foundation\Apache2.2. My templates directory is within my project folder.

What I don't want to do is use an absolute path, because I'd like to be able to move my project files around without having to tinker with the code to keep it working.

+1  A: 

If you're using mod_wsgi, the easiest solution is to set the home= option appropriately,

Alternatively, you can get the module's path and combine that with the template, i.e.

os.path.join(os.path.dirname(__file__), 'templates/')

Put it in a function if you need it often. Be aware that if you put it in a separate module, this module needs to be in the same folder as the templates directory or you'll end up with the wrong directory again.

In case you want to put it in a system wide package, you can find out the callers directory easily:

def abspath(path): 
    frame = sys._getframe(1)
    base = os.path.dirname(frame.f_globals['__file__'])
    return os.path.join(base, path)
Ivo van der Wijk
Thanks. Exactly the kind of info I needed to know. I especially appreciate your going through several options.
Mike M. Lin