How to use persistent - 10 common examples

To help you get started, we’ve selected a few persistent examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github eclipse / paho.mqtt.testing / interoperability / mqtt / brokers / start.py View on Github external
def setup_persistence(persistence_filename):
  import ZODB, ZODB.FileStorage, BTrees.OOBTree, transaction, persistent
  storage = ZODB.FileStorage.FileStorage(persistence_filename)
  db = ZODB.DB(storage)
  connection = db.open()
  root = connection.root

  if not hasattr(root, 'mqtt'):
    root.mqtt = BTrees.OOBTree.BTree()
    transaction.commit()

  if not root.mqtt.has_key("sharedData"):
    root.mqtt["sharedData"] = persistent.mapping.PersistentMapping()
    transaction.commit()

  sharedData = root.mqtt["sharedData"]
  return connection, sharedData
github liqd / adhocracy3 / src / adhocracy_core / adhocracy_core / sheets / test_init.py View on Github external
def test_set_and_add_dirty_flag_for_persistent_context(self, inst):
        from persistent.mapping import PersistentMapping
        inst.context = PersistentMapping()
        inst.context._p_jar = Mock()
        inst.set({'count': 2})
        assert inst.context._p_changed is True
github zopefoundation / grok / src / grok / ftests / utility / local.py View on Github external
grok.implements(IFireplace)

class Club(object):
    grok.implements(IClub)

class SpikyClub(object):
    grok.implements(IClub, ISpiky)

class Mammoth(grok.LocalUtility):
    grok.implements(IMammoth, IClub)

class SabretoothTiger(grok.LocalUtility):
    grok.implements(IMammoth, IClub)
    grok.provides(IMammoth)

class IPainting(persistent.interfaces.IPersistent):
    pass

class CavePainting(grok.LocalUtility):
    grok.implements(IPainting)

class ColoredCavePainting(grok.LocalUtility):
    grok.implements(IPainting)
    grok.provides(IPainting)

class Cave(grok.Model, grok.Site):
    grok.local_utility(Fireplace)
    grok.local_utility(Club)
    grok.local_utility(SpikyClub, provides=IClub, name='spiky')
    grok.local_utility(Mammoth, provides=IMammoth)
    grok.local_utility(SabretoothTiger, name='tiger')
    grok.local_utility(CavePainting, name='blackandwhite', provides=IPainting)
github diging / tethne / flask_backups / flask_old / old_flask_folder / login.py View on Github external
#                 else:
#                     print "inside else"
        storage = FileStorage('./storage/userdb.fs')
        conn = DB(storage)
        print "Type start:",conn, type(conn)
        dbroot = conn.open().root()
        #db()   # to check if the DB is already initialized
        # this part is commented as it is moved up in db()
        try:
            for val in ['userdb','graphdb','datadb','dsdb']:
                if val in dbroot.keys():
                    pass
        except:
                if not val in dbroot.keys():
                    print " donot create this always"
                    dbroot[val] = Dict()
                    print "TRY user db dbroot:",dbroot['userdb'], type (dbroot['userdb'])
        
        print "else:::::-->", request.form , form.email.data
        u=mod.User(form.name.data,form.email.data,\
                    sha256(form.password.data).hexdigest(), \
                    form.password.data,form.institution.data,\
                    form.security_question.data, form.security_answer.data        
                   )
        print "User:--->", u, "form.name.data",form.name.data
        dbroot['userdb'][u.name] = u
        session['username'] = u.name
        transaction.commit()
        print "Database added successfully", dbroot['userdb'][u.name], u.name, u
        flash('Registered successfuly')
        return redirect(url_for('login'))
    return render_template('forms/register.html', form = form)
github zopefoundation / Zope / lib / python / persistent / dict.py View on Github external
subclassed.
    """

    # IterableUserDict provides all of the mapping behavior.  The
    # PersistentDict class is responsible marking the persistent
    # state as changed when a method actually changes the state.  At
    # the mapping API evolves, we may need to add more methods here.

    __super_delitem = IterableUserDict.__delitem__
    __super_setitem = IterableUserDict.__setitem__
    __super_clear = IterableUserDict.clear
    __super_update = IterableUserDict.update
    __super_setdefault = IterableUserDict.setdefault
    __super_popitem = IterableUserDict.popitem

    __super_p_init = persistent.Persistent.__init__
    __super_init = IterableUserDict.__init__

    def __init__(self, dict=None):
        self.__super_init(dict)
        self.__super_p_init()

    def __delitem__(self, key):
        self.__super_delitem(key)
        self._p_changed = True

    def __setitem__(self, key, v):
        self.__super_setitem(key, v)
        self._p_changed = True

    def clear(self):
        self.__super_clear()
github indico / indico / indico / modules / base.py View on Github external
which is specified.
        """

        if type(moduleId) is int:
            moduleId = str(moduleId)
        if self._getIdx().has_key(str(moduleId)):
            return self._getIdx()[str(moduleId)]
        elif self._availableModules.has_key(moduleId):
            newmod=self._availableModules[moduleId]()
            self.add(newmod)
            return newmod
        else:
            raise MaKaCError( ("Module id %s does not exist") % str(moduleId) )


