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


Python expression.and_方法代码示例

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


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

示例1: bookmark

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def bookmark(book_id, book_format):
    bookmark_key = request.form["bookmark"]
    ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id),
                                              ub.Bookmark.book_id == book_id,
                                              ub.Bookmark.format == book_format)).delete()
    if not bookmark_key:
        ub.session.commit()
        return "", 204

    lbookmark = ub.Bookmark(user_id=current_user.id,
                            book_id=book_id,
                            format=book_format,
                            bookmark_key=bookmark_key)
    ub.session.merge(lbookmark)
    ub.session.commit()
    return "", 201 
开发者ID:janeczku,项目名称:calibre-web,代码行数:18,代码来源:web.py

示例2: get_search_results

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def get_search_results(self, term):
        term.strip().lower()
        self.session.connection().connection.connection.create_function("lower", 1, lcase)
        q = list()
        authorterms = re.split("[, ]+", term)
        for authorterm in authorterms:
            q.append(Books.authors.any(func.lower(Authors.name).ilike("%" + authorterm + "%")))
        return self.session.query(Books).filter(self.common_filters(True)).filter(
            or_(Books.tags.any(func.lower(Tags.name).ilike("%" + term + "%")),
                Books.series.any(func.lower(Series.name).ilike("%" + term + "%")),
                Books.authors.any(and_(*q)),
                Books.publishers.any(func.lower(Publishers.name).ilike("%" + term + "%")),
                func.lower(Books.title).ilike("%" + term + "%")
                )).order_by(Books.sort).all()

    # Creates for all stored languages a translated speaking name in the array for the UI 
开发者ID:janeczku,项目名称:calibre-web,代码行数:18,代码来源:db.py

示例3: feed_shelf

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def feed_shelf(book_id):
    off = request.args.get("offset") or 0
    if current_user.is_anonymous:
        shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.is_public == 1,
                                                  ub.Shelf.id == book_id).first()
    else:
        shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id),
                                                           ub.Shelf.id == book_id),
                                                      and_(ub.Shelf.is_public == 1,
                                                           ub.Shelf.id == book_id))).first()
    result = list()
    # user is allowed to access shelf
    if shelf:
        books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == book_id).order_by(
            ub.BookShelf.order.asc()).all()
        for book in books_in_shelf:
            cur_book = calibre_db.get_book(book.book_id)
            result.append(cur_book)
    pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
                            len(result))
    return render_xml_template('feed.xml', entries=result, pagination=pagination) 
开发者ID:janeczku,项目名称:calibre-web,代码行数:23,代码来源:opds.py

示例4: get_rse_account_usage

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def get_rse_account_usage(rse_id, session=None):
    """
    Returns the account limit and usage for all for all accounts on a RSE.

    :param rse_id:   The id of the RSE.
    :param session:  Database session in use.
    :return:         List of dictionaries.
    """
    result = []
    query = session.query(models.AccountUsage.account, models.AccountUsage.files, models.AccountUsage.bytes, models.AccountLimit.bytes, models.RSE.rse)
    query = query.filter(models.RSE.id == models.AccountUsage.rse_id)
    query = query.outerjoin(models.AccountLimit, and_(models.AccountUsage.account == models.AccountLimit.account, models.AccountUsage.rse_id == models.AccountLimit.rse_id)).filter(models.AccountUsage.rse_id == rse_id)
    account_limits_tmp = query.all()
    for row in account_limits_tmp:
        result.append({'rse_id': rse_id, 'rse': row[4], 'account': row[0], 'used_files': row[1], 'used_bytes': row[2], 'quota_bytes': row[3]})
    return result 
开发者ID:rucio,项目名称:rucio,代码行数:18,代码来源:account_limit.py

示例5: sql_anded_together

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def sql_anded_together(conditions):
        """ Take a list of conditions and AND then together into an SQL expression

            In a few places in the code, we keep conditions in a list without wrapping them
            explicitly into a Boolean expression: just to keep it simple, easy to go through.

            This method will put them together, as required.
        """
        # No conditions: just return True, which is a valid sqlalchemy expression for filtering
        if not conditions:
            return True

        # AND them together
        cc = and_(*conditions)
        # Put parentheses around it, if necessary
        return cc.self_group() if len(conditions) > 1 else cc 
开发者ID:kolypto,项目名称:py-mongosql,代码行数:18,代码来源:filter.py

示例6: prepare_filter_query

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def prepare_filter_query(session, filter_list):
    q = session.query(Order)
    if filter_list:
      for f in filter_list:
        filter_data = f.split(" ")
        if len(filter_data) == 3:
          if filter_data[0] == "user_id" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.user_id == int(filter_data[2])))
          elif filter_data[0] == "account_id" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.account_id == int(filter_data[2])))
          elif filter_data[0] == "has_cum_qty" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.has_cum_qty == int(filter_data[2])))
          elif filter_data[0] == "has_leaves_qty" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.has_leaves_qty == int(filter_data[2])))
          elif filter_data[0] == "has_cxl_qty" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.has_cxl_qty == int(filter_data[2])))
    return q 
