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


Python func.max方法代码示例

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


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

示例1: __init__

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def __init__(self, credentials: TwitterApiCredentials, screen_name: str):
        self._credentials = credentials
        self.screen_name = screen_name
        self.session = Session()

        row = self.session.query(func.max(Tweet.status_id)).first()
        if row is not None:
            since_id = row[0] if row[0] is not None else 0
        else:
            since_id = 0

        self._latest_tweet_processed_id = since_id

        self.scraper_status = self.session.query(ScraperStatus).filter(
            ScraperStatus.screen_name == self.screen_name).first()
        if self.scraper_status is None:
            self.scraper_status = ScraperStatus(screen_name=screen_name, since_id=since_id)
            self.session.add(self.scraper_status)
            self.session.commit() 
开发者ID:csvance,项目名称:armchair-expert,代码行数:21,代码来源:twitter.py

示例2: get_next_id

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def get_next_id(session, projectid):
    """ Returns the next identifier of a project ticket or pull-request
    based on the identifier already in the database.
    """
    query1 = session.query(func.max(model.Issue.id)).filter(
        model.Issue.project_id == projectid
    )

    query2 = session.query(func.max(model.PullRequest.id)).filter(
        model.PullRequest.project_id == projectid
    )

    ids = [el[0] for el in query1.union(query2).all() if el[0] is not None]
    nid = 0
    if ids:
        nid = max(ids)

    return nid + 1 
开发者ID:Pagure,项目名称:pagure,代码行数:20,代码来源:query.py

示例3: list_recent_networks

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def list_recent_networks(self) -> List[Network]:
        """List the most recently created version of each network (by name)."""
        most_recent_times = self.session.query(
            Network.name.label('network_name'),
            func.max(Network.created).label('max_created'),
        )

        most_recent_times = most_recent_times.group_by(Network.name).subquery('most_recent_times')

        and_condition = and_(
            most_recent_times.c.network_name == Network.name,
            most_recent_times.c.max_created == Network.created,
        )

        most_recent_networks = self.session.query(Network).join(most_recent_times, and_condition)

        return most_recent_networks.all() 
开发者ID:pybel,项目名称:pybel,代码行数:19,代码来源:cache_manager.py

示例4: test_00_verify_db

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def test_00_verify_db(self, testdb):
        b = testdb.query(Project).get(1)
        assert b is not None
        assert b.name == 'P1'
        assert b.notes == 'ProjectOne'
        assert b.is_active is True
        b = testdb.query(Project).get(2)
        assert b is not None
        assert b.name == 'P2'
        assert b.notes == 'ProjectTwo'
        assert b.is_active is True
        b = testdb.query(Project).get(3)
        assert b is not None
        assert b.name == 'P3Inactive'
        assert b.notes == 'ProjectThreeInactive'
        assert b.is_active is False
        assert testdb.query(Project).with_entities(
            func.max(Project.id)
        ).scalar() == 3
        assert testdb.query(BoMItem).with_entities(
            func.max(BoMItem.id)
        ).scalar() == 5 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:24,代码来源:test_projects.py

示例5: filter

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def filter(self, qs, value):
        if value in EMPTY_VALUES:
            return qs

        y_column = getattr(self.model, value['y_column'])

        if value['y_func'] == 'count':
            y_func = func.count(y_column)
        elif value['y_func'] == 'sum':
            y_func = func.sum(y_column)
        elif value['y_func'] == 'min':
            y_func = func.min(y_column)
        elif value['y_func'] == 'max':
            y_func = func.max(y_column)
        elif value['y_func'] == 'avg':
            y_func = func.avg(y_column)
        else:
            return qs.filter(sql.false())

        qs = qs.session.query(y_func).one()

        return qs 
开发者ID:jet-admin,项目名称:jet-bridge,代码行数:24,代码来源:model_aggregate.py

示例6: test_sort_aggregation_translation_failure

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def test_sort_aggregation_translation_failure(self):
        # This works around a nuance with our choice to hackishly fuse SortBy
        # after Aggregate to produce a single select statement rather than an
        # inline view.
        t = self.alltypes

        agg = t.group_by('string_col').aggregate(
            t.double_col.max().name('foo')
        )
        expr = agg.sort_by(ibis.desc('foo'))

        sat = self.sa_alltypes.alias('t1')
        base = (
            sa.select(
                [sat.c.string_col, F.max(sat.c.double_col).label('foo')]
            ).group_by(sat.c.string_col)
        ).alias('t0')

        ex = (
            sa.select([base.c.string_col, base.c.foo])
            .select_from(base)
            .order_by(sa.desc('foo'))
        )

        self._compare_sqla(expr, ex) 
