How to use the persistent.Persistent function in persistent

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 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 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
github Nexedi / wendelin.core / bigfile / file_zodb.py View on Github external
def __setstate__(self, state):
        super(ZBlk0, self).__init__()
        self._v_blkdata = state

    # ZBlk as initially created (empty placeholder)
    def __init__(self):
        self.__setstate__(None)


# ZBlk format 1: block splitted into chunks of fixed size in BTree
#
# NOTE zeros are not stored -> either no chunk at all, or trailing zeros
#      are stripped.

# data as Persistent object
class ZData(Persistent):
    __slots__ = ('data')
    def __init__(self, data):
        self.data = data

    def __getstate__(self):
        # request to pickle should go in only when zblk was set changed (by
        # storeblk), and only once.
        assert self._p_state is not GHOST

        data = self.data
        # do not waste memory for duplicated data - it was extracted from
        # memory page, so as soon as it lands to DB, we do not need to keep
        # data here. (see ZBlk0.__getstate__() for details)
        #
        # release .data and thus it will free after return will be processed
        # (invalidate because .data was changed - so deactivate won't work)
github cguardia / ZODB-Documentation / translations / ja / code / working / timetrax_zodb.py View on Github external
import sys
import cmd
import shlex

import persistent
import transaction
import ZODB
import ZODB.FileStorage

class Project(persistent.Persistent):
    def __init__(self, name, title):
        self.name = name
        self.title = title
        self.tasks = {}

    def addTask(self, name, description):
        task = Task(name, description)
        self.tasks[name] = task
        self._p_changed = True

class Task(persistent.Persistent):
    def __init__(self, name,  description):
        self.name = name
        self.description = description
        self.bookings = []
github plone / plone.namedfile / plone / namedfile / file.py View on Github external
from ZPublisher import HTTPRangeSupport

import piexif
import six
import transaction


log = getLogger(__name__)


MAXCHUNKSIZE = 1 << 16
IMAGE_INFO_BYTES = 1024
MAX_INFO_BYTES = 1 << 18


class FileChunk(Persistent):
    """Wrapper for possibly large data"""

    next = None

    def __init__(self, data):
        self._data = data

    def __getslice__(self, i, j):
        return self._data[i:j]

    def __len__(self):
        data = bytes(self)
        return len(data)

    def _get_contents(self):
        next = self.next
github indico / indico / indico / MaKaC / registration.py View on Github external
A registrant has modified his/her registration for '%s'. See information below:

                      %s
                      """)%(strip_ml_tags(regForm.getConference().getTitle()), \
                              body)
            maildata = { "fromAddr": fromAddr, "toList": self.getToList(), "ccList": self.getCCList(), "subject": subject, "body": bodyOrg }
            GenericMailer.send(GenericNotification(maildata))

    def exportXml(self, xmlGen):
        """Write xml tags about this object in the given xml generator of type XMLGen."""
        xmlGen.openTag( "notification" )
        xmlGen.writeTag( "toList", ", ".join(self.getToList()) )
        xmlGen.writeTag( "ccList", ", ".join(self.getCCList()) )
        xmlGen.closeTag( "notification" )

class BaseForm(Persistent):

    """
    Base class for registration forms

    It includes iterators/getters, provided if the class attribute
    _iterableContainer is present. _iterableContainer is a simple workaround for
    the problem of having a generic iterator interface over all the forms, even
    if the initial design didn't unify the form container into a BaseForm
    attribute. Since it is too late now for redesigning the DB schema, this
    attribute kind of fixes it.

    """

    # should be overloaded if iteration is to be provided
    _iterableContainer = None
github zopefoundation / persistent / persistent / mapping.py View on Github external
import persistent
from persistent._compat import IterableUserDict

class default(object):

    def __init__(self, func):
        self.func = func

    def __get__(self, inst, class_):
        if inst is None:
            return self
        return self.func(inst)


class PersistentMapping(IterableUserDict, persistent.Persistent):
    """A persistent wrapper for mapping objects.

    This class allows wrapping of mapping objects so that object
    changes are registered.  As a side effect, mapping objects may be
    subclassed.

    A subclass of PersistentMapping or any code that adds new
    attributes should not create an attribute named _container.  This
    is reserved for backwards compatibility reasons.
    """

    # UserDict provides all of the mapping behavior.  The
    # PersistentMapping 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.