本文整理匯總了Python中gateway.models.DBSession.add方法的典型用法代碼示例。如果您正苦於以下問題:Python DBSession.add方法的具體用法?Python DBSession.add怎麽用?Python DBSession.add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類gateway.models.DBSession
的用法示例。
在下文中一共展示了DBSession.add方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: update_tokens
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [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: make_tokens
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [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')
示例3: save_and_parse_message
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
def save_and_parse_message(interface, origin, text, id=None):
"""
"""
session = DBSession()
if id is None:
id = str(uuid.uuid4())
message = IncomingMessage(origin, text, id, interface)
session.add(message)
session.flush()
dispatcher.matchMessage(message)
return message
示例4: InterfaceHandler
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [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'})
return {'interface': self.interface,
'breadcrumbs': breadcrumbs,
'fields': get_fields(self.interface),
'logged_in': authenticated_userid(self.request)}
def save_and_parse_message(self, origin, text, id=None):
"""
Function to save incoming message based on relay type. Takes the
message class, the numner, the body of the message and a
session. Optional argument is the messages id. Parses the message
and return the message object.
"""
if id is None:
id = str(uuid.uuid4())
message = IncomingMessage(origin, text, id, self.interface)
self.session.add(message)
self.session.flush()
dispatcher.matchMessage(message)
return message
@action()
def send(self):
msg = self.save_and_parse_message(self.request.params['number'],
self.request.params['message'])
return Response(msg.uuid)
@action()
def remove(self):
self.session.delete(self.interface)
self.session.flush()
return HTTPFound(location="%s/" % self.request.application_url)
示例5: add_credit
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
def add_credit(message):
"""Allows consumer to add credit to their account.
Sends an outgoing message to the consumer.
"""
session = DBSession()
circuit = get_circuit(message)
token = get_token(message)
if circuit:
interface = circuit.meter.communication_interface
if token:
job = AddCredit(circuit=circuit, credit=token.value, token=token)
session.add(job)
session.flush()
interface.sendJob(job,
incoming=message.uuid)
session.merge(circuit)
session.flush()
示例6: pp
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
def pp(self):
"""
Primary log action. Should force the meter to provide authentication
"""
params = parse_qs(self.request.body)
session = DBSession()
if not self.meter or not self.circuit:
return Response(status=404)
log = PrimaryLog(circuit=self.circuit,
watthours=params["wh"][0],
use_time=params["tu"][0],
credit=params["cr"][0],
status=int(params["status"][0]))
self.circuit.credit = float(log.credit)
self.circuit.status = int(params["status"][0]) # fix
session.add(log)
session.merge(self.circuit)
return Response("ok")
示例7: add
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
def add(self):
errors = None
session = DBSession()
groups = session.query(Groups).all()
breadcrumbs = self.breadcrumbs[:]
breadcrumbs.append({'text': 'Add a new user'})
if self.request.method == 'GET':
return {'breadcrumbs': breadcrumbs,
'groups': groups,
'errors': errors}
elif self.request.method == 'POST':
name = self.request.params['name']
email = self.request.params['email']
password = self.request.params['password']
group = self.request.params['group']
user = Users(name=name, email=email,
group_id=group,
password=password)
session.add(user)
session.flush()
return HTTPFound(location='/')
示例8: parse_meter_message
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
def parse_meter_message(message):
"""
Parse message from the Meter. Takes a message object and returns
nothing. Logs an exception if the message is unable to be parsed.
TODO XXX this needs to be cleaned up
"""
session = DBSession()
meter = findMeter(message)
# compressed primary logs
if re.match("^\(l.*\)$", message.text):
inflatedlogs = compactsms.inflatelogs([message.text])
for log in inflatedlogs:
m = reduce_message(parse_qs(log))
circuit = findCircuit(m, meter)
meter_funcs.make_pp(m, circuit, session)
# old messages
elif re.match("(\w+) online", message.text.lower()):
meter_funcs.make_meter_online_alert(message, meter, session)
elif re.match("^\(.*\)$", message.text.lower()):
if message.text.startswith('(pcu'):
make_pcu_logs(message, meter, session)
else:
messageDict = clean_message(message)
if messageDict["job"] == "delete":
getattr(meter_funcs, "make_" + messageDict["job"])(messageDict, session)
else:
circuit = findCircuit(messageDict, meter)
if circuit: # double check that we have a circuit
if messageDict['job'] == "pp":
getattr(meter_funcs, "make_" + messageDict["job"])(messageDict, circuit, session)
elif messageDict['job'] == "alert":
if messageDict['alert'] == 'online':
meter_funcs.make_meter_online_alert(message, meter, session)
else:
getattr(meter_funcs, "make_" + messageDict["alert"])(messageDict, circuit, session)
else:
session.add(SystemLog(
'Unable to parse message %s' % message.uuid))
示例9: add_meter
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [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: CircuitHandler
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
#.........這裏部分代碼省略.........
return {
'logged_in': authenticated_userid(self.request),
'breadcrumbs': breadcrumbs,
'circuit': self.circuit}
@action(permission='admin')
def turn_off(self):
self.circuit.turnOff()
return HTTPFound(location=self.circuit.getUrl())
@action(permission='admin')
def turn_on(self):
self.circuit.turnOn()
return HTTPFound(location=self.circuit.getUrl())
@action(permission='admin')
def ping(self):
self.circuit.ping()
return HTTPFound(location=self.circuit.getUrl())
@action(permission='admin')
def remove_jobs(self):
[self.session.delete(job) for job in self.circuit.get_jobs()]
return HTTPFound(
location="%s%s" % (self.request.application_url,
self.circuit.getUrl()))
@action()
def jobs(self):
return Response([x.toJSON() for x in self.circuit.get_jobs()])
@action()
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])
@action()
def show_graphing_logs(self):
session = DBSession()
value = self.request.params.get('value', 'watthours')
start = datetime.strptime(self.request.params.get('start', '05/01/2011'), '%m/%d/%Y')
end = datetime.strptime(self.request.params.get('end', '06/01/2011'), '%m/%d/%Y')
logs = session.query(PrimaryLog)\
.filter(PrimaryLog.circuit == self.circuit)\
.filter(PrimaryLog.date > start)\
.filter(PrimaryLog.date <= end)\
.order_by(PrimaryLog.created)
if value == 'use_time':
values = map(lambda x: (getattr(x, value) / 3600), logs)
else:
values = map(lambda x: getattr(x, value), logs)
return json_response(
{'dates': map(lambda x: time.mktime(x.date.timetuple()), logs),
'values': values }
)
@action(permission='view')
def get_payment_logs(self):
"""
A view to render a circuit's payment history as a json object.
"""
session = DBSession()
payments = session.query(AddCredit)\
.filter_by(circuit=self.circuit).order_by(desc(AddCredit.start))
return json_response(
{'payments': [{'id': p.id,
'status': p.state,
'token': str(p.token),
'start': str(p.start),
'credit': p.credit,
'end': str(p.end),
'state': p.state} for p in payments]})
@action(permission='admin')
def add_credit(self):
interface = self.circuit.meter.communication_interface
job = AddCredit(circuit=self.circuit,
credit=self.request.params.get("amount"))
self.session.add(job)
self.session.flush()
interface.sendJob(job)
return HTTPFound(location=self.circuit.getUrl())
@action(permission="admin")
def remove(self):
self.session.delete(self.circuit)
return HTTPFound(location=self.meter.getUrl())
示例11: MeterHandler
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
#.........這裏部分代碼省略.........
.query(MeterChangeSet).filter_by(meter=self.meter),
'meter_config_keys': session.query(MeterConfigKey).all(),
'breadcrumbs': breadcrumbs}
@action()
def update_config(self):
return Response('ok')
@action(renderer='meter/messsage_graph.mako', permission='view')
def message_graph(self):
""" Message table.
"""
output = cStringIO.StringIO()
d = collections.defaultdict(list)
logs = self.meter.getLogs()
cids = sorted([c.id for c in self.meter.get_circuits()])
for log in logs:
d[log.date.strftime('%Y.%m.%d.%H.%M')].append(log)
for key in sorted(d.iterkeys(), reverse=True):
log_cids = [log.circuit.id for log in d[key]]
output.write(str(key) + " | ")
output.write(" ".join([str(x).ljust(3) if x in
log_cids else ' - ' for x in cids]))
output.write("\n")
return Response(output.getvalue(), content_type="text/plain")
@action(permission='admin')
def show_account_numbers(self):
""" Returns the account numbers as a csv file.
"""
output = cStringIO.StringIO()
output.write('Pin, IpAddress \n')
for c in self.meter.get_circuits():
output.write('%s, %s\n' % (c.pin, c.ip_address))
resp = Response(output.getvalue())
resp.content_type = 'application/x-csv'
resp.headers.add('Content-Disposition',
'attachment;filename=%s:accounts.csv' % \
str(self.meter.name))
return resp
# this serialization should be a class method.
@action(permission='view')
def circuits(self):
now = datetime.now()
last_month = now - timedelta(days=30)
return json_response(
[{'id':x.id,
'ipaddress': x.ip_address,
'language': x.account.lang,
'watthours': x.getWatthours(),
'last_msg': x.getLastLogTime(),
'credit_consumed': int(x.calculateCreditConsumed(last_month, now)),
'status': x.status,
'number_of_recharges': x.get_number_of_recharges(),
'account': x.pin,
'credit': int(x.credit)
}
for x in self.meter.get_circuits()]
)
@action()
def geometry(self):
point = loads(self.meter.geometry)
return Response(
content_type='application/json',
示例12: ManageHandler
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
class ManageHandler(object):
"""
"""
def __init__(self, request):
self.request = request
self.session = DBSession()
self.breadcrumbs = breadcrumbs[:]
@action(renderer='manage/index.mako')
def index(self):
return {
'breadcrumbs': self.breadcrumbs}
@action(renderer='manage/show_alerts.mako', permission='view')
def show_alerts(self):
return {'breadcrumbs': self.breadcrumbs}
@action(renderer='manage/meters.mako', permission='view')
def show_meters(self):
return {'breadcrumbs': self.breadcrumbs}
@action(permission='view')
def show_meters_json(self):
session = DBSession()
return json_response(
[
{'name': m.name,
'id': m.id,
'number_of_circuits': len(m.get_circuits()),
'uptime': find_meter_uptime(m),
'pv': m.panel_capacity,
'last_message': find_last_message_by_meter(m),
'phone': m.phone,
'battery': m.battery,
'location': m.location
} for m in session.query(Meter).all()
]
)
@action(renderer='manage/show_gaps.mako', permission='view')
def show_gaps(self):
return {'breadcrumbs': self.breadcrumbs}
@action(permission='view')
def show_gaps_json(self):
default_end = datetime.now() + timedelta(days=1)
end = datetime.strptime(
self.request.params.get('end', default_end.strftime("%m/%d/%Y")), '%m/%d/%Y')
default_start = end - timedelta(days=7)
start = datetime.strptime(self.request.params.get('start', default_start.strftime("%m/%d/%Y")), '%m/%d/%Y')
gap_seconds = int(self.request.params.get('gap', '5400'))
gap_res_set = PrimaryLog.get_gap_result(start, end, gap_seconds)
gap_rec_list = [dict(rec) for rec in gap_res_set]
for i in range(0, len(gap_rec_list)):
gap_rec_list[i]['id'] = i
return Response(
content_type='application/json',
body=simplejson.dumps(
gap_rec_list,
default = lambda obj: obj.isoformat() if isinstance(obj, datetime) else None))
@action(renderer='manage/add_meter.mako', permission='admin')
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
#.........這裏部分代碼省略.........
示例13: Dashboard
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
class Dashboard(object):
"""
Home page for the gateway
"""
def __init__(self, request):
self.request = request
self.breadcrumbs = breadcrumbs[:]
self.session = DBSession()
@action(renderer='index.mako', permission="view")
def index(self):
batchSchema = TokenBatchSchema()
batchForm = Form(batchSchema, buttons=('Add tokens',))
meters = self.session.query(Meter)
interfaces = self.session.query(CommunicationInterface).all()
tokenBatchs = self.session.query(TokenBatch).all()
system_logs = self.session.query(SystemLog).\
order_by(desc(SystemLog.created)).all()
return {
'batchForm': batchForm,
'interfaces': interfaces,
'logged_in': authenticated_userid(self.request),
'tokenBatchs': tokenBatchs,
'system_logs': system_logs,
'meters': meters,
'breadcrumbs': self.breadcrumbs }
@action(renderer="dashboard.mako", permission="admin")
def dashboard(self):
return {
"logged_in": authenticated_userid(self.request),
}
@action(renderer="meter/add.mako", permission="admin")
def add_meter(self):
breadcrumbs = self.breadcrumbs
breadcrumbs.append({"text": "Add a new meter"})
return form_route(self,
Meter,
buttons=['add_meter', 'Add new circuit'],
exludes=['slug',
'uuid',
'date'],
breadcrumbs=breadcrumbs)
@action(renderer='add_interface.mako', permission='admin')
def add(self):
_type = self.request.params.get('class')
cls = getattr(models, _type)
breadcrumbs = self.breadcrumbs[:]
breadcrumbs.append({'text': 'Add a new %s ' % _type})
return form_route(self,
cls,
buttons=['submit', 'Add new %s' % _type],
breadcrumbs=breadcrumbs)
@action(permission="admin")
def add_tokens(self):
self.request.params
batch = TokenBatch()
self.session.add(batch)
amount = self.request.params.get("amount", 100)
value = int(self.request.params.get("value", 10))
for number in xrange(0, int(amount)):
self.session.add(Token(
token=Token.get_random(),
value=value,
batch=batch))
return HTTPFound(location=self.request.application_url)
@action(permission="admin")
def upload_tokens(self):
csvReader = csv.reader(self.request.params['csv'].file, delimiter=',')
batch = TokenBatch()
self.session.add(batch)
header = csvReader.next()
for line in csvReader:
self.session.add(Token(
token=line[1],
value=line[2],
batch=batch))
return HTTPFound(location=self.request.application_url)
@action()
def system_logs(self):
return Response(
simplejson.dumps(
[x.text for x in self.session.query(SystemLog).all()]))
@action(permission="admin")
def send_message(self):
params = self.request.params
msgClass = getattr(models, params['delivery-type'])
msg = msgClass(
number=params.get("number"),
text=params.get("text"))
self.session.add(msg)
self.session.flush()
return HTTPFound(location=self.request.application_url)
示例14: CircuitHandler
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
#.........這裏部分代碼省略.........
@action(renderer="circuit/index.mako", permission="admin")
def index(self):
breadcrumbs = self.breadcrumbs[:]
breadcrumbs.extend([
{"text": "Meter Overview", "url": self.meter.getUrl()},
{"text": "Circuit Overview"}])
return {
"logged_in": authenticated_userid(self.request),
"breadcrumbs": breadcrumbs,
"jobs": self.circuit.get_jobs(),
"fields": get_fields(self.circuit),
"circuit": self.circuit }
@action(renderer="circuit/edit.mako", permission="admin")
def edit(self):
breadcrumbs = self.breadcrumbs
breadcrumbs.extend([
{"text": "Meter Overview", "url": self.meter.getUrl()},
{"text": "Circuit Overview", "url": self.circuit.url()},
{"text": "Circuit Edit"}])
return {
"logged_in": authenticated_userid(self.request),
"breadcrumbs": breadcrumbs,
"fields": get_fields(self.circuit),
"circuit": self.circuit }
@action(permission="admin")
def update(self):
circuit = model_from_request(
self.request, self.circuit)
self.session.merge(circuit)
return HTTPFound(
location="%s%s" % (self.request.application_url,
self.circuit.getUrl()))
@action(permission="admin")
def turn_off(self):
self.circuit.turnOff()
return HTTPFound(location=self.circuit.getUrl())
@action(permission="admin")
def turn_on(self):
self.circuit.turnOn()
return HTTPFound(location=self.circuit.getUrl())
@action(permission="admin")
def ping(self):
self.circuit.ping()
return HTTPFound(location=self.circuit.getUrl())
@action(permission="admin")
def remove_jobs(self):
[self.session.delete(job) for job in self.circuit.get_jobs()]
return HTTPFound(
location="%s%s" % (self.request.application_url,
self.circuit.getUrl()))
@action(renderer="circuit/build_graph.mako", permission="admin")
def build_graph(self):
return {
"logged_in": authenticated_userid(self.request),
"circuit": self.circuit }
@action(renderer="circuit/show_graph.mako", permission="admin")
def show_graph(self):
query = self.session.query(PrimaryLog)
params = self.request.params
# parse the date from the request
origin = parser.parse(params["from"])
to = parser.parse(params["to"])
yaxis = params["yaxis"]
logs = [x for x in query.all() if x.created > origin]
logs = [x for x in logs if x.created < to]
return {
"logged_in": authenticated_userid(self.request),
"data": [{"time": str(x.created.ctime()),
"value": x.get_property(yaxis)} for x in logs ],
"y_units": simplejson.dumps(params["yaxis"]),
"origin": simplejson.dumps(params["from"]),
"to": simplejson.dumps(params["to"])}
@action()
def jobs(self):
return Response([x.toJSON() for x in self.circuit.get_jobs()])
@action(permission="admin")
def add_credit(self):
interface = self.circuit.meter.communication_interface
job = AddCredit(circuit=self.circuit,
credit=self.request.params.get("amount"))
self.session.add(job)
self.session.flush()
interface.sendJob(job)
return HTTPFound(location=self.circuit.getUrl())
@action(permission="admin")
def remove(self):
self.session.delete(self.circuit)
return HTTPFound(location=self.meter.getUrl())
示例15: MeterHandler
# 需要導入模塊: from gateway.models import DBSession [as 別名]
# 或者: from gateway.models.DBSession import add [as 別名]
class MeterHandler(object):
"""
Meter handler, allows for user to edit and manage meters
"""
def __init__(self, request):
self.request = request
self.session = DBSession()
self.meter = self.session.query(Meter).\
filter_by(slug=self.request.matchdict['slug']).one()
self.breadcrumbs = breadcrumbs[:]
@action(renderer="meter/index.mako", permission="admin")
def index(self):
breadcrumbs = self.breadcrumbs[:]
breadcrumbs.append({"text": "Meter Overview"})
circuit_data = make_table_data(self.meter.get_circuits())
return {
"logged_in": authenticated_userid(self.request),
"meter": self.meter,
"circuit_header": make_table_header(Circuit),
"circuit_data": circuit_data,
"fields": get_fields(self.meter),
"breadcrumbs": breadcrumbs }
@action(request_method='POST', permission="admin")
def add_circuit(self):
params = self.request.params
pin = params.get("pin")
if len(pin) == 0:
pin = Circuit.get_pin()
account = Account(
lang=params.get("lang"),
phone=params.get("phone"))
circuit = Circuit(meter=self.meter,
account=account,
pin=pin,
ip_address=params.get("ip_address"),
energy_max=int(params.get("energy_max")),
power_max=int(params.get("power_max")))
self.session.add(account)
self.session.add(circuit)
self.session.flush()
return HTTPFound(location="%s%s" % (
self.request.application_url, self.meter.getUrl()))
@action(renderer="meter/edit.mako", permission="admin")
def edit(self):
return {
"fields": get_fields(self.meter),
"meter": self.meter }
@action(renderer="meter/build_graph.mako", permission="admin")
def build_graph(self):
return {
"logged_in": authenticated_userid(self.request),
"meter": self.meter }
@action(renderer="meter/show_graph.mako", permission="admin")
def show_graph(self):
#needs to be implemented
return {}
@action(permission="admin")
def logs(self):
days = int(self.request.params.get('days', 10))
date = datetime.now()
logs = find_meter_logs(meter=self.meter,
date=date, session=self.session,
days=days)
return Response(
simplejson.dumps(logs),
content_type='application/json')
@action(permission="admin")
def update(self):
meter = model_from_request(self.request,
self.meter)
self.session.merge(meter)
return HTTPFound(
location="%s%s" % (self.request.application_url,
self.meter.getUrl()))
@action(permission="admin")
def remove(self):
self.session.delete(self.meter)
[self.session.delete(x)
for x in self.session.query(Circuit).filter_by(meter=self.meter)]
return HTTPFound(location="/")
@action(permission="admin")
def ping(self):
job = Mping(self.meter)
self.session.add(job)
self.session.flush()
msgClass = self.meter.getMessageType(job=True)
self.session.add(msgClass(job, self.meter.phone, incoming=""))
return HTTPFound(location=self.meter.getUrl())