开发者ID:ibis-project,项目名称:ibis,代码行数:27,代码来源:test_sqlalchemy.py

示例7: _additional_events

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def _additional_events(self, tracker: DialogueStateTracker) -> Iterator:
        """Return events from the tracker which aren't currently stored."""

        from sqlalchemy import func
        query = self.session.query(func.max(self.SQLEvent.timestamp))
        max_timestamp = query.filter_by(sender_id=tracker.sender_id).scalar()

        if max_timestamp is None:
            max_timestamp = 0

        latest_events = []

        for event in reversed(tracker.events):
            if event.timestamp > max_timestamp:
                latest_events.append(event)
            else:
                break

        return reversed(latest_events) 
开发者ID:RasaHQ,项目名称:rasa_core,代码行数:21,代码来源:tracker_store.py

示例8: ini_names

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def ini_names(self, name_table, field):
        if field != GAME and field != STAT:
            s = select([name_table])
            name_dict = dict([(n.name.title().translate(removeDic), n.id)
                              for n in self.conn.execute(s)])

            if field == EVENT:
                self.event_dict = name_dict
            elif field == SITE:
                self.site_dict = name_dict
            elif field == PLAYER:
                self.player_dict = name_dict
            elif field == ANNOTATOR:
                self.annotator_dict = name_dict
            elif field == SOURCE:
                self.source_dict = name_dict

        s = select([func.max(name_table.c.id).label('maxid')])
        maxid = self.conn.execute(s).scalar()
        if maxid is None:
            next_id = 1
        else:
            next_id = maxid + 1

        return next_id 
开发者ID:pychess,项目名称:pychess,代码行数:27,代码来源:PgnImport.py

示例9: event_summery

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def event_summery(self):
        with self.session_scope() as session:
            time = session.query(func.min(Event.time), func.max(Event.time)).all()
            print(f'Event time duration:')
            print(f'From: {time[0][0].isoformat()}')
            print(f'To:   {time[0][1].isoformat()}\n')

            event_count = session.query(Event).count()
            print(f'Total {event_count} events\n')

            boundary = session.query(func.min(Event.longitude), func.max(Event.longitude),
                                     func.min(Event.latitude), func.max(Event.latitude)).all()
            print(f'Event boundary:')
            print(f'West: {boundary[0][0]:>8.4f}')
            print(f'East: {boundary[0][1]:>8.4f}')
            print(f'South: {boundary[0][2]:>7.4f}')
            print(f'North: {boundary[0][3]:>7.4f}\n')
            self.pick_summery() 
开发者ID:SeisNN,项目名称:SeisNN,代码行数:20,代码来源:db.py

示例10: get_last_run_per_resource

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def get_last_run_per_resource():
    """return last N Runs with results for each Resource"""

    # We need an Innerjoin on same table
    # example: https://stackoverflow.com/questions/2411559/
    #    how-do-i-query-sql-for-a-latest-record-date-for-each-user

    sql = """
    select t.resource_identifier, t.identifier, t.success
    from Run t
    inner join (
        select resource_identifier, max(identifier) as MaxId
        from Run
        group by resource_identifier
    ) tm on t.resource_identifier = tm.resource_identifier
    and t.identifier = tm.MaxId;
    """

    # Use raw query on SQLAlchemy, as the programmatic buildup
    # would be overly complex, if even possible.
    last_runs = DB.session.execute(sql)
    return last_runs 
开发者ID:geopython,项目名称:GeoHealthCheck,代码行数:24,代码来源:models.py

示例11: sync_time_gaps

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def sync_time_gaps(self, gaps=None):
        """
        Uses a list([start, end], [start, end])
        to request/load OHLC data from the API to the database.
        :param gaps:
        :return:
        """
        if gaps is None:
            gaps = self.get_time_gaps()

        for start, end in gaps:
            _, max = self.get_time_bump(start, end, bump_start=False)
            if max < end:
                df = DataFrame()
                while max < end:
                    df = df.append(self.request_ohlc(start, max))
                    start, max = self.get_time_bump(start, end)
            else:
                df = self.request_ohlc(start, end)

            if df.empty:
                logger.info("Failed 2nd time on gap {}: "
                            "{} {}".format(self.pair, start, end))
                continue
            self.load_df(df, thread=False,) 
