desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Save this object.'
| def save(self, session=None):
| if (not session):
session = get_session()
with session.begin(subtransactions=True):
session.add(self)
session.flush()
|
'Make the model object behave like a dict.'
| def update(self, values):
| for (k, v) in values.iteritems():
setattr(self, k, v)
|
'Make the model object behave like a dict.
Includes attributes from joins.'
| def iteritems(self):
| local = dict(self)
joined = dict([(k, v) for (k, v) in self.__dict__.iteritems() if (not (k[0] == '_'))])
local.update(joined)
return local.iteritems()
|
'Mark this object as deleted.'
| def soft_delete(self, session=None):
| self.deleted = self.id
self.deleted_at = timeutils.utcnow()
self.save(session=session)
|
'Get the actual backend. May be a module or an instance of
a class. Doesn\'t matter to us. We do this synchronized as it\'s
possible multiple greenthreads started very quickly trying to do
DB calls and eventlet can switch threads before self.__backend gets
assigned.'
| @lockutils.synchronized('dbapi_backend', 'ceilometer-')
def __get_backend(self):
| if self.__backend:
return self.__backend
backend_name = CONF.database.backend
self.__use_tpool = CONF.database.use_tpool
if self.__use_tpool:
from eventlet import tpool
self.__tpool = tpool
backend_path = self.__backend_mapping.get(backend_name, backend_name)
backend_mod ... |
':param retvalue: Value that LoopingCall.wait() should return.'
| def __init__(self, retvalue=True):
| self.retvalue = retvalue
|
'Allow loading of JSON rule data.'
| @classmethod
def load_json(cls, data, default_rule=None):
| rules = dict(((k, parse_rule(v)) for (k, v) in jsonutils.loads(data).items()))
return cls(rules, default_rule)
|
'Initialize the Rules store.'
| def __init__(self, rules=None, default_rule=None):
| super(Rules, self).__init__((rules or {}))
self.default_rule = default_rule
|
'Implements the default rule handling.'
| def __missing__(self, key):
| if ((not self.default_rule) or (self.default_rule not in self)):
raise KeyError(key)
return self[self.default_rule]
|
'Dumps a string representation of the rules.'
| def __str__(self):
| out_rules = {}
for (key, value) in self.items():
if isinstance(value, TrueCheck):
out_rules[key] = ''
else:
out_rules[key] = str(value)
return jsonutils.dumps(out_rules, indent=4)
|
'Create a new Rules object based on the provided dict of rules.
:param rules: New rules to use. It should be an instance of dict.
:param overwrite: Whether to overwrite current rules or update them
with the new rules.'
| def set_rules(self, rules, overwrite=True):
| if (not isinstance(rules, dict)):
raise TypeError((_('Rules must be an instance of dict or Rules, got %s instead') % type(rules)))
if overwrite:
self.rules = Rules(rules)
else:
self.update(rules)
|
'Clears Enforcer rules, policy\'s cache and policy\'s path.'
| def clear(self):
| self.set_rules({})
self.policy_path = None
|
'Loads policy_path\'s rules.
Policy file is cached and will be reloaded if modified.
:param force_reload: Whether to overwrite current rules.'
| def load_rules(self, force_reload=False):
| if (not self.policy_path):
self.policy_path = self._get_policy_path()
(reloaded, data) = fileutils.read_cached_file(self.policy_path, force_reload=force_reload)
if reloaded:
rules = Rules.load_json(data, self.default_rule)
self.set_rules(rules)
LOG.debug(_('Rules successfu... |
'Locate the policy json data file.
:param policy_file: Custom policy file to locate.
:returns: The policy path
:raises: ConfigFilesNotFoundError if the file couldn\'t
be located.'
| def _get_policy_path(self):
| policy_file = CONF.find_file(self.policy_file)
if policy_file:
return policy_file
raise cfg.ConfigFilesNotFoundError(path=CONF.policy_file)
|
'Checks authorization of a rule against the target and credentials.
:param rule: A string or BaseCheck instance specifying the rule
to evaluate.
:param target: As much information about the object being operated
on as possible, as a dictionary.
:param creds: As much information about the user performing the
action as p... | def enforce(self, rule, target, creds, do_raise=False, exc=None, *args, **kwargs):
| LOG.debug((_('Rule %s will be now enforced') % rule))
self.load_rules()
if isinstance(rule, BaseCheck):
result = rule(target, creds, self)
elif (not self.rules):
result = False
else:
try:
result = self.rules[rule](target, creds, self)
except... |
'String representation of the Check tree rooted at this node.'
| @abc.abstractmethod
def __str__(self):
| pass
|
'Triggers if instance of the class is called.
Performs the check. Returns False to reject the access or a
true value (not necessary True) to accept the access.'
| @abc.abstractmethod
def __call__(self, target, cred):
| pass
|
'Return a string representation of this check.'
| def __str__(self):
| return '!'
|
'Check the policy.'
| def __call__(self, target, cred):
| return False
|
'Return a string representation of this check.'
| def __str__(self):
| return '@'
|
'Check the policy.'
| def __call__(self, target, cred):
| return True
|
'Initiates Check instance.
:param kind: The kind of the check, i.e., the field before the
:param match: The match of the check, i.e., the field after
the \':\'.'
| def __init__(self, kind, match):
| self.kind = kind
self.match = match
|
'Return a string representation of this check.'
| def __str__(self):
| return ('%s:%s' % (self.kind, self.match))
|
'Initialize the \'not\' check.
:param rule: The rule to negate. Must be a Check.'
| def __init__(self, rule):
| self.rule = rule
|
'Return a string representation of this check.'
| def __str__(self):
| return ('not %s' % self.rule)
|
'Check the policy.
Returns the logical inverse of the wrapped check.'
| def __call__(self, target, cred):
| return (not self.rule(target, cred))
|
'Initialize the \'and\' check.
:param rules: A list of rules that will be tested.'
| def __init__(self, rules):
| self.rules = rules
|
'Return a string representation of this check.'
| def __str__(self):
| return ('(%s)' % ' and '.join((str(r) for r in self.rules)))
|
'Check the policy.
Requires that all rules accept in order to return True.'
| def __call__(self, target, cred):
| for rule in self.rules:
if (not rule(target, cred)):
return False
return True
|
'Adds rule to be tested.
Allows addition of another rule to the list of rules that will
be tested. Returns the AndCheck object for convenience.'
| def add_check(self, rule):
| self.rules.append(rule)
return self
|
'Initialize the \'or\' check.
:param rules: A list of rules that will be tested.'
| def __init__(self, rules):
| self.rules = rules
|
'Return a string representation of this check.'
| def __str__(self):
| return ('(%s)' % ' or '.join((str(r) for r in self.rules)))
|
'Check the policy.
Requires that at least one rule accept in order to return True.'
| def __call__(self, target, cred):
| for rule in self.rules:
if rule(target, cred):
return True
return False
|
'Adds rule to be tested.
Allows addition of another rule to the list of rules that will
be tested. Returns the OrCheck object for convenience.'
| def add_check(self, rule):
| self.rules.append(rule)
return self
|
'Create the class.
Injects the \'reducers\' list, a list of tuples matching token sequences
to the names of the corresponding reduction methods.'
| def __new__(mcs, name, bases, cls_dict):
| reducers = []
for (key, value) in cls_dict.items():
if (not hasattr(value, 'reducers')):
continue
for reduction in value.reducers:
reducers.append((reduction, key))
cls_dict['reducers'] = reducers
return super(ParseStateMeta, mcs).__new__(mcs, name, bases, cls_dic... |
'Initialize the ParseState.'
| def __init__(self):
| self.tokens = []
self.values = []
|
'Perform a greedy reduction of the token stream.
If a reducer method matches, it will be executed, then the
reduce() method will be called recursively to search for any more
possible reductions.'
| def reduce(self):
| for (reduction, methname) in self.reducers:
if ((len(self.tokens) >= len(reduction)) and (self.tokens[(- len(reduction)):] == reduction)):
meth = getattr(self, methname)
results = meth(*self.values[(- len(reduction)):])
self.tokens[(- len(reduction)):] = [r[0] for r in re... |
'Adds one more token to the state. Calls reduce().'
| def shift(self, tok, value):
| self.tokens.append(tok)
self.values.append(value)
self.reduce()
|
'Obtain the final result of the parse.
Raises ValueError if the parse failed to reduce to a single result.'
| @property
def result(self):
| if (len(self.values) != 1):
raise ValueError('Could not parse rule')
return self.values[0]
|
'Turn parenthesized expressions into a \'check\' token.'
| @reducer('(', 'check', ')')
@reducer('(', 'and_expr', ')')
@reducer('(', 'or_expr', ')')
def _wrap_check(self, _p1, check, _p2):
| return [('check', check)]
|
'Create an \'and_expr\'.
Join two checks by the \'and\' operator.'
| @reducer('check', 'and', 'check')
def _make_and_expr(self, check1, _and, check2):
| return [('and_expr', AndCheck([check1, check2]))]
|
'Extend an \'and_expr\' by adding one more check.'
| @reducer('and_expr', 'and', 'check')
def _extend_and_expr(self, and_expr, _and, check):
| return [('and_expr', and_expr.add_check(check))]
|
'Create an \'or_expr\'.
Join two checks by the \'or\' operator.'
| @reducer('check', 'or', 'check')
def _make_or_expr(self, check1, _or, check2):
| return [('or_expr', OrCheck([check1, check2]))]
|
'Extend an \'or_expr\' by adding one more check.'
| @reducer('or_expr', 'or', 'check')
def _extend_or_expr(self, or_expr, _or, check):
| return [('or_expr', or_expr.add_check(check))]
|
'Invert the result of another check.'
| @reducer('not', 'check')
def _make_not_expr(self, _not, check):
| return [('check', NotCheck(check))]
|
'Recursively checks credentials based on the defined rules.'
| def __call__(self, target, creds, enforcer):
| try:
return enforcer.rules[self.match](target, creds, enforcer)
except KeyError:
return False
|
'Check that there is a matching role in the cred dict.'
| def __call__(self, target, creds, enforcer):
| return (self.match.lower() in [x.lower() for x in creds['roles']])
|
'Check http: rules by calling to a remote server.
This example implementation simply verifies that the response
is exactly \'True\'.'
| def __call__(self, target, creds, enforcer):
| url = (('http:' + self.match) % target)
data = {'target': jsonutils.dumps(target), 'credentials': jsonutils.dumps(creds)}
post_data = urllib.urlencode(data)
f = urllib2.urlopen(url, post_data)
return (f.read() == 'True')
|
'Check an individual match.
Matches look like:
tenant:%(tenant_id)s
role:compute:admin'
| def __call__(self, target, creds, enforcer):
| match = (self.match % target)
if (self.kind in creds):
return (match == six.text_type(creds[self.kind]))
return False
|
'Initialize the service launcher.
:returns: None'
| def __init__(self):
| self._services = threadgroup.ThreadGroup()
self.backdoor_port = eventlet_backdoor.initialize_if_enabled()
|
'Start and wait for a service to finish.
:param service: service to run and wait for.
:returns: None'
| @staticmethod
def run_service(service):
| service.start()
service.wait()
|
'Load and start the given service.
:param service: The service you would like to start.
:returns: None'
| def launch_service(self, service):
| service.backdoor_port = self.backdoor_port
self._services.add_thread(self.run_service, service)
|
'Stop all services which are currently running.
:returns: None'
| def stop(self):
| self._services.stop()
|
'Waits until all services have been stopped, and then returns.
:returns: None'
| def wait(self):
| self._services.wait()
|
'Loop waiting on children to die and respawning as necessary.'
| def wait(self):
| LOG.debug(_('Full set of CONF:'))
CONF.log_opt_values(LOG, std_logging.DEBUG)
while self.running:
wrap = self._wait_child()
if (not wrap):
eventlet.greenthread.sleep(0.01)
continue
while (self.running and (len(wrap.children) < wrap.workers)):
... |
'Initialize a LocaleHandler
:param locale: locale to use for translating messages
:param target: logging.Handler object to forward
LogRecord objects to after translation'
| def __init__(self, locale, target):
| logging.Handler.__init__(self)
self.locale = locale
self.target = target
|
'Setup transformer.
Each time a transformed is involved in a pipeline, a new transformer
instance is created and chained into the pipeline. i.e. transformer
instance is per pipeline. This helps if transformer need keep some
cache and per-pipeline information.
:param kwargs: The parameters that are defined in pipeline c... | def __init__(self, **kwargs):
| super(TransformerBase, self).__init__()
|
'Flush counters cached previously.
:param context: Passed from the data collector.
:param source: Source of counters that are being published.'
| def flush(self, context, source):
| return []
|
'Iterate over all images.'
| def iter_images(self, ksclient):
| client = self.get_glance_client(ksclient)
rawImageList = list(itertools.chain(client.images.list(filters={'is_public': True}), client.images.list(filters={'is_public': False})))
imageIdSet = set((image.id for image in rawImageList))
for image in rawImageList:
if (image.id in imageIdSet):
... |
'Return a sequence of ExchangeTopics defining the exchange and
topics to be connected for this plugin.'
| @staticmethod
def get_exchange_topics(conf):
| return [plugin.ExchangeTopics(exchange=conf.glance_control_exchange, topics=set(((topic + '.info') for topic in conf.notification_topics)))]
|
'Returns a nova Client object.'
| def __init__(self):
| conf = cfg.CONF.service_credentials
tenant = ((conf.os_tenant_id and conf.os_tenant_id) or conf.os_tenant_name)
self.nova_client = nova_client.Client(username=cfg.CONF.service_credentials.os_username, api_key=cfg.CONF.service_credentials.os_password, project_id=tenant, auth_url=cfg.CONF.service_credentials.... |
'Returns list of instances on particular host.'
| @logged
def instance_get_all_by_host(self, hostname):
| search_opts = {'host': hostname, 'all_tenants': True}
return self._with_flavor(self.nova_client.servers.list(detailed=True, search_opts=search_opts))
|
'Returns all floating ips.'
| @logged
def floating_ip_get_all(self):
| return self.nova_client.floating_ips.list()
|
'Return a Connection instance based on the configuration settings.'
| def get_connection(self, conf):
| return Connection(conf)
|
'Write the data to the backend storage system.
:param data: a dictionary such as returned by
ceilometer.meter.meter_message_from_counter'
| def record_metering_data(self, data):
| LOG.info('metering data %s for %s: %s', data['counter_name'], data['resource_id'], data['counter_volume'])
|
'Return an iterable of user id strings.
:param source: Optional source filter.'
| def get_users(self, source=None):
| return []
|
'Return an iterable of project id strings.
:param source: Optional source filter.'
| def get_projects(self, source=None):
| return []
|
'Return an iterable of dictionaries containing resource information.
{ \'resource_id\': UUID of the resource,
\'project_id\': UUID of project owning the resource,
\'user_id\': UUID of user owning the resource,
\'timestamp\': UTC datetime of last update to the resource,
\'metadata\': most current metadata for the resour... | def get_resources(self, user=None, project=None, source=None, start_timestamp=None, end_timestamp=None, metaquery={}, resource=None):
| return []
|
'Return an iterable of dictionaries containing meter information.
{ \'name\': name of the meter,
\'type\': type of the meter (guage, counter),
\'resource_id\': UUID of the resource,
\'project_id\': UUID of project owning the resource,
\'user_id\': UUID of user owning the resource,
:param user: Optional ID for user that... | def get_meters(self, user=None, project=None, resource=None, source=None, limit=None, metaquery={}):
| return []
|
'Return an iterable of samples as created by
:func:`ceilometer.meter.meter_message_from_counter`.'
| def get_samples(self, sample_filter):
| return []
|
'Return a dictionary containing meter statistics.
described by the query parameters.
The filter must have a meter value set.
{ \'min\':
\'max\':
\'avg\':
\'sum\':
\'count\':
\'period\':
\'period_start\':
\'period_end\':
\'duration\':
\'duration_start\':
\'duration_end\':'
| def get_meter_statistics(self, sample_filter, period=None):
| return []
|
'Yields a lists of alarms that match filters'
| def get_alarms(self, name=None, user=None, project=None, enabled=True, alarm_id=None):
| return []
|
'update alarm'
| def update_alarm(self, alarm):
| return alarm
|
'Write the events.
:param events: a list of model.Event objects.'
| def record_events(self, events):
| raise NotImplementedError('Events not implemented.')
|
'Return an iterable of model.Event objects.
:param event_filter: EventFilter instance'
| def get_events(self, event_filter):
| raise NotImplementedError('Events not implemented.')
|
'Make the model object behave like a dict.'
| def update(self, values):
| for (k, v) in values.iteritems():
setattr(self, k, v)
|
'Create a new event.
:param event_name: Name of the event.
:param generated: UTC time for when the event occured.
:param traits: list of Traits on this Event.'
| def __init__(self, event_name, generated, traits):
| Model.__init__(self, event_name=event_name, generated=generated, traits=traits)
|
'Create a new resource.
:param resource_id: UUID of the resource
:param project_id: UUID of project owning the resource
:param source: the identifier for the user/project id definition
:param user_id: UUID of user owning the resource
:param metadata: most current metadata for the resource (a dict)
:param m... | def __init__(self, resource_id, project_id, source, user_id, metadata, meter):
| Model.__init__(self, resource_id=resource_id, project_id=project_id, source=source, user_id=user_id, metadata=metadata, meter=meter)
|
'Create a new resource meter.
:param counter_name: the name of the counter updating the resource
:param counter_type: one of gauge, delta, cumulative
:param counter_unit: official units name for the sample data'
| def __init__(self, counter_name, counter_type, counter_unit):
| Model.__init__(self, counter_name=counter_name, counter_type=counter_type, counter_unit=counter_unit)
|
'Create a new meter.
:param name: name of the meter
:param type: type of the meter (guage, counter)
:param unit: unit of the meter
:param resource_id: UUID of the resource
:param project_id: UUID of project owning the resource
:param source: the identifier for the user/project id definition
:param user_id: UUID of user... | def __init__(self, name, type, unit, resource_id, project_id, source, user_id):
| Model.__init__(self, name=name, type=type, unit=unit, resource_id=resource_id, project_id=project_id, source=source, user_id=user_id)
|
'Create a new sample.
:param source: the identifier for the user/project id definition
:param counter_name: the name of the measurement being taken
:param counter_type: the type of the measurement
:param counter_unit: the units for the measurement
:param counter_volume: the measured value
:param user_id: the user that ... | def __init__(self, source, counter_name, counter_type, counter_unit, counter_volume, user_id, project_id, resource_id, timestamp, resource_metadata, message_id, message_signature):
| Model.__init__(self, source=source, counter_name=counter_name, counter_type=counter_type, counter_unit=counter_unit, counter_volume=counter_volume, user_id=user_id, project_id=project_id, resource_id=resource_id, timestamp=timestamp, resource_metadata=resource_metadata, message_id=message_id, message_signature=mess... |
'Create a new statistics object.
:param min: The smallest volume found
:param max: The largest volume found
:param avg: The average of all volumes found
:param sum: The total of all volumes found
:param count: The number of samples found
:param period: The length of the time range covered by these stats
:param period_s... | def __init__(self, min, max, avg, sum, count, period, period_start, period_end, duration, duration_start, duration_end):
| Model.__init__(self, min=min, max=max, avg=avg, sum=sum, count=count, period=period, period_start=period_start, period_end=period_end, duration=duration, duration_start=duration_start, duration_end=duration_end)
|
'Register any configuration options used by this engine.'
| def register_opts(self, conf):
| conf.register_opts(self.OPTIONS)
|
'Return a Connection instance based on the configuration settings.'
| @staticmethod
def get_connection(conf):
| return Connection(conf)
|
'Write the data to the backend storage system.
:param data: a dictionary such as returned by
ceilometer.meter.meter_message_from_counter'
| @staticmethod
def record_metering_data(data):
| session = sqlalchemy_session.get_session()
with session.begin():
if data['source']:
source = session.query(Source).get(data['source'])
if (not source):
source = Source(id=data['source'])
session.add(source)
else:
source = None
... |
'Return an iterable of user id strings.
:param source: Optional source filter.'
| @staticmethod
def get_users(source=None):
| session = sqlalchemy_session.get_session()
query = session.query(User.id)
if (source is not None):
query = query.filter(User.sources.any(id=source))
return (x[0] for x in query.all())
|
'Return an iterable of project id strings.
:param source: Optional source filter.'
| @staticmethod
def get_projects(source=None):
| session = sqlalchemy_session.get_session()
query = session.query(Project.id)
if source:
query = query.filter(Project.sources.any(id=source))
return (x[0] for x in query.all())
|
'Return an iterable of api_models.Resource instances
:param user: Optional ID for user that owns the resource.
:param project: Optional ID for project that owns the resource.
:param source: Optional source filter.
:param start_timestamp: Optional modified timestamp start range.
:param end_timestamp: Optional modified t... | @staticmethod
def get_resources(user=None, project=None, source=None, start_timestamp=None, end_timestamp=None, metaquery={}, resource=None):
| session = sqlalchemy_session.get_session()
query = session.query(Meter).group_by(Meter.resource_id)
if (user is not None):
query = query.filter((Meter.user_id == user))
if (source is not None):
query = query.filter(Meter.sources.any(id=source))
if start_timestamp:
query = que... |
'Return an iterable of api_models.Meter instances
:param user: Optional ID for user that owns the resource.
:param project: Optional ID for project that owns the resource.
:param resource: Optional ID of the resource.
:param source: Optional source filter.
:param metaquery: Optional dict with metadata to match on.'
| @staticmethod
def get_meters(user=None, project=None, resource=None, source=None, metaquery={}):
| session = sqlalchemy_session.get_session()
query = session.query(Resource)
if (user is not None):
query = query.filter((Resource.user_id == user))
if (source is not None):
query = query.filter(Resource.sources.any(id=source))
if resource:
query = query.filter((Resource.id == ... |
'Return an iterable of api_models.Samples.
:param sample_filter: Filter.
:param limit: Maximum number of results to return.'
| @staticmethod
def get_samples(sample_filter, limit=None):
| if (limit == 0):
return
session = sqlalchemy_session.get_session()
query = session.query(Meter)
query = make_query_from_filter(query, sample_filter, require_meter=False)
if limit:
query = query.limit(limit)
samples = query.all()
for s in samples:
(yield api_models.Sam... |
'Returns complex Meter counter_volume query for max and sum.'
| @staticmethod
def _make_volume_query(sample_filter, counter_volume_func):
| session = sqlalchemy_session.get_session()
subq = session.query(Meter.id)
subq = make_query_from_filter(subq, sample_filter, require_meter=False)
subq = subq.subquery()
mainq = session.query(Resource.id, counter_volume_func)
mainq = mainq.join(Meter).group_by(Resource.id)
return mainq.filter... |
'Return an iterable of api_models.Statistics instances containing
meter statistics described by the query parameters.
The filter must have a meter value set.'
| def get_meter_statistics(self, sample_filter, period=None):
| if ((not period) or (not sample_filter.start) or (not sample_filter.end)):
res = self._make_stats_query(sample_filter).all()[0]
if (not period):
(yield self._stats_result_to_model(res, 0, res.tsmin, res.tsmax))
return
query = self._make_stats_query(sample_filter)
for (period_star... |
'Yields a lists of alarms that match filters
:param user: Optional ID for user that owns the resource.
:param project: Optional ID for project that owns the resource.
:param enabled: Optional boolean to list disable alarm.
:param alarm_id: Optional alarm_id to return one alarm.'
| def get_alarms(self, name=None, user=None, project=None, enabled=True, alarm_id=None):
| session = sqlalchemy_session.get_session()
query = session.query(Alarm)
if (name is not None):
query = query.filter((Alarm.name == name))
if (enabled is not None):
query = query.filter((Alarm.enabled == enabled))
if (user is not None):
query = query.filter((Alarm.user_id == u... |
'update alarm
:param alarm: the new Alarm to update'
| def update_alarm(self, alarm):
| session = sqlalchemy_session.get_session()
with session.begin():
if alarm.alarm_id:
alarm_row = session.merge(Alarm(id=alarm.alarm_id))
self._alarm_model_to_row(alarm, alarm_row)
else:
session.merge(User(id=alarm.user_id))
session.merge(Project(id=... |
'Delete a alarm
:param alarm_id: ID of the alarm to delete'
| @staticmethod
def delete_alarm(alarm_id):
| session = sqlalchemy_session.get_session()
with session.begin():
session.query(Alarm).filter((Alarm.id == alarm_id)).delete()
session.flush()
|
'Find the UniqueName entry for a given key, creating
one if necessary.
This may result in a flush.'
| def _get_or_create_unique_name(self, key, session=None):
| if (session is None):
session = sqlalchemy_session.get_session()
with session.begin(subtransactions=True):
unique = self._get_unique(session, key)
if (not unique):
unique = UniqueName(key=key)
session.add(unique)
session.flush()
return unique
|
'Make a new Trait from a Trait model.
Doesn\'t flush or add to session.'
| def _make_trait(self, trait_model, event, session=None):
| name = self._get_or_create_unique_name(trait_model.name, session=session)
value_map = Trait._value_map
values = {'t_string': None, 't_float': None, 't_int': None, 't_datetime': None}
value = trait_model.value
if (trait_model.dtype == api_models.Trait.DATETIME_TYPE):
value = utils.dt_to_decim... |
'Store a single Event, including related Traits.'
| def _record_event(self, session, event_model):
| with session.begin(subtransactions=True):
unique = self._get_or_create_unique_name(event_model.event_name, session=session)
generated = utils.dt_to_decimal(event_model.generated)
event = Event(unique, generated)
session.add(event)
new_traits = []
if event_model.traits... |
'Write the events to SQL database via sqlalchemy.
:param event_models: a list of model.Event objects.
Flush when they\'re all added, unless new UniqueNames are
added along the way.'
| def record_events(self, event_models):
| session = sqlalchemy_session.get_session()
with session.begin():
events = [self._record_event(session, event_model) for event_model in event_models]
session.flush()
for (model, actual) in zip(event_models, events):
(actual_event, actual_traits) = actual
model.id = actual_even... |
'Return an iterable of model.Event objects.
:param event_filter: EventFilter instance'
| def get_events(self, event_filter):
| start = utils.dt_to_decimal(event_filter.start)
end = utils.dt_to_decimal(event_filter.end)
session = sqlalchemy_session.get_session()
with session.begin():
sub_query = session.query(Event.id).join(Trait, (Trait.event_id == Event.id)).filter((Event.generated >= start), (Event.generated <= end))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.