本文整理汇总了Python中turbogears.database.session.query函数的典型用法代码示例。如果您正苦于以下问题:Python query函数的具体用法?Python query怎么用?Python query使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了query函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rate_object
def rate_object(self, **kwargs):
#log.info('args = %s' % str(args))
#log.info('kwargs = %s' % str(kwargs))
id = kwargs.get("ratingID")
rating = kwargs.get("value")
print "ID: %s" % id
print "RATING: %s" % rating
if id.startswith("Host"):
sep = id.find("@")
if sep == -1:
host_id = id[4:]
host = session.query(Host).filter_by(uuid=host_id).one()
host.rating = int(rating)
session.flush()
return dict()
host_id = id[4:sep]
id = id[sep+1:]
if id.startswith("Device"):
device_id = int(id[6:])
host = session.query(Host).filter_by(uuid=host_id).one()
for device in host.devices:
if device.device_id == device_id:
device.rating = int(rating)
session.flush([host, device])
return dict()
return dict()
示例2: test_exc_done_rollback
def test_exc_done_rollback():
"""No problems with error handler if controller manually rollbacks."""
app = make_app(RbRoot)
response = app.get('/doerr?id=28&dorb=1')
assert 'KARL27' in response, 'Exception handler should have answered'
assert session.query(User).get(28) is None
assert session.query(User).get(29) is not None
示例3: genkey
def genkey(self):
username = turbogears.identity.current.user_name
person = People.by_username(username)
created = time.strftime("%Y-%m-%dT%H:%M:%S")
hexctr = "%012x" % person.id
publicname = hex2modhex(hexctr)
internalname = gethexrand(12)
aeskey = gethexrand(32)
lockcode = gethexrand(12)
try:
new_ykksm = Ykksm(serialnr=person.id, publicname=publicname, created=created, internalname=internalname, aeskey=aeskey, lockcode=lockcode, creator=username)
session.add(new_ykksm)
session.flush()
except IntegrityError:
session.rollback()
old_ykksm = session.query(Ykksm).filter_by(serialnr=person.id).all()[0]
session.delete(old_ykksm)
new_ykksm = Ykksm(serialnr=person.id, publicname=publicname, created=created, internalname=internalname, aeskey=aeskey, lockcode=lockcode, creator=username)
old_ykksm = new_ykksm
session.flush()
try:
old_ykval = session.query(Ykval).filter_by(yk_publicname=publicname).all()[0]
session.delete(old_ykval)
session.flush()
except IndexError:
# No old record? Maybe they never used their key
pass
string = "%s %s %s" % (publicname, internalname, aeskey)
return dict(key=string)
示例4: deleteQuery
def deleteQuery(self, query_id, *args, **kwargs):
'''
Allows user to delete a query. Updates query logging.
@param query_id: identifies the query
@return: status of attempted delete operation of the query
'''
query = session.query(Query).get_by(query_id=int(query_id))
status = ""
if not query:
status = "Query not found"
elif session.query(ChatSession).get_by(query_id=int(query_id)):
status = "Chat already started"
elif query.user_id != identity.current.user.user_id:
status = "Permission denied"
else:
query.experts[:] = []
query_log=QueryLog(
query_id = int(query_id),
user_id = query.user_id,
user_name = session.query(User).get_by(user_id=query.user_id).user_name,
created = datetime.now(),
status = 'Deleted')
session.save(query_log)
session.flush()
session.delete(query);
session.flush();
return dict(status=status)
示例5: _handle_historical
def _handle_historical(session, data,myth_uuid):
showcount = 0
rectime = 0
db_age = 0
reccount = 0
try:
myth_hist = data['features']['historical']
except:
myth_hist = {}
#session.query(mythtvHistorical).filter_by(machine_id = machine_id).delete()
session.query(mythtvHistorical).filter_by(myth_uuid = myth_uuid).delete()
try:
showcount = myth_hist['showcount']
except:
pass
try:
rectime = myth_hist['rectime']
except:
pass
try:
db_age = myth_hist['db_age']
except:
pass
try:
reccount = myth_hist['reccount']
except:
pass
session.add(mythtvHistorical(myth_uuid,
showcount,rectime,db_age,reccount)
)
session.flush()
示例6: get_sa_catalog
def get_sa_catalog(domain):
"""
Retrieves all translations for locale and domain from database
and stores in thread data.
"""
if domain is None:
domain = turbogears.config.get("i18n.domain", "messages")
catalog = _catalogs.get(domain)
if not catalog:
catalog = {}
query = session.query(TG_Domain)
domain = query.filter(TG_Domain.name==domain).first()
if not domain:
return catalog
query = session.query(TG_Message)
query = query.filter(TG_Message.domain==domain)
for message in query:
locale = message.locale
messages = catalog.get(locale, {})
messages[message.name] = message.text
catalog[locale] = messages
_catalogs[domain.name] = catalog
return catalog
示例7: _handle_pbp
def _handle_pbp(session, data, machine_id):
name = "unknown"
profiles = ['unknown']
try:
myth_pb = data['features']['playbackprofile']
except:
myth_pb = {}
try:
name = myth_pb['name']
except:
pass
try:
profiles = myth_pb['profiles']
except:
pass
#Remove old entry
session.query(mythtvPbp).filter_by(machine_id = machine_id).delete()
#Add new entry
session.add(mythtvPbp(machine_id,name,profiles))
session.flush()
示例8: getStatistics
def getStatistics(self, *args, **kwargs):
'''
@return: statistics about the user for statistical box
'''
current_user = identity.current.user
n_users = getNumberOfAllUsers();
n_users_online = getNumberOfAllUsersCurrentlyOnline();
n_queries = session.query(Query).count()
n_chats = session.query(ChatSession).count(ChatSession.c.status == 'ONGOING');
user=session.query(User).get_by(user_id=current_user.user_id)
stats = user.user_stats
n_answered = stats.no_of_ques_answered
n_asked = stats.no_of_ques_asked
n_blogs = session.query(BlogEntry).count(BlogEntry.c.user_id==current_user.user_id)
name = current_user.user_name[:25]
if not " " in name:
name = name[:15]
return dict(user_name = name,
n_users = n_users,
n_users_online = n_users_online,
n_queries = n_queries,
n_chats = n_chats,
n_answered = n_answered,
n_asked = n_asked,
n_blogs = n_blogs
)
示例9: show
def show(self, shortname, buildname, epoch, version, rel, arch):
try:
repo = session.query(Repo).filter_by(shortname=shortname).one()
except NoResultFound:
flash('Repo "%s" was not found' % shortname)
redirect('/builds')
try:
build = session.query(PackageBuild)\
.join(PackageBuild.repos)\
.filter(and_(
PackageBuild.name==buildname,
PackageBuild.epoch==epoch,
PackageBuild.version==version,
PackageBuild.release==rel,
PackageBuild.architecture==arch,
Repo.id==repo.id))\
.one()
except NoResultFound:
flash('Build (%s-%s:%s-%s.%s) was not found' % (buildname, epoch, version, rel, arch))
redirect('/builds')
return dict(title=self.app_title, version=release.VERSION,
build=build)
示例10: doBlogRating
def doBlogRating(self, blogentry_id, rate, *args, **kwargs):
'''
Calculates blog rating. Updates note's score, score of the user who created
it and keeps track of who rated which note (this way user can rate note only once).
@param blogentry_id: identifies note
@param rate: points given
'''
#update the blogentry table
entry = session.query(BlogEntry).get_by(blogentry_id=int(blogentry_id))
if not entry:
return dict()
new_value=round(entry.average_rating*entry.no_ratings)
#print 'old blog score', new_value,'old average',entry.average_rating
entry.no_ratings+=1
entry.average_rating=(new_value+float(rate))/entry.no_ratings
#print 'rate', rate,'new average', entry.average_rating
session.flush()
#updates the user_blog table
new_rate=UserBlog()
new_rate.user_id = identity.current.user.user_id
new_rate.blogentry_id = blogentry_id
new_rate.rating = rate
new_rate.created = datetime.datetime.now()
session.save(new_rate)
session.flush()
#updates the user_stats table
user=session.query(User).get_by(user_id = entry.user_id)
user.user_stats.no_of_blog_ratings+=1
#print 'old averege blog rating',user.user_stats.average_blog_rating
user_blogs=session.query(BlogEntry).select(BlogEntry.c.user_id==entry.user_id) #[BlogEntry.c.average_rating, BlogEntry.c.no_ratings]
sum=0.0
no_blogs=0
for ub in user_blogs:
sum+=ub.average_rating*ub.no_ratings
no_blogs+=ub.no_ratings
sum=round(sum)/no_blogs
#print 'new average blog rating',sum
user.user_stats.average_blog_rating=sum
#print 'old score',user.user_stats.score
#print 'new values', user.user_stats.no_of_ques_answered_rated * user.user_stats.average_rating, user.user_stats.no_of_blog_ratings * user.user_stats.average_blog_rating
user.user_stats.score=round(user.user_stats.no_of_ques_answered_rated * user.user_stats.average_rating + user.user_stats.no_of_blog_ratings * user.user_stats.average_blog_rating)
#print 'new score',user.user_stats.score
session.flush()
return dict()
示例11: user_name_is_unique
def user_name_is_unique(user_name):
"Return True if the user_name is not yet in the database."
UserClass = user_class_finder.user_class
user_count = session.query(UserClass).count_by(user_name=user_name)
pending_count = session.query(RegistrationPendingUser).count_by(user_name=user_name)
if user_count or pending_count:
return False
else:
return True
示例12: test_setup
def test_setup(self):
"Make sure our setup is what we think it is."
u1 = session.query(User).filter_by(user_name='bobvilla')
l = session.query(User).all()
print u1
for u in l:
print u
assert u1[0].user_id==self.user1.user_id
assert u1[0].email_address=='[email protected]'
assert len(l) == 2
示例13: getIncomingLoad
def getIncomingLoad(self):
'''
@return: the number of questions in the users' inbox
'''
from spree.spree_model import QueryExpert, ChatSession
load=session.query(QueryExpert).count_by(and_(QueryExpert.c.expert_id == self.user_id,QueryExpert.c.status=='HANDSHAKE'))
load+=session.query(ChatSession).count_by(and_(ChatSession.c.expert_id == self.user_id,or_(ChatSession.c.status=='ONGOING', ChatSession.c.status=='HANDSHAKE')))
return load
示例14: email_is_unique
def email_is_unique(email):
"Return True if the email is not yet in the database."
UserClass = user_class_finder.user_class
user_count = session.query(UserClass).count_by(email_address=email)
pending_count = session.query(RegistrationPendingUser).count_by(email_address=email)
changed_count = session.query(RegistrationUserEmailChange).count_by(new_email_address=email)
if user_count or pending_count or changed_count:
return False
else:
return True
示例15: getWaitSearchContent
def getWaitSearchContent(self, query_id, *args, **kwargs):
'''
Serves content about the current status of the query (which experts are contacted, has anybody declined etc...)
to the loqged in user , after the query has been posted. Also provides related notes.
@param query_id: identifies the query
@return: values needed for the template
'''
query = session.query(Query).get_by(query_id=int(query_id))
if not query:
raise redirect("/content/search/getQueryOverviewContent/"+query_id)
#TODO: add matching logic here!!
blog_entries = query.relatedBlogs
length_blog_entries = len(blog_entries)
blogs = [{"topic": entry.title,
"id": entry.blogentry_id,
"user_id": entry.user_id,
"created": helpers.formatDate(entry.created),
"last_changed": entry.lastChanged,
"categories": entry.getCategoriesString(),
"user_name": session.query(User).get_by(user_id = entry.user_id).display_name} for entry in blog_entries]
experts = self.getExperts(int(query_id))
dic = {"text": query.text,
"created": helpers.formatDate(query.created),
"topic": query.getTopicString(True),
"id": query.query_id,
"blogs": blogs,
"lengthBlogEntries": length_blog_entries,
"query_status":query.status,
"profile": query.getCategoriesString(),
"all_experts":experts}
expert_strings = {"experts":"","experts_accepted":"","experts_declined":""}
for type in expert_strings:
for expert in experts[type]:
expert_strings[type] += expert + ", "
state=experts['state']
dic['doPolling'] = 'True'
if (state=='accepted') or (state=='all_declined') or (state=='nobody_available'):
dic['doPolling'] = 'False'
dic.update(experts)
dic['expert_strings'] = expert_strings
return dic