本文整理汇总了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
示例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
示例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()
示例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)
示例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)
示例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}))
示例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
示例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)
示例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)
示例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()
示例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
示例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