本文整理汇总了Python中netprofile.db.connection.DBSession类的典型用法代码示例。如果您正苦于以下问题:Python DBSession类的具体用法?Python DBSession怎么用?Python DBSession使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBSession类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: disable
def disable(self, moddef):
"""
Remove a module from the list of enabled modules.
"""
from netprofile_core.models import NPModule
if moddef not in self.modules:
logger.error(
'Can\'t find module "%s". Verify installation and try again.',
moddef)
return False
if moddef in self.loaded:
if not self.unload(moddef): # pragma: no cover
logger.error('Can\'t unload module "%s".', moddef)
return False
sess = DBSession()
try:
mod = sess.query(NPModule).filter(NPModule.name == moddef).one()
except NoResultFound:
return False
if not mod.enabled:
return True
mod.enabled = False
transaction.commit()
return True
示例2: client_chrate
def client_chrate(ctx, request):
loc = get_localizer(request)
csrf = request.POST.get('csrf', '')
rate_id = int(request.POST.get('rateid'), 0)
aent_id = int(request.POST.get('entityid'))
ent = request.user.parent
err = True
if csrf == request.get_csrf():
sess = DBSession()
aent = sess.query(AccessEntity).get(aent_id)
if ent and aent and (aent.parent == ent) and (aent in ctx.access_entities):
err = False
if 'clear' in request.POST:
rate_id = None
aent.next_rate_id = None
elif rate_id > 0:
aent.next_rate_id = rate_id
if err:
request.session.flash({
'text' : loc.translate(_('Error scheduling rate change')),
'class' : 'danger'
})
elif rate_id:
request.session.flash({
'text' : loc.translate(_('Rate change successfully scheduled'))
})
else:
request.session.flash({
'text' : loc.translate(_('Rate change successfully cancelled'))
})
return HTTPSeeOther(location=request.route_url('stashes.cl.accounts', traverse=()))
示例3: client_promise
def client_promise(ctx, request):
loc = get_localizer(request)
csrf = request.POST.get('csrf', '')
diff = request.POST.get('diff', '')
if 'submit' in request.POST:
sess = DBSession()
if csrf != request.get_csrf():
request.session.flash({
'text' : loc.translate(_('Error submitting form')),
'class' : 'danger'
})
return HTTPSeeOther(location=request.route_url('stashes.cl.accounts', traverse=()))
fp = FuturePayment()
fp.stash = ctx
fp.entity = request.user.parent
fp.origin = FuturePaymentOrigin.user
fp.difference = diff
sess.add(fp)
request.session.flash({
'text' : loc.translate(_('Successfully added new promised payment'))
})
return HTTPSeeOther(location=request.route_url('stashes.cl.accounts', traverse=()))
request.session.flash({
'text' : loc.translate(_('Error submitting form')),
'class' : 'danger'
})
return HTTPSeeOther(location=request.route_url('stashes.cl.accounts', traverse=()))
示例4: task_generate
def task_generate(srv_ids=(), station_ids=()):
cfg = app.settings
factory = ConfigGeneratorFactory(cfg, app.mmgr)
ret = []
sess = DBSession()
loc = sys_localizer(app.mmgr.cfg.registry)
q = sess.query(Server)
if len(srv_ids) > 0:
q = q.filter(Server.id.in_(srv_ids))
if len(station_ids) > 0:
q = q.filter(Server.host_id.in_(station_ids))
for srv in q:
gen = factory.get(srv.type.generator_name)
logger.info('Generating config of type %s for host %s', srv.type.generator_name, str(srv.host))
gen.generate(srv)
ret.append(loc.translate(_('Successfully generated %s configuration for host %s.')) % (
srv.type.name,
str(srv.host)
))
hosts = factory.deploy()
ret.append(loc.translate(_('Successfully deployed configuration for hosts: %s.')) % (', '.join(hosts),))
factory.restore_umask()
transaction.commit()
return ret
示例5: client_upload
def client_upload(request):
csrf = request.POST.get('csrf', '')
mode = request.POST.get('mode', '')
if not mode:
raise HTTPForbidden('Invalid upload use')
if csrf != request.get_csrf():
raise HTTPForbidden('Error uploading file')
sess = DBSession()
# FIXME: add folder cfg
tpldef = []
for fo in request.POST.getall('files'):
obj = File()
if fo.filename:
obj.name = obj.filename = fo.filename
sess.add(obj)
obj.set_from_file(fo.file, None, sess)
signal = request.run_hook('access.cl.upload', obj, mode, request, sess, tpldef)
if True not in signal:
tpldef.append({
'name' : obj.filename,
'size' : obj.size,
'error' : _('Error uploading file')
})
sess.delete(obj)
tpldef = { 'files' : tpldef }
request.run_hook('access.cl.tpldef.upload', tpldef, request)
return tpldef
示例6: dyn_priv_group_get
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
}
示例7: get_settings
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
示例8: dav_create
def dav_create(self, req, name, rtype=None, props=None, data=None):
# TODO: externalize type resolution
user = req.user
sess = DBSession()
if rtype and (dprops.COLLECTION in rtype):
obj = FileFolder(
user_id=user.id,
group_id=user.group_id,
name=name,
parent=None,
rights=F_DEFAULT_DIRS
)
sess.add(obj)
else:
obj = File(
user_id=user.id,
group_id=user.group_id,
filename=name,
name=name,
folder=None,
rights=F_DEFAULT_FILES
)
sess.add(obj)
if data is not None:
# TODO: detect type of data (fd / buffer)
obj.set_from_file(data, user, sess)
if props and (dprops.CONTENT_TYPE in props):
obj.mime_type = props[dprops.CONTENT_TYPE]
if props:
if dprops.CREATION_DATE in props:
obj.creation_time = props[dprops.CREATION_DATE]
if dprops.LAST_MODIFIED in props:
obj.modification_time = props[dprops.LAST_MODIFIED]
return (obj, False)
示例9: dav_children
def dav_children(self):
sess = DBSession()
for u in sess.query(User):
u.__req__ = self.req
u.__parent__ = self
u.__plugin__ = self
yield u
示例10: main
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
config = setup_config(settings)
reg = threadlocal.get_current_registry()
factory = pyramid_mako.MakoRendererFactory()
name_resolver = DottedNameResolver()
lookup_opts = pyramid_mako.parse_options_from_settings(settings, 'mako.', name_resolver.maybe_resolve)
lookup_opts.update({
'default_filters' : ['context[\'self\'].ddl.ddl_fmt']
})
factory.lookup = pyramid_mako.PkgResourceTemplateLookup(**lookup_opts)
reg.registerUtility(factory, IRendererFactory, name='.mak')
sess = DBSession()
mm = ModuleManager(config)
sess.execute(SetVariable('accessuid', 0))
sess.execute(SetVariable('accessgid', 0))
sess.execute(SetVariable('accesslogin', '[CREATEDB]'))
mm.scan()
mm.install('core', sess)
for moddef in mm.modules:
if moddef != 'core':
mm.install(moddef, sess)
示例11: dyn_globalsettings_form
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)
示例12: _cal_events_update
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
示例13: _cal_events
def _cal_events(evts, params, req):
if not has_permission('TICKETS_LIST', req.context, req):
return
ts_from = params.get('startDate')
ts_to = params.get('endDate')
if (not ts_from) or (not ts_to):
return
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()
q = sess.query(Ticket)\
.filter(
Ticket.assigned_time <= ts_to,
IntervalSeconds(Ticket.assigned_time, Ticket.duration) >= ts_from
)
for tkt in q:
ev = {
'id' : 'ticket-%d' % tkt.id,
'cid' : _cal['id'],
'title' : tkt.name,
'start' : tkt.assigned_time,
'end' : tkt.end_time,
'notes' : tkt.description,
'apim' : 'tickets',
'apic' : 'Ticket',
'apiid' : tkt.id,
'caned' : False
}
evts.append(ev)
示例14: sync
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
示例15: ff_tree_delete
def ff_tree_delete(params, request):
sess = DBSession()
user = request.user
root_ff = user.group.effective_root_folder
total = 0
for rec in params.get('records', ()):
ff_id = rec.get('id')
if ff_id == 'root':
continue
ff_id = int(ff_id)
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')
if (not cur_parent) and (not user.root_writable):
raise ValueError('Folder access denied')
# Extra precaution
if ff.user != user:
raise ValueError('Folder access denied')
sess.delete(ff)
total += 1
return {
'success' : True,
'total' : total
}