本文整理汇总了Python中z3c.saconfig.Session.query方法的典型用法代码示例。如果您正苦于以下问题:Python Session.query方法的具体用法?Python Session.query怎么用?Python Session.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类z3c.saconfig.Session
的用法示例。
在下文中一共展示了Session.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testChange
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def testChange(self):
import datetime
from z3c.saconfig import Session
from euphorie.client.model import AccountChangeRequest
from euphorie.client.model import Account
browser = self.browser
browser.handleErrors = False
browser.open("http://nohost/plone/client/nl/new-email")
browser.getControl(name="form.widgets.password").value = "guest"
browser.getControl(
name="form.widgets.loginname").value = "[email protected]"
browser.getControl(name="form.buttons.save").click()
self.assertEqual(
browser.url,
"http://nohost/plone/client/nl/account-settings")
self.assertTrue("Please confirm your new email" in browser.contents)
self.assertTrue("[email protected]" in browser.contents)
self.assertEqual(Session.query(AccountChangeRequest).count(), 1)
user = Session.query(Account).first()
self.assertTrue(user.change_request is not None)
self.assertEqual(user.change_request.value, "[email protected]")
self.assertTrue(user.change_request.expires >
datetime.datetime.now() + datetime.timedelta(days=6))
self.assertEqual(len(self.email_send), 1)
parameters = self.email_send[0]
self.assertEqual(parameters[0][1], "[email protected]")
示例2: handleSubmit
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def handleSubmit(self, action):
data, errors = self.extractData()
if not errors:
session = Session()
searched_categories = data.get('categories')
search = data.get('search')
if search == None:
search = u""
request = session.query(Organization)
if search:
additionalinformations = session.query(AdditionalInformation).filter(func.lower(AdditionalInformation.objectif).like(u'%{0}%'.format(search).lower())).all()
request = request.filter(or_
(func.lower(Organization.name).like(u'%{0}%'.format(search).lower()),
(Organization.organization_id.in_([addit.organization_id for addit in additionalinformations]))))
for categorie in searched_categories:
if categorie == 'enseignement_formation':
request = request.filter(
or_(Organization.category.has(getattr(Category, 'tutoring') == True),
Organization.category.has(getattr(Category, 'training') == True),
Organization.category.has(getattr(Category, 'education') == True)))
else:
request = request.filter(Organization.category.has(getattr(Category, categorie) == True))
request = request.filter(Organization.language == self.context.Language())
request = request.order_by(Organization.name)
self.searched_categories = searched_categories
self.results = request.all()
if len(self.results) == 0:
self.status = _(u"No organization found.")
else:
self.request.SESSION.set(SESSION_SEARCH, self.results)
self.request.SESSION.set(SESSION_CATEGORIES, self.searched_categories)
self.request.response.redirect('organizations_search?search_term={0}'.format(search.encode('utf8')))
示例3: test_add
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def test_add(self):
session = Session()
session.add(Organization(name=u"Vin", language="fr"))
self.assertEqual(len(session.query(Organization).all()), 1)
orga = session.query(Organization).first()
self.assertEqual(orga.name, u"Vin")
示例4: syncPloneQuestions
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def syncPloneQuestions(dbLec, lectureObj):
"""Ensure database has same questions as Plone"""
# Get all plone questions, turn it into a dict by path
if getattr(lectureObj, 'isAlias', False):
lectureObj = lectureObj._target
listing = lectureObj.portal_catalog.unrestrictedSearchResults(
path={'query': '/'.join(lectureObj.getPhysicalPath()), 'depth': 1},
object_provides=IQuestion.__identifier__
)
# Sort questions into a dict by path
ploneQns = _ploneQuestionDict(listing)
# Get all questions currently in the database
for dbQn in (Session.query(db.Question).filter(db.Question.lectures.contains(dbLec))):
qn = ploneQns.get(dbQn.plonePath, None)
if qn is not None:
# Question still there (or returned), update
dbQn.active = True
dbQn.correctChoices = json.dumps(qn['correctChoices'])
dbQn.incorrectChoices = json.dumps(qn['incorrectChoices'])
dbQn.lastUpdate = qn['lastUpdate']
# Dont add this question later
del ploneQns[dbQn.plonePath]
elif dbQn.active and not(dbQn.plonePath.startswith(dbLec.plonePath)):
# Remove slave symlink question from lecture
dbQn.lectures = [l for l in dbQn.lectures if l != dbLec]
dbQn.active = len(dbQn.lectures) > 0
dbQn.lastUpdate = datetime.datetime.utcnow()
elif dbQn.active:
# Remove question from all lectures and mark as inactive
dbQn.lectures = []
dbQn.active = False
dbQn.lastUpdate = datetime.datetime.utcnow()
else:
# No question & already removed from DB
pass
# Insert any remaining questions
for (path, qn) in ploneQns.iteritems():
try:
# If question already exists, add it to this lecture.
dbQn = Session.query(db.Question).filter(db.Question.plonePath == path).one()
dbQn.lectures.append(dbLec)
dbQn.active = True
except NoResultFound:
Session.add(db.Question(
plonePath=path,
qnType=qn['qnType'],
lastUpdate=qn['lastUpdate'],
correctChoices=json.dumps(qn['correctChoices']),
incorrectChoices=json.dumps(qn['incorrectChoices']),
timesAnswered=qn['timesAnswered'],
timesCorrect=qn['timesCorrect'],
lectures=[dbLec],
))
dbLec.lastUpdate = datetime.datetime.utcnow()
Session.flush()
return True
示例5: getStats
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def getStats(self):
"""Get statistics for all questions in the lecture"""
if IQuestion.providedBy(self.context):
# Return just the current question and it's DB object
dbQns = (Session.query(db.Question)
.filter(db.Question.plonePath == '/'.join(self.context.getPhysicalPath()))
.filter(db.Question.active == True)
.order_by(db.Question.plonePath))
else:
# TODO: Batching, optimise query
dbQns = (Session.query(db.Question)
.filter(db.Question.lectures.contains(self.getDbLecture()))
.filter(db.Question.active == True)
.order_by(db.Question.plonePath))
out = []
for dbQn in dbQns:
plonePath = str(dbQn.plonePath)
queryString = None
if '?' in plonePath:
(plonePath, queryString) = plonePath.split('?', 1)
plQn = self.portalObject().unrestrictedTraverse(plonePath)
out.append(dict(
url=plQn.absolute_url() + ('?%s' % queryString if queryString else ""),
id=plQn.getId() + ('?%s' % queryString if queryString else ""),
title=plQn.Title(),
timesAnswered=dbQn.timesAnswered,
timesCorrect=dbQn.timesCorrect,
))
return out
示例6: asDict
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def asDict(self, data):
"""Show coins given to student"""
student = self.getCurrentStudent()
# Add any additional subscriptions
for lec in toArray(data.get('add_lec', [])):
ploneLec = self.portalObject().restrictedTraverse(self.lectureUrlToPlonePath(lec))
ploneTutPath = '/'.join(ploneLec.aq_parent.getPhysicalPath())
try:
dbSub = (Session.query(db.Subscription)
.filter_by(student=student)
.filter_by(plonePath=ploneTutPath)
.one())
# Already there, so make sure it's available
dbSub.hidden = False
except NoResultFound:
Session.add(db.Subscription(
student=student,
plonePath=ploneTutPath,
))
Session.flush()
# Fish out all subscribed tutorials/classes, organised by tutorial
del_lec = toArray(data.get('del_lec', []))
subs = dict(children=[])
for dbSub in Session.query(db.Subscription).filter_by(student=student).filter_by(hidden=False).order_by(db.Subscription.plonePath):
try:
obj = self.portalObject().restrictedTraverse(str(dbSub.plonePath))
except KeyError:
# Subscription item vanished, hide it and move on
dbSub.hidden = True
Session.flush()
continue
if obj.portal_type == 'tw_tutorial':
lectures = (l.getObject() for l in obj.restrictedTraverse('@@folderListing')(portal_type='tw_lecture'))
elif obj.portal_type == 'tw_class':
lectures = (l.to_object for l in obj.lectures)
else:
raise ValueError("Unknown portal type!")
lectures = [dict(
uri=self.lectureObjToUrl(l),
title=l.Title(),
) for l in lectures]
if next((l for l in lectures if l['uri'] in del_lec), False):
dbSub.hidden = True
Session.flush()
else:
subs['children'].append(dict(
title=obj.Title(),
children=lectures,
))
return subs
示例7: get_translation
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def get_translation(self):
session = Session()
trans_orga = session.query(Association).filter(Association.canonical_id == self.organization_id).scalar()
attr = "translated_id"
if not trans_orga:
trans_orga = session.query(Association).filter(Association.translated_id == self.organization_id).scalar()
attr = "canonical_id"
if not trans_orga:
return False
return session.query(Organization).get(getattr(trans_orga, attr))
示例8: handleCategoriesButton
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def handleCategoriesButton(self, form, action):
form.widgets.get('search').value = u""
session = Session()
self.searched_categories = action.value
if action.value == 'enseignement_formation':
self.results = session.query(Organization).filter(or_(Organization.category.has(getattr(Category, 'tutoring') == True),
Organization.category.has(getattr(Category, 'training') == True),
Organization.category.has(getattr(Category, 'education') == True) )).filter(Organization.language == self.context.Language()).order_by(Organization.name).all()
else:
self.results = session.query(Organization).filter(Organization.category.has(getattr(Category, action.value) == True)).filter(Organization.language == self.context.Language()).order_by(Organization.name).all()
if len(self.results) == 0:
self.status = _(u"No organization found.")
示例9: test_translation
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def test_translation(self):
session = Session()
session.add(Organization(name=u"Vin", language="fr"))
session.add(Organization(name=u"Wijn", language="nl"))
self.assertEqual(len(session.query(Organization).all()), 2)
assoc = Association(association_type="lang")
[orgafr, organl] = [orga for orga in session.query(Organization).all()]
assoc.translated_id = organl.organization_id
assoc.canonical_id = orgafr.organization_id
session.add(assoc)
self.assertEqual(orgafr, organl.get_translation())
self.assertEqual(orgafr.get_translation().name, u"Wijn")
self.assertEqual(organl.get_translation().name, u"Vin")
示例10: search
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def search(self, search):
session = Session()
request = session.query(Organization)
additionalinformations = session.query(AdditionalInformation).filter(func.lower(AdditionalInformation.objectif).like(u'{0}'.format(search).lower())).all()
request = request.filter(or_
(func.lower(Organization.name).like(u'{0}'.format(search).lower()),
(Organization.organization_id.in_([addit.organization_id for addit in additionalinformations]))))
request = request.filter(Organization.language == self.context.Language())
request = request.order_by(Organization.name)
self.results = request.all()
if len(self.results) == 0:
self.status = _(u"No organization found.")
示例11: testInvalidDateDoesNotBreakRendering
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def testInvalidDateDoesNotBreakRendering(self):
import datetime
from euphorie.content.tests.utils import BASIC_SURVEY
from z3c.saconfig import Session
from euphorie.client import model
# Test for http://code.simplon.biz/tracker/tno-euphorie/ticket/150
self.loginAsPortalOwner()
addSurvey(self.portal, BASIC_SURVEY)
browser = Browser()
survey_url = self.portal.client.nl["ict"]["software-development"]\
.absolute_url()
browser.open(survey_url)
registerUserInClient(browser)
# Create a new survey session
browser.getControl(name="title:utf8:ustring").value = \
u"Sessiøn".encode("utf-8")
browser.getControl(name="next").click()
# Start the survey
browser.getForm().submit()
browser.getLink("Start Risk Identification").click()
# Update the risk
risk = Session.query(model.Risk).first()
risk.identification = "no"
risk.action_plans.append(model.ActionPlan(
action_plan=u"Do something awesome",
planning_start=datetime.date(1, 2, 3)))
# Render the report
browser.handleErrors = False
browser.open("http://nohost/plone/client/nl/ict/"
"software-development/report/view")
示例12: fernlehrgang_vocab
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def fernlehrgang_vocab(context):
rc = [SimpleTerm('', '', u'Fernlehrgang auswählen')]
session = Session()
from fernlehrgang.models import Fernlehrgang
sql = session.query(Fernlehrgang)
def getKTN(context, flg_id):
if IFernlehrgangApp.providedBy(context):
return
if not hasattr(context, 'kursteilnehmer'):
return True
for x in context.kursteilnehmer:
if flg_id == x.fernlehrgang_id:
return x
for flg in sql.all():
ktn = getKTN(context, flg.id)
if ktn:
value = "%s - %s, bereits Registriert" % (flg.titel, flg.jahr)
if ktn is True:
token = flg.id
else:
token = "%s,%s" %(ktn.id, flg.id)
rc.append(SimpleTerm(token, token, value))
else:
value = "%s - %s" % (flg.titel, flg.jahr)
rc.append(SimpleTerm(flg.id, flg.id, value))
return SimpleVocabulary(rc)
示例13: compareLgs
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def compareLgs(dbLec, globalSettings):
"""Compare stored settings to what plone returned"""
dbKeys = []
for dbLgs in (Session.query(db.LectureGlobalSetting)
.filter_by(lectureId=dbLec.lectureId)
.filter_by(lectureVersion=dbLec.currentVersion)
):
# Combine key and variant for comparison's sake, plone will leave them combined
key_variant = dbLgs.key + (":" + dbLgs.variant if dbLgs.variant else "")
dbKeys.append(key_variant)
# Does DB key exist in Plone?
if key_variant not in globalSettings:
return False
# Do each of the values set for it match?
for (k, v) in globalSettings[key_variant].iteritems():
dbValue = getattr(dbLgs, k)
if isinstance(dbValue, float):
if abs(dbValue - float(v)) > 0.00001:
return False
elif getattr(dbLgs, k) != v:
return False
# Are there are keys in plone we did not consider?
if set(dbKeys) != set(globalSettings.keys()):
return False
return True
示例14: get_results
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def get_results(self):
if not 'SESSION' in self.request.keys():
return None
if SESSION_JSON in self.request.SESSION.keys():
self.request.SESSION.delete(SESSION_JSON)
if len(self.results) == 0:
return None
session = Session()
json_organisations = []
sa_results = []
for orga in self.results:
sa_orga = session.query(Organization).get(orga.organization_id)
sa_results.append(sa_orga)
dict_orga = {}
dict_orga['id'] = sa_orga.organization_id
dict_orga['name'] = sa_orga.name
dict_orga['x'] = sa_orga.x
dict_orga['y'] = sa_orga.y
dict_orga['street'] = u"{0}, {1}".format(sa_orga.address.num, sa_orga.address.street)
dict_orga['city'] = u"{0} {1}".format(sa_orga.address.post_code, sa_orga.address.municipality)
dict_orga['url'] = "{0}/org/{1}/oview".format(self.context.absolute_url(), sa_orga.organization_id)
dict_orga['icon'] = "{0}/++resource++map_pin.png".format(self.context.portal_url())
json_organisations.append({'orga': dict_orga})
self.request.SESSION.set(SESSION_JSON, json_organisations)
self.results = sa_results
return sa_results
示例15: getQuestions
# 需要导入模块: from z3c.saconfig import Session [as 别名]
# 或者: from z3c.saconfig.Session import query [as 别名]
def getQuestions(self, uris=None, lockForUpdate=False, isAdmin=False, active=True):
query = Session.query(db.Question, db.Allocation).join(db.Allocation)
if lockForUpdate:
query = query.with_lockmode('update')
if uris is not None:
query = query.filter(db.Allocation.publicId.in_(
u.rsplit('/', 1)[-1] for u in uris
))
else:
# TODO: Use this instead of getAllQuestions
query = query.filter(db.Question.lectures.contains(self.dbLec)) \
.filter(db.Allocation.lectureId == self.dbLec.lectureId)
query = query.filter(db.Question.onlineOnly == False)
query = query.filter(db.Question.active == True)
if active is not None:
query = query.filter(db.Question.active == active)
# If not an admin, ensure we're the right user
if not isAdmin:
query = query.filter(db.Allocation.studentId == self.student.studentId)
for (dbQn, dbAlloc) in query:
yield (self._questionUrl(dbAlloc.publicId), dbQn)