本文整理汇总了Python中gateway.models.DBSession.query方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.query方法的具体用法?Python DBSession.query怎么用?Python DBSession.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gateway.models.DBSession
的用法示例。
在下文中一共展示了DBSession.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_tokens
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def update_tokens(self):
"""
We need to record these updates to token states and provide a
way to view this in the Gateway Interface.
"""
session = DBSession()
data = simplejson.loads(self.request.body)
if not 'device_id' in data:
return json_response('You must provide an device_id')
device = session.query(Device)\
.filter_by(device_id=data['device_id']).first()
if device:
for i in data['tokens']:
token = session.query(Token)\
.filter_by(token=i['token_id']).first()
if token:
circuit = session.query(Circuit)\
.filter_by(pin=i['account_id']).first()
if circuit:
job = AddCredit(token.value, circuit, token)
session.add(job)
token.state = 'used'
session.merge(token)
session.flush()
return json_response('ok')
else:
return json_response('You must provide a valid device_id')
示例2: SMSHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
class SMSHandler(object):
"""
Handler for most SMS operations
"""
def __init__(self, request):
self.request = request
self.breadcrumbs = breadcrumbs[:]
self.session = DBSession()
@action(renderer="sms/index.mako", permission="view")
def index(self):
breadcrumbs = self.breadcrumbs[:]
breadcrumbs.append({"text": "SMS Message"})
limit = self.request.params.get('limit', 1000)
count = self.session.query(Message).count()
messages = self.session.\
query(Message).order_by(desc(Message.id)).limit(limit)
return {
"limit": limit,
"count": count,
"messages": messages,
"table_headers": make_table_header(OutgoingMessage),
"breadcrumbs": breadcrumbs}
@action(renderer='sms/meter_messages.mako', permission='view')
def meter_messages(self):
from sqlalchemy import create_engine
db_string = self.request.registry.settings.get('db_string')
engine = create_engine(db_string, echo=False)
conn = engine.connect()
results = conn.execute(
"""
SELECT meter.name, meter.id, incoming_message.text, message.date
FROM meter, message, incoming_message
WHERE meter.phone = message.number
AND message.id = incoming_message.id ORDER BY message.date DESC LIMIT 1000;
""")
return {'results': results}
@action(permission="view")
def remove_all(self):
[self.session.delete(msg) for msg in self.session.query(Message).all()]
return HTTPFound(
location="%s/sms/index" % self.request.application_url)
@action()
def ping(self):
return Response('ok')
@action()
def received(self):
msgs = [msg.toDict() for msg in self.session.query(Message).\
filter_by(sent=False).filter(or_(Message.type == "job_message",
Message.type == "outgoing_message")).all()
if msg.number != '']
return Response(
content_type="application/json",
body=simplejson.dumps(msgs))
示例3: login
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def login(self):
session = DBSession()
came_from = self.request.params.get('came_from', '/')
message = ''
login = ''
password = ''
if 'form.submitted' in self.request.params:
name = self.request.params['name']
hash = hashlib.md5(self.request.params['password']).hexdigest()
user = session.query(Users)\
.filter_by(name=name)\
.filter_by(password=unicode(hash)).first()
if user:
print(name, hash)
headers = remember(self.request, user.name)
return HTTPFound(
location="%s" % came_from,
headers=headers)
message = 'Failed login'
return {
'message': message,
'url': self.request.application_url + '/login',
'came_from': came_from,
'login': login,
'password': password}
示例4: make_tokens
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def make_tokens(self):
session = DBSession()
batch = TokenBatch()
session.add(batch)
session.flush()
data = simplejson.loads(self.request.body)
if not 'device_id' in data:
return Response('You must provide an device_id')
else:
device = session.query(Device)\
.filter_by(device_id=data['device_id']).first()
if device:
if not 'tokens' in data:
return Response('You must provide an amount of tokens')
for group in data['tokens']:
for i in range(0, group['count']):
token = Token(Token.get_random(),
batch=batch,
value=group['denomination'])
session.add(token)
session.flush()
return json_response(
[{'token_id': int(token.token),
'denomination':
float(token.value)} for token in batch.getTokens()])
else:
return json_response('Not a valid device')
示例5: send
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def send(self):
session = DBSession()
twilio = session.query(TwilioInterface).first()
msg = save_and_parse_message(twilio,
self.request.params['From'],
self.request.params['Body'],
id=self.request.params['SmsMessageSid'])
return Response(msg.uuid)
示例6: groupfinder
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def groupfinder(userid, request):
"""
Rough cut of user admin system.
"""
session = DBSession()
user = session.query(Users).filter_by(name=userid).first()
if user:
if user.group:
return [user.group.name]
示例7: findMeter
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def findMeter(message):
"""
Takes a message object and returns either a meter or none.
Looks up the meter based on the message's number.
"""
session = DBSession()
meter = session.query(Meter).filter_by(phone=str(message.number)).first()
if meter:
return meter
示例8: SMSHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
class SMSHandler(object):
"""
Handler for most SMS operations
"""
def __init__(self, request):
self.request = request
self.breadcrumbs = breadcrumbs[:]
self.session = DBSession()
@action(renderer="sms/index.mako", permission="admin")
def index(self):
breadcrumbs = self.breadcrumbs[:]
breadcrumbs.append({"text": "SMS Message"})
limit = self.request.params.get('limit', 1000)
count = self.session.query(Message).count()
messages = self.session.\
query(Message).order_by(desc(Message.id)).limit(limit)
return {
"logged_in": authenticated_userid(self.request),
"limit": limit,
"count": count,
"messages": messages,
"table_headers": make_table_header(OutgoingMessage),
"breadcrumbs": breadcrumbs }
@action(permission="admin")
def remove_all(self):
[self.session.delete(msg) for msg in self.session.query(Message).all()]
return HTTPFound(
location="%s/sms/index" % self.request.application_url)
@action()
def ping(self):
return Response('ok')
@action()
def received(self):
msgs = [msg.toDict() for msg in self.session.query(Message).\
filter_by(sent=False).filter(or_(Message.type == "job_message",
Message.type == "outgoing_message")).all()
if msg.number != '']
return Response(
content_type="application/json",
body=simplejson.dumps(msgs))
示例9: add_meter
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def add_meter(self):
session = DBSession()
if self.request.method == 'GET':
comms = session.query(CommunicationInterface).all()
return {'comms': comms,
'breadcrumbs': self.breadcrumbs
}
elif self.request.method == 'POST':
comm = session.query(CommunicationInterface)\
.get(int(self.request.params.get('communication-interface')))
meter_name = self.request.params.get('meter-name')
meter_phone = self.request.params.get('meter-phone')
meter_location = self.request.params.get('meter-location')
batter_capacity = self.request.params.get('battery-capacity')
panel_capacity = self.request.params.get('panel-capacity')
meter = Meter(name=meter_name,
phone=meter_phone,
location=meter_location,
geometry='POINT(1 1)',
battery=batter_capacity,
status=True,
panel_capacity=panel_capacity,
communication_interface_id=comm.id)
# save the meter
session.add(meter)
session.flush()
# start at mains as every meter needs a mains
start_ip_address = 200
for x in range(0, int(self.request.params.get('number-of-circuits'))):
ip_address = '192.168.1.%s' % (start_ip_address + x)
# create an account for each circuit
account = Account(lang=self.request.params.get('default-language'))
session.add(account)
session.flush()
# create the circuit
circuit = Circuit(
meter=meter,
account=account,
ip_address=ip_address,
power_max=self.request.params.get('power-emax'),
energy_max=self.request.params.get('default-emax'))
session.add(circuit)
session.flush()
return HTTPFound(location='/manage/show_meters')
示例10: job
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def job(self):
session = DBSession()
job = session.query(Job).get(self.request.matchdict["id"])
if self.request.method == "DELETE":
job.state = False
job.end = datetime.now()
session.merge(job)
return Response(str(job))
else:
return Response(simplejson.dumps(job.toDict()))
示例11: FunctionalTests
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
class FunctionalTests(unittest.TestCase):
""" Unit tests for the Gateway UI """
def setUp(self):
self.config = testing.setUp()
import ConfigParser
from gateway.models import DBSession
from gateway.models import initialize_sql
config = ConfigParser.ConfigParser()
config.readfp(open('testing.ini'))
db_string = config.get('app:gateway', 'db_string')
initialize_sql(db_string)
from gateway import main
from webtest import TestApp
app = main(None, **{'db_string': db_string,
'mako.directories': config.get('app:gateway', 'mako.directories')})
self.testapp = TestApp(app)
self.session = DBSession()
def tearDown(self):
testing.tearDown()
def test_number_of_meter(self):
from gateway.models import Meter
meters = self.session.query(Meter).all()
self.assertEquals(len(meters), 1)
def test_index(self):
res = self.testapp.get('/', status=200)
self.assertEquals(res.status, '200 ok')
def test_number_of_circuits(self):
from gateway.models import Circuit
circuits = self.session.query(Circuit).all()
self.assertEquals(len(circuits), 11)
def test_number_of_comm_interfaces(self):
from gateway.models import CommunicationInterface
interfaces = self.session.query(CommunicationInterface).all()
self.assertEquals(len(interfaces), 1)
def test_balance_english(self):
from gateway.models import CommunicationInterface
from gateway.models import Circuit
示例12: findCircuit
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def findCircuit(message, meter):
"""Looks up circuit from meter and message.
"""
session = DBSession()
try:
circuit = session.query(Circuit).\
filter_by(ip_address=message["cid"]).\
filter_by(meter=meter).first()
if circuit:
return circuit
except Exception as e:
print e, message
示例13: get_token
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def get_token(message):
"""Tries to match message to token."""
session = DBSession()
tokenNumber = message.text.split(delimiter)[2]
token = session.query(Token).filter_by(state="new").filter_by(token=tokenNumber).first()
if token:
return token
else:
interface = message.communication_interface
interface.sendMessage(
message.number, make_message_body("no-token.txt", lang=message.langauge), incoming=message.uuid
)
return False
示例14: InterfaceHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
class InterfaceHandler(object):
"""
A handler for managing the interfaces.
"""
def __init__(self, request):
self.breadcrumbs = breadcrumbs
self.request = request
self.session = DBSession()
self.interface = self.session.query(
CommunicationInterface).get(self.request.matchdict.get('id'))
@action(renderer='interface/index.mako', permission='admin')
def index(self):
breadcrumbs = self.breadcrumbs[:]
breadcrumbs.append({'text': 'Interface overview'})
messages = self.session.query(IncomingMessage)\
.filter_by(communication_interface=self.interface)\
.order_by(desc(IncomingMessage.id))\
.limit(200)
return {'interface': self.interface,
'breadcrumbs': breadcrumbs,
'messages': messages,
'fields': get_fields(self.interface)}
@action()
def send(self):
msg = save_and_parse_message(
self.interface,
self.request.params['number'],
self.request.params['message'])
return Response(msg.uuid)
@action(permission='admin')
def remove(self):
self.session.delete(self.interface)
self.session.flush()
return HTTPFound(location="%s/" % self.request.application_url)
示例15: show_primary_logs
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import query [as 别名]
def show_primary_logs(self):
session = DBSession()
logs = session.query(PrimaryLog)\
.filter_by(circuit=self.circuit)\
.order_by(desc(PrimaryLog.created))\
.limit(200)
return json_response([{'id': l.id,
'status': l.status,
'use_time': l.use_time,
'gateway_date': l.created.strftime('%Y-%m-%d %H:%M:%S'),
'meter_date': l.date.strftime('%Y-%m-%d %H:%M:%S'),
'time_difference': find_time_different(l),
'watthours': "{0:.1f}".format(l.watthours),
'credit': int(l.credit)} for l in logs])