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


Python sqlalchemy.asc方法代码示例

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


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

示例1: get_table

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def get_table(request: web.Request) -> web.Response:
    instance_id = request.match_info.get("id", "")
    instance = PluginInstance.get(instance_id, None)
    if not instance:
        return resp.instance_not_found
    elif not instance.inst_db:
        return resp.plugin_has_no_database
    tables = instance.get_db_tables()
    try:
        table = tables[request.match_info.get("table", "")]
    except KeyError:
        return resp.table_not_found
    try:
        order = [tuple(order.split(":")) for order in request.query.getall("order")]
        order = [(asc if sort.lower() == "asc" else desc)(table.columns[column])
                 if sort else table.columns[column]
                 for column, sort in order]
    except KeyError:
        order = []
    limit = int(request.query.get("limit", 100))
    return execute_query(instance, table.select().order_by(*order).limit(limit)) 
开发者ID:maubot,项目名称:maubot,代码行数:23,代码来源:instance_database.py

示例2: load_slice

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def load_slice(cls, context, limit, offset, *,
                         domain_name=None, group_id=None, user_id=None,
                         order_key=None, order_asc=None):
        from .user import users
        async with context['dbpool'].acquire() as conn:
            if order_key is None:
                _ordering = vfolders.c.created_at
            else:
                _order_func = sa.asc if order_asc else sa.desc
                _ordering = _order_func(getattr(vfolders.c, order_key))
            j = sa.join(vfolders, users, vfolders.c.user == users.c.uuid)
            query = (
                sa.select([vfolders])
                .select_from(j)
                .order_by(_ordering)
                .limit(limit)
                .offset(offset)
            )
            if domain_name is not None:
                query = query.where(users.c.domain_name == domain_name)
            if group_id is not None:
                query = query.where(vfolders.c.group == group_id)
            if user_id is not None:
                query = query.where(vfolders.c.user == user_id)
            return [cls.from_row(context, r) async for r in conn.execute(query)] 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:27,代码来源:vfolder.py

示例3: execute

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def execute(self):
        from saq.database import Message
        attempted_ids = [] # list of Message.id values we want to delete
        for message in saq.db.query(Message).order_by(Message.insert_date.asc()):
            try:
                dispatch(message)
                attempted_ids.append(message.id)
            except Exception as e:
                logging.error(f"unable to dispatch {message}: {e}")

            if control_function is not None and control_function():
                break

        if attempted_ids:
            saq.db.execute(Message.__table__.delete().where(Message.id.in_(attempted_ids)))
            saq.db.commit()

#
# global mapping of notification systems to the handlers that process them 
开发者ID:IntegralDefense,项目名称:ACE,代码行数:21,代码来源:__init__.py

示例4: dispatch_messages

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def dispatch_messages(control_function=None):
    """Dispatches all messages currently in queue.
       An optional control_function can return True to break out of the loop prematurely."""
    from saq.database import Message
    attempted_ids = [] # list of Message.id values we want to delete
    for message in saq.db.query(Message).order_by(Message.insert_date.asc()):
        try:
            dispatch(message)
            attempted_ids.append(message.id)
        except Exception as e:
            logging.error(f"unable to dispatch {message}: {e}")

        if control_function is not None and control_function():
            break

    if attempted_ids:
        saq.db.execute(Message.__table__.delete().where(Message.id.in_(attempted_ids)))
        saq.db.commit() 
开发者ID:IntegralDefense,项目名称:ACE,代码行数:20,代码来源:__init__.py

示例5: __init__

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def __init__(self, params, sort_dir=constants.DEFAULT_SORT_DIR):
        """Pagination Helper takes params and a default sort direction

        :param params: Contains the following:
                       limit: maximum number of items to return
                       marker: the last item of the previous page; we return
                               the next results after this value.
                       sort: array of attr by which results should be sorted
        :param sort_dir: default direction to sort (asc, desc)
        """
        self.marker = params.get('marker')
        self.sort_dir = self._validate_sort_dir(sort_dir)
        self.limit = self._parse_limit(params)
        self.sort_keys = self._parse_sort_keys(params)
        self.params = params
        self.filters = None
        self.page_reverse = params.get('page_reverse', 'False') 
