sqlalchemy.not_

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

61 Examples 7

Page 1 Selected Page 2

Example 1

Project: aiohttp-security Source File: db_auth.py
    @asyncio.coroutine
    def authorized_userid(self, identity):
        with (yield from self.dbengine) as conn:
            where = sa.and_(db.users.c.login == identity,
                            sa.not_(db.users.c.disabled))
            query = db.users.count().where(where)
            ret = yield from conn.scalar(query)
            if ret:
                return identity
            else:
                return None

Example 2

Project: alchy Source File: test_search.py
    def test_notany_(self):
        test = search.notany_(
            Search.many, search.eq(SearchMany.string))(self.value)
        target = not_(Search.many.any(SearchMany.string == self.value))

        self.assertEqual(str(test), str(target))

Example 3

Project: timesketch Source File: acl.py
Function: collaborators
    @property
    def collaborators(self):
        """Get list of users that have explicit read permission on the object.

        Returns:
            List of users (instances of timesketch.models.user.User)
        """
        # pylint: disable=singleton-comparison
        aces = self.AccessControlEntry.query.filter(
            not_(self.AccessControlEntry.user == self.user),
            not_(self.AccessControlEntry.user == None),
            self.AccessControlEntry.permission == u'read',
            self.AccessControlEntry.parent == self).all()
        return set(ace.user for ace in aces)

Example 4

Project: ibis Source File: alchemy.py
def _exists_subquery(t, expr):
    op = expr.op()
    ctx = t.context

    filtered = (op.foreign_table.filter(op.predicates)
                .projection([ir.literal(1).name(ir.unnamed)]))

    sub_ctx = ctx.subcontext()
    clause = to_sqlalchemy(filtered, context=sub_ctx, exists=True)

    if isinstance(op, transforms.NotExistsSubquery):
        clause = sa.not_(clause)

    return clause

Example 5

Project: sqlalchemy Source File: test_query.py
    @testing.emits_warning('.*empty sequence.*')
    def test_literal_in(self):
        """similar to test_bind_in but use a bind with a value."""

        users.insert().execute(user_id=7, user_name='jack')
        users.insert().execute(user_id=8, user_name='fred')
        users.insert().execute(user_id=9, user_name=None)

        s = users.select(not_(literal("john").in_([])))
        r = s.execute().fetchall()
        assert len(r) == 3

Example 6

Project: debsources Source File: query.py
def get_pkg_filter_prefix(session, prefix, suite=None):
    '''Get packages filter by `prefix`

    '''
    result = (session.query(PackageName)
              .filter(sql_func.lower(PackageName.name)
                      .startswith(prefix)))

    if prefix == 'l':  # we exclude 'lib*' from the 'l' prefix
        result = (result
                  .filter(not_(sql_func.lower(PackageName.name)
                               .startswith('lib'))))

    result = result.order_by(PackageName.name)

    if suite is not None and suite is not "":
        return filter_pkg_by_suite(session, result, suite)
    else:
        return result

Example 7

Project: adhocracy Source File: randomize_usernames.py
def main():
    users = User.all_q(include_deleted=None)\
        .filter(not_(User.user_name.in_(EXCLUDED_USERNAMES))).all()

    for user in users:
        user_name = None
        while user_name is None:
            try_user_name = random_username()
            if User.find(try_user_name) is None:
                user_name = try_user_name
        if SET_DISPLAY_NAMES and user.display_name is None:
            user.display_name = user.user_name
        user.user_name = user_name
        meta.Session.flush()

    meta.Session.commit()

Example 8

Project: build-relengapi Source File: __init__.py
Function: branches
@bp.route('/branches')
@apimethod([unicode])
def branches():
    "Return a list of all the branches clobberer knows about."
    session = g.db.session(DB_DECLARATIVE_BASE)
    branches = session.query(Build.branch).distinct()
    # Users shouldn't see any branch associated with a release builddir
    branches = branches.filter(not_(Build.builddir.startswith(BUILDDIR_REL_PREFIX)))
    branches = branches.order_by(Build.branch)
    return [branch[0] for branch in branches]

Example 9

