Acess content in the static directory from Python codeΒΆ

Author:Sebastian Ware (jhsware)
Version:Grok <= 1.2.x

An interesting addition to this tutorial is how to access these static resources through python code, for instance inside a grok View.

I’ll quickly describe it here and you guys can massage it into mini-tutorial style whichever way you want. CAVEAT, almost nothing below was tested, I mostly read the “zope.app.publisher.browser.directoryresource” and ”...fileresource” code.

say you have:

class MyView(grok.View):

  def someMethod(self):
       [...]

inside the method above, you can access the static resources through “self.static” which is a DirectoryResource, a dictionary-like object representing the “static” folder.

suppose you have an “image.png” file inside an “images” folder inside the “static” directory, you can access it like:

image_resource = self.static['images']['image.png']

or even:

image_resource = self.static['images/image.png']

The forward slash is important as this actually represents a url traversal, not a file-system traversal.

If you’re not sure the image is really there, you can do:

image_resource = self.static.get('images/image.png', None)

if you got None back the image is not there.

Now that you have the image resource, what do you do with it? The main motivation for accessing the static resources is returning their URLs on the server to the browser, so you can do this by just calling the resource:

return image_resource() # returns the URL for the static resource.

If you really need to manipulate the resource in the filesystem, you can do it like this:

fspath = image_resource.context.path
file = open(fspath, "rb")

The same goes for snooping the static resource directory and subdiretories under it:

image_dir = self.static['images'].context.path
os.listdir(image_dir)

Cheers, Leo