开发者ID:openstack,项目名称:octavia,代码行数:19,代码来源:pagination.py

示例6: get

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def get(self):
        resdata = []
        prices = db_session.query(
            FuelFill
        ).filter(
            FuelFill.cost_per_gallon.__ne__(None)
        ).order_by(asc(FuelFill.date))
        for point in prices.all():
            ds = point.date.strftime('%Y-%m-%d')
            resdata.append({
                'date': ds,
                'price': float(point.cost_per_gallon)
            })
        res = {
            'data': resdata
        }
        return jsonify(res) 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:19,代码来源:fuel.py

示例7: _unpick_search

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def _unpick_search(sort, allowed_fields=None, total=None):
    ''' This is a helper function that takes a sort string
    eg 'name asc, last_modified desc' and returns a list of
    split field order eg [('name', 'asc'), ('last_modified', 'desc')]
    allowed_fields can limit which field names are ok.
    total controls how many sorts can be specifed '''
    sorts = []
    split_sort = sort.split(',')
    for part in split_sort:
        split_part = part.strip().split()
        field = split_part[0]
        if len(split_part) > 1:
            order = split_part[1].lower()
        else:
            order = 'asc'
        if allowed_fields:
            if field not in allowed_fields:
                raise ValidationError('Cannot sort by field `%s`' % field)
        if order not in ['asc', 'desc']:
            raise ValidationError('Invalid sort direction `%s`' % order)
        sorts.append((field, order))
    if total and len(sorts) > total:
        raise ValidationError(
            'Too many sort criteria provided only %s allowed' % total)
    return sorts 
开发者ID:italia,项目名称:daf-recipes,代码行数:27,代码来源:get.py

示例8: query_for_task_instance

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def query_for_task_instance(task_instance, descending=False, session=None):
        """
        Returns query for task reschedules for a given the task instance.

        :param session: the database session object
        :type session: sqlalchemy.orm.session.Session
        :param task_instance: the task instance to find task reschedules for
        :type task_instance: airflow.models.TaskInstance
        :param descending: If True then records are returned in descending order
        :type descending: bool
        """
        TR = TaskReschedule
        qry = (
            session
            .query(TR)
            .filter(TR.dag_id == task_instance.dag_id,
                    TR.task_id == task_instance.task_id,
                    TR.execution_date == task_instance.execution_date,
                    TR.try_number == task_instance.try_number)
        )
        if descending:
            return qry.order_by(desc(TR.id))
        else:
            return qry.order_by(asc(TR.id)) 
开发者ID:apache,项目名称:airflow,代码行数:26,代码来源:taskreschedule.py

示例9: get_by_time

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def get_by_time(cls, ts, range=None):
        if range == None:
            # XXX TODO: Test this
            return database.db.getSession().query(Blocks).filter(Blocks.timestamp <= ts).first()
        else:
            ts_start = ts-range
            ts_end = ts
            return list(database.db.getSession().query(Blocks).filter(and_(Blocks.timestamp >= ts_start, Blocks.timestamp <= ts_end)).order_by(asc(Blocks.height)))



# def main():
#     PROCESS = "GrinPoolBaseModelBlockTest"
#     from grinlib import lib
#     config = lib.get_config()
#     logger = lib.get_logger(PROCESS)
#     logger.error("test")
#     database = lib.get_db()
# 
# 
# if __name__ == "__main__":
#     main() 
开发者ID:grin-pool,项目名称:grin-pool,代码行数:24,代码来源:blocks.py

示例10: __init__

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def __init__(self, x):
        if isinstance(x, str):
            x = column(x)
        if _get_order_direction(x) is None:
            x = asc(x)
        self.uo = x
        _warn_if_nullable(self.comparable_value)
        self.full_name = str(self.element)
        try:
            table_name, name = self.full_name.split('.', 1)
        except ValueError:
            table_name = None
            name = self.full_name

        self.table_name = table_name
        self.name = name 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:18,代码来源:columns.py

