我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用google.appengine.ext.ndb.OR。
def gae_ndb_delete_expired_sessions(dormant_for=86400, limit=500): """Deletes expired sessions A session is expired if it expires date is set and has passed or if it has not been accessed for a given period of time. max_age: seconds since last access to delete sessions, defaults to 24 hours. limit: amount to delete in one call of the method, the maximum and default for this is the NDB fetch limit of 500""" from vishnu.backend.client.ndb.gae import VishnuSession from google.appengine.ext import ndb from datetime import datetime from datetime import timedelta now = datetime.utcnow() last_accessed = now - timedelta(seconds=dormant_for) query = VishnuSession.query(ndb.OR( ndb.AND(VishnuSession.expires <= now, VishnuSession.expires != None), VishnuSession.last_accessed <= last_accessed )) results = query.fetch(keys_only=True, limit=limit) ndb.delete_multi(results) return len(results) < limit
def query_display(cls, user_id, delta_minutes=60): """ Query all jobs that have state scheduled, queued or sent (but not done) OR are done and have been scheduled for no longer than delta_minutes ago. """ shortly_ago = datetime.datetime.utcnow() - datetime.timedelta( minutes=delta_minutes) # query all jobs that are return cls.query(ndb.OR(cls.state.IN(['scheduled', 'queued', 'sent']), ndb.AND(cls.scheduled_at >= shortly_ago, cls.state == 'done')), cls.user_id == user_id)
def _CheckUserHasAccessMaybeSetStatus(self, tourney, ns_pair, ew_pair): ''' Tests if the current user has access to a hand with given players. Uses the pair id code, if any, set in the request header to see if the user is in one of the teams playing the hand. Directors always have access. Args: tourney. Tournament. Current tournament. ns_pair: Integer. Pair number of team playing North/South. ew_pair: Integer. Pair number of team playing East/West. Returns: A (Boolean, Integer) pair. First member is True iff the user has access to the hand between ns_pair and ew_pair. Second member is the pair number of the user. Only set if first member is True. ''' user = users.get_current_user() error = "Forbidden User" if user and tourney.owner_id == user.user_id(): return (True, 0) pair_id = GetPairIdFromRequest(self.request) if not pair_id: SetErrorStatus(self.response, 403, error, "User does not own tournament and is not authenticated " + "with a pair code to overwrite this hand.") return (False, None) player_pairs = PlayerPair.query( ndb.OR(PlayerPair.pair_no == int(ns_pair), PlayerPair.pair_no == int(ew_pair)), ancestor=tourney.key).fetch() if (not player_pairs) or (pair_id not in [p.id for p in player_pairs]): SetErrorStatus(self.response, 403, error, "User does not own tournament and is authenticated with " + "the wrong code for involved pairs") return (False, None) return (True, next(p.pair_no for p in player_pairs if p.id == pair_id))
def query_article_inequality_explicit(): query = Article.query(ndb.OR(Article.tags < 'perl', Article.tags > 'perl')) return query
def query_article_in_equivalent(): query = Article.query(ndb.OR(Article.tags == 'python', Article.tags == 'ruby', Article.tags == 'php')) return query
def query_article_nested(): query = Article.query(ndb.AND(Article.tags == 'python', ndb.OR(Article.tags.IN(['ruby', 'jruby']), ndb.AND(Article.tags == 'php', Article.tags != 'perl')))) return query
def pull_and_publish_event(): oauth_tokens = db.OAuthToken.query( db.OAuthToken.valid_token == True, ndb.OR(db.OAuthToken.next_post_time < datetime.datetime.now(), db.OAuthToken.next_post_time == None) ).fetch(100) q1 = taskqueue.Queue(EVENT_PULL_QUEUE_HIGH) q2 = taskqueue.Queue(EVENT_PULL_QUEUE) for token in oauth_tokens: logging.info("Can post to OAuthToken %s: %s", token.queue_id(), token) tasks = q1.lease_tasks_by_tag(120, 1, token.queue_id()) q = q1 if not tasks: tasks = q2.lease_tasks_by_tag(120, 1, token.queue_id()) q = q2 logging.info("Fetching %d tasks with queue id %s", len(tasks), token.queue_id()) if tasks: # Should only be one task if len(tasks) != 1: logging.error('Found too many tasks in our lease_tasks_by_tag: %s', len(tasks)) task = tasks[0] # Backwards compatibility for items in the queue if '{' not in task.payload: data = { 'type': 'event', 'event_id': task.payload, } else: data = json.loads(task.payload) logging.info('Processing data payload: %r', data) posted = _post_data_with_authtoken(data, token) q.delete_tasks(task) # Only mark it up for delay, if we actually posted... if posted: next_post_time = datetime.datetime.now() + datetime.timedelta(seconds=token.time_between_posts) token = token.key.get() token.next_post_time = next_post_time token.put()
def get_user_scores(self, user): """Returns a list of scores by the requested user""" scores = Score.query(ndb.OR(Score.winner == user.key, Score.loser == user.key)).fetch() return scores #----------------------------------------------------------------------- #Create a form from a score #-----------------------------------------------------------------------
def get_user_games(self, user): """Returns a list of active games by the requested user""" games = Game.query(ndb.OR(Game.first_user == user.key, Game.second_user == user.key)).filter(Game.game_over == False).fetch() return games #----------------------------------------------------------------------- #Creation of a new game of memory #-----------------------------------------------------------------------
def processLog(log): topics = log['topics'] eventId = topics[0].lower() address = log['address'].lower() logging.info("Log for %s from %s", eventId, address) if len(topics) == 0: return q = models.Hook.query(models.Hook.eventId == eventId, ndb.OR( models.Hook.address == address, models.Hook.address == "")) for hook in q: notifyHook(hook, log)
def exist_by_user_id( cls, user_id ): count = cls.query( ndb.OR( cls.friends == user_id, cls.friends == user_id )).count( 1 ) return count > 0
def count_by_user_id( cls, user_id ): return cls.query( ndb.OR( cls.friends == user_id, cls.friends == user_id )).count()
def query_by_user_id( cls, user_id ): return cls.query( ndb.OR( ndb.AND( cls.user_id == user_id, cls.time_updated > ( datetime.datetime.now() - datetime.timedelta( seconds = settings.SESSION_MAX_IDLE_AGE ))), ndb.AND( cls.user_id == user_id, cls.stay_logged_in == True, cls.time_updated > ( datetime.datetime.now() - datetime.timedelta( seconds = settings.SESSION_MAX_IDLE_AGE_STAY_LOGGED_IN )))))
def fetch_keys_expired( cls ): return cls.query( ndb.OR( cls.time_updated > ( datetime.datetime.now() - datetime.timedelta( seconds = settings.SESSION_MAX_IDLE_AGE_STAY_LOGGED_IN )), ndb.AND( cls.stay_logged_in == False, cls.time_updated > ( datetime.datetime.now() - datetime.timedelta( seconds = settings.SESSION_MAX_IDLE_AGE )))) ).fetch( keys_only = True ) #=== UTILITIES ================================================================
def exist_by_purchaser_or_activator( cls, user_id ): count = cls.query( ndb.OR( cls.purchaser_user_id == user_id, cls.activated_by_user == user_id )).count( 1 ) return count > 0
def fetch_keys_sent_or_received( cls, user_id ): return cls.query( ndb.OR( cls.sender == user_id, cls.recipient == user_id )).fetch( keys_only = True ) #=== UTILITIES ================================================================
def filter_by_user_visibility(cls, query, user): if user is None: query = query.filter(cls.is_public == True) elif not user.is_server_admin(): # server admin can see anything query = query.filter(ndb.OR(cls.is_public == True, cls.admins == user.key )) return query