def __init__(self, object): if not getattr(object, '_p_oid', None): connection = IConnection(object, None) if connection is None: raise zope.keyreference.interfaces.NotYet(object) connection.add(object) self.object = object
def hash_persistent(obj): oid = obj._p_oid connection = obj._p_jar if oid is None or connection is None: connection = IConnection(obj, None) if connection is None: raise zope.keyreference.interfaces.NotYet(obj) connection.add(obj) oid = obj._p_oid database_name = connection.db().database_name return hash((database_name, oid))
def persistent_transaction_manager(obj): """Transaction manager adapter for persistent objects""" conn = IConnection(obj) # typically this will be # zope.keyreference.persistent.connectionOfPersistent try: return conn.transaction_manager except AttributeError: return conn._txn_mgr # pylint: disable=protected-access
def reportPdfByQueryList(self, queryList): filename = datetime.now().strftime('ictrpt_%Y%m%d%H%M%S.pdf') f_handle, f_name = tempfile.mkstemp(filename) authorStr = self.request.principal.title my_formatter = self.request.locale.dates.getFormatter( 'dateTime', 'medium') userTZ = getUserTimezone() longTimeString = my_formatter.format(\ userTZ.fromutc(datetime.utcnow())) versionStr = "%s [%s]" % (longTimeString, getIkVersion()) connection = IConnection(removeSecurityProxy(self.context)) parser = RPEQueryParser() oc = connection.root()['_oq_collection'] thisReporter = PDFReporter(f_name, self.request) thisReporter.setAuthorName(authorStr) thisReporter.setVersionStr(versionStr) queryproc = QueryProcessor(parser, oc) import pdb pdb.set_trace() queryResultsList = [(queryn, queryproc(queryv)) for (queryn, queryv) in queryList] # first run for (queryName, queryResults) in queryResultsList: thisReporter.extendAllContentObjects(queryResults) # second run for (queryName, queryResults) in queryResultsList: thisReporter.appendTitle1(queryName) thisReporter.append(queryResults) # debug output #for i_obj in thisReporter.allContentObjects: # print "%s (%s)" % (i_obj.ikName, i_obj.objectID) thisReporter.buildPdf() thisReporter.cleanup() self.request.response.setHeader('Content-Type', 'application/pdf') self.request.response.setHeader(\ 'Content-Disposition', 'attachment; filename=\"%s\"' % filename) setNoCacheHeaders(self.request.response) datafile = open(f_name, "r") dataMem = datafile.read() datafile.close() os.remove(f_name) return dataMem
def __init__(self, wrapped_obj): # make sure our object is wrapped by containment only try: self.path = '/'.join(wrapped_obj.getPhysicalPath()) except AttributeError: self.path = None # If the path ends with /, it means the object had an empty id. # This means it's not yet added to the container, and so we have # to defer. if self.path is not None and self.path.endswith('/'): raise NotYet(wrapped_obj) self.object = aq_base(wrapped_obj) connection = IConnection(wrapped_obj, None) if not getattr(self.object, '_p_oid', None): if connection is None: raise NotYet(wrapped_obj) connection.add(self.object) try: root = get_root(wrapped_obj) except AttributeError: # If the object is unwrapped we can try to use the Site from the # threadlocal as our acquisition context, hopefully it's not # something odd. root = get_root(getSite()) self.root_oid = root._p_oid self.root_dbname = IConnection(root).db().database_name self.oid = self.object._p_oid self.dbname = connection.db().database_name
def generatePdf(self, absFilename, authorStr, versionStr, request=None): """ will generate a object pdf report steps to do: - toReportSet = set([]) - 1. select of objects (e.g. locations), append toReportSet - 2. select of objects (e.g. buildings), append toReportSet - 3. select of objects (e.g. rooms), append toReportSet - generate Report (1st run, content) - generate Report (2nd run, references) """ ## ## ## TODO: ## ## evil, very alpha, evaluation code for some kind of "Query Language" ## ... to be removed ... ## ## #-> from ZODB.interfaces import IConnection #-> connection = IConnection(self) #(Pdb) #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(447)generatePdf() #-> from gocept.objectquery.collection import ObjectCollection #(Pdb) connection #<Connection at 01f19910> #(Pdb) dir(connection) #['_Connection__onCloseCallbacks', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__implemented__', '__init__', '__module__', '__new__', '__providedBy__', '__provides__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_abort', '_abort_savepoint', '_added', '_added_during_commit', '_cache', '_cache_items', '_code_timestamp', '_commit', '_commit_savepoint', '_conflicts', '_creating', '_db', '_debug_info', '_flush_invalidations', '_handle_independent', '_handle_one_serial', '_handle_serial', '_implicitlyAdding', '_import', '_importDuringCommit', '_inv_lock', '_invalidate_creating', '_invalidated', '_invalidatedCache', '_load_before_or_conflict', '_load_count', '_log', '_modified', '_needs_to_join', '_normal_storage', '_opened', '_pre_cache', '_reader', '_register', '_registered_objects', '_resetCache', '_reset_counter', '_rollback', '_savepoint_storage', '_setstate', '_setstate_noncurrent', '_storage', '_storage_sync', '_store_count', '_store_objects', '_tpc_cleanup', '_txn_time', '_version', 'abort', 'add', 'afterCompletion', 'beforeCompletion', 'cacheGC', 'cacheMinimize', 'close', 'commit', 'connections', 'db', 'exchange', 'exportFile', 'get', 'getDebugInfo', 'getTransferCounts', 'getVersion', 'get_connection', 'importFile', 'invalidate', 'invalidateCache', 'isReadOnly', 'modifiedInVersion', 'newTransaction', 'new_oid', 'oldstate', 'onCloseCallback', 'open', 'register', 'root', 'savepoint', 'setDebugInfo', 'setstate', 'sortKey', 'sync', 'tpc_abort', 'tpc_begin', 'tpc_finish', 'tpc_vote', 'transaction_manager'] #(Pdb) connection.transaction_manager #<transaction._manager.ThreadTransactionManager object at 0x1239bf0> #(Pdb) pp dir(connection.transaction_manager) #['__class__', # '__delattr__', # '__dict__', # '__doc__', # '__getattribute__', # '__hash__', # '__init__', # '__module__', # '__new__', # '__reduce__', # '__reduce_ex__', # '__repr__', # '__setattr__', # '__str__', # '__weakref__', # '_synchs', # '_txns', # 'abort', # 'begin', # 'commit', # 'doom', # 'free', # 'get', # 'isDoomed', # 'registerSynch', # 'savepoint', # 'unregisterSynch'] #(Pdb) connection.transaction_manager.registerSynch(index_synch) #(Pdb) connection.root()['_oq_collection'] = oc #*** NameError: name 'oc' is not defined #(Pdb) l #442 publ = request.publication #443 import pdb #444 pdb.set_trace() #445 from ZODB.interfaces import IConnection #446 connection = IConnection(self) #447 -> from gocept.objectquery.collection import ObjectCollection #448 from gocept.objectquery.pathexpressions import RPEQueryParser #449 from gocept.objectquery.processor import QueryProcessor #450 from zope.app import zapi #451 parser = RPEQueryParser() #452 oc = ObjectCollection(connection) #(Pdb) n #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(448)generatePdf() #-> from gocept.objectquery.pathexpressions import RPEQueryParser #(Pdb) #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(449)generatePdf() #-> from gocept.objectquery.processor import QueryProcessor #(Pdb) #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(450)generatePdf() #-> from zope.app import zapi #(Pdb) #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(451)generatePdf() #-> parser = RPEQueryParser() #(Pdb) #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(452)generatePdf() #-> oc = ObjectCollection(connection) #(Pdb) #> /Users/markus/Projekte/ict_ok.org/inst/lib/python/org/ict_ok/components/superclass/superclass.py(453)generatePdf() #-> d1 = zapi.getParent(self) #(Pdb) connection.root()['_oq_collection'] = oc #(Pdb) connection.transaction_manager.commit() #(Pdb) from org.ict_ok.components.happliance.interfaces import IHardwareAppliance if IHardwareAppliance.providedBy(self): publ = request.publication from ZODB.interfaces import IConnection connection = IConnection(self) from gocept.objectquery.collection import ObjectCollection from gocept.objectquery.pathexpressions import RPEQueryParser from gocept.objectquery.processor import QueryProcessor from zope.app import zapi parser = RPEQueryParser() oc = ObjectCollection(connection) d1 = zapi.getParent(self) d2 = zapi.getParent(d1) d3 = zapi.getParent(d2) from pprint import pprint print "-" * 80 print "class_index:" pprint(list(oc.class_index._index)) # print "attribute_index:" # pprint(list(oc.attribute_index._index)) # print "structure_index:" # pprint(list(oc.structure_index.paths)) oc.index(connection.root()) print "-" * 80 print "class_index:" pprint(list(oc.class_index._index)) print "attribute_index:" pprint(list(oc.attribute_index._index)) print "structure_index:" pprint(list(oc.structure_index.paths)) oc.index(d2) print "-" * 80 print "class_index:" pprint(list(oc.class_index._index)) print "attribute_index:" pprint(list(oc.attribute_index._index)) print "structure_index:" pprint(list(oc.structure_index.paths)) oc.index(d1) print "-" * 80 print "class_index:" pprint(list(oc.class_index._index)) print "attribute_index:" pprint(list(oc.attribute_index._index)) print "structure_index:" pprint(list(oc.structure_index.paths)) oc.index(self) print "-" * 80 print "class_index:" pprint(list(oc.class_index._index)) print "attribute_index:" pprint(list(oc.attribute_index._index)) print "structure_index:" pprint(list(oc.structure_index.paths)) print "-" * 80 if0 = self.interfaces[0] oc.index(if0) oc3 = connection.root()['_oq_collection'] query = QueryProcessor(parser, oc3) tt2 = oc3.is_child(self._p_oid, d1._p_oid) tt1 = oc3.is_child(d1._p_oid, d2._p_oid) tt3 = oc3.is_child(self._p_oid, if0._p_oid) tt4 = oc3.is_child(if0._p_oid, self._p_oid) ee = query('/Folder') ff = query('/Folder/HardwareApplianceFolder/HardwareAppliance') print "ff: ", ff files2delete = [] document = RptDocument(absFilename) #document.setVolumeNo("1") document.setAuthorName(authorStr) document.setVersionStr(versionStr) adapterRptPdf = IRptPdf(self) if adapterRptPdf: adapterRptPdf.document = document adapterRptPdf.traverse4Rpt(1, True) files2delete.extend(adapterRptPdf.files2delete) del adapterRptPdf document.buildPdf() document.outConsoleTree(0) for i_filename in files2delete: try: os.remove(i_filename) except OSError: pass
def notifyRemovedEvent(instance, event): logger.info(u"superclass.objcollect.notifyRemovedEvent: event: %s" % event) raw_instance = removeSecurityProxy(instance) connection = IConnection(raw_instance) oc = connection.root()['_oq_collection'] oc.unindex(raw_instance)
def root(self): # It is possible that the root is not in the same db that the # object. Asking the root object on the wrong db can trigger # an POSKeyError. connection = IConnection(self.object).get_connection(self.root_dbname) return connection[self.root_oid]
def add_object_to_connection(ob, event): """Pre-add new objects to their persistence connection""" connection = IConnection(ob, None) if None is not connection: connection.add(aq_base(ob))
def to_external_oid(self, default=None, add_to_connection=False, add_to_intids=False, use_cache=True): # Override the signature to *not* document use_cache. """ to_external_oid(self, default=None, add_to_connection=False, add_to_intids=False) -> bytes For a `persistent object <persistent.Persistent>`, returns its `persistent OID <persistent.interfaces.IPersistent._p_oid>` in a parseable external format (see :func:`.from_external_oid`). This format includes the database name (so it works in a ZODB multi-database) and the integer ID from the closest :class:`zope.intid.interfaces.IIntIds` utility. If the object implements a method ``toExternalOID()``, that method will be called and its result (or the *default*) will be returned. This should generally be considered legacy behaviour. If the object has not been saved, and *add_to_connection* is `False` (the default) returns the *default*. :param bool add_to_connection: If the object is persistent but not yet added to a connection, setting this to true will attempt to add it to the nearest connection in its containment tree, thus letting it have an OID. :param bool add_to_intids: If we can obtain an OID for this object, but it does not have an intid, and an intid utility is available, then if this is `True` (not the default) we will register it with the utility. :return: A :class:`bytes` string. """ # TODO: Simplify # pylint:disable=too-many-branches try: return self.toExternalOID() or default except AttributeError: pass if use_cache: # XXX: And yet we still set it always. try: # See comments in to_external_ntiid_oid return getattr(self, '_v_to_external_oid') except AttributeError: pass # because if it was proxied, we should still read the right thing above; # this saves time self = removeAllProxies(self) try: oid = self._p_oid except AttributeError: return default jar = None if not oid: if add_to_connection: try: jar = IConnection(self) except TypeError: return default jar.add(self) oid = self._p_oid else: return default # The object ID is defined to be 8 charecters long. It gets # padded with null chars to get to that length; we strip # those out. Finally, it probably has chars that # aren't legal in UTF or ASCII, so we go to hex and prepend # a flag, '0x' # TODO: Why are we keeping this as a bytes string, not unicode? oid = oid.lstrip(b'\x00') oid = b'0x' + binascii.hexlify(oid) try: jar = jar or self._p_jar except AttributeError: pass if jar: db_name = jar.db().database_name oid = oid + b':' + binascii.hexlify(bytes_(db_name)) intutility = component.queryUtility(IIntIds) if intutility is not None: intid = intutility.queryId(self) if intid is None and add_to_intids: intid = intutility.register(self) if intid is not None: if not jar: oid = oid + b':' # Ensure intid is always the third part oid = oid + b':' + bytes_(to_external_string(intid)) try: setattr(self, str('_v_to_external_oid'), oid) except (AttributeError, TypeError): # pragma: no cover pass return oid
def __init__(self, app): self.root_folder = app self.connection = IConnection(app)