sqlalchemy.and_

Here are the examples of the python api sqlalchemy.and_ taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

868 Examples 7

3 Source : other.py
with GNU General Public License v3.0
from akhefale

def vetoed():


    posts = Post.query.filter(
        and_(
            Post.union_id == current_user.union_id,
            Post.vetoed_by_id != None
        )
    ).all()

    if posts:
        return render_template('vetoed.html', posts=posts)
    else:
        return render_template('vetoed.html', msg=NO_RESULTS_ERROR)


# veto a solution
@view.route('/veto/  <  int:post_id>', methods=['GET', 'POST'])

3 Source : other.py
with GNU General Public License v3.0
from akhefale

def completed():
    # Find posts
    posts = Post.query.filter(
        and_(
            Post.phase == 4,
            Post.union_id == current_user.union_id,
            Post.vetoed_by_id == None
        )
    ).all()

    if posts:
        return render_template('completed.html', posts=posts)
    else:
        return render_template('completed.html', msg=NO_RESULTS_ERROR)


@view.route('/about')

3 Source : phase1.py
with GNU General Public License v3.0
from akhefale

def get():
    # find posts
    posts = Post.query.filter(
        and_(
            Post.union_id == current_user.union_id,
            Post.phase == 1)).all()

    if posts:
        return render_template('phase1.html', posts=posts)
    else:
        return render_template('phase1.html', msg=NO_RESULTS_ERROR)


# single post, phase 1
@view.route('/phase1/post/  <  int:post_id>', methods=['GET', 'POST'])

3 Source : phase2.py
with GNU General Public License v3.0
from akhefale

def get():

    # find posts
    posts = Post.query.filter(
        and_(
            Post.union_id == current_user.union_id,
            Post.phase == 2)).all()

    if posts:
        return render_template('phase2.html', posts=posts)
    else:
        return render_template('phase2.html', msg=NO_RESULTS_ERROR)


# single post, phase 2
@view.route('/phase2/post/  <  int:post_id>', methods=['GET', 'POST'])

3 Source : phase3.py
with GNU General Public License v3.0
from akhefale

def get():
    # find posts
    posts = Post.query.filter(
        and_(
            Post.union_id == current_user.union_id,
            Post.phase == 3,
            Post.vetoed_by == None
        )).all()

    if posts:
        return render_template('phase3.html', posts=posts)

    else:
        return render_template('phase3.html', msg=NO_RESULTS_ERROR)


# single post, phase 3
@view.route('/phase3/post/  <  int:post_id>')

3 Source : exporter.py
with MIT License
from alexandermendes

    def _stream_annotation_data(self, collection):
        """Stream the contents of an AnnotationCollection from the database."""
        table = Annotation.__table__
        where_clauses = [
            table.c.collection_key == collection.key,
            table.c.deleted is not True
        ]

        query = table.select().where(and_(*where_clauses))
        exec_opts = dict(stream_results=True)
        res = db.session.connection(execution_options=exec_opts).execute(query)
        while True:
            chunk = res.fetchmany(10000)
            if not chunk:
                break
            for row in chunk:
                yield dict(row)

    def generate_data(self, collection_id):

3 Source : bag_controller.py
with MIT License
from AMZ-Driverless

def find_bag_in_database(session, store_name, bag_name):
    q = session.query(RosbagStore).filter(RosbagStore.name == store_name)  # type: Query
    if q.count() == 0:
        return None, Error(code=404, message="Store not found")
    store = q[0]

    q = session.query(Rosbag).filter(
        and_(Rosbag.store_id == store.uid, Rosbag.name == bag_name)
    )  # type: Query

    if q.count() == 0:
        return None, Error(code=404, message="Bag not found")

    return q[0], None


@auth.requires_auth_with_permission(Permissions.BagWrite)

