当前位置: 首页>>代码示例>>Python>>正文


Python DBSession.add方法代码示例

本文整理汇总了Python中netprofile.db.connection.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在netprofile.db.connection.DBSession的用法示例。


在下文中一共展示了DBSession.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: file_ul

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
def file_ul(request):
	sess = DBSession()
	try:
		ff_id = request.POST['ffid']
	except KeyError:
		ff_id = None
	folder = None
	if ff_id:
		ff_id = int(ff_id)
		folder = sess.query(FileFolder).get(ff_id)
	if folder and not folder.can_write(request.user):
		raise ValueError('Folder access denied')
	for fo in request.POST.getall('file'):
		obj = File(
			user_id=request.user.id,
			user=request.user,
			group_id=request.user.group.id,
			group=request.user.group,
			rights=F_DEFAULT_FILES
		)
		if fo.filename:
			obj.name = obj.filename = fo.filename
		obj.folder = folder
		sess.add(obj)
		obj.set_from_file(fo.file, request.user, sess)
	res = Response(html_escape(json.dumps({
		'success' : True,
		'msg'     : 'File(s) uploaded'
	}), False))
	res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN'))
	return res
开发者ID:hermes-jr,项目名称:npui,代码行数:33,代码来源:views.py

示例2: xop_request

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
def xop_request(ctx, request):
	# TODO: add optional redirect-to-site?
	if not ctx.can_access(request):
		raise HTTPForbidden('Access Denied')
	gw = ctx.get_gateway()
	if (not gw) or (not hasattr(gw, 'process_request')):
		raise HTTPForbidden('Access Denied')
	if not callable(gw.process_request):
		raise HTTPForbidden('Access Denied')

	try:
		sess = DBSession()
		xoplist = gw.process_request(request, sess)
	except Exception as e:
		# TODO: cancel and log?
		raise HTTPForbidden('Access Denied')
	for xop in xoplist:
		ctx.check_operation(xop)
		sess.add(xop)

	if hasattr(gw, 'generate_response') and callable(gw.generate_response):
		return gw.generate_response(request, xoplist)

	resp = Response(body='OK', content_type='text/plain', charset='UTF-8')
	return resp
开发者ID:baloon11,项目名称:npui,代码行数:27,代码来源:views.py

示例3: dav_create

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
	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)
开发者ID:annndrey,项目名称:npui,代码行数:36,代码来源:dav.py

示例4: client_upload

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
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
开发者ID:baloon11,项目名称:npui,代码行数:29,代码来源:views.py

示例5: client_promise

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
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=()))
开发者ID:nikitos,项目名称:npui,代码行数:32,代码来源:views.py

示例6: dyn_usersettings_submit

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
def dyn_usersettings_submit(param, request):
	"""
	ExtDirect method for submitting user setting section form.
	"""

	sess = DBSession()
	s = None
	if 'auth.settings' in request.session:
		s = request.session['auth.settings']
	for (ust, us) in sess \
		.query(UserSettingType, UserSetting) \
		.outerjoin(UserSetting, and_(
			UserSettingType.id == UserSetting.type_id,
			UserSetting.user_id == request.user.id
		)) \
		.filter(UserSettingType.name.in_(param.keys())):
			if ust.name in param:
				if us:
					us.value = ust.param_to_db(param[ust.name])
				else:
					us = UserSetting()
					us.user = request.user
					us.type = ust
					us.value = ust.param_to_db(param[ust.name])
					sess.add(us)
				if s:
					s[ust.name] = ust.parse_param(param[ust.name])
	if s:
		request.session['auth.settings'] = s
	return {
		'success' : True
	}
开发者ID:hermes-jr,项目名称:npui,代码行数:34,代码来源:views.py