开发者ID:zbarge,项目名称:stocklook,代码行数:27,代码来源:db.py

示例12: _raw_statistics_time_range

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def _raw_statistics_time_range(cls, s, statistics_owner=None):
        '''
        The time range over which statistics exist (optionally restricted by owner),
        ignoring constants at "time zero".  This is the first to the last time for
        any statistics - it pays no attention to gaps.
        '''
        from .statistic import StatisticJournal, StatisticName
        q = s.query(func.min(StatisticJournal.time), func.max(StatisticJournal.time)). \
            filter(StatisticJournal.time > to_time(2 * 24 * 60 * 60.0))
        if statistics_owner:
            q = q.join(StatisticName).filter(StatisticName.owner == statistics_owner)
        start, finish = q.one()   # skip entire first day because tz
        if start and finish:
            return start, finish
        else:
            raise NoStatistics('No statistics are currently defined') 
开发者ID:andrewcooke,项目名称:choochoo,代码行数:18,代码来源:source.py

示例13: get_apps

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def get_apps(request: Request, app_type: str, page: int):
    """
    获取app
    - uri[app类型(all/iOS/android)-app_type: str, 页码(从1起)-page: int], format[时间s-t: int]
    :param request:
    :return:
    """
    time = Date.time2datetime(request.args.get('t'))
    if not time:
        raise BadRequest('')

    if page <= 0:
        log.debug('page need greater zero')
        raise BadRequest('')

    kw = request.args.get('kw')

    session = Session()
    query = session.query(AppModel, AppVersionModel.version_code, AppVersionModel.version_name,
                          func.max(AppVersionModel.create_at).label('_update_at')) \
        .join(AppVersionModel, AppModel.id == AppVersionModel.app_id) \
        .filter(AppModel.create_at <= time)
    if app_type != 'all':  # 安装包类型过滤
        query = query.filter(AppModel.type == app_type)

    if kw:
        query = query.filter(AppModel.name.like('%{}%'.format(kw)))

    result = query.order_by(desc(AppModel.create_at)) \
        .group_by(AppModel.short_chain_uri_) \
        .offset((page - 1) * Config.apps_limit) \
        .limit(Config.apps_limit) \
        .all()

    datas = []
    for app, version_code, version_name, _ in result:
        app.version_code = version_code
        app.version_name = version_name
        datas.append(app)

    return JsonResult.ok(datas).response_json() 
开发者ID:skytoup,项目名称:AppServer,代码行数:43,代码来源:apps.py

示例14: get_max_block_number

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def get_max_block_number(cls):
        current_session = get_current_session()
        with current_session.db_session_scope():

            max_block_number = current_session.db_session.query(
                               func.max(cls.block_number)).scalar()
        return max_block_number 
开发者ID:analyseether,项目名称:ether_sql,代码行数:9,代码来源:blocks.py

示例15: apply

# 需要导入模块: from sqlalchemy import func [as 别名]
# 或者: from sqlalchemy.func import max [as 别名]
def apply(self, q, bindings, fields, distinct=False):
        """ Define a set of fields to return for a non-aggregated query. """
        info = []

        group_by = None

        for field in self.parse(fields):
            for concept in self.cube.model.match(field):
                info.append(concept.ref)
                table, column = concept.bind(self.cube)
                bindings.append(Binding(table, concept.ref))
                if distinct:
                    if group_by is None:
                        q = q.group_by(column)
                        group_by = column
                    else:
                        min_column = func.max(column)
                        min_column = min_column.label(column.name)
                        column = min_column
                q = q.column(column)

        if not len(self.results):
            # If no fields are requested, return all available fields.
            for concept in list(self.cube.model.attributes) + \
                    list(self.cube.model.measures):
                info.append(concept.ref)
                table, column = concept.bind(self.cube)
                bindings.append(Binding(table, concept.ref))
                q = q.column(column)

        return info, q, bindings 
开发者ID:openspending,项目名称:babbage,代码行数:33,代码来源:fields.py


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