3 Source : block_task_meta.py
with Apache License 2.0
from analyseether

    def get_blocks_to_be_pushed_in_queue(cls, current_session):
        current_session = get_current_session()
        current_eth_blocknumber = current_session.w3.eth.blockNumber
        block_lag = current_session.settings.BLOCK_LAG
        query = current_session.db_session.query(cls.block_number).filter(
            and_(cls.state=='WAITING',
            cls.block_number   <   current_eth_blocknumber-block_lag))
        return query.from_self().distinct()

3 Source : test_types.py
with MIT License
from analyzeDFIR

    def test_crit_spaces_in_key(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c['data']

        # limit the rows here to avoid PG error
        # "cannot extract field from a non-object", which is
        # fixed in 9.4 but may exist in 9.3
        self._test_index_criteria(
            and_(
                name.in_(["r1", "r2", "r3"]),
                cast(col["key two"], String) == '"value2"'
            ),
            "r2"
        )

    @config.requirements.json_array_indexes

3 Source : test_types.py
with MIT License
from analyzeDFIR

    def test_crit_simple_int(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c['data']

        # limit the rows here to avoid PG error
        # "cannot extract array element from a non-array", which is
        # fixed in 9.4 but may exist in 9.3
        self._test_index_criteria(
            and_(name == 'r4', cast(col[1], String) == '"two"'),
            "r4"
        )

    def test_crit_mixed_path(self):

3 Source : test_types.py
with MIT License
from analyzeDFIR

    def test_crit_against_string_basic(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c['data']

        self._test_index_criteria(
            and_(name == 'r6', cast(col["b"], String) == '"some value"'),
            "r6"
        )

    def test_crit_against_string_coerce_type(self):

3 Source : test_types.py
with MIT License
from analyzeDFIR

    def test_crit_against_string_coerce_type(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c['data']

        self._test_index_criteria(
            and_(name == 'r6',
                 cast(col["b"], String) == type_coerce("some value", JSON)),
            "r6",
            test_literal=False
        )

    def test_crit_against_int_basic(self):

3 Source : test_types.py
with MIT License
from analyzeDFIR

    def test_crit_against_int_basic(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c['data']

        self._test_index_criteria(
            and_(name == 'r6', cast(col["a"], String) == '5'),
            "r6"
        )

    def test_crit_against_int_coerce_type(self):

3 Source : test_types.py
with MIT License
from analyzeDFIR

    def test_crit_against_int_coerce_type(self):
        name = self.tables.data_table.c.name
        col = self.tables.data_table.c['data']

        self._test_index_criteria(
            and_(name == 'r6', cast(col["a"], String) == type_coerce(5, JSON)),
            "r6",
            test_literal=False
        )

    def test_unicode_round_trip(self):

3 Source : sql.py
with Apache License 2.0
from andrewyates

    def clear_zombie_runs(self):
        # TODO first find runs, then do for_update later when clearing them only
        with self.session_scope() as session:
            for run in (
                session.query(Run)
                .filter(sa.and_(Run.status == "RUNNING", Run.hostname == socket.gethostname()))
                .with_for_update()
            ):
                if not os.path.exists(f"/proc/{run.pid}"):
                    print(f"found zombie run_id={run.run_id} with pid: {run.pid}")
                    run.status = "FAILED"
                    session.add(run)

    def get_eligible_run(self, max_tries=3):

3 Source : calendar.py
with MIT License
from apoclyps

def get_all_calendar():
    """Get all calendar"""
    location = request.args.get("location", "belfast", type=str)
    location = location.lower()

    current_time = datetime.utcnow()
    recent_past = current_time - timedelta(hours=6)

    events = Event.query.filter(
        and_(Event.location == location, Event.start >= recent_past)
    )

    response_object = {
        "status": "success",
        "data": [_transform(index, event) for index, event in enumerate(events)],
    }
    return jsonify(response_object), 200

3 Source : database_explorer.py
with Apache License 2.0
from arkhn

def handle_between_filter(col, value):
    values = value.split(",")
    if len(values) != 2:
        raise ValueError("BETWEEN filter expects 2 values separated by a comma.")
    min_val = values[0].strip()
    max_val = values[1].strip()
    return and_(col.__ge__(min_val), col.__le__(max_val))


SQL_RELATIONS_TO_METHOD: Dict[str, Callable[[Column, str], Callable]] = {

3 Source : users.py
with MIT License
from arsalasif

    def validate_email(cls, email, values):
        if email and User.exists(and_(User.email == email, User.id != values['model'].id)):
            raise ValueError('email already exists')
        return email

    @validator('username')

3 Source : users.py
with MIT License
from arsalasif

    def validate_username(cls, username, values):
        if username and User.exists(and_(User.username == username, User.id != values['model'].id)):
            raise ValueError('username already exists')
        return username

    @validator('password')

3 Source : filters.py
with MIT License
from art1415926535

    def is_moderator_filter(cls, info, query, value):
        membership = cls.aliased(query, Membership, name='is_moderator')

        query = query.join(
            membership,
            and_(
                User.id == membership.user_id,
                membership.is_moderator.is_(True),
            ),
        )

        if value:
            filter_ = membership.id.isnot(None)
        else:
            filter_ = membership.id.is_(None)
        return query, filter_

    @classmethod

3 Source : available_items_subview.py
with MIT License
from artemShelest

    def action_borrow(self, ids):
        client_id = request.form.get('client_id')
        if not client_id:
            flash("Client id required", "error")
            return
        Item.query.filter(and_(Item.id.in_(ids))).update({Item.holder_id: client_id}, synchronize_session=False)
        db.session.commit()
        len_ids = len(ids)
        if len_ids > 1:
            flash("Borrowed {} items".format(len_ids))
        else:
            flash("Borrowed an item")

    @expose("/borrow/", methods=("POST",))

3 Source : holding_items_subview.py
with MIT License
from artemShelest

    def action_return(self, ids):
        Item.query.filter(and_(Item.id.in_(ids))).update({Item.holder_id: Item.owner_id}, synchronize_session=False)
        db.session.commit()
        len_ids = len(ids)
        if len_ids > 1:
            flash("Returned {} items".format(len_ids))
        else:
            flash("Returned an item")

    @expose("/return/", methods=("POST",))

3 Source : agnostic_boolean_check.py
with Apache License 2.0
from astro-projects

    def prep_results(self, results):
        return (
            select(["*"])
            .select_from(text(self.table.qualified_name()))
            .where(and_(*[text(self.checks[index].expression) for index in results]))
            .limit(self.max_rows_returned)
        )


def boolean_check(table: Table, checks: List[Check] = [], max_rows_returned: int = 100):

3 Source : port.py
with MIT License
from Aurora-Admin-Panel

def get_port(db: Session, server_id: int, port_id: int) -> Port:
    return (
        db.query(Port)
        .filter(and_(Port.server_id == server_id, Port.id == port_id))
        .options(joinedload(Port.allowed_users).joinedload(PortUser.user))
        .options(joinedload(Port.forward_rule))
        .options(joinedload(Port.usage))
        .first()
    )


def get_port_with_num(db: Session, server_id: int, port_num: int) -> Port:

3 Source : port.py
with MIT License
from Aurora-Admin-Panel

def get_port_with_num(db: Session, server_id: int, port_num: int) -> Port:
    return (
        db.query(Port)
        .filter(and_(Port.server_id == server_id, Port.num == port_num))
        .options(joinedload(Port.usage))
        .first()
    )


def get_port_by_id(db: Session, port_id: int) -> Port:

3 Source : port.py
with MIT License
from Aurora-Admin-Panel

def get_port_users(
    db: Session, server_id: int, port_id: int
) -> t.List[PortUser]:
    port_users = (
        db.query(PortUser)
        .filter(and_(Port.server_id == server_id, PortUser.port_id == port_id))
        .options(joinedload(PortUser.user))
        .all()
    )
    return port_users


def get_port_user(

3 Source : port.py
with MIT License
from Aurora-Admin-Panel

def get_port_user(
    db: Session, server_id: int, port_id: int, user_id: int,
) -> PortUser:
    return (
        db.query(PortUser)
        .filter(and_(Port.server_id == server_id, PortUser.port_id == port_id, PortUser.user_id == user_id))
        .options(joinedload(PortUser.user))
        .first()
    )


def add_port_user(

3 Source : port.py
with MIT License
from Aurora-Admin-Panel

def delete_port_user(
    db: Session, server_id: int, port_id: int, user_id: int
) -> PortUser:
    db_port_user = (
        db.query(PortUser)
        .filter(and_(PortUser.port_id == port_id, PortUser.user_id == user_id))
        .first()
    )
    db.delete(db_port_user)
    db.commit()
    return db_port_user

3 Source : port_forward.py
with MIT License
from Aurora-Admin-Panel

def get_forward_rule(
    db: Session, server_id: int, port_id: int, user: User = None
) -> PortForwardRule:
    forward_rule = (
        db.query(PortForwardRule)
        .join(Port)
        .filter(
            and_(
                PortForwardRule.port_id == port_id, Port.server_id == server_id
            )
        )
        .first()
    )
    return forward_rule


def get_forward_rule_for_server(

3 Source : port_forward.py
with MIT License
from Aurora-Admin-Panel

def get_all_gost_rules(db: Session, server_id: int) -> t.List[PortForwardRule]:
    return (
        db.query(PortForwardRule)
        .join(Port)
        .filter(
            and_(
                PortForwardRule.method == MethodEnum.GOST,
                Port.server_id == server_id,
            )
        )
        .all()
    )


def get_all_iptables_rules(db: Session) -> t.List[PortForwardRule]:

3 Source : server.py
with MIT License
from Aurora-Admin-Panel

def get_server(db: Session, server_id: int) -> Server:
    return (
        db.query(Server)
        .filter(and_(Server.id == server_id, Server.is_active == True))
        .options(joinedload(Server.ports).joinedload(Port.allowed_users))
        .first()
    )


def get_server_with_ports_usage(db: Session, server_id: int) -> Server:

3 Source : server.py
with MIT License
from Aurora-Admin-Panel

def get_server_with_ports_usage(db: Session, server_id: int) -> Server:
    return (
        db.query(Server)
        .filter(and_(Server.id == server_id, Server.is_active == True))
        .options(joinedload(Server.ports).joinedload(Port.usage))
        .first()
    )


def create_server(db: Session, server: ServerCreate) -> Server:

3 Source : server.py
with MIT License
from Aurora-Admin-Panel

def get_server_user(db: Session, server_id: int, user_id: int) -> ServerUser:
    return (
        db.query(ServerUser)
        .filter(
            and_(
                ServerUser.server_id == server_id, ServerUser.user_id == user_id
            )
        )
        .options(joinedload(ServerUser.user))
        .first()
    )


def add_server_user(

3 Source : user.py
with MIT License
from Aurora-Admin-Panel

def get_user_servers(db: Session, user_id: int) -> t.List[ServerUser]:
    return (
        db.query(ServerUser)
        .filter(and_(ServerUser.user_id == user_id))
        .options(joinedload(ServerUser.server))
        .all()
    )


def get_user_ports(db: Session, user_id: int) -> t.List[PortUser]:

3 Source : membership.py
with Apache License 2.0
from bcgov

    def get_pending_members_count_by_org_id(cls, org_id) -> int:
        """Return the count of pending members."""
        query = db.session.query(Membership).filter(
            and_(Membership.status == Status.PENDING_APPROVAL.value)). \
            join(OrgModel).filter(OrgModel.id == org_id)
        count_q = query.statement.with_only_columns([func.count()]).order_by(None)
        count = query.session.execute(count_q).scalar()
        return count

    @classmethod

3 Source : membership.py
with Apache License 2.0
from bcgov

    def find_members_by_org_id_by_status_by_roles(cls, org_id, roles, status=Status.ACTIVE.value) -> List[Membership]:
        """Return all members of the org with a status."""
        return db.session.query(Membership).filter(
            and_(Membership.status == status, Membership.membership_type_code.in_(roles))). \
            join(OrgModel).filter(OrgModel.id == org_id).all()

    @classmethod

3 Source : membership.py
with Apache License 2.0
from bcgov

    def get_count_active_owner_org_id(cls, org_id) -> int:
        """Return the count of pending members."""
        query = db.session.query(Membership).filter(
            and_(Membership.org_id == org_id, Membership.status == Status.ACTIVE.value,
                 Membership.membership_type_code == ADMIN)). \
            join(OrgModel).filter(OrgModel.id == org_id)
        count_q = query.statement.with_only_columns([func.count()]).order_by(None)
        count = query.session.execute(count_q).scalar()
        return count

    @classmethod

3 Source : membership.py
with Apache License 2.0
from bcgov

    def check_if_active_admin_or_owner_org_id(cls, org_id, user_id) -> int:
        """Return the count of pending members."""
        query = db.session.query(Membership).filter(
            and_(Membership.user_id == user_id, Membership.org_id == org_id, Membership.status == Status.ACTIVE.value,
                 Membership.membership_type_code.in_((ADMIN, COORDINATOR)))). \
            join(OrgModel).filter(OrgModel.id == org_id)
        count_q = query.statement.with_only_columns([func.count()]).order_by(None)
        count = query.session.execute(count_q).scalar()
        return count

    def reset(self):

3 Source : org.py
with Apache License 2.0
from bcgov

    def find_similar_org_by_name(cls, name, org_id=None, branch_name=None):
        """Find an Org instance that matches the provided name."""
        query = cls.query.filter(and_(
            func.upper(Org.name) == name.upper(),
            (func.upper(func.coalesce(Org.branch_name, '')) == ((branch_name or '').upper())))
        ).filter(Org.status_code != OrgStatusEnum.INACTIVE.value)

        if org_id:
            query = query.filter(Org.id != org_id)
        return query.all()

    @classmethod

3 Source : org.py
with Apache License 2.0
from bcgov

    def get_count_of_org_created_by_user_id(cls, user_id: int):
        """Find the count of the organisations created by the user."""
        return cls.query.filter(and_(
            Org.created_by_id == user_id, Org.status_code == 'ACTIVE'  # pylint: disable=comparison-with-callable
        )).with_entities(func.count()).scalar()

    def update_org_from_dict(self, org_info: dict, exclude=EXCLUDED_FIELDS):

3 Source : product_subscription.py
with Apache License 2.0
from bcgov

    def find_by_org_id(cls, org_id, valid_statuses=VALID_SUBSCRIPTION_STATUSES):
        """Find an product subscription instance that matches the provided id."""
        return cls.query.filter(
            and_(ProductSubscription.org_id == org_id, ProductSubscription.status_code.in_(valid_statuses))).all()

    @classmethod

3 Source : user.py
with Apache License 2.0
from bcgov

    def find_by_jwt_token(cls, **kwargs):
        """Find an existing user by the keycloak GUID and (idpUserId is null or from token) in the provided token."""
        user_from_context: UserContext = kwargs['user_context']
        return db.session.query(User).filter(
            and_(User.keycloak_guid == user_from_context.sub,
                 or_(User.idp_userid == user_from_context.token_info.get('idp_userid', None),
                     User.idp_userid.is_(None)))).one_or_none()

    @classmethod

3 Source : models.py
with MIT License
from bihealth

    def _purge_variant_set(self, variant_set):
        variant_set.__class__.objects.filter(pk=variant_set.id).update(state="deleting")
        for table_name, variant_set_attr in self.table_names:
            table = get_meta().tables[table_name]
            get_engine().execute(
                table.delete().where(
                    and_(
                        getattr(table.c, variant_set_attr) == variant_set.id,
                        table.c.case_id == variant_set.case.id,
                    )
                )
            )
        variant_set.__class__.objects.filter(pk=variant_set.id).delete()

    def _yield_pedigree(self):

3 Source : invoice_helpers.py
with MIT License
from Blockstream

def get_pending_invoices(order_id):
    return Invoice.query.filter(
        and_(Invoice.order_id == order_id,
             Invoice.status == constants.InvoiceStatus.pending.value)).all()


def expire_invoice(invoice):

3 Source : buser.py
with Mozilla Public License 2.0
from BoyaaDataCenter

    def _get_role(self, uid):
        roles = self.session.query(Role)\
            .join(BUserRole, and_(
                BUserRole.role_id == Role.id,
                BUserRole.user_id == uid,
                BUserRole.bussiness_id == g.bussiness_id)
            ).all()
        roles = [role.row2dict() for role in roles]
        return roles


class UnBuserList(RestfulBaseView):

3 Source : user.py
with Mozilla Public License 2.0
from BoyaaDataCenter

    def _get_role(self, uid):
        roles = self.session.query(Role.role)\
            .join(BUserRole, and_(
                BUserRole.role_id == Role.id,
                BUserRole.user_id == uid,
                BUserRole.bussiness_id == g.bussiness_id)
            ).all()
        return roles


class UserMenu(RestfulBaseView):

3 Source : user.py
with Mozilla Public License 2.0
from BoyaaDataCenter

    def get(self):
        if require_admin():
            # 如果是业务管理员以上,返回当前业务的所有菜单
            query_session = self.session.query(MenuModel, "True").filter(MenuModel.bussiness_id == g.bussiness_id)
        else:
            # 其他角色通过关联用户角色表来获取到当前的菜单
            query_session = self.session.query(MenuModel, RoleMenu.role_permission)\
                .join(RoleMenu, and_(RoleMenu.bussiness_id == g.bussiness_id, MenuModel.id == RoleMenu.menu_id))\
                .join(BUser, and_(BUser.bussiness_id==g.bussiness_id, BUser.user_id==g.user.id))\
                .join(BUserRole, and_(BUserRole.bussiness_id == g.bussiness_id, RoleMenu.role_id == BUserRole.role_id, BUserRole.user_id==BUser.id))

        menu_data = query_session.all()
        menus = self._encode_menus(menu_data)

        return self.response_json(self.HttpErrorCode.SUCCESS, data=menus)

    def _encode_menus(self, menus):

3 Source : account.py
with MIT License
from buxx

    def get_account_for_reset_password_token(self, token: str) -> AccountDocument:
        try:
            return (
                self._kernel.server_db_session.query(AccountDocument)
                .filter(
                    and_(
                        AccountDocument.reset_password_token == token,
                        AccountDocument.reset_password_expire > round(time.time()),
                    )
                )
                .one()
            )
        except NoResultFound:
            raise AccountNotFound(f"Account not found for token '{token}'")

    def send_new_password_request(self, username_or_email: str) -> None:

3 Source : fido2_key_dao.py
with MIT License
from cds-snc

def delete_fido2_key(user_id, id):
    db.session.query(Fido2Key).filter(and_(Fido2Key.user_id == user_id, Fido2Key.id == id)).delete()
    db.session.commit()


def get_fido2_key(user_id, id):

3 Source : utils.py
with GNU General Public License v3.0
from chopicalqui

    def delete_incomplete_commands(self, workspace: str) -> None:
        """This method resets all status that have not successfully completed to status pending"""
        with self.session_scope() as session:
            # todo: update for new collector
            command_ids = session.query(Command.id) \
                .join(Workspace, and_(Command.workspace_id == Workspace.id,
                                      Workspace.name == workspace)) \
                .filter(Command.status.in_([CommandStatus.pending, CommandStatus.collecting])).scalar_subquery()
            session.query(Command).filter(Command.id.in_(command_ids)).delete(synchronize_session='fetch')

    def _patch_database(self, version: Version):

See More Examples