Here are the examples of the python api sqlalchemy.or_ taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
189 Examples
5
Example 1
Project: raggregate Source File: hotness.py
def recentize_contro(recalc_timediff = timedelta(seconds = 1), age_timediff = timedelta(hours = 48)):
"""
Ensure that upvote and downvote tallies of stories added in the last age_timediff time
are no older than recalc_timediff time. Recalculate if so, do nothing if not.
"""
stories = dbsession.query(Submission).filter(Submission.deleted == False).filter(Submission.added_on > (general.now_in_utc() - age_timediff)).filter(sqlalchemy.or_(sqlalchemy.or_(Submission.upvote_tally_timestamp < (general.now_in_utc() - recalc_timediff), Submission.downvote_tally_timestamp < (general.now_in_utc() - recalc_timediff)), sqlalchemy.or_(Submission.upvote_tally_timestamp == None, Submission.downvote_tally_timestamp == None))).all()
for s in stories:
count_story_votes(s.id)
return 0
3
Example 2
@staticmethod
def size():
"""How deep is the queue at the moment"""
qry = ImportQueue.query.filter(or_(
ImportQueue.status != COMPLETE,
ImportQueue.status != ERROR))
return qry.count()
3
Example 3
Project: changes Source File: sync_job_step.py
def has_missing_targets(step):
return db.session.query(BazelTarget.query.filter(
BazelTarget.step_id == step.id,
BazelTarget.status == Status.in_progress,
or_(
BazelTarget.result_source == ResultSource.from_self,
# None value for result_source implies `from_self`
BazelTarget.result_source.is_(None),
),
).exists()).scalar()
3
Example 4
Project: open-event-orga-server Source File: data_getter.py
@staticmethod
def get_past_events():
events = Event.query.join(Event.roles, aliased=True).filter_by(user_id=login.current_user.id) \
.filter(Event.end_time <= datetime.datetime.now()).filter(
or_(Event.state == 'Completed', Event.state == 'Published')).filter(Event.in_trash is not True)
return DataGetter.trim_attendee_events(events)
3
Example 5
Project: autonomie Source File: company_invoice.py
def _filter_paid(self, query):
inv_paid = Invoice.paid_states
cinv_valid = CancelInvoice.valid_states
return query.filter(
or_(
and_(
Task.CAEStatus.in_(inv_paid),
Task.type_ == 'invoice'
),
and_(
Task.CAEStatus.in_(cinv_valid),
Task.type_ == 'cancelinvoice',
),
)
)
3
Example 6
def test_delete_rollback(self):
User = self.classes.User
sess = Session()
john, jack, jill, jane = sess.query(User).order_by(User.id).all()
sess.query(User).filter(
or_(User.name == 'john', User.name == 'jill')).\
delete(synchronize_session='evaluate')
assert john not in sess and jill not in sess
sess.rollback()
assert john in sess and jill in sess
3
Example 7
@with_session
def from_cache(session=None, search_params=None, cache_type=None):
"""
Returns a result from requested table based on search params
:param session: Current session
:param search_params: Relevant search params. Should match table column names
:param cache_type: Object for search
:return: Query result
"""
if not any(search_params.values()):
raise LookupError('No parameters sent for cache lookup')
else:
log.debug('searching db {0} for the values {1}'.format(cache_type.__tablename__, list(search_params.items())))
result = session.query(cache_type).filter(
or_(getattr(cache_type, col) == val for col, val in search_params.items() if val)).first()
return result
3
Example 8
Project: tvb-framework Source File: datatype_dao.py
def try_load_last_entity_of_type(self, project_id, datatype_class):
query = self.session.query(datatype_class
).join((model.Operation, datatype_class.fk_from_operation == model.Operation.id)
).outerjoin(model.Links
).filter(or_(model.Operation.fk_launched_in == project_id,
model.Links.fk_to_project == project_id))
query = query.order_by(desc(datatype_class.id)).limit(1)
result = query.all()
if result is not None and len(result):
return result[0]
return None
3
Example 9
def check_active(self, handler, send):
# Re-schedule check_active
self.defer(3600, False, self.check_active, handler, send)
if not self.handler.config.getboolean('feature', 'voiceactive'):
return
# Mark inactive after 24 hours.
active_time = datetime.now() - timedelta(hours=24)
with handler.db.session_scope() as session:
with handler.data_lock:
for name in handler.channels.keys():
for nick, voiced in handler.voiced[name].items():
if voiced and session.query(Log).filter(Log.source == nick, Log.time >= active_time,
or_(Log.type == 'pubmsg', Log.type == 'action')).count() == 0:
handler.rate_limited_send('mode', name, '-v %s' % nick)
3
Example 10
def get_filter(self, column_orderings, cursor):
column_cursors = tuple(zip(column_orderings, cursor))
return sa.or_(
self.get_filter_clause(column_cursors[:i + 1])
for i in range(len(column_cursors))
)
3
Example 11
Project: pypi-notifier Source File: user.py
@classmethod
def send_emails(cls):
users = cls.query.filter(
or_(
cls.email_sent_at <= datetime.utcnow() - timedelta(days=7),
cls.email_sent_at == None
)
).all()
for user in users:
with ignored(Exception):
logger.info(user)
user.send_email()
user.email_sent_at = datetime.utcnow()
db.session.commit()
3
Example 12
Project: grano Source File: files_api.py
@blueprint.route('/api/1/files', methods=['GET'])
def index():
query = File.all()
query = query.join(Project)
query = query.outerjoin(Permission)
query = query.filter(or_(Project.private == False, # noqa
and_(Permission.reader == True, # noqa
Permission.account == request.account)))
if request.args.get('project'):
query = query.filter(Project.slug == request.args.get('project'))
query = query.distinct()
pager = Pager(query)
validate_cache(keys=pager.cache_keys())
return jsonify(pager, index=True)
3
Example 13
Project: centos-package-cron Source File: annoyance_check.py
def remove_old_alerts_for_package(self, package):
old_versions = self.session.query(Package) \
.filter(Package.name == package.name) \
.filter(or_(Package.version != package.version, Package.release != package.release)) \
.all()
for old_ver in old_versions:
self.session.delete(old_ver)
self.session.commit()
3
Example 14
Project: alchy Source File: query.py
def simple_filter(self, search_terms=None):
"""Return the compiled simple search filter mapped to `search_terms`.
"""
if search_terms is None: # pragma: no cover
search_terms = []
filter_funcs = self.get_search_filters(self.__simple_search__)
# Only support AND'ing search terms together. Apply each simple search
# filter to each search term and group them together.
term_filters = [[func(term) for func in filter_funcs.values()]
for term in search_terms]
# Each item in term_filters is a list of filters applied to one of
# the search terms contained in search_string. We need at least one
# simple filter to match for each term. We need all search terms to
# have at least simple filter match.
return and_(*[or_(*filters) for filters in term_filters])
3
Example 15
Project: knowledge-repo Source File: web_editor.py
@blueprint.route('/webposts', methods=['GET'])
@PageView.logged
def gitless_drafts():
""" Render the gitless posts that a user has created in table form
Editors can see all the posts created via Gitless_Editing
"""
query = (db_session.query(Post))
if current_app.config.get('WEB_EDITOR_PREFIXES', None):
query = query.filter(or_(*[Post.path.like(p + '%') for p in current_app.config['WEB_EDITOR_PREFIXES']]))
if g.user.username not in current_repo.config.editors:
query = (query.outerjoin(PostAuthorAssoc, PostAuthorAssoc.post_id == Post.id)
.filter(PostAuthorAssoc.user_id == g.user.id))
webposts = query.all()
return render_template("web_posts.html", posts=webposts)
3
Example 16
Project: taxtastic Source File: taxonomy.py
def children_of(self, tax_id, n):
if tax_id is None:
return None
parent_id, rank = self._node(tax_id)
s = select([self.nodes.c.tax_id],
and_(self.nodes.c.parent_id == tax_id,
or_(*[self.nodes.c.rank == r
for r in self.ranks_below(rank)]))).limit(n)
res = s.execute()
output = res.fetchall()
if not output:
return []
else:
r = [x[0] for x in output]
for x in r:
assert self.is_ancestor_of(x, tax_id)
return r
3
Example 17
Project: sqlalchemy Source File: test_update_delete.py
def test_delete_without_session_sync(self):
User = self.classes.User
sess = Session()
john, jack, jill, jane = sess.query(User).order_by(User.id).all()
sess.query(User).filter(
or_(User.name == 'john', User.name == 'jill')).\
delete(synchronize_session=False)
assert john in sess and jill in sess
eq_(sess.query(User).order_by(User.id).all(), [jack, jane])
3
Example 18
Project: open-event-orga-server Source File: query_filters.py
def event_location(value, query):
"""
Return all queries which contain either A or B or C
when location is A,B,C
TODO: Proper ordering of results a/c proximity
"""
locations = list(value.split(','))
queries = []
for i in locations:
queries.append(func.lower(Event.location_name).contains(i.lower()))
return query.filter(or_(*queries))
3
Example 19
Project: hnapp Source File: search.py
def filter(self):
"""
Return filter for use in SQLAlchemy query
Calls itself recursively to handle joins
"""
if len(self.tokens) == 0:
raise QueryError('Operator %s has no sides' % self.prefix)
filters = []
operators = {
'|': sqlalchemy.or_,
'&': sqlalchemy.and_
}
for token in self.tokens:
filters.append(token.filter())
return operators[self.prefix](*filters)
3
Example 20
def __call__(self, view, arg_value):
if not self._separator or self._separator not in arg_value:
return self.get_arg_clause(view, arg_value)
return sa.or_(
self.get_arg_clause(view, value)
for value in arg_value.split(self._separator)
)
3
Example 21
def search(self, search_query):
"""Filters the query based on a list of fields & search query."""
if search_query:
search_query = '%%%s%%' % search_query
from sqlalchemy import or_
fields = [getattr(self.model, x) for x in self.searchables]
self.query = self.query.filter(or_(*[x.like(search_query) for x in fields]))
3
Example 22
Project: pypi-notifier Source File: package.py
@classmethod
def update_all_packages(cls):
packages = cls.query.filter(
or_(
cls.last_check <= datetime.utcnow() - timedelta(days=1),
cls.last_check == None
)
).all()
for package in packages:
with ignored(Exception):
package.update_from_pypi()
db.session.commit()
3
Example 23
Project: pybossa Source File: user_repository.py
def search_by_name(self, keyword):
if len(keyword) == 0:
return []
keyword = '%' + keyword.lower() + '%'
return self.db.session.query(User).filter(or_(func.lower(User.name).like(keyword),
func.lower(User.fullname).like(keyword))).all()
3
Example 24
Project: cslbot Source File: workers.py
def check_babble(self, handler, send):
# Re-schedule check_babble
self.defer(3600, False, self.check_babble, handler, send)
cmdchar = handler.config['core']['cmdchar']
ctrlchan = handler.config['core']['ctrlchan']
with handler.db.session_scope() as session:
# If we don't actually update anything, don't bother checking the last row.
if not babble.update_markov(session, handler.config):
return
last = session.query(Babble_last).first()
row = session.query(Log).filter(or_(Log.type == 'pubmsg', Log.type == 'privmsg'), ~Log.msg.startswith(cmdchar),
Log.target != ctrlchan).order_by(Log.id.desc()).first()
if last is None or row is None:
return
if abs(last.last - row.id) > 1:
raise Exception("Last row in babble cache (%d) does not match last row in log (%d)." % (last.last, row.id))
3
Example 25
Project: glottolog3 Source File: datatables.py
def base_query(self, query):
query = query.filter(Language.active == True)\
.filter(Languoid.status == LanguoidStatus.established)\
.outerjoin(self.top_level_family, self.top_level_family.pk == Languoid.family_pk)\
.options(
contains_eager(Languoid.family, alias=self.top_level_family),
subqueryload(Languoid.macroareas))
if self.type == 'families':
return query.filter(
or_(Languoid.level == LanguoidLevel.family,
and_(Languoid.level == LanguoidLevel.language,
Languoid.father_pk == None)))
else:
return query.filter(Languoid.level == LanguoidLevel.language)
3
Example 26
Project: glottolog3 Source File: check_db_consistency.py
def invalid_query(self, session, **kw):
cte = session.query(Languoid.pk, Languoid.father_pk, Languoid.level)\
.filter(Languoid.father_pk != None).cte(recursive=True) # noqa
parent = orm.aliased(Languoid)
cte = cte.union_all(session.query(cte.c.pk, parent.father_pk, cte.c.level)\
.join(parent, cte.c.father_pk == parent.pk)\
.filter(parent.father_pk != None)) # noqa
return session.query(Languoid)\
.outerjoin(cte, Languoid.pk == cte.c.father_pk)\
.group_by(Language.pk, Languoid.pk)\
.having(or_(
func.coalesce(Languoid.child_family_count, -1) !=
func.count(func.nullif(cte.c.level != LanguoidLevel.family, True)),
func.coalesce(Languoid.child_language_count, -1) !=
func.count(func.nullif(cte.c.level != LanguoidLevel.language, True)),
func.coalesce(Languoid.child_dialect_count, -1) !=
func.count(func.nullif(cte.c.level != LanguoidLevel.dialect, True))))\
.order_by((Languoid.id))
3
Example 27
def filter(self, q, partial=False):
if self.filtered:
cond = self.column == self.node.value
if self.optional:
cond = or_(cond, self.column==None)
q = q.where(cond)
return q
3
Example 28
@blueprint.route('/get_members/', methods=['GET'])
@requires_pos_api_key
def get_members():
data = {
user.id: user.name for user in User.query.filter(
or_(User.has_payed == True, # noqa
User.honorary_member == True, # noqa
User.favourer == True) # noqa
).all()
}
return jsonify(data=data), 200
3
Example 29
Project: pittsburgh-purchasing-suite Source File: scrape_county.py
def get_contract(description, ifb):
return db.session.query(
ContractBase.id, ContractBase.description,
ContractProperty.key, ContractProperty.value
).join(ContractProperty).filter(or_(
ContractBase.description.ilike(description),
ContractProperty.value.ilike(ifb.split('-')[1])
)).first()
3
Example 30
Project: dokomoforms Source File: survey.py
def administrator_filter(user_id):
"""Filter a query by administrator id."""
return (sa.or_(
Survey.creator_id == user_id,
_administrator_table.c.user_id == user_id
))
3
Example 31
def get_holidays(start_date=None, end_date=None, user_id=None):
"""
Return the user's declared holidays
"""
holidays = Holiday.query()
if start_date and end_date:
holidays = holidays.filter(
or_(Holiday.start_date.between(start_date, end_date),
Holiday.end_date.between(start_date, end_date)))
if user_id:
holidays = holidays.filter(Holiday.user_id == user_id)
holidays.order_by("start_date")
return holidays
3
Example 32
def test_delete(self):
User = self.classes.User
sess = Session()
john, jack, jill, jane = sess.query(User).order_by(User.id).all()
sess.query(User).filter(
or_(User.name == 'john', User.name == 'jill')).delete()
assert john not in sess and jill not in sess
eq_(sess.query(User).order_by(User.id).all(), [jack, jane])
3
Example 33
Project: suma Source File: link.py
def get_link_by_id_or_hashid(self, id_or_hashid):
args = []
if str(id_or_hashid).isdigit():
args.append(Link.id == id_or_hashid)
args.append(Link.hashid == str(id_or_hashid))
try:
return self.dbsession.query(Link).filter(
or_(*args)
).one()
except NoResultFound:
return None
3
Example 34
def invalid_query(self, session, **kw):
return session.query(Languoid)\
.filter_by(active=False).filter(or_(
Languoid.father_pk != None,
Languoid.children.any()))\
.order_by(Languoid.id) # noqa
3
Example 35
Project: data-act-broker-backend Source File: function_bag.py
def get_submission_stats(submission_id):
"""Get summarized dollar amounts by submission."""
sess = GlobalDB.db().session
base_query = sess.query(func.sum(AwardFinancial.transaction_obligated_amou)).\
filter(AwardFinancial.submission_id == submission_id)
procurement = base_query.filter(AwardFinancial.piid != None)
fin_assist = base_query.filter(or_(AwardFinancial.fain != None, AwardFinancial.uri != None))
return {
"total_obligations": float(base_query.scalar() or 0),
"total_procurement_obligations": float(procurement.scalar() or 0),
"total_assistance_obligations": float(fin_assist.scalar() or 0)
}
3
Example 36
Project: sqlalchemy Source File: test_update_delete.py
def test_delete_rollback_with_fetch(self):
User = self.classes.User
sess = Session()
john, jack, jill, jane = sess.query(User).order_by(User.id).all()
sess.query(User).filter(
or_(User.name == 'john', User.name == 'jill')).\
delete(synchronize_session='fetch')
assert john not in sess and jill not in sess
sess.rollback()
assert john in sess and jill in sess
3
Example 37
def get_list(self, term, offset=0, limit=DEFAULT_PAGE_SIZE):
query = self.session.query(self.model)
filters = (field.ilike(u'%%%s%%' % term) for field in self._cached_fields)
query = query.filter(or_(*filters))
if self.order_by:
query = query.order_by(self.order_by)
return query.offset(offset).limit(limit).all()
3
Example 38
Project: tvb-framework Source File: datatype_dao.py
def count_datatypes(self, project_id, datatype_class):
query = self.session.query(datatype_class
).join((model.Operation, datatype_class.fk_from_operation == model.Operation.id)
).outerjoin(model.Links
).filter(or_(model.Operation.fk_launched_in == project_id,
model.Links.fk_to_project == project_id))
return query.count()
3
Example 39
Project: Flexget Source File: entry_list.py
def _entry_query(self, session, entry):
db_entry = session.query(EntryListEntry).filter(and_(
EntryListEntry.list_id == self._db_list(session).id,
or_(
EntryListEntry.title == entry['title'], and_(
EntryListEntry.original_url,
EntryListEntry.original_url == entry[
'original_url'])))).first()
return db_entry
3
Example 40
Project: sqlalchemy Source File: test_update_delete.py
def test_delete_with_fetch_strategy(self):
User = self.classes.User
sess = Session()
john, jack, jill, jane = sess.query(User).order_by(User.id).all()
sess.query(User).filter(
or_(User.name == 'john', User.name == 'jill')).\
delete(synchronize_session='fetch')
assert john not in sess and jill not in sess
eq_(sess.query(User).order_by(User.id).all(), [jack, jane])
3
Example 41
Project: open-event-orga-server Source File: query_filters.py
def event_search_location(value, query):
"""
Return all queries which contain either A or B or C
when location is A,B,C
TODO: Proper ordering of results a/c proximity
"""
locations = list(value.split(','))
queries = []
for i in locations:
response = requests.get(
"https://maps.googleapis.com/maps/api/geocode/json?address=" + unicode(i)).json()
if response["results"]:
lng = float(response["results"][0]["geometry"]["location"]["lng"])
lat = float(response["results"][0]["geometry"]["location"]["lat"])
queries.append(get_query_close_area(lng, lat))
queries.append(func.lower(Event.searchable_location_name).contains(i.lower()))
queries.append(func.lower(Event.location_name).contains(i.lower()))
return query.filter(or_(*queries))
3
Example 42
Project: pele Source File: database.py
def getTransitionStatesMinimum(self, min1):
"""return all transition states connected to a minimum
Returns
-------
ts : None or TransitionState
"""
candidates = self.session.query(TransitionState).\
filter(or_(TransitionState.minimum1==min1,
TransitionState.minimum2==min1))
return candidates.all()
3
Example 43
Project: open-event-orga-server Source File: ticketing.py
@staticmethod
def get_orders_of_user(user_id=None, upcoming_events=True):
"""
:return: Return all order objects with the current user
"""
if not user_id:
user_id = login.current_user.id
query = Order.query.join(Order.event) \
.filter(Order.user_id == user_id) \
.filter(or_(Order.status == 'completed', Order.status == 'placed'))
if upcoming_events:
return query.filter(Event.start_time >= datetime.now())
else:
return query.filter(Event.end_time < datetime.now())
3
Example 44
Project: KaraKara Source File: _logic.py
def _queue_item_base_query(request, DBSession):
time_limit = request.registry.settings.get('karakara.queue.add.duplicate.time_limit')
return DBSession.query(QueueItem) \
.filter(or_(
QueueItem.status == 'pending',
and_(QueueItem.status == 'played', QueueItem.time_touched >= datetime.datetime.now()-time_limit)
)) \
.order_by(QueueItem.queue_weight)
3
Example 45
def get_messages(cursor, cmdchar, ctrlchan, speaker, newer_than_id):
query = cursor.query(Log).filter(Log.id > newer_than_id)
# Ignore commands, and messages addressed to the ctrlchan
query = query.filter(or_(Log.type == 'pubmsg', Log.type == 'privmsg', Log.type == 'action'), ~Log.msg.startswith(cmdchar), Log.target != ctrlchan)
if speaker is not None:
location = 'target' if speaker.startswith(('#', '+', '@')) else 'source'
query = query.filter(getattr(Log, location).ilike(speaker, escape='$'))
return query.order_by(Log.id).all()
3
Example 46
Project: pele Source File: database.py
def getTransitionState(self, min1, min2):
"""return the TransitionState between two minima
Returns
-------
ts : None or TransitionState
"""
m1, m2 = min1, min2
candidates = self.session.query(TransitionState).\
filter(or_(
and_(TransitionState.minimum1==m1,
TransitionState.minimum2==m2),
and_(TransitionState.minimum1==m2,
TransitionState.minimum2==m1),
))
for m in candidates:
return m
return None
3
Example 47
Project: pychess Source File: database.py
def build_where_tags(self, text):
if text:
text = unicode(text)
self.where_tags = or_(
pl1.c.name.startswith(text),
pl2.c.name.startswith(text),
event.c.name.startswith(text),
site.c.name.startswith(text),
annotator.c.name.startswith(text),
)
else:
self.where_tags = None
3
Example 48
Project: cronq Source File: mysql.py
def get_job_to_inject(self, session):
to_run = or_(
Job.next_run < datetime.datetime.utcnow(),
Job.run_now == True, # noqa
)
job = session.query(Job).filter(to_run).first()
if job is None:
return None
logger.info('[cronq_job_id:{0}] Found a job: {1} {2}'.format(
job.id, job.name, job.next_run))
return job
3
Example 49
@ratings.route('/profile')
@login_required
def profile():
form = AddPlayerForm()
form.server.choices = [(server.id, server.name) for server in GoServer.query.all()]
players = Player.query.filter(Player.user_id == current_user.id).order_by(Player.name.asc()).all()
if current_user.is_ratings_admin():
games = Game.query.limit(30).all()
else:
games = itertools.chain(*(Game.query.filter(or_(Game.white_id == player.id, Game.black_id == player.id)) for player in players))
return render_template('profile.html', user=current_user, games=games, players=players, form=form)
3
Example 50
def invalid_query(self, session, **kw):
return session.query(Languoid)\
.filter(Languoid.identifiers.any(or_(
Identifier.name.op('~')(ur'^\s|\s$'),
Identifier.name.op('~')(ur'[`_*:\xa4\xab\xb6\xbc]'),
), type='name', description='Glottolog'))\
.order_by(Languoid.id)