Project: glottolog3 Source File: phonologies.py
def main(args):
    with open(args.data_file('phoible-isocodes.json')) as fp:
        covered = json.load(fp).keys()

    q = DBSession.query(Ref).join(Ref.languages).join(Ref.doctypes).join(Ref.providers)\
        .filter(Doctype.pk.in_([3, 8, 11]))\
        .filter(Provider.pk == 21)\
        .filter(not_(Languoid.hid.in_(covered)))\
        .options(joinedload(Ref.languages))
    print q.count()

    with open(args.data_file('phoible-phonologies.bib'), 'w') as fp:
        for ref in q:
            rec = ref.bibtex()
            rec['glottolog_url'] = 'http://glottolog.org/resource/reference/id/%s' % ref.id
            rec['languages'] = ', '.join('%s [%s][%s]' % (l.name, l.id, l.hid) for l in ref.languages if l.hid not in covered)
            fp.write('\n%s' % unicode(rec).encode('utf8'))

Example 10

Project: aiohttp-security Source File: db_auth.py
Function: check_credentials
@asyncio.coroutine
def check_credentials(db_engine, username, password):
    with (yield from db_engine) as conn:
        where = sa.and_(db.users.c.login == username,
                        sa.not_(db.users.c.disabled))
        query = db.users.select().where(where)
        ret = yield from conn.execute(query)
        user = yield from ret.fetchone()
        if user is not None:
            hash = user[2]
            return sha256_crypt.verify(password, hash)
    return False

Example 11

Project: alchy Source File: test_search.py
    def test_nothas(self):
        test = search.nothas(
            Search.one, search.eq(SearchOne.string))(self.value)
        target = not_(Search.one.has(SearchOne.string == self.value))

        self.assertEqual(str(test), str(target))

Example 12

Project: adhocracy Source File: page.py
Function: all_q
    @classmethod
    def all_q(cls, instance=None, functions=[], exclude=[],
              include_deleted=False):
        q = meta.Session.query(Page)
        if not include_deleted:
            q = q.filter(or_(Page.delete_time == None,  # noqa
                             Page.delete_time > datetime.utcnow()))
        if functions != []:
            q = q.filter(Page.function.in_(functions))
        if instance is not None:
            q = q.filter(Page.instance == instance)
        if exclude != []:
            q = q.filter(not_(Page.id.in_([p.id for p in exclude])))
        return q

Example 13

Project: autonomie Source File: main.py
    def disable_actions(self, appstruct, factory):
        """
        Disable actions that are not active anymore
        """
        # on récupère les ids des actions encore dans la config
        ids = self.recursive_collect_ids(appstruct, 'actions')
        from sqlalchemy import not_

        for element in factory.query().filter(
            not_(getattr(factory, 'id').in_(ids))
        ):
            element.active = False
            self.dbsession.merge(element)

Example 14

Project: timesketch Source File: acl.py
Function: groups
    @property
    def groups(self):
        """List what groups have acess to this sketch.

        Returns:
            Set of groups (instance of timesketch.models.user.Group)
        """
        # pylint: disable=singleton-comparison
        group_aces = self.AccessControlEntry.query.filter(
            not_(self.AccessControlEntry.group == None),
            self.AccessControlEntry.parent == self).all()
        return set(ace.group for ace in group_aces)

Example 15

Project: mediadrop Source File: auth.py
    @classmethod
    def custom_groups(cls, *columns):
        query_object = columns or (Group, )
        return DBSession.query(*query_object).\
            filter(
                not_(Group.group_name.in_([u'anonymous', u'authenticated']))
            )

Example 16

Project: glottolog3 Source File: endangeredlanguages.py
def lquery():
    for lang in DBSession.query(Languoid)\
            .filter(Languoid.hid != None)\
            .filter(not_(icontains(Languoid.hid, 'nocode'))):
        if len(lang.hid) == 3:
            yield lang

Example 17

Project: autonomie Source File: workshop.py
    def filter_notfilled(self, query, appstruct):
        """
        Filter the workshops for which timeslots have not been filled
        """
        notfilled = appstruct.get('notfilled')
        if notfilled:
            logger.debug(u"Filtering the workshop that where not filled")
            attendance_query = DBSESSION().query(distinct(Attendance.event_id))
            attendance_query = attendance_query.filter(
                Attendance.status != 'registered'
            )

            timeslot_ids = [item[0] for item in attendance_query]

            query = query.filter(
                not_(
                    models.Workshop.timeslots.any(
                        models.Timeslot.id.in_(timeslot_ids)
                    )
                )
            )
        return query

