本文整理汇总了Python中sqlalchemy.sql.expression.func.max方法的典型用法代码示例。如果您正苦于以下问题:Python func.max方法的具体用法?Python func.max怎么用?Python func.max使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.sql.expression.func
的用法示例。
在下文中一共展示了func.max方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_any_issue_needs_reminder
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def check_any_issue_needs_reminder(self, search_timedelta, records):
"""Checks if the issue among the provided ones with the most recent sent_at value has that value older than the
`search_timedelta`, that is, a reminder should be sent for the issue.
NOTE: if all database records for a fingerprint given in the `records` list have the sent_at values set to Null,
then this fingerprint will be treated as NOT needing a reminder, which might be unintuitive.
Args:
search_timedelta (datetime.timedelta): reminder interval
records (list): list of EventRecord objects to check
Returns:
bool: True if any of the provided records represents an issue that needs to be reminded about
"""
fingerprints = [record.fingerprint for record in records]
timestamps = (
self.session.query(func.max(EventRecord.sent_at))
.filter(EventRecord.fingerprint.in_(fingerprints) & EventRecord.sent_at.isnot(None))
.group_by(EventRecord.fingerprint)
.all()
)
if timestamps:
return max(timestamps)[0] <= datetime.utcnow() - search_timedelta
return False
示例2: get_any_issues_need_reminder
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def get_any_issues_need_reminder(self, search_timedelta, records):
"""Returns all the `fingerprints` having corresponding `event` table entries with the latest `sent_at`
more then search_timedelta ago.
NOTE: if all database records for a fingerprint given in the `records` list have the sent_at values set to Null,
then this fingerprint will be treated as NOT needing a reminder, which might be unintuitive.
Args:
search_timedelta (datetime.timedelta): reminder interval
records (list): list of EventRecord objects to check
Returns:
list: list of fingerprints that represent issues that need to be reminded about
"""
fingerprints = [record.fingerprint for record in records]
fingerprints_to_remind = (
self.session.query(func.max(EventRecord.sent_at).label("sent_at"), EventRecord.fingerprint)
.filter(EventRecord.fingerprint.in_(fingerprints) & EventRecord.sent_at.isnot(None))
.group_by(EventRecord.fingerprint)
.all()
)
result = []
deltat = datetime.utcnow() - search_timedelta
for f in fingerprints_to_remind:
if f.sent_at <= deltat:
result.append(f.fingerprint)
return result
示例3: test_scenario_detail
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def test_scenario_detail(self):
# Jane can get her scenario, and it matches what we expect from the database
rv = self.get('%s/%i' % (self.SCENARIOS_PATH, self.jane_scenario_id), self.jane_doe_credentials)
self.assertEqual(rv.status_code, 200)
resp = json.loads(rv.data)
with api.app.app_context():
jane_scenario = models.Scenario.query.get(self.jane_scenario_id)
self.assertEqual(resp['name'], jane_scenario.name)
self.assertEqual(resp['description'], jane_scenario.description)
self.assertEqual(len(resp['demand_package_group_ids']), len(jane_scenario.demand_case.data))
self.assertEqual(len(resp['supply_package_group_ids']), len(jane_scenario.supply_case.data))
self.assertFalse(resp['is_built_in'])
self.assertEqual(resp['status']['name'], 'Never run')
# Jane can also get the built-in scenario, but not the admin's scenario
rv = self.get('%s/%i' % (self.SCENARIOS_PATH, self.builtin_scenario_id), self.jane_doe_credentials)
self.assertEqual(rv.status_code, 200)
with self.assertRaises(api.Forbidden):
self.get('%s/%i' % (self.SCENARIOS_PATH, self.admin_scenario_id), self.jane_doe_credentials)
# Trying to get an id that doesn't exist results in a 404 Not Found
with api.app.app_context():
max_id = models.db.session.query(func.max(models.Scenario.id)).scalar()
with self.assertRaises(api.NotFound):
self.get('%s/%i' % (self.SCENARIOS_PATH, max_id + 1), self.jane_doe_credentials)
示例4: null_out_last_stop_departures
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def null_out_last_stop_departures(cls, db):
"""
delete all 'depature_time' values that appear for the last stop
time of a given trip (e.g., the trip ends there, so there isn't a
further vehicle departure / customer pickup for that stop time / trip pair)...
-- query below shows null'd out stop times
select * from ott.stop_times
where COALESCE(arrival_time,'')='' or COALESCE(departure_time,'')=''
NOTE: we know this breaks the current GTFS spec, which states that departure &
arrival times must both exist for every stop time. Sadly, GTFS is kinda wrong...
"""
# step 1: remove the departure times at the end of a trip
log.info("QUERY StopTime for all trip end times")
sq = db.session.query(StopTime.trip_id, func.max(StopTime.stop_sequence).label('end_sequence'))
sq = sq.group_by(StopTime.trip_id).subquery()
q = db.session.query(StopTime)
q = q.filter_by(trip_id=sq.c.trip_id, stop_sequence=sq.c.end_sequence)
for st in q:
if st.pickup_type == 1:
st.departure_time = None
# remove the arrival times at the start of a trip
log.info("QUERY StopTime for all trip start times")
sq = db.session.query(StopTime.trip_id, func.min(StopTime.stop_sequence).label('start_sequence'))
sq = sq.group_by(StopTime.trip_id).subquery()
q = db.session.query(StopTime)
q = q.filter_by(trip_id=sq.c.trip_id, stop_sequence=sq.c.start_sequence)
for st in q:
if st.drop_off_type == 1:
st.arrival_time = None
db.session.flush()
db.session.commit()
db.session.close()
示例5: get_unprocessed_events_batch
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def get_unprocessed_events_batch(self, wait_for_more, max_wait, source_type):
"""Get all unprocessed events of the given source_type but only if the latest event is older than
`wait_for_more` or the oldest event is older than `max_wait`.
Metrics emitted:
events-hit-max-wait
Args:
wait_for_more (datetime.timedelta): the amount of time to wait since the latest event
max_wait (datetime.timedelta): the amount of time to wait since the earliest event
source_type (str): source type of the events to look for
Returns:
list: list of `EventRecord`s, or empty list if there is nothing to return
"""
# https://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/
events = (
self.session.query(EventRecord)
.filter((EventRecord.processed_at.is_(None)) & (EventRecord.source_type == source_type))
.order_by(EventRecord.received_at.asc())
.all()
)
now = datetime.utcnow()
if events and events[-1].received_at < now - wait_for_more:
return events
if events and events[0].received_at < now - max_wait:
# METRIC_RELAY.emit('events-hit-max-wait', 1,
# {'source-type': source_type})
return events
return []
示例6: _get_latest_update
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def _get_latest_update(session, source_id):
return session.query(func.max(FeedEntry.published)).filter_by(source_id=source_id).scalar()
示例7: lastseenuid
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def lastseenuid(account_id, session, folder_id):
q = bakery(lambda session: session.query(func.max(ImapUid.msg_uid)))
q += lambda q: q.filter(
ImapUid.account_id == bindparam('account_id'),
ImapUid.folder_id == bindparam('folder_id'))
res = q(session).params(account_id=account_id,
folder_id=folder_id).one()[0]
return res or 0
示例8: _update_categories
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def _update_categories(db_session, message, synced_categories):
now = datetime.utcnow()
# We make the simplifying assumption that only the latest syncback action
# matters, since it reflects the current local state.
actionlog_id = db_session.query(func.max(ActionLog.id)).filter(
ActionLog.namespace_id == message.namespace_id,
ActionLog.table_name == 'message',
ActionLog.record_id == message.id,
ActionLog.action.in_(['change_labels', 'move'])).scalar()
if actionlog_id is not None:
actionlog = db_session.query(ActionLog).get(actionlog_id)
# Do /not/ overwrite message.categories in case of a recent local
# change - namely, a still 'pending' action or one that completed
# recently.
if (actionlog.status == 'pending' or
(now - actionlog.updated_at).seconds <= 90):
return
# We completed the syncback action /long enough ago/ (on average and
# with an error margin) that:
# - if it completed successfully, sync has picked it up; so, safe to
# overwrite message.categories
# - if syncback failed, the local changes made can be overwritten
# without confusing the API user.
# TODO[k]/(emfree): Implement proper rollback of local state in this case.
# This is needed in order to pick up future changes to the message,
# the local_changes counter is reset as well.
message.categories = synced_categories
message.categories_changes = False
示例9: add_to_shelf
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def add_to_shelf(shelf_id, book_id):
xhr = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
if shelf is None:
log.error("Invalid shelf specified: %s", shelf_id)
if not xhr:
flash(_(u"Invalid shelf specified"), category="error")
return redirect(url_for('web.index'))
return "Invalid shelf specified", 400
if not check_shelf_edit_permissions(shelf):
if not xhr:
flash(_(u"Sorry you are not allowed to add a book to the the shelf: %(shelfname)s", shelfname=shelf.name),
category="error")
return redirect(url_for('web.index'))
return "Sorry you are not allowed to add a book to the the shelf: %s" % shelf.name, 403
book_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id,
ub.BookShelf.book_id == book_id).first()
if book_in_shelf:
log.error("Book %s is already part of %s", book_id, shelf)
if not xhr:
flash(_(u"Book is already part of the shelf: %(shelfname)s", shelfname=shelf.name), category="error")
return redirect(url_for('web.index'))
return "Book is already part of the shelf: %s" % shelf.name, 400
maxOrder = ub.session.query(func.max(ub.BookShelf.order)).filter(ub.BookShelf.shelf == shelf_id).first()
if maxOrder[0] is None:
maxOrder = 0
else:
maxOrder = maxOrder[0]
shelf.books.append(ub.BookShelf(shelf=shelf.id, book_id=book_id, order=maxOrder + 1))
shelf.last_modified = datetime.utcnow()
try:
ub.session.merge(shelf)
ub.session.commit()
except (OperationalError, InvalidRequestError):
ub.session.rollback()
flash(_(u"Settings DB is not Writeable"), category="error")
if "HTTP_REFERER" in request.environ:
return redirect(request.environ["HTTP_REFERER"])
else:
return redirect(url_for('web.index'))
if not xhr:
flash(_(u"Book has been added to shelf: %(sname)s", sname=shelf.name), category="success")
if "HTTP_REFERER" in request.environ:
return redirect(request.environ["HTTP_REFERER"])
else:
return redirect(url_for('web.index'))
return "", 204
示例10: search_to_shelf
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def search_to_shelf(shelf_id):
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
if shelf is None:
log.error("Invalid shelf specified: %s", shelf_id)
flash(_(u"Invalid shelf specified"), category="error")
return redirect(url_for('web.index'))
if not check_shelf_edit_permissions(shelf):
flash(_(u"You are not allowed to add a book to the the shelf: %(name)s", name=shelf.name), category="error")
return redirect(url_for('web.index'))
if current_user.id in searched_ids and searched_ids[current_user.id]:
books_for_shelf = list()
books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).all()
if books_in_shelf:
book_ids = list()
for book_id in books_in_shelf:
book_ids.append(book_id.book_id)
for searchid in searched_ids[current_user.id]:
if searchid not in book_ids:
books_for_shelf.append(searchid)
else:
books_for_shelf = searched_ids[current_user.id]
if not books_for_shelf:
log.error("Books are already part of %s", shelf)
flash(_(u"Books are already part of the shelf: %(name)s", name=shelf.name), category="error")
return redirect(url_for('web.index'))
maxOrder = ub.session.query(func.max(ub.BookShelf.order)).filter(ub.BookShelf.shelf == shelf_id).first()
if maxOrder[0] is None:
maxOrder = 0
else:
maxOrder = maxOrder[0]
for book in books_for_shelf:
maxOrder = maxOrder + 1
shelf.books.append(ub.BookShelf(shelf=shelf.id, book_id=book, order=maxOrder))
shelf.last_modified = datetime.utcnow()
try:
ub.session.merge(shelf)
ub.session.commit()
flash(_(u"Books have been added to shelf: %(sname)s", sname=shelf.name), category="success")
except (OperationalError, InvalidRequestError):
ub.session.rollback()
flash(_(u"Settings DB is not Writeable"), category="error")
else:
flash(_(u"Could not add books to shelf: %(sname)s", sname=shelf.name), category="error")
return redirect(url_for('web.index'))
示例11: test_scenarios_with_outputs
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def test_scenarios_with_outputs(self):
outputs_query_str = '?outputs'
# If we request Jane's scenario without asking for outputs, no outputs field is provided in the response
rv = self.get('%s/%i' % (self.SCENARIOS_PATH, self.jane_scenario_id), self.jane_doe_credentials)
self.assertEqual(rv.status_code, 200)
resp = json.loads(rv.data)
self.assertFalse('outputs' in resp)
janes_scenario_with_outputs = '%s/%i%s' % (self.SCENARIOS_PATH, self.jane_scenario_id, outputs_query_str)
# If we request the scenario with outputs, we receive an outputs key in the response, but its value is
# None because there are no outputs yet
rv = self.get(janes_scenario_with_outputs, self.jane_doe_credentials)
self.assertEqual(rv.status_code, 200)
resp = json.loads(rv.data)
self.assertIsNone(resp['outputs'])
# Add some fake outputs. For the purposes of this test, we don't care whether the Outputs actually
# have data attached.
with api.app.app_context():
run = models.ScenarioRun(scenario_id=self.jane_scenario_id, status_id=models.ScenarioRunStatus.SUCCESS_ID)
max_basic_output_type_id = max(models.OutputType.BASIC_OUTPUT_TYPE_IDS)
# The first output we add will be a "basic" one, the second one will not be (because its
# output_type_id is one larger than the largest basic output_type_id).
for output_type_id in [max_basic_output_type_id, max_basic_output_type_id + 1]:
run.outputs.append(models.Output(
output_type_id=output_type_id,
unit=self.TEST_OUTPUT_UNIT,
))
models.db.session.add(run)
models.db.session.commit()
# Now when we request the scenario with outputs, we get two outputs back
rv = self.get(janes_scenario_with_outputs, self.jane_doe_credentials)
self.assertEqual(rv.status_code, 200)
resp = json.loads(rv.data)
self.assertEqual(len(resp['outputs']), 2)
# When we request the scenarios list, Jane's scenario has only the basic output
rv = self.get(self.SCENARIOS_PATH + outputs_query_str, self.jane_doe_credentials)
self.assertEqual(rv.status_code, 200)
resp = json.loads(rv.data)
janes_scenario_from_list = [s for s in resp if s['id'] == self.jane_scenario_id][0]
self.assertEqual(len(janes_scenario_from_list['outputs']), 1)
示例12: main
# 需要导入模块: from sqlalchemy.sql.expression import func [as 别名]
# 或者: from sqlalchemy.sql.expression.func import max [as 别名]
def main(self):
running_builds = self.db.query(CoprRebuild)\
.filter(CoprRebuild.state == Build.RUNNING)\
.count()
if running_builds >= get_config('copr.max_builds'):
self.log.debug("{} running builds, not scheduling".format(running_builds))
return
last_index = self.db.query(
func.coalesce(
func.max(CoprRebuildRequest.scheduler_queue_index),
0
)
).scalar() + 1
request = self.db.query(CoprRebuildRequest)\
.order_by(CoprRebuildRequest.scheduler_queue_index.nullsfirst())\
.filter(CoprRebuildRequest.state == 'in progress')\
.first()
if not request:
self.log.debug("No schedulable requests")
return
# move all requests of given user to the queue end
self.db.query(CoprRebuildRequest)\
.filter(CoprRebuildRequest.user_id == request.user_id)\
.update({'scheduler_queue_index': last_index})
build_count = self.db.query(CoprRebuild)\
.filter(CoprRebuild.request_id == request.id)\
.filter(CoprRebuild.copr_build_id != None)\
.count()
if build_count >= request.schedule_count:
request.state = 'scheduled'
self.db.commit()
return
rebuild = self.db.query(CoprRebuild)\
.filter(CoprRebuild.copr_build_id == None)\
.order_by(CoprRebuild.order)\
.first()
if not rebuild:
request.state = 'scheduled'
self.db.commit()
else:
self.schedule_rebuild(rebuild)