File: Rack.py

package info (click to toggle)
zope-zpatterns 0.4.3p2-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 476 kB
  • ctags: 814
  • sloc: python: 2,817; ansic: 310; makefile: 52; sh: 39
file content (493 lines) | stat: -rw-r--r-- 11,666 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
from DataManagers import DataManager
from SheetProviders import SheetProvider
from AttributeProviders import AttributeProvider
from Providers import LinkToParentProviders
from Globals import DTMLFile, default__class_init__, PersistentMapping
from ComputedAttribute import ComputedAttribute
from Transactions import Kept
from DataSkins import DataSkin
from Products.PlugIns import MakePICBase
import Products

_marker=[]

SelfKey = 'ZPatterns.Rack','Self'



























class Rack(DataManager, Kept):

    """
    Basic Rack - supports sheet and attribute provider plugins, as
    well as persistent storage of any ZClass object and arbitrary
    associated data (using "slots").
    """

    # Template (i.e. abstract) methods, should be left as-is

    def getItem(self, key):
        """Get an item from the rack by key"""
        
        # Borrow canonicals map for per-transaction item cache
        item = self._fromCache(key,_marker)
        
        if item is _marker:
            item = self.retrieveItem(key)
            self._toCache(key,item) # XXX Should we cache non-existence?
            
        return item


    def newItem(self, key=None):
        """Create a new item - attempts to generate key if not supplied"""

        if key is None:
            key=getattr(self,'newKey',None)
            key=key and key()
            if key is None: return None

        return self.createItem(key)
        

    def _objectDeleting(self,client):
        DataManager._objectDeleting(self,client)
        self._delSlotFor(client)




    # Methods to be overridden in subclasses for non-ZODB storage

    loadAttrib = ''  # If not empty, attribute to use when loading an item


    def retrieveItem(self,key):

        # Retrieve an object, identified by key

        a = self.loadAttrib
        item = None

        if a:
            item = self._RawItem(key)
            if hasattr(item.aq_base, a):
                return item

        else:
            # The block below is what you want to replace
            # if you're creating a non-ZODB storage.
            # In practice, from version 0.4.0 on, there's
            # no reason to do such a thing in the first place.
            
            slot = self._readableSlot(key)

            if slot:
                item = slot[SelfKey]

                # XXX class remapping should go here??

                self = self.aq_inner
                item._setRack(self)
                item._setSlot(slot)
                return item.__of__(self.aq_parent)







    def createItem(self,key):

        # Create a new object, identified by key

        item = self.getItem(key)

        # XXX What if all items potentially exist?
        
        if item is not None:
            raise KeyError,("'%s' already exists" % key)

        item = self._RawItem(key)

        a = self.loadAttrib
        if not a:
            slot = self._writeableSlot(key)
            slot[SelfKey] = item.aq_base    # strip acquisition wrapping
            item._setSlot(slot)             # Not needed for non-ZODB storage

        item._objectCreating()
        item._objectAdding()

        self._toCache(key,item) # XXX Should we cache non-creation?
        
        return item
















    # Optionally overrideable methods for additional functionality

    #def newKey(self):
    #    """Generate a new object key"""
    #    pass    # must be defined if key autogeneration is desired
    #
    # def countItems(self): pass
    # def deleteAll(self): pass

    _initialized = 0
    
    def _setup(self):
        # set up default providers
        
        if self._initialized:
            # We must only initialize once, since _setup gets called on pastes,
            # imports, etc.
            return
            
        self._installPlugIn(
            LinkToParentProviders('SpecialistPlugIns', 
                title='Plug-ins from parent Specialist')
        )
        
        self._installPlugIn(
            SheetProvider('PersistentSheets', title='Sheets stored in Rack slots')
        )
        
        self._installPlugIn(
            AttributeProvider('PersistentAttributes',
                title='Attributes stored persistently in objects')
        )
        
        self._initialized = 1
        






    # ZClass Machinery (Optionally overrideable)

    _defaultClass = None

    def _v_itemConstructor(self):
        c = getattr(self, '_zclass', None) or self._defaultClass

        if c:
            if type(c) is type(''):
                c = self._unifiedZClassRegistry()[c][1]   #Products.meta_classes[c]
        else:
            def err(key):
                raise TypeError, "No ZClass set - please use 'Storage' tab"
            return err

        c = getattr(c,'_zclass_',c)
        self._v_itemConstructor = c
        return c

    _v_itemConstructor = ComputedAttribute(lambda s,v=ComputedAttribute(_v_itemConstructor): v)  

    def _RawItem(self, key):
        """
        Create an empty object of the right class
        """
        self = self.aq_inner
        item = self._v_itemConstructor()
        
        item._setRack(self)                 # Connect to rack
        item._setId(key)
        
        item = item.__of__(self.aq_parent.aq_inner)  # Link to Specialist
        return item


    def _isSelected(self, name, path, klass):
        Z = self._v_itemConstructor
        Z = getattr(Z, 'aq_self', Z)
        return klass._zclass_ is Z


    # Caching

    def _v_cache(self):
        self._v_Keeper
        l = self._v_cache = {}
        return l

    _v_cache = ComputedAttribute(_v_cache)

    __per_transaction_cache_attrs__ = ('_v_cache',)

    def _fromCache(self, key, default=None):
        return self._v_cache.get(key,default)

    def _toCache(self, key, item):
        self._v_cache[key] = item
    
























    # Persistence Machinery - little need to override, but to be extended
    # for future multi-ZODB support

    storageInfo = ''    # Reserved for configuring future multi-ZODB support
    __storage = None    # This rack's storage object for sheets and/or objects

    def storageInUse(self):
        """How many racked items have persistent storage use?"""
        return len(self.__readableStorage)

    def __writeableStorage(self):
        """Create new a mapping-like object for storing 'persistent' stuff and save it in self"""
        from BTrees.OOBTree import OOBTree
        s = self.__readableStorage = self.__writeableStorage = OOBTree()
        return s
        
    __readableStorage = {}
    __writeableStorage = ComputedAttribute(__writeableStorage)
        

    def _migrateStorage(self,storage):
        """Move existing data to new kind of storage"""

        #if self.storageInUse():
        #    raise ValueError, "Cannot change storage with contents present"

        raise "NotImplemented", "Only self-storage is currently supported"

        # XXX self.storageInfo = storage; del self.__storage

    def manage_storageOptions(self):
        """Return a list of key-value pair tuples listing storage options"""
        return [('', 'Directly in this object')]

    def _getClientID(self,client):
        return client.getId()





    def _readableSlotFor(self, client):
        slot = self._readableSlot(self._getClientID(client),_marker)
        if slot is not _marker: 
            client._setSlot(slot)
            return slot
        else:
            return {}

    def _writeableSlotFor(self, client):
        slot = self._writeableSlot(self._getClientID(client))
        client._setSlot(slot)
        return slot

    def _readableSlot(self, key, default={}):
        return self.__readableStorage.get(key,default)

    def _writeableSlot(self, key):
        r = self.__writeableStorage.get(key,_marker)
        if r is _marker:
            r = self.__writeableStorage[key] = PersistentMapping()
        return r


    def _delSlotFor(self, client):

        """Delete persistent mapping for client, if present"""

        id = self._getClientID(client)
        if self.__readableStorage.has_key(id): del self.__writeableStorage[id]
        
    def getPersistentItemIDs(self):
        return self.__readableStorage.keys()









    # Management interface

    manage_storageForm = DTMLFile('www/storageForm', globals())

    def manage_setStorage(self, zclass=None, storage=None, use_attrib=None, \
        load_attrib=None, REQUEST=None):

        """
        Change class of returned items, and persistent storage used
        to store them
        """

        if zclass is not None:
            if self._unifiedZClassRegistry().has_key(zclass):
                #if Products.meta_classes.has_key(zclass):
                    self._zclass = zclass
                #else:
                #    self._zclass = self._unifiedZClassRegistry()[zclass][1]
                    if self.__dict__.has_key('_v_itemConstructor'):
                         del self._v_itemConstructor
            else:
                raise NameError,("Invalid/nonexistent ZClass '%s'" % zclass)

        if storage is not None and storage != self.storageInfo:
            self._migrateStorage(storage)

        if use_attrib is not None and load_attrib is not None:
            self.loadAttrib = (use_attrib=="YES") and load_attrib or ""

        if REQUEST is not None:
            return self.manage_storageForm(self, REQUEST,
                manage_tabs_message='Updated storage settings.')









    def manage_pack(self,REQUEST=None):
        """Pack storage by copying to new storage and skipping unused objects"""

        if self.__readableStorage:
            old = self.__writeableStorage
            del self.__writeableStorage     # force a new one to be created
            new = self.__writeableStorage
            
            self.__readableStorage = old
            c=0
            for k,v in old.items():
                if self.getItem(k) is None: continue
                new[k]=v
                c=(c+1) % 1000
                if not c:
                    get_transaction().commit(1)
                    old._p_jar.cacheMinimize(3)

            self.__readableStorage = new
            get_transaction().commit(1)
            old._p_jar.cacheMinimize(3)
            
        if REQUEST is not None:
            return self.manage_storageForm(self, REQUEST,
                manage_tabs_message='Pack completed.')


    manage_options_right = (
                {'label':'Storage',
                 'action':'manage_storageForm'},
    ) + DataManager.manage_options_right


    meta_type = "Rack"
    __plugin_kind__ = "Rack"
    icon = 'misc_/ZPatterns/rack'







    __ac_permissions__ = (
        ('Change Rack storage settings',
            ('manage_storageForm','manage_setStorage','manage_storageOptions',
             'manage_pack'),
        ),

        ('Access contents information',
            ('getItem','retrieveItem','storageInUse','getPersistentItemIDs'),
        ),

        ('Add Items to Racks', ('newItem','createItem','newKey'), ),
    )

default__class_init__(Rack); MakePICBase(Rack)

manage_addRackForm = DTMLFile('addRack', globals())

def manage_addRack(self, id, title='', REQUEST=None):
    """Add a Rack"""
    ob = Rack(id, title)
    return self.Destination()._installPlugIn(ob,'Added Rack.',REQUEST)


class RackMountable(DataSkin):
    meta_type="Rack-mountable"


def initialize(context):

    context.registerPlugInClass(
        Rack,
        permission = 'Add Racks',
        constructors = (manage_addRackForm,
                        manage_addRack),
        icon = 'www/rack.gif',
    )

    context.registerPIContainerBase(Rack)