[Grok-dev] Re: Relative filesystem path?
Philipp von Weitershausen
philipp at weitershausen.de
Sun Sep 16 14:29:31 EDT 2007
Jim Washington wrote:
> I'm working on something like zif.xtemplate in grok.
> lxml 2.0 alpha has made huge strides in HTML usefulness, making most of
> the zif.xtemplate code redundant, so I am refactoring it for grok.
> One thing I need is a location for pure-html templates. The idea is
> that the structure of a page (or many pages) may be done as a framework
> in an HTML template, and locations for dynamic stuff would be
> identified by id attributes. After the page is parsed, the locations
> are obtained by lxml.html.get_element_by_id('id') and other lxml.etree
> and lxml.html functions can be used to fill out the page. Ultimately
> we use lxml's fast serialization to create the page. It's
> zope-page-template-less, but existing pagetemplate code can of course be
> inserted as the results of viewPageTemplate().
> What I have currently in the library package to find the current source
> directory relative to the instance is
> loc = os.path.abspath(os.curdir)
By the way, I'd spell that
loc = os.getcwd()
> z = os.path.split(loc)
> localpackage = z[-1].lower()
> localpath = os.path.join(loc,'src',localpackage)
> should refer to a sibling folder of app_templates in the same directory
> as app.py.
> It works now on Sample/src/sample as in the tutorial, but changing
> directory names so that "sample" is not the lowercase of "Sample", for
> example, would break things in the current implementation. I realize
> that Grok is about convention over configuration, but is the current
> directory structure convention something I can rely on?
No. First of call, you can't rely on whatever the current working
directory (CWD) is. Second, you can't rely on where the package you're
dealing with is installed. grokproject suggests a pretty common
directory structure, but in the end who knows where people are
> Is there a good alternative? Does grok have a hook I can use for this
> that would not be so susceptible to breakage? I've looked, but it seems
> that the path I need is consumed and made unimportant by martian.
I hope I'm understanding you right. I assume you want to be able to
refer to files in a package. So your relative filenames are relative to
package (much like app_templates, for example, is relative to the
package that app.py is in).
The canonical way to do that is to use __file__. For example, let's say
I'm in foo.py and wanted to read xyz.txt which is next to foo.py:
foo_directory = os.path.dirname(__file__)
xyz_txt = os.path.join(foo_directory, 'xyz.txt')
http://worldcookery.com -- Professional Zope documentation and training
More information about the Grok-dev