本文整理汇总了Python中netprofile.db.connection.DBSession.query方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.query方法的具体用法?Python DBSession.query怎么用?Python DBSession.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netprofile.db.connection.DBSession
的用法示例。
在下文中一共展示了DBSession.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: postfix_mailboxes
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def postfix_mailboxes(request):
loc = get_localizer(request)
cfg = request.registry.settings
sess = DBSession()
errmess = None
csrf = request.POST.get('csrf', '')
if 'submit' in request.POST:
if csrf != request.get_csrf():
request.session.flash({
'text' : loc.translate(_('Error submitting form')),
'class' : 'danger'
})
return HTTPSeeOther(location=request.route_url('postfix.cl.mail'))
access_user = sess.query(AccessEntity).filter_by(nick=str(request.user)).first()
userdomains = sess.query(PDNSDomain).filter_by(account=str(access_user.nick))
admindomains = sess.query(PostfixDomainAdmins).filter_by(username=str(request.user))
maildomains = sess.query(PostfixDomain).filter(PostfixDomain.domain.in_([ad.domain for ad in admindomains]))
mailboxes = sess.query(PostfixMailbox).filter(PostfixMailbox.domain.in_([md.domain for md in maildomains]))
tpldef = {'errmessage':errmess,
'accessuser':access_user,
'userdomains':userdomains,
'admindomains':admindomains,
'maildomains':maildomains,
'mailboxes':mailboxes,
'aliases':None,
}
request.run_hook('access.cl.tpldef', tpldef, request)
return(tpldef)
示例2: dyn_acl_user_set
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def dyn_acl_user_set(px, request):
"""
ExtDirect method for setting user's ACLs.
"""
if 'records' not in px:
raise ValueError('No records found')
sess = DBSession()
for params in px['records']:
uid = int(params.get('owner'))
aclid = int(params.get('privid'))
code = params.get('code')
value = params.get('value')
if uid <= 0:
raise KeyError('Invalid user ID')
user = sess.query(User).get(uid)
if user is None:
raise KeyError('Invalid user ID')
if value not in {True, False, None}:
raise ValueError('Invalid capability value')
priv = sess.query(Privilege)\
.join(NPModule)\
.filter(Privilege.code == code, NPModule.enabled == True, Privilege.can_be_set == True)\
.one()
code = priv.code
if value is None:
if (code, aclid) in user.acls:
del user.acls[(code, aclid)]
else:
user.acls[(code, aclid)] = value
return { 'success' : True }
示例3: dyn_priv_group_set
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def dyn_priv_group_set(px, request):
"""
ExtDirect method for setting group's capabilities.
"""
if 'records' not in px:
raise ValueError('No records found')
sess = DBSession()
for params in px['records']:
gid = int(params.get('owner'))
privid = int(params.get('privid'))
value = params.get('value')
if gid <= 0:
raise KeyError('Invalid group ID')
group = sess.query(Group).get(gid)
if group is None:
raise KeyError('Invalid group ID')
if value not in {True, False, None}:
raise ValueError('Invalid capability value')
priv = sess.query(Privilege)\
.join(NPModule)\
.filter(Privilege.id == privid, NPModule.enabled == True, Privilege.can_be_set == True)\
.one()
code = priv.code
if value is None:
if code in group.privileges:
del group.privileges[code]
else:
group.privileges[code] = value
return { 'success' : True }
示例4: dyn_priv_group_get
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def dyn_priv_group_get(params, request):
"""
ExtDirect method for getting group's capabilities.
"""
gid = int(params.get('owner'))
if gid <= 0:
raise KeyError('Invalid group ID')
recs = []
sess = DBSession()
group = sess.query(Group).get(gid)
if group is None:
raise KeyError('Invalid group ID')
for priv in sess.query(Privilege)\
.join(NPModule)\
.filter(NPModule.enabled == True, Privilege.can_be_set == True)\
.order_by(Privilege.name):
prx = {
'privid' : priv.id,
'owner' : group.id,
'code' : priv.code,
'name' : priv.name,
'hasacls' : priv.has_acls,
'value' : None
}
if priv.code in group.caps:
prx['value'] = group.caps[priv.code].value
recs.append(prx)
return {
'records' : recs,
'total' : len(recs),
'success' : True
}
示例5: sync
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def sync(self):
to_update = []
sess = DBSession()
if len(self._pending_results) > 0:
task_uuids = [k
for k, v
in self._pending_results.items()
if v.ready()]
if len(task_uuids) > 0:
for log in sess.query(TaskLog).filter(
TaskLog.celery_id.in_(task_uuids)):
log.update(self._pending_results[log.celery_id])
to_update.append(log)
del self._pending_results[log.celery_id]
if len(self._sync_needed) > 0:
sn = self._sync_needed
for task in sess.query(Task).filter(Task.id.in_(sn.keys())):
task.last_run_time = sn[task.id].last_run_time
task.run_count = sn[task.id].run_count
to_update.append(task)
self._sync_needed = {}
self._schedule = self.get_from_db()
self.install_default_entries(self._schedule)
self._heap = None
示例6: dyn_ticket_uwiz_update
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def dyn_ticket_uwiz_update(params, request):
tid = int(params['ticketid'])
del params['ticketid']
sess = DBSession()
model = ExtModel(Ticket)
ticket = sess.query(Ticket).get(tid)
if ticket is None:
raise KeyError('Invalid ticket ID')
for param in ('tstid', 'toid', 'name', 'descr'):
if param in params:
del params[param]
# TODO: ENTITIES_LIST
if not request.has_permission('TICKETS_CHANGE_STATE'):
if 'ttrid' in params:
del params['ttrid']
if not request.has_permission('TICKETS_CHANGE_FLAGS'):
if 'flags' in params:
del params['flags']
# TODO: USERS_LIST
# TODO: GROUPS_LIST
sess.execute(SetVariable('ticketid', ticket.id))
if 'ttrid' in params:
ttr_id = params['ttrid']
if ttr_id:
ttr_id = int(ttr_id)
trans = sess.query(TicketStateTransition).get(ttr_id)
if trans:
sess.execute(SetVariable('ttrid', trans.id))
trans.apply(ticket)
del params['ttrid']
if 'show_client' in params:
show_cl = params['show_client'].lower()
if show_cl in {'true', '1', 'on'}:
show_cl = True
else:
show_cl = False
del params['show_client']
else:
show_cl = False
sess.execute(SetVariable('show_client', npbool(show_cl)))
if ('comments' in params) and request.has_permission('TICKETS_COMMENT', request.context, request):
sess.execute(SetVariable('comments', params['comments']))
del params['comments']
else:
sess.execute(SetVariable('comments', None))
model.set_values(ticket, params, request)
sess.flush()
sess.execute(SetVariable('tcid', None))
return {
'success' : True,
'action' : {
'do' : 'close',
'redraw' : []
}
}
示例7: __iter__
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def __iter__(self):
user = self.req.user
root = None
if user:
root = user.group.effective_root_folder
sess = DBSession()
# TODO: add access controls
for t in sess.query(FileFolder.name).filter(FileFolder.parent == root):
yield t[0]
for t in sess.query(File.filename).filter(File.folder == root):
yield t[0]
示例8: _cal_events
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def _cal_events(evts, params, req):
ts_from = params.get('startDate')
ts_to = params.get('endDate')
if (not ts_from) or (not ts_to):
return
cals = params.get('cals')
if isinstance(cals, Iterable) and len(cals):
try:
cals = [int(cal[5:]) for cal in cals if cal[:5] == 'user-']
except (TypeError, ValueError):
cals = ()
if len(cals) == 0:
return
else:
cals = None
ts_from = dparse(ts_from).replace(hour=0, minute=0, second=0, microsecond=0)
ts_to = dparse(ts_to).replace(hour=23, minute=59, second=59, microsecond=999999)
sess = DBSession()
cal_q = sess.query(Calendar).filter(Calendar.user == req.user)
if cals:
cal_q = cal_q.filter(Calendar.id.in_(cals))
cal_ids = [cal.id for cal in cal_q]
for cali in sess.query(CalendarImport).filter(CalendarImport.user_id == req.user.id):
cal = cali.calendar
if cal.user == req.user:
continue
if cals and (cal.id not in cals):
continue
if not cal.can_read(req.user):
continue
if cal.id in cal_ids:
continue
cal_ids.append(cal.id)
q = sess.query(Event)\
.filter(
Event.calendar_id.in_(cal_ids),
Event.event_start <= ts_to,
Event.event_end >= ts_from
)
for e in q:
ev = {
'id' : 'event-%u' % e.id,
'cid' : 'user-%u' % e.calendar_id,
'title' : e.summary,
'start' : e.event_start,
'end' : e.event_end,
'ad' : e.all_day,
'notes' : e.description,
'loc' : e.location,
'url' : e.url,
'caned' : e.calendar.can_write(req.user)
}
evts.append(ev)
示例9: get_pkpass
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def get_pkpass(request):
loc = get_localizer(request)
cfg = request.registry.settings
sess = DBSession()
client_pass = None
token = None
passserial = request.current_route_path().split('/')[-1].split("?")[0]
try:
token = request.params.get('authtoken', None)
sess = DBSession()
if token:
try:
client_pass = sess.query(PassbookPass).filter(
PassbookPass.token == token,
).one()
except NoResultFound:
raise KeyError('Invalid token')
else:
try:
client_pass = sess.query(PassbookPass).filter(
PassbookPass.serial == passserial,
).one()
token = client_pass.token
except NoResultFound:
raise KeyError('Invalid setial')
except ValueError:
pass
p12_cert = cfg.get('netprofile.client.pkpass.p12', None)
pem_cert = cfg.get('netprofile.client.pkpass.pem', None)
teamId = cfg.get('netprofile.client.pkpass.teamId', None)
passId = cfg.get('netprofile.client.pkpass.passId', None)
passfile = tempfile.NamedTemporaryFile()
pkpass = P.PyPKPass.PKPass.PKPass(passId, passserial)
pkpass.webServiceURL = request.url.split("?")[0]
pkpass.authenticationToken = token
pkpass.backgroundColor="rgb(23, 187, 82)"
pkpass.teamIdentifier=teamId
pkpass.passTypeIdentifier=passId
pkpass.addHeaderField("Name", "Netprofile Account", 'My Netprofile Account Details')
pkpass.addPrimaryField("username", client_pass.stash.entity.nick, "Username")
pkpass.addPrimaryField("Account Name", client_pass.stash.name, 'Account Name')
pkpass.addSecondaryField("Amount", "{0}".format(client_pass.stash.amount), "Amont")
pkpass.addSecondaryField("Credit", "{0}".format(client_pass.stash.credit), "Credit")
pkpass.sign(p12_cert, "", passfile.name, pem_cert)
resp = FileResponse(passfile.name)
resp.content_disposition = 'attachment; filename="{0}.pkpass"'.format(passId)
return resp
示例10: dav_children
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def dav_children(self):
user = self.req.user
root = None
if user:
root = user.group.effective_root_folder
sess = DBSession()
for t in itertools.chain(
sess.query(FileFolder).filter(FileFolder.parent == root),
sess.query(File).filter(File.folder == root)
):
t.__req__ = self.req
t.__parent__ = self
t.__plugin__ = self
yield t
示例11: ff_tree_update
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def ff_tree_update(params, request):
sess = DBSession()
user = request.user
root_ff = user.group.effective_root_folder
for rec in params.get('records', ()):
ff_id = rec.get('id')
if ff_id == 'root':
continue
ff_id = int(ff_id)
ff_name = rec.get('text')
ff_parent = rec.get('parentId')
# TODO: support changing uid/gid and rights, maybe?
if not ff_name:
raise ValueError('Empty folder names are not supported')
if ff_parent and (ff_parent != 'root'):
ff_parent = int(ff_parent)
else:
ff_parent = None
ff = sess.query(FileFolder).get(ff_id)
if ff is None:
raise KeyError('Unknown folder ID %d' % ff_id)
if root_ff and (not ff.is_inside(root_ff)):
raise ValueError('Folder access denied')
cur_parent = ff.parent
if cur_parent and ((not cur_parent.can_write(user)) or (not cur_parent.can_traverse_path(user))):
raise ValueError('Folder access denied')
ff.name = ff_name
if ff_parent:
new_parent = sess.query(FileFolder).get(ff_parent)
if new_parent is None:
raise KeyError('Unknown parent folder ID %d' % ff_parent)
if (not new_parent.can_write(user)) or (not new_parent.can_traverse_path(user)):
raise ValueError('Folder access denied')
if root_ff and (not new_parent.is_inside(root_ff)):
raise ValueError('Folder access denied')
if new_parent.is_inside(ff):
raise ValueError('Folder loop detected')
ff.parent = new_parent
elif not user.root_writable:
raise ValueError('Folder access denied')
else:
ff.parent = None
return {
'success' : True
}
示例12: find_princs_digest
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def find_princs_digest(param, request):
sess = DBSession()
try:
user = sess.query(User).filter(User.state == UserState.active,
User.enabled.is_(True),
User.login == param['username']).one()
except NoResultFound:
return None
if not user.password_ha1:
return None
req_path = unquote(request.path.lower())
uri_path = unquote(param['uri'].lower())
if req_path != uri_path:
return None
ha2 = hashlib.md5(('%s:%s' % (request.method,
param['uri'])).encode()).hexdigest()
data = '%s:%s:%s:%s:%s' % (param['nonce'], param['nc'],
param['cnonce'], 'auth', ha2)
resp = hashlib.md5(('%s:%s' % (user.password_ha1,
data)).encode()).hexdigest()
if hmac.compare_digest(resp, param['response']):
groups = ['g:%s' % (user.group.name,)]
for sgr in user.secondary_groups:
if sgr == user.group:
continue
groups.append('g:%s' % (sgr.name,))
return groups
return None
示例13: get_settings
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def get_settings(request):
# FIXME: implement settings cache invalidation
if 'auth.settings' in request.session:
return request.session['auth.settings']
mmgr = request.registry.getUtility(IModuleManager)
all_settings = mmgr.get_settings('user')
user = request.user
if user is None:
ret = {}
for moddef, sections in all_settings.items():
for sname, section in sections.items():
for setting_name, setting in section.items():
if setting.default is None:
continue
ret['%s.%s.%s' % (moddef,
sname,
setting_name)] = setting.default
else:
sess = DBSession()
ret = dict(
(s.name, s.value)
for s
in sess.query(UserSetting).filter(UserSetting.user == user))
for moddef, sections in all_settings.items():
for sname, section in sections.items():
for setting_name, setting in section.items():
fullname = '%s.%s.%s' % (moddef, sname, setting.name)
if fullname in ret:
ret[fullname] = setting.parse_param(ret[fullname])
elif setting.default is not None:
ret[fullname] = setting.default
request.session['auth.settings'] = ret
return ret
示例14: _cal_events_update
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def _cal_events_update(params, req):
cal_id = params.get('CalendarId', '')
if cal_id != _cal['id']:
return
if 'EventId' not in params:
return
evtype, evid = params['EventId'].split('-')
if evtype != 'ticket':
return
evid = int(evid)
if not has_permission('TICKETS_UPDATE', req.context, req):
return
sess = DBSession()
tkt = sess.query(Ticket).get(evid)
if tkt is None:
return
sess.execute(SetVariable('ticketid', tkt.id))
if 'StartDate' in params:
new_ts = dparse(params['StartDate']).replace(tzinfo=None, microsecond=0)
if new_ts:
tkt.assigned_time = new_ts
if ('EndDate' in params) and tkt.assigned_time:
new_ts = dparse(params['EndDate']).replace(tzinfo=None, microsecond=0)
if new_ts:
delta = new_ts - tkt.assigned_time
tkt.duration = delta.seconds
示例15: dyn_globalsettings_form
# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import query [as 别名]
def dyn_globalsettings_form(param, request):
"""
ExtDirect method to populate a global settings form.
"""
node = param['section']
path = node.split('.')
if len(path) != 2:
raise ValueError('Invalid section node ID specified: %r' % (node,))
moddef = path[0]
sname = path[1]
mmgr = request.registry.getUtility(IModuleManager)
if moddef not in mmgr.loaded:
raise ValueError('Unknown, uninstalled or disabled module name requested: %r' % (moddef,))
all_settings = mmgr.get_settings('global')
if moddef not in all_settings or sname not in all_settings[moddef]:
raise ValueError('Setting doesn\'t exist: %r' % (node,))
form = []
section = all_settings[moddef][sname]
sess = DBSession()
values = dict(
(s.name, s.value)
for s
in sess.query(GlobalSetting).filter(
GlobalSetting.name.startswith('%s.%s.' % (moddef, sname))
)
)
for setting_name, setting in section.items():
fullname = '%s.%s.%s' % (moddef, sname, setting_name)
if fullname in values:
values[fullname] = setting.parse_param(values[fullname])
return section.get_form_cfg(request, moddef, values)