示例7: dyn_usersettings_submit

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
def dyn_usersettings_submit(param, request):
	"""
	ExtDirect method for submitting user settings form.
	"""

	sess = DBSession()
	mmgr = request.registry.getUtility(IModuleManager)
	cached = None
	if 'auth.settings' in request.session:
		cached = request.session['auth.settings']

	all_settings = mmgr.get_settings('user')
	values = dict(
		(s.name, s)
		for s
		in sess.query(UserSetting).filter(UserSetting.user == request.user)
	)

	for moddef, sections in all_settings.items():
		for sname, section in sections.items():
			if section.read_cap and not request.has_permission(section.read_cap):
				continue
			for setting_name, setting in section.items():
				if setting.read_cap and not request.has_permission(setting.read_cap):
					continue
				if setting.write_cap and not request.has_permission(setting.write_cap):
					continue
				fullname = '%s.%s.%s' % (moddef, sname, setting_name)
				old_value = setting.default
				if fullname in values:
					old_value = setting.parse_param(values[fullname].value)
				new_value = old_value
				if fullname in param:
					new_value = setting.parse_param(param[fullname])

				if new_value == setting.default:
					if fullname in values:
						sess.delete(values[fullname])
						del values[fullname]
					if cached:
						cached[fullname] = setting.default
					continue
				if new_value != old_value:
					if fullname in values:
						values[fullname].value = setting.format_param(new_value)
					else:
						values[fullname] = UserSetting(
							user=request.user,
							name=fullname,
							value=setting.format_param(new_value)
						)
						sess.add(values[fullname])
					if cached:
						cached[fullname] = new_value

	if cached:
		request.session['auth.settings'] = cached
	return { 'success' : True }
开发者ID:annndrey,项目名称:npui,代码行数:60,代码来源:views.py

示例8: clone

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
	def clone(self, req, ctx, recurse=True, _flush=True):
		sess = DBSession()
		obj = ctx.dav_clone(req)
		sess.add(obj)
		if recurse:
			for ch in self.children(ctx):
				newch = self.clone(req, ch, recurse, False)
				obj.dav_append(req, newch, ch.__name__)
		return obj
开发者ID:baloon11,项目名称:npui,代码行数:11,代码来源:__init__.py

示例9: _wizcb_future_submit

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
def _wizcb_future_submit(wiz, em, step, act, val, req):
	sess = DBSession()
	obj = FuturePayment()
	em.set_values(obj, val, req, True)
	sess.add(obj)
	return {
		'do'     : 'close',
		'reload' : True
	}
开发者ID:annndrey,项目名称:npui,代码行数:11,代码来源:models.py

示例10: _cal_events_create

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
def _cal_events_create(params, req):
	sess = DBSession()
	ev = Event()
	ev.creation_time = dt.datetime.now()
	if not _ev_set(sess, ev, params, req):
		del ev
		return False
	ev.user = req.user
	sess.add(ev)
	return True
开发者ID:hermes-jr,项目名称:npui,代码行数:12,代码来源:views.py

示例11: dav_sync_token

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
	def dav_sync_token(self):
		varname = 'DAV:SYNC:ABC:%u' % (self.user.id,)
		try:
			var = NPVariable.get_ro(varname)
		except NoResultFound:
			sess = DBSession()
			cvar = NPVariable.get_ro('DAV:SYNC:PLUG:UABOOKS')
			var = NPVariable(name=varname, integer_value=cvar.integer_value)
			sess.add(var)
		return var.integer_value
开发者ID:annndrey,项目名称:npui,代码行数:12,代码来源:dav.py

示例12: _wizcb_aent_submit

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
 def _wizcb_aent_submit(wiz, em, step, act, val, req):
     sess = DBSession()
     em = ExtModel(AccessEntity)
     obj = AccessEntity()
     # Work around field name clash
     if 'state' in val:
         del val['state']
     em.set_values(obj, val, req, True)
     sess.add(obj)
     return {'do': 'close', 'reload': True}
开发者ID:unikmhz,项目名称:npui,代码行数:12,代码来源:models.py

示例13: _wizcb_stashio_submit

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
def _wizcb_stashio_submit(wiz, em, step, act, val, req):
    sess = DBSession()
    obj = StashIO()
    em.set_values(obj, val, req, True)
    sess.add(obj)
    if obj.difference:
        stash = sess.query(Stash).get(obj.stash_id)
        if stash:
            stash.amount += obj.difference
    return {"do": "close", "reload": True}