Example 18

Project: alchy Source File: test_search.py
    def test_noteqenum_invalid(self):
        test = search.noteqenum(Search.status, OrderStatus)('invalid')
        target = not_(None)

        self.assertEqual(str(test), str(target))

Example 19

Project: alchy Source File: test_search.py
    def test_notinenum_invalid(self):
        test = search.notinenum(Search.status, OrderStatus)('invalid')
        target = not_(None)

        self.assertEqual(str(test), str(target))

Example 20

Project: sqlalchemy Source File: test_query.py
    @testing.emits_warning('.*empty sequence.*')
    def test_in_filtering(self):
        """test the behavior of the in_() function."""

        users.insert().execute(user_id=7, user_name='jack')
        users.insert().execute(user_id=8, user_name='fred')
        users.insert().execute(user_id=9, user_name=None)

        s = users.select(users.c.user_name.in_([]))
        r = s.execute().fetchall()
        # No username is in empty set
        assert len(r) == 0

        s = users.select(not_(users.c.user_name.in_([])))
        r = s.execute().fetchall()
        # All usernames with a value are outside an empty set
        assert len(r) == 2

        s = users.select(users.c.user_name.in_(['jack', 'fred']))
        r = s.execute().fetchall()
        assert len(r) == 2

        s = users.select(not_(users.c.user_name.in_(['jack', 'fred'])))
        r = s.execute().fetchall()
        # Null values are not outside any set
        assert len(r) == 0

Example 21

Project: debsources Source File: updater.py
Function: garbage_collect
def garbage_collect(status, conf, session, mirror):
    """update stage: list db and remove disappeared and expired packages

    """
    logging.info('garbage collection...')
    for version in session.query(Package).filter(not_(Package.sticky)):
        pkg = SourcePackage.from_db_model(version)
        pkg_id = (pkg['package'], pkg['version'])
        pkgdir = pkg.extraction_dir(conf['sources_dir'])
        if pkg_id not in mirror.packages:
            # package is in in Debsources db, but gone from mirror: we
            # might have to garbage collect it (depending on expiry)
            expire_days = conf['expire_days']
            age = None
            if os.path.exists(pkgdir):
                age = datetime.now() - \
                    datetime.fromtimestamp(os.path.getmtime(pkgdir))
            if not age or age.days >= expire_days:
                _rm_package(pkg, conf, session, db_package=version)
            else:
                logging.debug('not removing %s as it is too young' % pkg)

        if conf['force_triggers']:
            try:
                notify_plugins(conf['observers'], 'rm-package',
                               session, pkg, pkgdir,
                               triggers=conf['force_triggers'],
                               dry=conf['dry_run'])
            except:
                logging.exception('trigger failure on %s' % pkg)

Example 22

Project: aiohttp-security Source File: db_auth.py
Function: permits
    @asyncio.coroutine
    def permits(self, identity, permission, context=None):
        if identity is None:
            return False

        with (yield from self.dbengine) as conn:
            where = sa.and_(db.users.c.login == identity,
                            sa.not_(db.users.c.disabled))
            query = db.users.select().where(where)
            ret = yield from conn.execute(query)
            user = yield from ret.fetchone()
            if user is not None:
                user_id = user[0]
                is_superuser = user[3]
                if is_superuser:
                    return True

                where = db.permissions.c.user_id == user_id
                query = db.permissions.select().where(where)
                ret = yield from conn.execute(query)
                result = yield from ret.fetchall()
                if ret is not None:
                    for record in result:
                        if record.perm_name == permission:
                            return True

            return False

Example 23