示例11: test_oc

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def test_oc():
    a = asc('a')
    b = desc('a')
    c = asc('b')
    n = nullslast(desc('a'))

    a = OC(a)
    b = OC(b)
    c = OC(c)
    n = OC(n)

    assert str(a) == str(OC('a'))
    assert a.is_ascending
    assert not b.is_ascending
    assert not n.reversed.reversed.is_ascending
    assert n.reversed.is_ascending
    assert not n.is_ascending # make sure reversed doesn't modify in-place
    assert str(a.element) == str(b.element) == str(n.element)
    assert str(a) == str(b.reversed)
    assert str(n.reversed.reversed) == str(n)

    assert a.name == 'a'
    assert n.name == 'a'
    assert n.quoted_full_name == 'a'
    assert repr(n) == '<OC: a DESC NULLS LAST>' 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:27,代码来源:test_internals.py

示例12: test_order_manipulation

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def test_order_manipulation():
    is_asc = lambda c: _get_order_direction(c) == asc_op
    flip = _reverse_order_direction
    scrub = _remove_order_direction
    base = column('a')
    l = base.label('test')
    a = asc(base)
    d = desc(base)
    assert is_asc(a)
    assert not is_asc(d)
    equal_pairs = [
        (scrub(a), base),
        (scrub(d), base),
        (scrub(asc(l)), scrub(a.label('test'))),
        (flip(a), d),
        (flip(d), a),
    ]
    for lhs, rhs in equal_pairs:
        assert str(lhs) == str(rhs) 
开发者ID:djrobstep,项目名称:sqlakeyset,代码行数:21,代码来源:test_internals.py

示例13: test_paginate_query_no_pagination

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def test_paginate_query_no_pagination(self):
        self.query.order_by.return_value = self.query
        self.mock_asc.side_effect = ['asc']
        self.mock_desc.side_effect = ['desc']

        utils.paginate_query(self.query, self.model, 5,
                             ['user_id', 'project_id'],
                             sort_dirs=['asc', 'desc'])

        self.mock_asc.assert_called_once_with(self.model.user_id)
        self.mock_desc.assert_called_once_with(self.model.project_id)
        self.query.order_by.assert_has_calls([
            mock.call('asc'),
            mock.call('desc'),
        ])
        self.query.limit.assert_called_once_with(5) 
开发者ID:openstack,项目名称:oslo.db,代码行数:18,代码来源:test_utils.py

示例14: all_training_data

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def all_training_data(self, limit: int = None, order_by: str = None, order='desc') -> List[Tuple[bytes]]:
        query = self._session.query(self._table_type.text)
        if order_by and order == 'desc':
            query = query.order_by(desc(order_by))
        elif order_by and order == 'asc':
            query = query.order_by(asc(order_by))
        if limit:
            query = query.limit(limit)
        return query.all() 
开发者ID:csvance,项目名称:armchair-expert,代码行数:11,代码来源:storage_common.py

示例15: load_slice

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import asc [as 别名]
def load_slice(
        cls, context, limit, offset, *,
        scaling_group=None,
        status=None,
        order_key=None,
        order_asc=True,
    ) -> Sequence[Agent]:
        async with context['dbpool'].acquire() as conn:
            # TODO: optimization for pagination using subquery, join
            if order_key is None:
                _ordering = agents.c.id
            else:
                _order_func = sa.asc if order_asc else sa.desc
                _ordering = _order_func(getattr(agents.c, order_key))
            query = (
                sa.select([agents])
                .select_from(agents)
                .order_by(_ordering)
                .limit(limit)
                .offset(offset)
            )
            if scaling_group is not None:
                query = query.where(agents.c.scaling_group == scaling_group)
            if status is not None:
                status = AgentStatus[status]
                query = query.where(agents.c.status == status)
            return [
                cls.from_row(context, row) async for row in conn.execute(query)
            ] 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:31,代码来源:agent.py


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