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