Project: datanommer Source File: __init__.py
    @classmethod
    def grep(cls, start=None, end=None,
             page=1, rows_per_page=100,
             order="asc", msg_id=None,
             users=None, not_users=None,
             packages=None, not_packages=None,
             categories=None, not_categories=None,
             topics=None, not_topics=None,
             contains=None,
             defer=False):
        """ Flexible query interface for messages.

        Arguments are filters.  start and end should be :mod:`datetime` objs.

        Other filters should be lists of strings.  They are applied in a
        conjunctive-normal-form (CNF) kind of way

        for example, the following::

          users = ['ralph', 'lmacken']
          categories = ['bodhi', 'wiki']

        should return messages where

          (user=='ralph' OR user=='lmacken') AND
          (category=='bodhi' OR category=='wiki')

        Furthermore, you can use a negative version of each argument.

            users = ['ralph']
            not_categories = ['bodhi', 'wiki']

        should return messages where

            (user == 'ralph') AND
            NOT (category == 'bodhi' OR category == 'wiki')

        ----

        If the `defer` argument evaluates to True, the query won't actually
        be executed, but a SQLAlchemy query object returned instead.
        """

        users = users or []
        not_users = not_users or []
        packages = packages or []
        not_packs = not_packages or []
        categories = categories or []
        not_cats = not_categories or []
        topics = topics or []
        not_topics = not_topics or []
        contains = contains or []

        query = Message.query

        # A little argument validation.  We could provide some defaults in
        # these mixed cases.. but instead we'll just leave it up to our caller.
        if (start != None and end == None) or (end != None and start == None):
            raise ValueError("Either both start and end must be specified "
                             "or neither must be specified")

        if start and end:
            query = query.filter(between(Message.timestamp, start, end))

        if msg_id:
            query = query.filter(Message.msg_id == msg_id)

        # Add the four positive filters as necessary
        if users:
            query = query.filter(or_(
                *[Message.users.any(User.name == u) for u in users]
            ))

        if packages:
            query = query.filter(or_(
                *[Message.packages.any(Package.name == p) for p in packages]
            ))

        if categories:
            query = query.filter(or_(
                *[Message.category == category for category in categories]
            ))

        if topics:
            query = query.filter(or_(
                *[Message.topic == topic for topic in topics]
            ))

        if contains:
            query = query.filter(or_(
                *[Message._msg.like('%%%s%%' % contain)
                  for contain in contains]
            ))

        # And then the four negative filters as necessary
        if not_users:
            query = query.filter(not_(or_(
                *[Message.users.any(User.name == u) for u in not_users]
            )))

        if not_packs:
            query = query.filter(not_(or_(
                *[Message.packages.any(Package.name == p) for p in not_packs]
            )))

        if not_cats:
            query = query.filter(not_(or_(
                *[Message.category == category for category in not_cats]
            )))

        if not_topics:
            query = query.filter(not_(or_(
                *[Message.topic == topic for topic in not_topics]
            )))

        # Finally, tag on our pagination arguments
        total = query.count()
        query = query.order_by(getattr(Message.timestamp, order)())

        if rows_per_page is None:
            pages = 1
        else:
            pages = int(math.ceil(total / float(rows_per_page)))
            query = query.offset(rows_per_page * (page - 1)).limit(rows_per_page)

        if defer:
            return total, page, query
        else:
            # Execute!
            messages = query.all()
            return total, pages, messages

Example 24

Project: alchy Source File: test_search.py
    def test_notlike(self):
        test = search.notlike(Search.string)(self.value)
        target = not_(Search.string.like(self.value))

        self.assertEqual(str(test), str(target))

Example 25

Project: data-act-broker-backend Source File: fileTypeTests.py
    @staticmethod
    def load_definitions(sess, force_tas_load, ruleList=None):
        """Load file definitions."""
        validator_config_path = os.path.join(CONFIG_BROKER["path"], "dataactvalidator", "config")
        integration_test_data_path = os.path.join(CONFIG_BROKER["path"], "tests", "integration", "data")

        SchemaLoader.loadAllFromPath(validator_config_path)
        SQLLoader.loadSql("sqlRules.csv")

        if ruleList is not None:
            # If rule list provided, drop all other rules
            sess.query(RuleSql).filter(not_(
                RuleSql.rule_label.in_(ruleList))).delete(synchronize_session='fetch')
            sess.commit()

        # Load domain values tables
        loadDomainValues(
            validator_config_path,
            os.path.join(integration_test_data_path, "program_activity.csv"))
        if sess.query(TASLookup).count() == 0 or force_tas_load:
            # TAS table is empty, load it
            loadTas(tasFile=os.path.join(integration_test_data_path, "cars_tas.csv"))

        # Load test SF-133
        load_all_sf133(integration_test_data_path)

