本文整理汇总了Python中gateway.models.DBSession类的典型用法代码示例。如果您正苦于以下问题:Python DBSession类的具体用法?Python DBSession怎么用?Python DBSession使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBSession类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: EditModel
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())
示例2: update_tokens
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')
示例3: make_tokens
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')
示例4: login
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}
示例5: MessageHandler
class MessageHandler(object):
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')
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(renderer='sms/delete_msg.mako')
def delete(self):
if self.request.method == 'POST':
return Response("Removed Message")
elif self.request.method == 'GET':
return {'message': self.message }
示例6: AddClass
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}
示例7: send
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)
示例8: SMSHandler
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))
示例9: findMeter
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
示例10: groupfinder
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]
示例11: job
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()))
示例12: save_and_parse_message
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
示例13: findCircuit
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
示例14: get_token
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
示例15: show_pculogs
def show_pculogs(self):
session = DBSession()
value = self.request.params.get('pcu-value', 'battery_volts')
start = datetime.strptime(
self.request.params.get('start', '05/01/2011'), '%m/%d/%Y')
end = datetime.strptime(
self.request.params.get('end', '07/20/2011'), '%m/%d/%Y')
pculogs = session.query(PCULog)\
.filter(PCULog.meter == self.meter)\
.filter(PCULog.timestamp >= start)\
.filter(PCULog.timestamp <= end)
return json_response(
{'dates': map(lambda x: time.mktime(x.timestamp.timetuple()), pculogs),
'values': map(lambda x: getattr(x, value), pculogs)})