开发者ID:bitex-coin,项目名称:backend,代码行数:19,代码来源:models.py

示例7: get_last_trades

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def get_last_trades(session, since = None, page_size = None, offset = None, sort_column = None, sort_order='ASC'):
        if since is not None:
          if since > 1000000000:
            since = datetime.utcfromtimestamp(since)
            filter_obj  = and_(Trade.created >= since)
          else:
            filter_obj  = and_(Trade.id > int(since))
        else:
          today = datetime.now()
          since = today - timedelta(days=1)
          filter_obj  = and_(Trade.created >= since)

        trades = session.query(Trade).filter(filter_obj).order_by( Trade.id.desc())

        if page_size:
            trades = trades.limit(page_size)
        if offset:
            trades = trades.offset(offset)
        if sort_column:
            if sort_order == 'ASC':
                trades = trades.order(sort_column)
            else:
                trades = trades.order(sort_column).desc()

        return trades 
开发者ID:bitex-coin,项目名称:backend,代码行数:27,代码来源:models.py

示例8: subject_add_to_parent

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def subject_add_to_parent(request, *args, **kw):
    context = request.context
    parent_row = context.subject_row

    if not request.has_perm(perm_global_manage_subjects):
        raise APIError(403, "forbidden")

    q = t_subjects_subjects.select().where(and_(
        t_subjects_subjects.c.subject_id == request.validated_params.body["subject_id"],
        t_subjects_subjects.c.part_of_id == parent_row["id"],
    ))

    r = DBSession.execute(q).fetchone()

    if not r:
        q = t_subjects_subjects.insert({
            'subject_id': request.validated_params.body["subject_id"],
            'part_of_id': parent_row["id"],
        })

        update_connection().execute(q)

    return r_status.output({
        "status": "ok"
    }) 
开发者ID:ActiDoo,项目名称:gamification-engine,代码行数:27,代码来源:__init__.py

示例9: subject_remove_from_parent

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def subject_remove_from_parent(request, *args, **kw):
    context = request.context
    parent_row = context.subject_row

    if not request.has_perm(perm_global_manage_subjects):
        raise APIError(403, "forbidden")

    q = t_subjects_subjects.select().where(and_(
        t_subjects_subjects.c.subject_id == request.validated_params.body["subject_id"],
        t_subjects_subjects.c.part_of_id == parent_row["id"],
    ))

    r = DBSession.execute(q).fetchone()

    if r:
        q = t_subjects_subjects.delete().where(and_(
            t_subjects_subjects.c.subject_id == request.validated_params.body["subject_id"],
            t_subjects_subjects.c.part_of_id == parent_row["id"],
        ))

        update_connection().execute(q)

    return r_status.output({
        "status": "ok"
    }) 
开发者ID:ActiDoo,项目名称:gamification-engine,代码行数:27,代码来源:__init__.py

示例10: append

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def append(self,obj):
        with self.obj.backend.transaction(implicit = True):

            #if the object is not yet in a DB, we save it first.

            if obj.pk is None:
                self.obj.backend.save(obj)

            relationship_table = self.params['relationship_table']
            condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk,
                             relationship_table.c[self.params['pk_field_name']] == self.obj.pk)
            s = select([func.count(text('*'))]).where(condition)
            result = self.obj.backend.connection.execute(s)
            cnt = result.first()[0]
            if cnt:
                return #the object is already inside
            values = {
                self.params['pk_field_name'] : self.obj.pk,
                self.params['related_pk_field_name'] : obj.pk
            }
            insert = relationship_table.insert().values(**values)
            self.obj.backend.connection.execute(insert)
            self._queryset = None 
开发者ID:adewes,项目名称:blitzdb,代码行数:25,代码来源:relations.py

示例11: _make_simple_select

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def _make_simple_select(cls: Type[T], *args: ClauseElement) -> Select:
        """
        Create a simple ``SELECT * FROM table WHERE <args>`` statement.

        Args:
            *args: The WHERE clauses. If there are many elements, they're joined with AND.

        Returns:
            The SQLAlchemy SELECT statement object.
        """
        if len(args) > 1:
            return cls.t.select().where(and_(*args))
        elif len(args) == 1:
            return cls.t.select().where(args[0])
        else:
            return cls.t.select() 
开发者ID:tulir,项目名称:mautrix-python,代码行数:18,代码来源:base.py

示例12: scheduled_operation_log_delete_oldest

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def scheduled_operation_log_delete_oldest(context, operation_id,
                                          retained_num, excepted_states):
    table = models.ScheduledOperationLog
    session = get_session()
    with session.begin():
        result = model_query(context, table, session=session).filter_by(
            operation_id=operation_id).order_by(
            expression.desc(table.created_at)).limit(retained_num).all()

        if not result or len(result) < retained_num:
            return
        oldest_create_time = result[-1]['created_at']

        if excepted_states and isinstance(excepted_states, list):
            filters = expression.and_(
                table.operation_id == operation_id,
                table.created_at < oldest_create_time,
                table.state.notin_(excepted_states))
        else:
            filters = expression.and_(
                table.operation_id == operation_id,
                table.created_at < oldest_create_time)

        model_query(context, table, session=session).filter(
            filters).delete(synchronize_session=False) 