Example 26

Project: partify Source File: queue.py
@with_mpd_lock
def _ensure_mpd_playlist_consistency(mpd):
    """Responsible for ensuring that the Partify play queue database table is in sync with the Mopidy play queue.

    This function should ensure consistency according to the following criteria:
    * The Mopidy playlist is authoritative.
    * The function should be lightweight and should not make undue modifications to the database.

    The function first checks to make sure there are no :class:`partify.models.PlayQueueEntry` that have mpd_ids that are
    no longer in the MPD play queue. If there are, remove those :class:`partify.models.PlayQueueEntry`.
    Then the playback_priority of each :class:`PlayQueueEntry` is adjusted to reflect the MPD queue.
    Next, the selection scheme corresponding to the 'SELECTION_SCHEME' configuration value is run. Note that this
    function is likely to only make one modification to the MPD queue, which will cause a cascading playlist change
    event which will trigger this function again (through :func:`on_playlist_update`).
    Finally the player state is checked for consistency and corrected if inconsistent.

    :param mpd: The MPD client used to manipulate the MPD queue
    :type mpd: ``MPDClient``
    """
    playlist_tracks = mpd.playlistinfo()
    playlist_ids = [track['id'] for track in playlist_tracks]

    # Purge all the database entries that don't have IDs present
    purge_entries = PlayQueueEntry.query.filter(not_(PlayQueueEntry.mpd_id.in_(playlist_ids))).all()
    for purge_entry in purge_entries:
        # Remove the votes for this track, too
        votes = [v for v in Vote.query.filter(Vote.pqe_id == purge_entry.id).all()]
        for v in votes:
            if v.phe == None:
                db.session.delete(v)
            else:
                v.pqe = None
        db.session.delete(purge_entry)
    db.session.commit()

    # Next, make sure that we have a database entry for each track in the MPD queue
    for track in playlist_tracks:
        # This could cause some undue load on the database. We can do this in memory if it's too intensive to be doing DB calls
        queue_track = PlayQueueEntry.query.filter(PlayQueueEntry.mpd_id == track['id']).first() # Don't need to worry about dups since this field is unique in the DB

        if queue_track is not None:
            # Do some checking here to make sure that all of the information is correct...
            # Ensure that the playback position is correct
            queue_track.playback_priority = track['pos']
            db.session.add(queue_track)
        else:
            # We need to add the track to the Partify representation of the Play Queue
            new_track = track_from_spotify_url(track['file'])
            new_track_entry = PlayQueueEntry(track=new_track, user_id=None, mpd_id=track['id'], playback_priority=track['pos'])
            db.session.add(new_track_entry)

    db.session.commit()

    # Ensure that the playlist's order follows the configured selection method
    db_tracks = PlayQueueEntry.query.order_by(PlayQueueEntry.playback_priority.asc()).all()
    if len(db_tracks) > 0:
        selection_method = get_selection_scheme(app.config['SELECTION_SCHEME'])
        selection_method(mpd, db_tracks)

    _ensure_mpd_player_state_consistency(mpd)

    status = _get_status(mpd)
        
    if status['state'] != ipc.get_desired_player_state()[0]:
        tn_fn = getattr(mpd, ipc.get_desired_player_state()[1])
        tn_fn()

    db.session.commit()

Example 27

Project: sqlalchemy Source File: test_evaluator.py
Function: test_boolean_ops
    def test_boolean_ops(self):
        User = self.classes.User

        eval_eq(and_(User.name == 'foo', User.id == 1), testcases=[
            (User(id=1, name='foo'), True),
            (User(id=2, name='foo'), False),
            (User(id=1, name='bar'), False),
            (User(id=2, name='bar'), False),
            (User(id=1, name=None), None),
        ])

        eval_eq(or_(User.name == 'foo', User.id == 1), testcases=[
            (User(id=1, name='foo'), True),
            (User(id=2, name='foo'), True),
            (User(id=1, name='bar'), True),
            (User(id=2, name='bar'), False),
            (User(id=1, name=None), True),
            (User(id=2, name=None), None),
        ])

        eval_eq(not_(User.id == 1), testcases=[
            (User(id=1), False),
            (User(id=2), True),
            (User(id=None), None),
        ])