class Module(Persistent):
    """
    This class represents a general module that it is stored in the database.
    A module class is a way to access the main data for a general Indico module.
    A module could be news management, plugins management, etc and anything not
    related to Indico settings (HelperMaKaCInfo) categories and conferences.
    """

    id = ""

    def getId(self):
        return self.id

    def setId(self, id):
        self.id = id
        return self.id
github enkore / borgcube / src / borgcube / core / models.py View on Github external
def __getstate__(self):
        ghost = self._p_jar is not None and self._p_changed is None
        if ghost:
            self._evolve()
        state = super().__getstate__()
        state.setdefault('version', self.version)
        return state

    def _set_changed(self, value):
        ghost = self._p_jar is not None and self._p_changed is None
        if ghost:
            self._evolve()
        persistent.Persistent._p_changed.__set__(self, value)

    _p_changed = property(persistent.Persistent._p_changed.__get__, _set_changed, persistent.Persistent._p_changed.__delete__)

    @property
    def _p_mtime(self):
        ghost = self._p_jar is not None and self._p_changed is None
        if ghost:
            self._evolve()
        return persistent.Persistent._p_mtime.__get__(self)

    def _evolve(self):
        current_version = type(self).version
        needs_evolution = self.version != current_version
        if needs_evolution:
            def evolves(member):
                is_method = inspect.ismethod(member)
                if not is_method:
                    return False
github ConsenSys / mythril / mythril / ether / contractstorage.py View on Github external
if not contract_balance:
                        continue

                    ethcontract = ETHContract(contract_code, tx['input'])

                    m = hashlib.md5()
                    m.update(contract_code.encode('UTF-8'))
                    contract_hash = m.digest()

                    contracts[contract_hash] = {'ethcontract': ethcontract, 'address': contract_address, 'balance': contract_balance}

        blockNum -= 1

    return contracts

class ContractStorage(persistent.Persistent):

    def __init__(self):
        self.contracts = BTree()
        self.instance_lists = BTree()
        self.last_block = 0
        self.eth = None

    def get_contract_by_hash(self, contract_hash):
        return self.contracts[contract_hash]

    def initialize(self, eth):

        self.eth = eth

        if self.last_block:
            blockNum = self.last_block
github indico / indico / indico / MaKaC / plugins / RoomBooking / notifications.py View on Github external
recipients = set()
    recipients.update(getRoomBookingOption('notificationEmails'))
    if getRoomBookingOption('notificationEmailsToBookedFor'):
        recipients.update(getEmailList(resv.contactEmail))
    if resv.room.resvNotificationToResponsible:
        recipients.add(resv.room.getResponsible().getEmail())
    maildata = {
        'fromAddr': Config.getInstance().getNoReplyEmail(),
        'toList': list(recipients),
        'subject': subject.format(**msgArgs),
        'body': msg.format(**msgArgs)
    }
    GenericMailer.send(GenericNotification(maildata))

class ReservationStartEndNotification(Persistent, Observable):

    def __init__(self, resv):
        self._resv = resv
        self._notificationsSent = set()

    @cached_property
    def _daysBefore(self):
        roomSpecificDays = self._resv.room.resvStartNotificationBefore
        if roomSpecificDays is not None:
            return timedelta(days=roomSpecificDays)
        return timedelta(days=getRoomBookingOption('notificationBefore'))

    def sendStartNotification(self, logger):
        if self._resv.isCancelled:
            if DEBUG:
                print 'Reservation %s is cancelled, no email will be sent' % self._resv.guid
github indico / indico / indico / MaKaC / common / log.py View on Github external
from indico.util.string import seems_html
from MaKaC.common.timezoneUtils import nowutc

class ModuleNames:

    MATERIAL = "Material"
    PAPER_REVIEWING = "Paper Reviewing"
    PARTICIPANTS = "Participants"
    REGISTRATION = "Registration"
    TIMETABLE = "Timetable"

    def __init__(self):
        pass


class LogItem(Persistent) :

    def __init__(self, user, logInfo, module):
        self._logId = None
        self._logDate = nowutc()
        self._logType = "generalLog"

        # User who has performed / authorised the logged action
        self._responsibleUser = user if user else ContextManager.get("currentUser")

        # Indico module, the logged action comes from
        self._module = module

        # DICTIONARY containing infos that have to be logged
        # MUST CONTAIN entry with key : "subject"
        # keys as well as values should be meaningful
        self._logInfo = logInfo