d4af37d4a5a86f66b2a05ec22d052511e23c599d
[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 from PLC.Roles import Roles, Role
14
15 # implementation
16 class Accessor (object) :
17     """This is placeholder for storing accessor-related tag checkers.
18 Methods in this class are defined by the accessors factory
19
20 This is implemented as a singleton, so we can cache results over time"""
21
22     _instance = None
23
24     def __init__ (self, api):
25         self.api=api
26         # 'tagname'=>'tag_id'
27         self.cache={}
28
29     def has_cache (self,tagname): return self.cache.has_key(tagname)
30     def get_cache (self,tagname): return self.cache[tagname]
31     def set_cache (self,tagname,tag_type): self.cache[tagname]=tag_type
32
33     def locate_or_create_tag (self, tagname, category, description, roles):
34         "search tag type from tagname & create if needed"
35
36         # cached ?
37         if self.has_cache (tagname):
38             return self.get_cache(tagname)
39         # search
40         tag_types = TagTypes (self.api, {'tagname':tagname})
41         if tag_types:
42             tag_type = tag_types[0]
43         else:
44             # not found: create it
45             tag_type_fields = {'tagname':tagname,
46                                'category' :  category,
47                                'description' : description}
48             tag_type = TagType (self.api, tag_type_fields)
49             tag_type.sync()
50             for role in roles:
51                 try: 
52                     role_obj=Roles (self.api, role)[0]
53                     tag_type.add_role(role_obj)
54                 except:
55                     # xxx todo find a more appropriate way of notifying this
56                     print "Accessor.locate_or_create_tag: Could not add role %r to tag_type %s"%(role,tagname)
57         self.set_cache(tagname,tag_type)
58         return tag_type
59
60
61 ####################
62 # make it a singleton so we can cache stuff in there over time
63 def AccessorSingleton (api):
64     if not Accessor._instance:
65         Accessor._instance = Accessor(api)
66     return Accessor._instance