9226c70867ff0010b7d83293ef0a2486f348ec94
[invirt/packages/python-routefs.git] / routefs / dictfs.py
1 """
2 DictFS allows you to easily create read-only filesystems when the
3 file tree is known in advance.
4
5 To create your own DictFS descendent, simply override the files
6 property, which can be created either using the property
7 decorator, or just a simple assignment.
8
9 A dictionary represents a directory, with keys corresponding to
10 file names and the values corresponding to the file contents.
11 """
12
13
14 import os
15
16 from routes import Mapper
17
18 import routefs
19
20
21 class DictFS(routefs.RouteFS):
22     controllers = ['handler']
23
24     @property
25     def files(self):
26         """
27         This property should be overridden in your DictFS descendant
28         """
29         return dict()
30
31     def make_map(self):
32         m = Mapper()
33
34         m.connect('/{path:.*}', controller='handler')
35
36         return m
37
38     def handler(self, path, **kwargs):
39         if path != '':
40             elements = path.split(os.path.sep)
41         else:
42             elements = []
43
44         try:
45             tree = self.files
46             for elt in elements:
47                 tree = tree[elt]
48         except KeyError:
49             return
50
51         if type(tree) is dict:
52             return tree.keys()
53         else:
54             return tree