當前位置: 首頁>>代碼示例>>Python>>正文


Python ndb.AND屬性代碼示例

本文整理匯總了Python中google.appengine.ext.ndb.AND屬性的典型用法代碼示例。如果您正苦於以下問題:Python ndb.AND屬性的具體用法?Python ndb.AND怎麽用?Python ndb.AND使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在google.appengine.ext.ndb的用法示例。


在下文中一共展示了ndb.AND屬性的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_random

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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 
開發者ID:google,項目名稱:loaner,代碼行數:27,代碼來源:survey_models.py

示例2: scoring

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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 
開發者ID:google,項目名稱:arithmancer,代碼行數:26,代碼來源:scorer.py

示例3: list_by_user

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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() 
開發者ID:google,項目名稱:loaner,代碼行數:12,代碼來源:device_model.py

示例4: list

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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) 
開發者ID:google,項目名稱:loaner,代碼行數:30,代碼來源:survey_models.py

示例5: query_display

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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) 
開發者ID:Schibum,項目名稱:sndlatr,代碼行數:16,代碼來源:models.py

示例6: get

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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})) 
開發者ID:einaregilsson,項目名稱:MyLife,代碼行數:13,代碼來源:postdates.py

示例7: query_article_nested

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:8,代碼來源:snippets.py

示例8: get_result_summaries_query

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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) 
開發者ID:luci,項目名稱:luci-py,代碼行數:30,代碼來源:task_result.py

示例9: GetTradesForPredictionId

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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) 
開發者ID:google,項目名稱:arithmancer,代碼行數:7,代碼來源:main.py

示例10: price

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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() 
開發者ID:google,項目名稱:arithmancer,代碼行數:12,代碼來源:price.py

示例11: get_previous_meetings

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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 
開發者ID:Yelp,項目名稱:beans,代碼行數:53,代碼來源:match_utils.py

示例12: _QueryModel

# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import AND [as 別名]
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 
開發者ID:google,項目名稱:upvote,代碼行數:50,代碼來源:handler_utils.py


注:本文中的google.appengine.ext.ndb.AND屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。