Example 28

Project: sqlalchemy Source File: test_query.py
    @testing.emits_warning('.*empty sequence.*')
    @testing.fails_on('firebird', "uses sql-92 rules")
    @testing.fails_on('sybase', "uses sql-92 rules")
    @testing.fails_if(
        lambda: testing.against('mssql+pyodbc') and not
        testing.db.dialect.freetds, "uses sql-92 rules")
    def test_bind_in(self):
        """test calling IN against a bind parameter.

        this isn't allowed on several platforms since we
        generate ? = ?.

        """

        users.insert().execute(user_id=7, user_name='jack')
        users.insert().execute(user_id=8, user_name='fred')
        users.insert().execute(user_id=9, user_name=None)

        u = bindparam('search_key')

        s = users.select(not_(u.in_([])))
        r = s.execute(search_key='john').fetchall()
        assert len(r) == 3
        r = s.execute(search_key=None).fetchall()
        assert len(r) == 0

Example 29

Project: grano Source File: accounts_api.py
@blueprint.route('/api/1/accounts/_suggest', methods=['GET'])
def suggest():
    authz.require(authz.logged_in())
    query = request.args.get('q', '') + '%'
    q = db.session.query(Account)
    q = q.filter(or_(Account.full_name.ilike(query),
                     Account.login.ilike(query),
                     Account.email.ilike(query)))
    excluded = request.args.getlist('exclude')
    if len(excluded):
        q = q.filter(not_(Account.id.in_(excluded)))
    pager = Pager(q)

    def convert(accounts):
        data = []
        for account in accounts:
            data.append({
                'display_name': account.display_name,
                'id': account.id
            })
        return data

    validate_cache(keys='#'.join([d.display_name for d in pager]))
    return jsonify(pager.to_dict(results_converter=convert))

Example 30

Project: alchy Source File: test_search.py
    def test_notstartswith(self):
        test = search.notstartswith(Search.string)(self.value)
        target = not_(Search.string.startswith(self.value))

        self.assertEqual(str(test), str(target))

Example 31

Project: alchy Source File: test_search.py
    def test_noteqenum(self):
        test = search.noteqenum(Search.status, OrderStatus)(self.value)
        target = not_(Search.status == OrderStatus.from_string(self.value))

        self.assertEqual(str(test), str(target))

Example 32

Project: glottolog3 Source File: ethnologue.py
def update(args):
    codes = {}
    for lang in reader(args.data_file(DATA_FILE), namedtuples=True):
        codes[lang.LangID] = 1

    count = 0
    for lang in DBSession.query(Languoid)\
            .filter(Languoid.hid != None)\
            .filter(not_(icontains(Languoid.hid, 'nocode'))):
        if lang.hid in codes:
            lang.update_jsondata(ethnologue=LANGUAGE_URL + lang.hid)
        else:
            lang.update_jsondata(ethnologue=None)
            count += 1

    print count, 'iso codes have no ethnologue code'

    ethnologue = args.json

    leafsets = defaultdict(list)
    for id_, doc in ethnologue['docs'].items():
        for sid, spec in get_classification(id_, doc).items():
            leafs = sorted(set([p[0] for p in spec[2]]))
            if leafs:
                leafsets[tuple(leafs)].append(sid)

    all = 0
    matched = 0
    for family in DBSession.query(Languoid)\
            .filter(Languoid.level == LanguoidLevel.family)\
            .filter(Language.active == True):
        leafs = []
        all += 1
        for row in DBSession.query(TreeClosureTable.child_pk, Languoid.hid)\
                .filter(TreeClosureTable.parent_pk == family.pk)\
                .filter(TreeClosureTable.child_pk == Languoid.pk)\
                .filter(Languoid.hid != None):
            if len(row[1]) == 3:
                leafs.append(row[1])
        leafs = tuple(sorted(set(leafs)))
        for i, subgroup in enumerate(leafsets.get(leafs, [])):
            if i == 0:
                matched += 1
                family.update_jsondata(ethnologue=SUBGROUP_URL + subgroup)
                break
    print matched, 'of', all, 'families have an exact counterpart in ethnologue!'

Example 33

