- Change .py files to use 4-space indents and no hard tab characters.
[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 from PLC.TagTypes import TagTypes, TagType
11
12 # implementation
13 class Accessor (object) :
14     """This is placeholder for storing accessor-related tag checkers
15 methods in this class are defined by the accessors factory
16
17 This is implemented as a singleton, so we can cache results over time"""
18
19     _instance = None
20
21     def __init__ (self, api):
22         self.api=api
23         # 'tagname'=>'tag_id'
24         self.cache={}
25
26     def has_cache (self,tagname): return self.cache.has_key(tagname)
27     def get_cache (self,tagname): return self.cache[tagname]
28     def set_cache (self,tagname,tag_id): self.cache[tagname]=tag_id
29
30     def locate_or_create_tag (self,tagname,category, description, min_role_id):
31         "search tag type from tagname & create if needed"
32
33         # cached ?
34         if self.has_cache (tagname):
35             return self.get_cache(tagname)
36         # search
37         tag_types = TagTypes (self.api, {'tagname':tagname})
38         if tag_types:
39             tag_type = tag_types[0]
40         else:
41             # not found: create it
42             tag_type_fields = {'tagname':tagname,
43                                'category' :  category,
44                                'description' : description,
45                                'min_role_id': min_role_id}
46             tag_type = TagType (self.api, tag_type_fields)
47             tag_type.sync()
48         tag_type_id = tag_type['tag_type_id']
49         self.set_cache(tagname,tag_type_id)
50         return tag_type_id
51
52
53 ####################
54 # make it a singleton so we can cache stuff in there over time
55 def AccessorSingleton (api):
56     if not Accessor._instance:
57         Accessor._instance = Accessor(api)
58     return Accessor._instance