开发者ID:nikitos,项目名称:npui,代码行数:12,代码来源:models.py

示例14: _check_session

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
def _check_session(event):
    request = event.request
    if not isinstance(event.policy, SessionAuthenticationPolicy):
        return
    user = request.user
    route_name = None
    if request.matched_route:
        route_name = request.matched_route.name
        # TODO: unhardcode excluded routes
        if route_name in {'core.login',
                          'debugtoolbar',
                          'core.logout.direct',
                          'core.wellknown'}:
            return
    if not user:
        _goto_login(request)
    settings = request.registry.settings

    skey = settings.get('redis.sessions.cookie_name')
    if not skey:
        skey = settings.get('session.key')
    assert skey is not None, 'Session cookie name does not exist'

    sess = DBSession()
    sname = request.cookies.get(skey)
    if sname:
        now = dt.datetime.now()
        oldsess = True

        try:
            npsess = sess.query(NPSession).filter(
                    NPSession.session_name == sname).one()
        except NoResultFound:
            npsess = user.generate_session(request, sname, now)
            if npsess is None:
                _goto_login(request)
            oldsess = False
            sess.add(npsess)

        if oldsess and not npsess.check_request(request, now):
            _goto_login(request)

        pw_age = request.session.get('sess.pwage', 'ok')
        if pw_age == 'force':
            # TODO: unhardcode excluded routes
            if route_name not in {'extrouter',
                                  'extapi',
                                  'core.home',
                                  'core.js.webshell'}:
                _goto_login(request)

        npsess.update_time(now)
        request.np_session = npsess
    else:
        _goto_login(request)
开发者ID:unikmhz,项目名称:npui,代码行数:57,代码来源:auth.py

示例15: lock

# 需要导入模块: from netprofile.db.connection import DBSession [as 别名]
# 或者: from netprofile.db.connection.DBSession import add [as 别名]
	def lock(self):
		req = self.req
		ctx = req.context
		req.dav.user_acl(req, ctx, dprops.ACL_WRITE_CONTENT)

		path = req.dav.ctx_path(ctx)
		str_path = '/'.join(path)
		locks = req.dav.get_locks(path)
		lock = None

		if req.body:
			# New lock
			oldlock = None
			for oldlock in locks:
				if oldlock.scope == DAVLock.SCOPE_EXCLUSIVE:
					raise dav.DAVConflictingLockError(lock=oldlock)
			lreq = dav.DAVLockRequest(req)
			lock = lreq.get_lock(DAVLock)
			if oldlock and (lock.scope != DAVLock.SCOPE_SHARED):
				raise dav.DAVConflictingLockError(lock=oldlock)
			lock.uri = str_path
			lock.depth = req.dav.get_http_depth(req)
			if isinstance(ctx, File):
				lock.file = ctx
		else:
			# Refreshing old lock
			ifh = self.get_if()
			if not ifh:
				raise dav.DAVBadRequestError('No If: headers supplied in LOCK refresh request.')
			try:
				for oldlock in locks:
					for ifobj in ifh:
						for token in ifobj['tokens']:
							if oldlock.test_token(token['tok']):
								lock = oldlock
								raise StopIteration
			except StopIteration:
				pass
			if lock is None:
				if len(locks):
					raise dav.DAVLockedError('Resource is locked.', lock=locks[0])
				else:
					raise dav.DAVBadRequestError('New LOCK request must be accompanied by a request body.')

		lock.refresh(req.dav.get_http_timeout(req))

		if req.body:
			sess = DBSession()
			sess.add(lock)

		resp = dav.DAVLockResponse(lock=lock, request=req, new_file=False)
		resp.make_body()
		return resp
开发者ID:annndrey,项目名称:npui,代码行数:55,代码来源:dav.py


注:本文中的netprofile.db.connection.DBSession.add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。