开发者ID:openstack,项目名称:karbor,代码行数:27,代码来源:api.py

示例13: toggle_read

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def toggle_read(book_id):
    if not config.config_read_column:
        book = ub.session.query(ub.ReadBook).filter(and_(ub.ReadBook.user_id == int(current_user.id),
                                                         ub.ReadBook.book_id == book_id)).first()
        if book:
            if book.read_status == ub.ReadBook.STATUS_FINISHED:
                book.read_status = ub.ReadBook.STATUS_UNREAD
            else:
                book.read_status = ub.ReadBook.STATUS_FINISHED
        else:
            readBook = ub.ReadBook(user_id=current_user.id, book_id = book_id)
            readBook.read_status = ub.ReadBook.STATUS_FINISHED
            book = readBook
        if not book.kobo_reading_state:
            kobo_reading_state = ub.KoboReadingState(user_id=current_user.id, book_id=book_id)
            kobo_reading_state.current_bookmark = ub.KoboBookmark()
            kobo_reading_state.statistics = ub.KoboStatistics()
            book.kobo_reading_state = kobo_reading_state
        ub.session.merge(book)
        ub.session.commit()
    else:
        try:
            calibre_db.update_title_sort(config)
            book = calibre_db.get_filtered_book(book_id)
            read_status = getattr(book, 'custom_column_' + str(config.config_read_column))
            if len(read_status):
                read_status[0].value = not read_status[0].value
                calibre_db.session.commit()
            else:
                cc_class = db.cc_classes[config.config_read_column]
                new_cc = cc_class(value=1, book=book_id)
                calibre_db.session.add(new_cc)
                calibre_db.session.commit()
        except (KeyError, AttributeError):
            log.error(u"Custom Column No.%d is not exisiting in calibre database", config.config_read_column)
        except OperationalError as e:
            calibre_db.session.rollback()
            log.error(u"Read status could not set: %e", e)

    return "" 
开发者ID:janeczku,项目名称:calibre-web,代码行数:42,代码来源:web.py

示例14: toggle_archived

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def toggle_archived(book_id):
    archived_book = ub.session.query(ub.ArchivedBook).filter(and_(ub.ArchivedBook.user_id == int(current_user.id),
                                                                  ub.ArchivedBook.book_id == book_id)).first()
    if archived_book:
        archived_book.is_archived = not archived_book.is_archived
        archived_book.last_modified = datetime.utcnow()
    else:
        archived_book = ub.ArchivedBook(user_id=current_user.id, book_id=book_id)
        archived_book.is_archived = True
    ub.session.merge(archived_book)
    ub.session.commit()
    return "" 
开发者ID:janeczku,项目名称:calibre-web,代码行数:14,代码来源:web.py

示例15: common_filters

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import and_ [as 别名]
def common_filters(self, allow_show_archived=False):
        if not allow_show_archived:
            archived_books = (
                ub.session.query(ub.ArchivedBook)
                    .filter(ub.ArchivedBook.user_id == int(current_user.id))
                    .filter(ub.ArchivedBook.is_archived == True)
                    .all()
            )
            archived_book_ids = [archived_book.book_id for archived_book in archived_books]
            archived_filter = Books.id.notin_(archived_book_ids)
        else:
            archived_filter = true()

        if current_user.filter_language() != "all":
            lang_filter = Books.languages.any(Languages.lang_code == current_user.filter_language())
        else:
            lang_filter = true()
        negtags_list = current_user.list_denied_tags()
        postags_list = current_user.list_allowed_tags()
        neg_content_tags_filter = false() if negtags_list == [''] else Books.tags.any(Tags.name.in_(negtags_list))
        pos_content_tags_filter = true() if postags_list == [''] else Books.tags.any(Tags.name.in_(postags_list))
        if self.config.config_restricted_column:
            pos_cc_list = current_user.allowed_column_value.split(',')
            pos_content_cc_filter = true() if pos_cc_list == [''] else \
                getattr(Books, 'custom_column_' + str(self.config.config_restricted_column)). \
                    any(cc_classes[self.config.config_restricted_column].value.in_(pos_cc_list))
            neg_cc_list = current_user.denied_column_value.split(',')
            neg_content_cc_filter = false() if neg_cc_list == [''] else \
                getattr(Books, 'custom_column_' + str(self.config.config_restricted_column)). \
                    any(cc_classes[self.config.config_restricted_column].value.in_(neg_cc_list))
        else:
            pos_content_cc_filter = true()
            neg_content_cc_filter = false()
        return and_(lang_filter, pos_content_tags_filter, ~neg_content_tags_filter,
                    pos_content_cc_filter, ~neg_content_cc_filter, archived_filter)

    # Fill indexpage with all requested data from database 
开发者ID:janeczku,项目名称:calibre-web,代码行数:39,代码来源:db.py


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