Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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
# NOTE: This detection works, but it isn't so flexible.
if os.path.exists(os.path.join(processingParameters["dirPrefix"], runDir, subsystem)):
self.fileLocationSubsystem = self.subsystem
else:
self.fileLocationSubsystem = "HLT"
else:
self.fileLocationSubsystem = fileLocationSubsystem
if self.showRootFiles is True and self.subsystem != self.fileLocationSubsystem:
logger.info("It is requested to show ROOT files for subsystem {subsystem}, but the subsystem does not have specific data files. Using HLT data files!".format(subsystem = subsystem))
# Files
# Be certain to set these after the subsystem has been created!
# Contains all files for that particular run
self.files = BTrees.OOBTree.BTree()
self.timeSlices = persistent.mapping.PersistentMapping()
# Only one combined file, so we do not need a dict!
self.combinedFile = None
# Directories
self.setupDirectories(runDir)
# Times
self.startOfRun = startOfRun
self.endOfRun = endOfRun
# The run length is in minutes
self.runLength = self.calculateRunLength()
# Histograms
self.histGroups = persistent.list.PersistentList()
# Should be accessed through the group usually, but this provides direct access
self.histsInFile = BTrees.OOBTree.BTree()
def __basicnew__():
r=persistent.mapping.PersistentMapping()
r.__setstate__=fixer
return r
def reset(self, agentsOnly=False, trackOnly=False):
"""
Resets database structures
.. WARNING::
This erases any agents and contents in the MPT
"""
if not trackOnly:
self._agents = mapping.PersistentMapping()
if not agentsOnly:
self._track = SetMultiPointerTrack()
yet exist.
Args:
db (PersistentMapping): The root database persistent mapping.
overwriteSecretKey (bool): If true, the secret key in the database should be overwritten
with a new value read from the configuration.
Returns:
None.
"""
# We retrieve the configuration related to the webApp module because we may want to
# update options that are defined only for he webApp (such as the users).
(sensitiveParameters, filesRead) = config.readConfig(config.configurationType.webApp)
# Ensure that the config exists
if "config" not in db:
db["config"] = persistent.mapping.PersistentMapping()
logger.warning("Needed to create the config!")
# Users
# Create mapping if not already there
if "users" not in db['config']:
db["config"]["users"] = persistent.mapping.PersistentMapping()
logger.info("Created the users dict!")
# Add each user, overriding an existing settings
users = db["config"]["users"]
for user, pw in iteritems(sensitiveParameters["_users"]):
users[user] = pw
logger.info("Adding user {user}".format(user = user))
# Secret key
# Set the secret key to the one set in the server parameters.
import zope.interface
import zope.component
import zope.schema
from zope.interface.common import mapping
from zope.security.interfaces import ForbiddenAttribute
from zope.security.checker import canAccess, canWrite, Proxy
from z3c.form import interfaces
_marker = []
ALLOWED_DATA_CLASSES = [dict]
try:
import persistent.mapping
import persistent.dict
ALLOWED_DATA_CLASSES.append(persistent.mapping.PersistentMapping)
ALLOWED_DATA_CLASSES.append(persistent.dict.PersistentDict)
except ImportError:
pass
@zope.interface.implementer(interfaces.IDataManager)
class DataManager(object):
"""Data manager base class."""
class AttributeField(DataManager):
"""Attribute field."""
zope.component.adapts(
zope.interface.Interface, zope.schema.interfaces.IField)
def __init__(self, context, field):
self.context = context
def todict(obj, classkey=None):
""" Converts object to dictionary.
For more information see https://stackoverflow.com/questions/1036409/recursively-convert-python-object-graph-to-dictionary
"""
if isinstance(obj, dict) or isinstance(obj, BTrees.OOBTree.BTree) \
or isinstance(obj, persistent.mapping.PersistentMapping):
data = Map()
for (k, v) in obj.items():
data[str(k)] = todict(v, classkey)
return data
elif hasattr(obj, "_ast"):
return todict(obj._ast())
elif hasattr(obj, "__iter__") and not isinstance(obj, str):
return [todict(v, classkey) for v in obj]
elif hasattr(obj, "__dict__"):
data = Map([(key, todict(value, classkey))
for key, value in obj.__dict__.items()
if not callable(value) and not key.startswith('_')])
if classkey is not None and hasattr(obj, "__class__"):
data[classkey] = obj.__class__.__name__
return data
else:
Returns:
None.
"""
# We retrieve the configuration related to the webApp module because we may want to
# update options that are defined only for he webApp (such as the users).
(sensitiveParameters, filesRead) = config.readConfig(config.configurationType.webApp)
# Ensure that the config exists
if "config" not in db:
db["config"] = persistent.mapping.PersistentMapping()
logger.warning("Needed to create the config!")
# Users
# Create mapping if not already there
if "users" not in db['config']:
db["config"]["users"] = persistent.mapping.PersistentMapping()
logger.info("Created the users dict!")
# Add each user, overriding an existing settings
users = db["config"]["users"]
for user, pw in iteritems(sensitiveParameters["_users"]):
users[user] = pw
logger.info("Adding user {user}".format(user = user))
# Secret key
# Set the secret key to the one set in the server parameters.
if overwriteSecretKey or "secretKey" not in db["config"]:
# NOTE: There will always be a secret key in the sensitive paramers (by default, it just generates a random one),
# so we can just use the value without worrying whether it exists.
db["config"]["secretKey"] = sensitiveParameters["_secretKey"]
logger.info("Adding secret key to db!")