Project: alchy Source File: test_search.py
    def test_notinenum(self):
        test = search.notinenum(Search.status, OrderStatus)(self.value)
        target = not_(Search.status.in_([OrderStatus.from_string(self.value)]))

        self.assertEqual(str(test), str(target))

Example 34

Project: alchy Source File: test_search.py
    def test_notendswith(self):
        test = search.notendswith(Search.string)(self.value)
        target = not_(Search.string.endswith(self.value))

        self.assertEqual(str(test), str(target))

Example 35

Project: grano Source File: entities_api.py
@blueprint.route('/api/1/entities/_suggest', methods=['GET'])
def suggest():
    if 'q' not in request.args or not len(request.args.get('q').strip()):
        raise BadRequest("Missing the query ('q' parameter).")

    q = db.session.query(Property)
    q = q.join(Entity)
    q = q.filter(Entity.project_id.in_(authz.permissions().get('reader')))
    q = q.filter(Property.name == 'name')
    q = q.filter(Property.active == True) # noqa
    q = q.filter(Property.entity_id != None) # noqa
    q = q.filter(Property.value_string.ilike(request.args.get('q') + '%'))
    if 'project' in request.args:
        q = q.join(Project)
        q = q.filter(Project.slug == request.args.get('project'))
    if 'exclude' in request.args:
        ents = request.args.getlist('exclude')
        q = q.filter(not_(Property.entity_id.in_(ents)))
    q = q.distinct()
    pager = Pager(q)

    data = []

    def convert(props):
        for prop in props:
            data.append({
                'properties': {
                    'name': prop.to_dict_index(),
                },
                'id': prop.entity_id,
                'api_url': url_for('entities_api.view', id=prop.entity_id)
            })
        return data

    validate_cache(keys='#'.join([d['name'] for d in data]))
    return jsonify(pager.to_dict(results_converter=convert))

Example 36

Project: alchy Source File: test_search.py
Function: test_not_contains
    def test_notcontains(self):
        test = search.notcontains(Search.string)(self.value)
        target = not_(Search.string.contains(self.value))

        self.assertEqual(str(test), str(target))

Example 37

Project: alchy Source File: search.py
Function: call
    def __call__(self, value):
        return not_(super(NegateOperator, self).__call__(value))

Example 38

Project: fresque Source File: models.py
Function: active
    @active.expression
    def active(cls):
        return sa.not_(cls.state.in_(["done", "rejected"]))

Example 39

Project: alchy Source File: test_search.py
    def test_notilike(self):
        test = search.notilike(Search.string)(self.value)
        target = not_(Search.string.ilike(self.value))

        self.assertEqual(str(test), str(target))

Example 40

Project: alchy Source File: test_search.py
    def test_noticontains(self):
        test = search.noticontains(Search.string)(self.value)
        target = not_(Search.string.ilike('%{0}%'.format(self.value)))

        self.assertEqual(str(test), str(target))

Example 41

Project: autonomie Source File: __init__.py
    def filter_nnll(self, attr):
        """ not null """
        return not_(attr.in_(self.none_values))

Example 42

Project: alchy Source File: test_search.py
Function: test_not_in
    def test_notin_(self):
        test = search.notin_(Search.string)(self.value)
        target = not_(Search.string.in_(self.value))

        self.assertEqual(str(test), str(target))

Example 43

Project: alchy Source File: test_search.py
    def test_notgt(self):
        test = search.notgt(Search.string)(self.value)
        target = not_(Search.string > self.value)

        self.assertEqual(str(test), str(target))

Example 44

Project: autonomie Source File: __init__.py
    def filter_nhas(self, attr):
        """ not contains """
        f = self.filter_has(attr)
        if f is not None:
            return not_(f)

Example 45

Project: alchy Source File: test_search.py
    def test_notge(self):
        test = search.notge(Search.string)(self.value)
        target = not_(Search.string >= self.value)

        self.assertEqual(str(test), str(target))

Example 46

