本文整理汇总了Python中sqlalchemy.sql.label函数的典型用法代码示例。如果您正苦于以下问题:Python label函数的具体用法?Python label怎么用?Python label使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了label函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: totalList
def totalList():
if not redis.llen('rank:total'):
total_row = db_session.query(
User.id,
User.username,
label('number', func.count(Investment.amount)),
label('total_amount', func.sum(Investment.amount))
).filter(
Investment.user_id == User.id,
).group_by(User.id).order_by(
func.sum(Investment.amount).desc()
).limit(15).all()
total_list = []
for i in total_row:
i = dict(zip(i.keys(), i))
data = {
'id': i['id'],
'username': i['username'],
'total_amount': float(i['total_amount']),
'number': i['number']
}
total_list.append(data)
redis.rpush('rank:total', json.dumps(data))
redis.expire('rank:total', 3600)
else:
total_list = [json.loads(i.decode()) for i in redis.lrange('rank:total', 0, redis.llen('rank:total'))]
return total_list
示例2: weekList
def weekList():
if not redis.llen('rank:week'):
rows = db_session.query(
User.id,
User.username,
label('number', func.count(Investment.amount)),
label('total_amount', func.sum(Investment.amount))
).filter(
Investment.user_id == User.id,
cast(Investment.added_at, Date) <= datetime.datetime.today(),
cast(Investment.added_at, Date) >= datetime.datetime.today() -
datetime.timedelta(weeks=1)
).group_by(User.id).order_by(
func.sum(Investment.amount).desc()
).limit(15).all()
rank_list = []
for i in rows:
i = dict(zip(i.keys(), i))
data = {
'id': i['id'],
'username': i['username'],
'total_amount': float(i['total_amount']),
'number': i['number']
}
rank_list.append(data)
redis.rpush('rank:week', json.dumps(data))
redis.expire('rank:week', 3600)
else:
rank_list = [json.loads(i.decode()) for i in redis.lrange('rank:week', 0, redis.llen('rank:week'))]
return rank_list
示例3: select_tz
def select_tz (self):
"""Select time zones and other related fields from database.
Selects count of messages, count of distinct senders,
time zone.
Returns
-------
Query object
"""
query = self.add_columns(
label("tz",
((DB.Messages.first_date_tz.op('div')(3600) + 36) % 24) - 12),
label("messages",
func.count(func.distinct(DB.Messages.message_ID))),
label("authors",
func.count(func.distinct(DB.MessagesPeople.email_address))))
self.joined.append (DB.Messages)
if DB.MessagesPeople not in self.joined:
query = query.join (DB.MessagesPeople)
self.joined.append (DB.MessagesPeople)
query = query.filter (DB.MessagesPeople.type_of_recipient == "From")
return query
示例4: select_personsdata
def select_personsdata(self, kind):
"""Adds columns with persons data to select clause.
Adds people.name, people.email to the select clause of query.
Does not join new tables.
Parameters
----------
kind: {"authors", "committers"}
Kind of person to select
Returns
-------
SCMObject: Result query, with new fields: id, name, email
"""
query = self.add_columns (label("person_id", DB.People.id),
label("name", DB.People.name),
label('email', DB.People.email))
if kind == "authors":
person = DB.SCMLog.author_id
elif kind == "committers":
person = DB.SCMLog.committer_id
else:
raise Exception ("select_personsdata: Unknown kind %s." \
% kind)
if DB.SCMLog in self.joined:
query = query.filter (DB.People.id == person)
else:
self.joined.append (DB.SCMLog)
query = query.join (DB.SCMLog, DB.People.id == person)
return query
示例5: get_query
def get_query(qtype = 'none', qobject = 'none'):
if qtype != 'none' and qobject != 'none':
# built queries for specified subset of patients
query = db.session.query(label('sid', qobject.c.patient_sid),
label('value_d', qobject.c.double_value),
label('value_s', qobject.c.string_value),
label('attribute', qobject.c.attribute_value))
elif qtype == 'count' and qobject == 'none':
# count of patients
query = db.session.query(distinct(Clinical.patient_sid).label('sid'))
else:
# entire population
query = db.session.query(distinct(Clinical.patient_sid).label('sid'),
literal_column("'complement'").label('attribute'),
literal_column("'0'").label('value_d'),
literal_column("'null'").label('value_s'))
db.session.commit()
db.session.close()
return query
示例6: pending_requests_for_user
def pending_requests_for_user(self, user):
# type: (str) -> List[UserGroupRequest]
requester = aliased(User)
on_behalf_of = aliased(User)
sql_requests = self.session.query(
Request.id,
Request.status,
label("requester", requester.username),
Group.groupname,
label("on_behalf_of", on_behalf_of.username),
).filter(
Request.on_behalf_obj_type == OBJ_TYPES["User"],
Request.on_behalf_obj_pk == on_behalf_of.id,
Request.requester_id == requester.id,
Request.requesting_id == Group.id,
Request.status == "pending",
)
requests = []
for sql_request in sql_requests:
request = UserGroupRequest(
id=sql_request.id,
user=sql_request.on_behalf_of,
group=sql_request.groupname,
requester=sql_request.requester,
status=sql_request.status,
)
requests.append(request)
return requests
示例7: select_listpersons
def select_listpersons(self, kind = "all"):
"""Select a list of persons (authors, committers)
- kind: kind of person to select
authors: authors of commits
committers: committers of commits
all: authors and committers
Returns a SCMQuery object, with (id, name, email) selected.
"""
query = self.add_columns (label("id", func.distinct(People.id)),
label("name", People.name),
label('email', People.email))
if kind == "authors":
return query.join (SCMLog, People.id == SCMLog.author_id)
elif kind == "committers":
return query.join (SCMLog, People.id == SCMLog.committer_id)
elif kind == "all":
return query.join (SCMLog,
People.id == SCMLog.author_id or
People.id == SCMLog.committer_id)
else:
raise Exception ("select_listpersons: Unknown kind %s." \
% kind)
示例8: group_by_period
def group_by_period (self):
"""Group by time period (per month)"""
return self \
.add_columns (label("month", func.month(SCMLog.date)),
label("year", func.year(SCMLog.date))) \
.group_by("month", "year").order_by("year", "month")
示例9: query_start
def query_start (changes = None):
"""Produce a query for selecting chnage start events.
The query will select "date" as the date for the event, and
"change" for the change number. The date is calculated as
the date of the first revision.
Parameters
----------
changes: list of int
List of change numbers to consider.
Returns
-------
query_gerrit.query: produced query
"""
q = session.query(
label ("date", func.min(DB.Revision.date)),
label ("change", DB.Change.number),
) \
.join(DB.Change)
q = q.group_by(DB.Change.uid)
if changes is not None:
q = q.filter(DB.Change.number.in_(changes))
return q
示例10: calc_duration_changes
def calc_duration_changes(max):
"""Calculate duration of changes (time from created to updated).
This will print sumary stats about the duration of the
changes in the review system, and will show some of them.
Parameters
----------
max: int
Max number of changes to show.
"""
res = session.query(
label ("number",
DB.Change.number),
label ("start",
DB.Change.created),
label ("finish",
DB.Change.updated),
) \
.filter (DB.Change.created < DB.Change.updated) \
.order_by (desc (func.datediff(DB.Change.updated,
DB.Change.created)))
cases = res.limit(max).all()
for case in cases:
print str(case.number) + ": " + str(case.start) + \
" (start), " + str(case.finish) + " (finish) Duration: " + \
str(case.finish - case.start)
示例11: check_abandon_cont
def check_abandon_cont(max):
"""Check changes with an "Abandoned" but continuing with activity.
Parameters
----------
max: int
Max number of cases to show among those violating the check.
"""
q_abandons = session.query(
label("id", DB.Change.uid),
label("date", func.min(DB.Message.date)),
label("num", DB.Change.number)
) \
.select_from(DB.Change) \
.join(DB.Message) \
.filter (or_ (DB.Message.header == "Abandoned",
DB.Message.header.like ("Patch%Abandoned"))) \
.group_by(DB.Change.uid) \
.subquery()
q = session.query(
label("num", q_abandons.c.num)
) \
.join(DB.Message,
DB.Message.change_id == q_abandons.c.id) \
.filter(DB.Message.date > q_abandons.c.date) \
.group_by(q_abandons.c.id)
changes = q.count()
print "Changes abandoned, with activity after abandon (" \
+ str(changes) + "): ",
for change in q.limit(max).all():
print change.num
print
示例12: check_first_revision
def check_first_revision(max):
"""Check that changes have a first revision.
Parameters
----------
max: int
Max number of cases to show among those violating the check.
"""
q = session.query(
label ("revision", DB.Revision.uid),
) \
.join (DB.Change) \
.filter (DB.Revision.number == 1) \
.group_by (DB.Change.uid)
print "Changes with first revision: " + str(q.count())
first = session.query(
label ("change", DB.Revision.change_id),
) \
.filter (DB.Revision.number == 1) \
.subquery()
q = session.query(
label ("change", DB.Change.number),
) \
.filter (~DB.Change.uid.in_(first))
for change in q.limit(max).all():
print change.change
print "Changes with no first revision: " + str(q.count())
示例13: check_newer_dates
def check_newer_dates(max):
"""Check that dates related to a change are newer than creation date.
This will print sumary stats about dates that are not correct,
and will show at most max cases.
Parameters
----------
max: int
Max number of cases to show among those violating the check.
"""
res = session.query(
label ("number",
DB.Change.number),
label ("created",
DB.Change.created),
label ("updated",
DB.Change.updated)
) \
.filter (DB.Change.created > DB.Change.updated) \
.order_by (desc (func.datediff(DB.Change.created,
DB.Change.updated)))
cases = res.limit(max).all()
for case in cases:
print str(case.number) + ": " + str(case.created) + \
" (created), " + str(case.updated) + " (updated) Mismatch: " + \
str(case.created - case.updated) + ")"
print "Total number of mismatchs: " + str(res.count())
示例14: select_listpersons_uid
def select_listpersons_uid(self, kind = "all"):
"""Select a list of persons (authors, committers), using uids
- kind: kind of person to select
authors: authors of commits
committers: committers of commits
all: authors and committers
Returns a SCMQuery object, with (id, name, email) selected.
"""
query = self.add_columns (label("id", func.distinct(UPeople.id)),
label("name", UPeople.identifier)) \
.join (PeopleUPeople, UPeople.id == PeopleUPeople.upeople_id)
if kind == "authors":
return query.join (SCMLog,
PeopleUPeople.people_id == SCMLog.author_id)
elif kind == "committers":
return query.join (SCMLog,
PeopleUPeople.people_id == SCMLog.committer_id)
elif kind == "all":
return query.join (SCMLog,
PeopleUPeople.people_id == SCMLog.author_id or
PeopleUPeople.people_id == SCMLog.committer_id)
else:
raise Exception ("select_listpersons_uid: Unknown kind %s." \
% kind)
示例15: select_listcommits
def select_listcommits(self):
"""Select a list of commits"""
if DB.SCMLog not in self.joined:
self.joined.append(DB.SCMLog)
return self \
.add_columns (label("id", func.distinct(DB.SCMLog.id)),
label("date", DB.SCMLog.date))