reviewing the tags permission system
[plcapi.git] / PLC / Accessor.py
1 #
2 # Thierry Parmentelat - INRIA
3 #
4 #
5 # just a placeholder for storing accessor-related tag checkers
6 # this is filled by the accessors factory
7 #
8 # NOTE. If you ever come to manually delete a TagType that was created
9 # by the Factory, you need to restart your python instance / web server
10 # as the cached information then becomes wrong
11
12 from PLC.TagTypes import TagTypes, TagType
13
14 # implementation
15 class Accessor (object) :
16     """This is placeholder for storing accessor-related tag checkers.
17 Methods in this class are defined by the accessors factory
18
19 This is implemented as a singleton, so we can cache results over time"""
20
21     _instance = None
22
23     def __init__ (self, api):
24         self.api=api
25         # 'tagname'=>'tag_id'
26         self.cache={}
27
28     def has_cache (self,tagname): return self.cache.has_key(tagname)
29     def get_cache (self,tagname): return self.cache[tagname]
30     def set_cache (self,tagname,tag_id): self.cache[tagname]=tag_id
31
32     def locate_or_create_tag (self,tagname,category, description, min_role_id):
33         "search tag type from tagname & create if needed"
34
35         # cached ?
36         if self.has_cache (tagname):
37             return self.get_cache(tagname)
38         # search
39         tag_types = TagTypes (self.api, {'tagname':tagname})
40         if tag_types:
41             tag_type = tag_types[0]
42         else:
43             # not found: create it
44             tag_type_fields = {'tagname':tagname,
45                                'category' :  category,
46                                'description' : description,
47                                'min_role_id': min_role_id}
48             tag_type = TagType (self.api, tag_type_fields)
49             tag_type.sync()
50         tag_type_id = tag_type['tag_type_id']
51         self.set_cache(tagname,tag_type_id)
52         return tag_type_id
53
54
55 ####################
56 # make it a singleton so we can cache stuff in there over time
57 def AccessorSingleton (api):
58     if not Accessor._instance:
59         Accessor._instance = Accessor(api)
60     return Accessor._instance