本文整理汇总了Python中sngconnect.database.DBSession.query方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.query方法的具体用法?Python DBSession.query怎么用?Python DBSession.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sngconnect.database.DBSession
的用法示例。
在下文中一共展示了DBSession.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_message
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def create_message(self, message):
DBSession.add(message)
DBSession.flush()
if message.confirmation_required:
if message.feed is not None:
users = DBSession.query(User).join(
FeedUser
).filter(
FeedUser.feed == message.feed,
).all()
else:
users = DBSession.query(User).all()
self.confirmations.set_unconfirmed(
[user.id for user in users],
message.id
)
if message.send_notifications:
if message.feed is not None:
self.notification_service.notify_feed_users(
message.feed,
# TODO What to send in email subject and SMS notification?
"",
message
)
else:
self.notification_service.notify_all(
# TODO What to send in email subject and SMS notification?
"",
message
)
示例2: test_reset_requested_value
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def test_reset_requested_value(self):
# Request value in data stream.
self.assertEqual(
DBSession.query(DataStream).filter(
DataStream.id == 2
).value('requested_value'),
1234
)
# Pretend value has not yet been set by tinyputer - requested_value
# still exists.
request = self.get_request(1, 'data_stream_2', json_body={
'datapoints': [
{
'at': '2012-10-13T17:01:00.345123Z',
'value': '134.2344',
},
{
'at': '2012-10-13T17:02:00.425Z',
'value': '-23.24525',
},
]
})
response = views.feed_data_stream(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(
DBSession.query(DataStream).filter(
DataStream.id == 2
).value('requested_value'),
1234
)
# Pretend value has been set by tinyputer - requested_value reset.
request = self.get_request(1, 'data_stream_2', json_body={
'datapoints': [
{
'at': '2012-10-13T17:02:30.345123Z',
'value': '1234',
},
]
})
#with transaction.manager
response = views.feed_data_stream(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(
DBSession.query(DataStream).filter(
DataStream.id == 2
).value('requested_value'),
None
)
request = self.get_request(1, 'data_stream_2', json_body={
'datapoints': [
{
'at': '2012-10-13T17:03:30.345123Z',
'value': '4321',
},
]
})
response = views.feed_data_stream(request)
self.assertEqual(response.status_code, 200)
示例3: insert_data_points
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def insert_data_points(feed_id, data_stream, data_points, message_service):
Measurements().insert_data_points(data_stream.id, data_points)
# FIXME This may be not wise for production use due to race condition
# concerns.
dates = map(lambda x: x[0], data_points)
HourlyAggregates().recalculate_aggregates(data_stream.id, dates)
DailyAggregates().recalculate_aggregates(data_stream.id, dates)
MonthlyAggregates().recalculate_aggregates(data_stream.id, dates)
LastDataPoints().update(feed_id, data_stream.id)
last_date, last_value = LastDataPoints().get_last_data_stream_data_point(
feed_id,
data_stream.id
)
last_value = decimal.Decimal(last_value)
# Turn alarms associated with datastreams on/off
alarm_definitions = DBSession.query(AlarmDefinition).filter(
AlarmDefinition.data_stream_id == data_stream.id
)
alarm_messages = []
alarms_on = []
alarms_off = []
for alarm_definition in alarm_definitions:
message_content = alarm_definition.check_value(last_value)
if message_content is None:
alarms_off.append(alarm_definition.id)
else:
alarms_on.append(alarm_definition.id)
alarm_messages.append(
Message(
feed=alarm_definition.data_stream.feed,
data_stream=alarm_definition.data_stream,
message_type='ERROR',
date=last_date,
content=message_content
)
)
Alarms().set_alarms_on(feed_id, data_stream.id, alarms_on, last_date)
Alarms().set_alarms_off(feed_id, data_stream.id, alarms_off)
for message in alarm_messages:
message_service.create_message(message)
# Set requested value to None if applied.
if data_stream.writable and data_stream.requested_value is not None:
error = abs(data_stream.requested_value - last_value)
maximal_error = (
decimal.Decimal(str(sys.float_info.epsilon)) * max((
2 ** -1022,
abs(data_stream.requested_value),
abs(last_value))
)
)
if error <= maximal_error:
DBSession.query(DataStream).filter(
DataStream.id == data_stream.id
).update({
'requested_value': None,
'value_requested_at': None,
})
示例4: feed_template_delete
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def feed_template_delete(request):
try:
feed_template = DBSession.query(FeedTemplate).filter(
FeedTemplate.id == request.matchdict['feed_template_id']
).one()
except database_exceptions.NoResultFound:
raise httpexceptions.HTTPNotFound()
delete_form = forms.DeleteFeedTemplateForm(
feed_template_id=feed_template.id,
csrf_context=request
)
delete_form.process(request.POST)
if delete_form.validate():
dependent_feed_count = DBSession.query(Feed).filter(
Feed.template == feed_template
).count()
dependent_data_stream_template_count = DBSession.query(
DataStreamTemplate
).filter(
DataStreamTemplate.feed_template == feed_template
).count()
if dependent_feed_count > 0:
request.session.flash(
_(
"Device template cannot be deleted as there are"
" already devices based on it. Contact the system"
" support for further information."
),
queue='error'
)
elif dependent_data_stream_template_count > 0:
request.session.flash(
_(
"Device template cannot be deleted as it has parameter"
" templates assigned to it. Contact the system support for"
" further information."
),
queue='error'
)
else:
DBSession.delete(feed_template)
request.session.flash(
_("Device template has been successfully deleted."),
queue='success'
)
else:
request.session.flash(
_(
"There were some problems with your request."
" Contact the system support."
),
queue='error'
)
return httpexceptions.HTTPFound(
request.route_url('sngconnect.devices.feed_templates')
)
示例5: test_normal_operation
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def test_normal_operation(self):
request = self.get_request(1)
response = views.feed(request)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(
json.loads(response.body),
{'datastreams': [],}
)
DBSession.query(DataStream).filter(DataStream.id == 2).update({
'requested_value': decimal.Decimal('2345.5'),
'value_requested_at': _utc_datetime(2012, 10, 9, 12, 34, 11),
})
#transaction.commit()
request = self.get_request(1)
response = views.feed(request)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(
json.loads(response.body),
{
u'datastreams': [
{
u'id': u'2',
u'label': u'data_stream_2',
u'requested_value': u'2345.5000000000000000000000000',
u'value_requested_at': u'2012-10-09T12:34:11+00:00',
},
],
}
)
DBSession.query(DataStream).filter(DataStream.id == 2).update({
'requested_value': decimal.Decimal('-144.25'),
'value_requested_at': _utc_datetime(2012, 10, 9, 12, 35, 11),
})
#transaction.commit()
request = self.get_request(1)
response = views.feed(request)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(
json.loads(response.body),
{
u'datastreams': [
{
u'id': u'2',
u'label': u'data_stream_2',
u'requested_value': u'-144.2500000000000000000000000',
u'value_requested_at': u'2012-10-09T12:35:11+00:00',
},
],
}
)
示例6: data_stream_template_delete
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def data_stream_template_delete(request):
try:
feed_template, data_stream_template = DBSession.query(
FeedTemplate,
DataStreamTemplate
).filter(
FeedTemplate.id == request.matchdict['feed_template_id'],
(DataStreamTemplate.id ==
request.matchdict['data_stream_template_id']),
DataStreamTemplate.feed_template_id == FeedTemplate.id
).one()
except database_exceptions.NoResultFound:
raise httpexceptions.HTTPNotFound()
delete_form = forms.DeleteDataStreamTemplateForm(
data_stream_template_id=data_stream_template.id,
csrf_context=request,
locale=get_locale_name(request)
)
delete_form.process(request.POST)
if delete_form.validate():
dependent_count = DBSession.query(DataStream).filter(
DataStream.template == data_stream_template
).count()
if dependent_count == 0:
DBSession.delete(data_stream_template)
request.session.flash(
_("Parameter template has been successfully deleted."),
queue='success'
)
else:
request.session.flash(
_(
"Parameter template cannot be deleted as there are"
" already parameters based on it. Contact the system"
" support for further information."
),
queue='error'
)
else:
request.session.flash(
_(
"There were some problems with your request."
" Contact the system support."
),
queue='error'
)
return httpexceptions.HTTPFound(
request.route_url(
'sngconnect.devices.feed_template',
feed_template_id=feed_template.id
)
)
示例7: set_requested_value
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def set_requested_value(self, data_stream, value):
DBSession.query(DataStream).filter(
DataStream.id == data_stream.id
).update({
'requested_value': value,
'value_requested_at': pytz.utc.localize(
datetime.datetime.utcnow()
),
})
self.registry['scheduler'].add_date_job(
DataStreamService.assert_requested_value,
datetime.datetime.now() + self._requested_value_timeout,
[self.registry, data_stream.id]
)
示例8: validate_name
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def validate_name(self, field):
if field.errors:
return
try:
DBSession.query(ChartDefinition).filter(
ChartDefinition.feed_template == self.feed_template,
ChartDefinition.feed == None,
ChartDefinition.name == field.data
).one()
except database_exceptions.NoResultFound:
pass
else:
raise validators.ValidationError(
_("This chart name is already taken.")
)
示例9: activate
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def activate(request):
successful_activation = False
try:
user = DBSession.query(User).filter(
User.email == request.matchdict['email'],
User.email_activation_code ==
request.matchdict['email_activation_code'],
User.activated == None
).one()
except database_exceptions.NoResultFound:
raise httpexceptions.HTTPNotFound()
activation_form = forms.ActivationForm(csrf_context=request)
if request.method == 'POST':
activation_form.process(request.POST)
if activation_form.validate():
if (user.phone_activation_code.upper() !=
activation_form.phone_activation_code.data.upper()):
request.session.flash(
_("The activation code you entered is invalid."),
queue='error'
)
else:
# Regenerate activation code so user cannot reactivate his
# account after being banned.
user.regenerate_email_activation_code()
user.activated = pytz.utc.localize(datetime.datetime.utcnow())
DBSession.add(user)
successful_activation = True
return {
'activation_form': activation_form,
'successful_activation': successful_activation,
}
示例10: upload_log
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def upload_log(request):
"""
Store new piece of log sent by tinyputer. Logs can be sent as a response to 'upload_log' command
which created placeholder LogRequest objects.
Parameters:
log_request_id
log_request_hash
"""
try:
log_request_id = int(request.matchdict['log_request_id'])
log_request_hash = str(request.matchdict['log_request_hash'])
except (KeyError, ValueError):
raise httpexceptions.HTTPNotFound("Invalid request arguments.")
try:
log_request = DBSession.query(LogRequest).filter(
LogRequest.id == log_request_id,
LogRequest.hash == log_request_hash,
LogRequest.log == None
).one()
except database_exceptions.NoResultFound:
raise httpexceptions.HTTPNotFound("Log request not found.")
log_request.log = request.body
DBSession.add(log_request)
return Response()
示例11: commands
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def commands(request):
"""
Issue commands FOR the device
"""
try:
feed_id = int(request.matchdict['feed_id'])
except (KeyError, ValueError):
raise httpexceptions.HTTPNotFound("Invalid request arguments.")
authorize_request(request, feed_id)
commands = DBSession.query(
Command.command,
Command.arguments,
).filter(
Command.feed_id == feed_id,
)
cstruct = schemas.GetCommandsResponse().serialize({
'commands': [
{
'command': command.command,
'arguments': command.arguments,
}
for command in commands
]
})
return Response(
json.dumps(cstruct),
content_type='application/json'
)
示例12: get_all_feed_users
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def get_all_feed_users(self, feed):
return DBSession.query(User).join(
FeedUser
).filter(
FeedUser.feed == feed
).order_by(
self.default_order
).all()
示例13: validate_email
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def validate_email(self, field):
count = DBSession.query(User).filter(
User.email == field.data
).count()
if count != 0:
raise validators.ValidationError(
_("There is already an account registered with this e-mail"
" address.")
)
示例14: assert_requested_value
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def assert_requested_value(cls, registry, data_stream_id):
data_stream = DBSession.query(DataStream).filter(
DataStream.id == data_stream_id
).one()
if data_stream is None:
return
timeout_time_ago = (
pytz.utc.localize(datetime.datetime.utcnow())
- cls._requested_value_timeout
)
if (data_stream.requested_value is not None and
data_stream.value_requested_at <= timeout_time_ago):
with transaction.manager:
DBSession.query(DataStream).filter(
DataStream.id == data_stream.id
).update({
'requested_value': None,
'value_requested_at': None,
})
message = Message(
feed=data_stream.feed,
data_stream=data_stream,
message_type='ERROR',
date=pytz.utc.localize(datetime.datetime.utcnow()),
content=_(
"${feed_name} did not respond to the request.",
mapping={
'feed_name': data_stream.feed.name,
}
)
)
notification_service = NotificationService(registry)
with transaction.manager:
notification_service.notify_feed_users(
data_stream.feed,
_(
"Unable to set parameter ${parameter_name}.",
mapping={
'parameter_name': data_stream.name
}
),
message
)
示例15: set_user_permissions
# 需要导入模块: from sngconnect.database import DBSession [as 别名]
# 或者: from sngconnect.database.DBSession import query [as 别名]
def set_user_permissions(self):
if not self.can_manage_users:
raise httpexceptions.HTTPForbidden()
post_items = filter(
lambda x: x[0].startswith('role-'),
self.request.POST.iteritems()
)
feed_user_roles = {}
feed_users_to_delete = []
for key, value in post_items:
value = value.strip()
try:
id = int(key.split('-')[1])
except (IndexError, ValueError):
continue
if value:
feed_user_roles[id] = value
else:
feed_users_to_delete.append(id)
DBSession.query(FeedUser).filter(
FeedUser.feed == self.feed,
FeedUser.id.in_(feed_users_to_delete),
FeedUser.user_id != self.user_id
).delete(synchronize_session=False)
for feed_user_id, role in feed_user_roles.iteritems():
DBSession.query(FeedUser).filter(
FeedUser.feed == self.feed,
FeedUser.id == feed_user_id,
FeedUser.user_id != self.user_id
).update({
'role': role
}, synchronize_session=False)
self.request.session.flash(
_("User permissions have been successfully saved."),
queue='success'
)
return httpexceptions.HTTPFound(
self.request.route_url(
'sngconnect.telemetry.feed_permissions',
feed_id=self.feed.id
)
)