本文整理汇总了Python中gateway.models.DBSession.flush方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.flush方法的具体用法?Python DBSession.flush怎么用?Python DBSession.flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gateway.models.DBSession
的用法示例。
在下文中一共展示了DBSession.flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AddClass
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [as 别名]
class AddClass(RestView):
"""
An genertic view that allows for adding models to our system.
"""
def __init__(self, request):
self.request = request
self.session = DBSession()
self.cls = self.look_up_class()
self.breadcrumbs = breadcrumbs[:]
self.breadcrumbs\
.append({'text': 'Add a new %s' % self.cls.__name__})
def get(self):
fs = FieldSet(self.cls, session=self.session)
return {
'breadcrumbs': self.breadcrumbs,
'fs': fs, 'cls': self.cls}
def post(self):
fs = FieldSet(self.cls, session=self.session).\
bind(self.cls(), data=self.request.POST)
if fs.validate():
fs.sync()
self.session.flush()
return HTTPFound(location=fs.model.getUrl())
else:
return {'fs': fs, 'cls': self.cls}
示例2: MessageHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [as 别名]
class MessageHandler(object):
""" Handler that allows the system to manage messages
"""
def __init__(self, request):
self.session = DBSession()
self.request = request
self.message = self.session.\
query(Message).filter_by(
uuid=self.request.matchdict["id"]).first()
@action(renderer='sms/index_msg.mako', permission='admin')
def index(self):
global breadcrumbs
breadcrumbs.extend({})
return {
'breadcrumbs': breadcrumbs,
'message': self.message}
@action(request_method="POST")
def remove(self):
self.message.sent = True
self.session.merge(self.message)
return Response("ok")
@action(permission='admin')
def delete(self):
self.session.delete(self.message)
self.session.flush()
return HTTPFound(location='/')
示例3: update_tokens
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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')
示例4: make_tokens
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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: EditModel
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [as 别名]
class EditModel(RestView):
"""
A view that allows models to be edited. Takes the class name as a
string parameter and returns the correct html form.
"""
def __init__(self, request):
self.request = request
self.session = DBSession()
self.cls = self.look_up_class()
self.instance = self.look_up_instance()
self.breadcrumbs = breadcrumbs[:]
self.breadcrumbs.append({'text': 'Edit %s' % self.instance})
def get(self):
fs = FieldSet(self.instance)
return {'fs': fs,
'breadcrumbs': self.breadcrumbs[:],
'instance': self.instance,
'cls': self.cls}
def post(self):
fs = FieldSet(self.instance,
data=self.request.POST)
if fs.validate():
fs.sync()
self.session.flush()
return HTTPFound(location=fs.model.getUrl())
示例6: save_and_parse_message
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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
示例7: InterfaceHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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)
示例8: add_credit
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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()
示例9: add
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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='/')
示例10: InterfaceHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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)
示例11: add_meter
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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')
示例12: CircuitHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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())
示例13: MeterHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [as 别名]
#.........这里部分代码省略.........
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',
body=simplejson.dumps(
{'type': 'FeatureCollection',
'features': [{
'type':'Feature',
'geometry': {'type': 'Point',
'coordinates': list(point.coords)[0]},
'properties': {}
}]}))
@action(renderer='meter/grid_graph.mako')
def grid_graph(self):
return {'meter': self.meter}
@action(request_method='POST', permission="admin")
def add_circuit(self):
"""A view that allows users to add an circuit to an
"""
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,
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 Response(simplejson.dumps(circuit.id))
@action(permission="admin")
def remove(self):
"""Allows users to remove an meter.
"""
[self.session.delete(c)
for c in self.session.query(Circuit).filter_by(meter=self.meter)]
self.session.delete(self.meter)
return HTTPFound(location="/manage/show_meters")
@action(permission="admin")
def ping(self):
job = Mping(self.meter)
self.session.add(job)
self.session.flush()
interface = self.meter.communication_interface
interface.sendJob(job)
return HTTPFound(location=self.meter.getUrl())
示例14: MeterHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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())
示例15: CircuitHandler
# 需要导入模块: from gateway.models import DBSession [as 别名]
# 或者: from gateway.models.DBSession import flush [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())