本文整理汇总了Python中google.appengine.api.datastore_types.Key类的典型用法代码示例。如果您正苦于以下问题:Python Key类的具体用法?Python Key怎么用?Python Key使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Key类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_result
def get_result(self):
if self.cache_result is not None:
return self.cache_result
if len(self.exception) >= 1:
raise self.exception[0]
resp = self.rpc.response
keys = resp.key_list()
entities = self._entities
multiple = self.multiple
tx = self.tx
num_keys = len(keys)
num_entities = len(entities)
if num_keys != num_entities:
raise datastore_errors.InternalError(
'Put accepted %d entities but returned %d keys.' %
(num_entities, num_keys))
for entity, key in zip(entities, keys):
entity._Entity__key._Key__reference.CopyFrom(key)
if tx:
tx.entity_group = entities[0].entity_group()
if multiple:
return [Key._FromPb(k) for k in keys]
else:
return Key._FromPb(resp.key(0))
示例2: createPlayer
def test_given_score_and_ThreeDisapprovingReviewerOfWhichTwoAgree_then_NonAgreeingReviewerAndPLayerAreCheater(self):
score = {'score' : 99, 'proof' : "sdsd", 'time' : 0}
playerId = "test"
createPlayer(playerId, playerId)
service.start(playerId)
service.setScore(playerId, score)
playerKey = Key.from_path('Player', playerId)
createReviewerAndReview("test2", playerKey, {'score':3, 'time': 0})
createReviewerAndReview("test3", playerKey, {'score':999, 'time': 0})
createReviewerAndReview("test4", playerKey, {'score':3, 'time': 0})
verifiedScore = VerifiedScore.get_by_key_name("verified", parent=playerKey)
playerRecord = Record.get_by_key_name('record', parent=playerKey)
self.assertTrue(verifiedScore is None or verifiedScore.value == 0)
self.assertEqual(playerRecord.numCheat, 1)
playerKey = Key.from_path('Player', 'test3')
playerRecord = Record.get_by_key_name('record', parent=playerKey)
self.assertEqual(playerRecord.numCheat, 1)
示例3: setReviewTimeUnit
def test_given_aAdminReviewerTryingToReviewAsAdmin_ItShouldSucceedAndDeclareNonAgreeingConflictingReviewerAsCheaters(self):
setReviewTimeUnit(0)
score = {'score' : 99, 'proof' : "sdsd", 'time' : 0}
playerId = "test"
createPlayer(playerId, playerId)
service.start(playerId)
service.setScore(playerId, score)
playerKey = Key.from_path('Player', playerId)
createReviewerAndReview("test2", playerKey, {'score':3, 'time': 0})
createReviewerAndReview("test3", playerKey, {'score':999, 'time': 0})
createReviewerAndReview("test4", playerKey, {'score':3, 'time': 0}, True)
verifiedScore = VerifiedScore.get_by_key_name("verified", parent=playerKey)
playerRecord = Record.get_by_key_name('record', parent=playerKey)
self.assertTrue(verifiedScore is None or verifiedScore.value == 0)
self.assertEqual(playerRecord.numCheat, 1)
playerKey = Key.from_path('Player', 'test3')
playerRecord = Record.get_by_key_name('record', parent=playerKey)
self.assertEqual(playerRecord.numCheat, 1)
playerKey = Key.from_path('Player', 'test2')
playerRecord = Record.get_by_key_name('record', parent=playerKey)
self.assertEqual(playerRecord.numCheat, 0)
示例4: test_key_kind
def test_key_kind(self):
"""
Checks that db.Keys stored in the database use proper kinds.
Key kind should be the name of the table (db_table) of a model
for primary keys of entities, but for foreign keys, references
in general, it should be the db_table of the model the field
refers to.
Note that Django hides the underlying db.Key objects well, and
it does work even with wrong kinds, but keeping the data
consistent may be significant for external tools.
TODO: Add DictField / EmbeddedModelField and nesting checks.
"""
parent = ParentKind.objects.create(pk=1)
child = ChildKind.objects.create(
pk=2, parent=parent, parents=[parent.pk])
self.assertEqual(child.parent.pk, parent.pk)
self.assertEqual(child.parents[0], parent.pk)
from google.appengine.api.datastore import Get
from google.appengine.api.datastore_types import Key
parent_key = Key.from_path(parent._meta.db_table, 1)
child_key = Key.from_path(child._meta.db_table, 2)
parent_entity = Get(parent_key)
child_entity = Get(child_key)
parent_column = child._meta.get_field('parent').column
parents_column = child._meta.get_field('parents').column
self.assertEqual(child_entity[parent_column], parent_key)
self.assertEqual(child_entity[parents_column][0], parent_key)
示例5: test_newPlayerWithoutReviewAssigned_shouldGetNoReviews
def test_newPlayerWithoutReviewAssigned_shouldGetNoReviews(self):
playerId = "test"
createPlayer(playerId, playerId)
playerKey = Key.from_path('Player', playerId)
reviewSession = ReviewSession.get_by_key_name('reviewSession', parent=playerKey)
self.assertEqual(reviewSession, None)
示例6: test_given_aAdminReviewerTryingToReviewAsAdmin_ItShouldSucceed
def test_given_aAdminReviewerTryingToReviewAsAdmin_ItShouldSucceed(self):
setReviewTimeUnit(0)
score = {'score' : 3, 'proof' : "sdsd", 'time' : 0}
playerId = "test1"
createPlayer(playerId, playerId)
service.start(playerId)
service.setScore(playerId, score)
createPlayer("reviewer1", "reviewer1")
admin = getAdmin()
admin.playerList.append('reviewer1')
setAdmin(admin)
service.getRandomScore("reviewer1")
response = service.reviewScore("reviewer1", {'score':3, 'time': 0}, True)
self.assertTrue('result' in response)
playerKey = Key.from_path('Player', playerId)
verifiedScoreWrapper = VerifiedScoreWrapper.get_by_key_name('verifiedScore', parent=playerKey)
verifiedScore = verifiedScoreWrapper.verified
self.assertEqual(verifiedScore.value, 3)
self.assertEqual(verifiedScore.approvedByAdmin, True)
示例7: __init__
def __init__(
self,
left,
op=None,
right=None,
):
self.get_all = self.get_one = None
if isinstance(left, list):
self.filters = left
return
if isinstance(right, (Field, Expression)):
raise SyntaxError, \
'Query: right side of filter must be a value or entity: %s' \
% right
if isinstance(left, Field):
# normal filter: field op value
assert_filter_fields(left)
if left.type == 'id':
try:
if type(right) == list:
#make this work for belongs
right = [long(r) for r in right]
else:
right = long(right or 0)
except ValueError:
raise SyntaxError, 'id value must be integer: %s' % id
if op != '=' and not (op == '>' and right == 0):
#get key (or keys) based on path. Note if we later support
# ancesters this will not be the proper key for items with
# ancesters.
#in GAE (with no ancesters) the key is base64 encoded
# "table_name: id=<id>". GAE decodes the string and compares
# the id
if op=='IN':
right = [Key.from_path(left._tablename, r) for r in right]
else:
right = Key.from_path(left._tablename, right)
elif op=='IN':
right = [dateobj_to_datetime(obj_represent(r, left.type, left._db)) \
for r in right]
else:
# filter dates/times need to be datetimes for GAE
right = dateobj_to_datetime(obj_represent(right, left.type, left._db))
self.filters = [Filter(left, op, right)]
return
raise SyntaxError, 'not supported'
示例8: setUser_MakerSecret
def setUser_MakerSecret(id, maker_secret):
key = Key.from_path('UserData', id)
entity = datastore.Get(key)
entity.update({
'maker_secret': maker_secret
})
datastore.Put(entity)
memcache.set(key="MakerSecret-" + id, value=maker_secret)
示例9: test_db_conversion
def test_db_conversion(self):
actual_datetime = datetime.datetime.now()
entity = FieldsWithoutOptionsModel(
datetime=actual_datetime, date=actual_datetime.date(),
time=actual_datetime.time(), floating_point=5.97, boolean=True,
null_boolean=False, text='Hallo', email='[email protected]',
comma_seperated_integer='5,4,3,2',
ip_address='194.167.1.1', slug='you slugy slut :)',
url='http://www.scholardocs.com', long_text=1000 * 'A',
indexed_text='hello',
integer=-400, small_integer=-4, positive_integer=400,
positive_small_integer=4)
entity.save()
# Get the gae entity (not the django model instance) and test
# if the fields have been converted right to the corresponding
# GAE database types.
gae_entity = Get(
Key.from_path(FieldsWithoutOptionsModel._meta.db_table,
entity.pk))
opts = FieldsWithoutOptionsModel._meta
for name, types in [('long_text', Text),
('indexed_text', unicode),
('text', unicode), ('ip_address', unicode), ('slug', unicode),
('email', unicode), ('comma_seperated_integer', unicode),
('url', unicode), ('time', datetime.datetime),
('datetime', datetime.datetime), ('date', datetime.datetime),
('floating_point', float), ('boolean', bool),
('null_boolean', bool), ('integer', (int, long)),
('small_integer', (int, long)),
('positive_integer', (int, long)),
('positive_small_integer', (int, long))]:
column = opts.get_field_by_name(name)[0].column
if not isinstance(types, (list, tuple)):
types = (types, )
self.assertTrue(type(gae_entity[column]) in types)
# Get the model instance and check if the fields convert back
# to the right types.
model = FieldsWithoutOptionsModel.objects.get()
for name, types in [
('long_text', unicode),
('indexed_text', unicode),
('text', unicode), ('ip_address', unicode),
('slug', unicode),
('email', unicode), ('comma_seperated_integer', unicode),
('url', unicode), ('datetime', datetime.datetime),
('date', datetime.date), ('time', datetime.time),
('floating_point', float), ('boolean', bool),
('null_boolean', bool), ('integer', (int, long)),
('small_integer', (int, long)),
('positive_integer', (int, long)),
('positive_small_integer', (int, long))]:
if not isinstance(types, (list, tuple)):
types = (types, )
self.assertTrue(type(getattr(model, name)) in types)
示例10: key_from_path
def key_from_path(db_table, value):
"""
Workaround for GAE choosing not to validate integer ids when
creating keys.
TODO: Should be removed if it gets fixed.
"""
if isinstance(value, (int, long)):
ValidateInteger(value, 'id')
return Key.from_path(db_table, value)
示例11: test_given_aScoreSubmitedTooEarly_ItShouldNotBeSubmited
def test_given_aScoreSubmitedTooEarly_ItShouldNotBeSubmited(self):
score = {'score' : 3, 'proof' : "sdsd", 'time' : 10000}
playerId = "test"
createPlayer(playerId, playerId)
service.start(playerId)
service.setScore(playerId, score)
playerKey = Key.from_path('Player', playerId)
pendingScore = PendingScore.get_by_key_name('pendingScore', parent=playerKey)
self.assertEqual(pendingScore, None)
示例12: getUser_MakerSecret
def getUser_MakerSecret(id):
secret = memcache.get(key="MakerSecret-" + id)
if secret == None:
try:
key = Key.from_path('UserData', id)
entity = datastore.Get(key)
secret = entity['maker_secret']
memcache.set(key="MakerSecret-" + id, value=secret)
except:
logging.debug(id + u"のIFTTT Maker Secretは登録されていません。")
return secret
示例13: deleteUserData
def deleteUserData(id):
# memcache.delete(key="MakerSecret-"+id)
# memcache.delete(key="USER-"+id)
# dashid=memcache.get(key="User-dash-"+id)
# memcache.delete(key = "User-dash-"+id)
# memcache.delete(key = "Dash-user-"+str(dashid))
try:
key = Key.from_path('UserData', id)
entity = datastore.Delete(key)
except:
logging.debug(id + u"は登録されていません。")
示例14: key_from_path
def key_from_path(db_table, value):
"""
Workaround for GAE choosing not to validate integer ids when
creating keys.
TODO: Should be removed if it gets fixed.
"""
from google.appengine.api.datastore_types import Key, ValidateInteger
if isinstance(value, (int, long)):
ValidateInteger(value, 'id')
return Key.from_path(db_table, value)
示例15: _approveScore
def _approveScore():
scoreToApprove = db.get(scoreToApproveKey)
if scoreToApprove is None:
return {'cheater' : None, 'nonCheaters': []}
approvedPlayerKey = scoreToApprove.parent_key()
cheater = None
nonCheaters = []
if scoreToApprove.value == scoreValue and scoreToApprove.time == scoreTime:
scoreToApprove.approvedByAdmin = True
scoreToApprove.put()
else:
approvedPlayerRecord = Record.get_by_key_name('record', parent=approvedPlayerKey)
approvedPlayerRecord.numCheat += 1
approvedPlayerRecord.put()
cheater = Key.from_path('Player', scoreToApprove.verifier)
for nonCheaterId in scoreToApprove.conflictingReviewers:
nonCheaters.append(Key.from_path('Player', nonCheaterId))
scoreToApprove.delete()
db.delete(Key.from_path('VerifiedScoreWrapper', 'verifiedScore', parent = approvedPlayerKey))
return {'cheater' : cheater, 'nonCheaters': nonCheaters}