Python google.appengine.ext.ndb.AND Examples
The following are 12
code examples of google.appengine.ext.ndb.AND().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
google.appengine.ext.ndb
, or try the search function
.
Example #1
Source File: survey_models.py From loaner with Apache License 2.0 | 6 votes |
def get_random(cls, question_type): """Get a random survey question by type. Args: question_type: QuestionType, The type of question requested. Returns: An instance of the Question, returns None if no questions of the provided type are found. """ total_weight = 0 questions = [] active_questions = cls.query(ndb.AND( cls.enabled == True, cls.question_type == question_type)).fetch() # pylint: disable=g-explicit-bool-comparison,singleton-comparison for question in active_questions: total_weight += question.rand_weight questions.append( RandomChoice(question, question.rand_weight)) value = random.uniform(0, total_weight) upto = 0 for question, weight in questions: if upto + weight >= value: return question upto += weight return None
Example #2
Source File: scorer.py From arithmancer with Apache License 2.0 | 6 votes |
def scoring(): #go through all predictions, check if should be scored predictions = Prediction.query( ndb.AND(Prediction.outcome != "UNKNOWN", Prediction.resolved == False)).fetch() audit = [] # Get all trades by prediction_id for p in predictions: resolve = p.outcome trades = Trade.query(Trade.prediction_id == p.key).fetch() # Get user id from those trades users = [trade.user_id.get() for trade in trades] for u in users: # check user ledger, map outcome to 1 or 0 based on prediction outcome ledger = [i for i in u.user_ledger if i.prediction_id == p.key.urlsafe()] if resolve == 'CONTRACT_ONE': earned = ledger[0].contract_one else: earned = ledger[0].contract_two u.balance += earned audit.append({'user': u, 'earned': earned}) u.put() p.resolved = True p.put() return audit
Example #3
Source File: device_model.py From loaner with Apache License 2.0 | 5 votes |
def list_by_user(cls, user): """Returns a list of devices assigned to a user. Args: user: str, the user's email address. Returns: A query of devices assigned to the user. """ return cls.query(ndb.AND(cls.assigned_user == user)).fetch()
Example #4
Source File: survey_models.py From loaner with Apache License 2.0 | 5 votes |
def list( cls, question_type=None, enabled=True, page_size=100, next_cursor=None, **kwargs): """List all questions with filters. Args: question_type: QuestionType, The type of question to be queried for. enabled: bool, True to retrieve enabled surveys. page_size: int, The number of answers to return. next_cursor: datastore_query.Cursor, Next page of results. **kwargs: each kwarg name is the name of a Question property by which to filter the query and its value (string, integer, boolean, etc.). Returns: A tuple of a list of Question instances, datastore_query.Cursor instance, and a boolean representing whether or not there are more to retrieve. """ query = cls.query( cls.enabled == enabled, # pylint: disable=g-explicit-bool-comparison ndb.AND(cls.question_type == question_type)) for filters, values in kwargs.items(): if not isinstance(values, (list, tuple)): values = (values,) for value in values: query = query.filter(ndb.GenericProperty(filters) == value) return query.fetch_page(page_size=page_size, start_cursor=next_cursor)
Example #5
Source File: models.py From sndlatr with Apache License 2.0 | 5 votes |
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)
Example #6
Source File: postdates.py From MyLife with MIT License | 5 votes |
def get(self, year, month): year, month = int(year), int(month) from_date = datetime.date(int(year), int(month), 1) next_month = from_date + datetime.timedelta(days=33) to_date = datetime.date(next_month.year, next_month.month, 1) days = [p.date.day for p in Post.query(ndb.AND(Post.date >= from_date, Post.date < to_date)).order(-Post.date).fetch()] self.response.headers['Content-Type'] = "application/json" self.response.write(json.dumps({"key" : from_date.strftime('%Y-%m'), "days": days}))
Example #7
Source File: snippets.py From python-docs-samples with Apache License 2.0 | 5 votes |
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
Example #8
Source File: task_result.py From luci-py with Apache License 2.0 | 5 votes |
def get_result_summaries_query(start, end, sort, state, tags): """Returns TaskResultSummary.query() with these filters. Arguments: start: Earliest creation date of retrieved tasks. end: Most recent creation date of retrieved tasks, normally None. sort: Order to use. Must default to 'created_ts' to use the default. Cannot be used along start and end. state: One of State enum value as str. Use 'all' to get all tasks. tags: List of search for one or multiple task tags. """ # Disable the in-process local cache. This is important, as there can be up to # a thousand entities loaded in memory, and this is a pure memory leak, as # there's no chance this specific instance will need these again, therefore # this leads to 'Exceeded soft memory limit' AppEngine errors. q = TaskResultSummary.query( default_options=ndb.QueryOptions(use_cache=False)) # Filter by one or more tags. if tags: # Add TaskResultSummary indexes if desired. if sort != 'created_ts': raise ValueError( 'Add needed indexes for sort:%s and tags if desired' % sort) tags_filter = TaskResultSummary.tags == tags[0] for tag in tags[1:]: tags_filter = ndb.AND(tags_filter, TaskResultSummary.tags == tag) q = q.filter(tags_filter) return _filter_query(TaskResultSummary, q, start, end, sort, state)
Example #9
Source File: main.py From arithmancer with Apache License 2.0 | 5 votes |
def GetTradesForPredictionId(prediction_id): user = users.get_current_user() trades = Trade.query(ndb.AND(Trade.prediction_id == ndb.Key(urlsafe=prediction_id), Trade.user_id == ndb.Key('Profile', user.user_id()))).fetch() return str(trades)
Example #10
Source File: price.py From arithmancer with Apache License 2.0 | 5 votes |
def price(): predictions = Prediction.query( ndb.AND(Prediction.outcome == "UNKNOWN", Prediction.resolved == False)).fetch() input_date = datetime.datetime.now() for p in predictions: price = Price(prediction_id=p.key, date=input_date, value=p.GetPriceByPredictionId()) price.put()
Example #11
Source File: match_utils.py From beans with MIT License | 4 votes |
def get_previous_meetings(subscription, cooldown=None): if cooldown is None: cooldown = get_config()['meeting_cooldown_weeks'] meetings = defaultdict(list) # get all meeting specs from x weeks ago til now time_threshold_for_meetings = datetime.now() - timedelta(weeks=cooldown) meeting_spec_keys = [ spec.key for spec in MeetingSpec.query( ndb.AND(MeetingSpec.datetime > time_threshold_for_meetings, MeetingSpec.meeting_subscription == subscription) ).fetch() ] logging.info('Previous Meeting History: ') logging.info([meeting.get().datetime.strftime("%Y-%m-%d %H:%M") for meeting in meeting_spec_keys]) if meeting_spec_keys == []: return set([]) # get all meetings from meeting specs meeting_keys = [meeting.key for meeting in Meeting.query().filter( Meeting.meeting_spec.IN(meeting_spec_keys)).fetch()] if meeting_keys == []: return set([]) # get all participants from meetings participants = MeetingParticipant.query().filter( MeetingParticipant.meeting.IN(meeting_keys) ).fetch() if participants == []: return set([]) # group by meeting Id for participant in participants: meetings[participant.meeting.id()].append(participant.user) # ids are sorted, all matches should be in increasing order by id for the matching algorithm to work disallowed_meetings = set([tuple(sorted(meeting, key=lambda Key: Key.id())) for meeting in meetings.values()]) logging.info('Past Meetings') logging.info([tuple([meeting.get().get_username() for meeting in meeting]) for meeting in disallowed_meetings]) disallowed_meetings = {tuple([meeting.id() for meeting in meeting]) for meeting in disallowed_meetings} return disallowed_meetings
Example #12
Source File: handler_utils.py From upvote with Apache License 2.0 | 4 votes |
def _QueryModel(self, search_dict, ancestor=None): """Queries the model class for field-value pairs. Args: search_dict: A dictionary mapping from field name to search by to the search term. ancestor: ndb.Key, If provided, the ancestor for the query. Returns: The model query. Raises: QueryError: If the queried field is not a property of the model. QueryTypeError: If search_term does not match the type of the search_base model property. """ filter_nodes = [] for search_base, search_term in search_dict.items(): field_name = string_utils.CamelToSnakeCase(search_base) # If the model class offers a translation function for property queries, # invoke it and set the field and search term to the result. try: field_name, search_term = self.MODEL_CLASS.TranslatePropertyQuery( field_name, search_term) except AttributeError: pass else: logging.info('Converted query to (%s = %s)', field_name, search_term) # Check for the property on the model itself (as opposed to, say, catching # a getattr exception) to ensure that the field being accessed is an ndb # property as opposed to a Python attribute. if not datastore_utils.HasProperty(self.MODEL_CLASS, field_name): raise QueryError('Invalid searchBase %s' % field_name) field = getattr(self.MODEL_CLASS, field_name) # If the field is of a non-string type, attempt to coerce the argument to # conform to this type search_term = _CoerceQueryParam(field, search_term) filter_nodes.append(ndb.FilterNode(field_name, '=', search_term)) query = self.MODEL_CLASS.query(ancestor=ancestor) if filter_nodes: query = query.filter(ndb.AND(*filter_nodes)) return query