Project: realms-wiki Source File: model.py
    def _set_columns(self, **kwargs):
        force = kwargs.get('_force')

        readonly = []
        if hasattr(self, 'readonly_fields'):
            readonly = self.readonly_fields
        if hasattr(self, 'hidden_fields'):
            readonly += self.hidden_fields

        readonly += [
            'id',
            'created',
            'updated',
            'modified',
            'created_at',
            'updated_at',
            'modified_at',
        ]

        changes = {}

        columns = self.__table__.columns.keys()
        relationships = self.__mapper__.relationships.keys()

        for key in columns:
            allowed = True if force or key not in readonly else False
            exists = True if key in kwargs else False
            if allowed and exists:
                val = getattr(self, key)
                if val != kwargs[key]:
                    changes[key] = {'old': val, 'new': kwargs[key]}
                    setattr(self, key, kwargs[key])

        for rel in relationships:
            allowed = True if force or rel not in readonly else False
            exists = True if rel in kwargs else False
            if allowed and exists:
                is_list = self.__mapper__.relationships[rel].uselist
                if is_list:
                    valid_ids = []
                    query = getattr(self, rel)
                    cls = self.__mapper__.relationships[rel].argument()
                    for item in kwargs[rel]:
                        if 'id' in item and query.filter_by(id=item['id']).limit(1).count() == 1:
                            obj = cls.query.filter_by(id=item['id']).first()
                            col_changes = obj.set_columns(**item)
                            if col_changes:
                                col_changes['id'] = str(item['id'])
                                if rel in changes:
                                    changes[rel].append(col_changes)
                                else:
                                    changes.update({rel: [col_changes]})
                            valid_ids.append(str(item['id']))
                        else:
                            col = cls()
                            col_changes = col.set_columns(**item)
                            query.append(col)
                            db.session.flush()
                            if col_changes:
                                col_changes['id'] = str(col.id)
                                if rel in changes:
                                    changes[rel].append(col_changes)
                                else:
                                    changes.update({rel: [col_changes]})
                            valid_ids.append(str(col.id))

                    # delete related rows that were not in kwargs[rel]
                    for item in query.filter(not_(cls.id.in_(valid_ids))).all():
                        col_changes = {
                            'id': str(item.id),
                            'deleted': True,
                        }
                        if rel in changes:
                            changes[rel].append(col_changes)
                        else:
                            changes.update({rel: [col_changes]})
                        db.session.delete(item)

                else:
                    val = getattr(self, rel)
                    if self.__mapper__.relationships[rel].query_class is not None:
                        if val is not None:
                            col_changes = val.set_columns(**kwargs[rel])
                            if col_changes:
                                changes.update({rel: col_changes})
                    else:
                        if val != kwargs[rel]:
                            setattr(self, rel, kwargs[rel])
                            changes[rel] = {'old': val, 'new': kwargs[rel]}

        return changes

Example 47

Project: sqlalchemy Source File: test_query.py
    @testing.requires.boolean_col_expressions
    def test_or_and_as_columns(self):
        true, false = literal(True), literal(False)

        eq_(testing.db.execute(select([and_(true, false)])).scalar(), False)
        eq_(testing.db.execute(select([and_(true, true)])).scalar(), True)
        eq_(testing.db.execute(select([or_(true, false)])).scalar(), True)
        eq_(testing.db.execute(select([or_(false, false)])).scalar(), False)
        eq_(
            testing.db.execute(select([not_(or_(false, false))])).scalar(),
            True)

        row = testing.db.execute(
            select(
                [or_(false, false).label("x"),
                    and_(true, false).label("y")])).first()
        assert row.x == False  # noqa
        assert row.y == False  # noqa

        row = testing.db.execute(
            select(
                [or_(true, false).label("x"),
                    and_(true, false).label("y")])).first()
        assert row.x == True  # noqa
        assert row.y == False  # noqa

Example 48

Project: alchy Source File: test_search.py
    def test_notlt(self):
        test = search.notlt(Search.string)(self.value)
        target = not_(Search.string < self.value)

        self.assertEqual(str(test), str(target))

Example 49

Project: autonomie Source File: __init__.py
    def filter_nioo(self, attr):
        """ is not one of """
        if self.searches:
            return not_(attr.in_(self.searches))

Example 50

Project: alchy Source File: test_search.py
    def test_notle(self):
        test = search.notle(Search.string)(self.value)
        target = not_(Search.string <= self.value)

        self.assertEqual(str(test), str(target))
See More Examples - Go to Next Page
Page 1 Selected Page 2