为应用引擎数据存储生成唯一编号序列作为实体键
有没有人能分享一些示例代码,用来生成一个独特的数字序列,这个序列可以作为Google应用引擎数据存储中某个实体的键?
我想用顺序的数字作为这个键。
2 个回答
2
你可以看看这个链接:如何在Google AppEngine上实现“自增”功能,里面有关于序列号的实现方法。
6
使用 db.allocate_ids()
,具体用法可以参考这里,来为你的实体生成唯一的ID。
下面是一个简单的例子,来源于上面链接中的示例:
from google.appengine.ext import db
# get unique ID number - I just get 1 here, but you could get many ...
new_ids = db.allocate_ids(handmade_key, 1)
# db.allocate_ids() may return longs but db.Key.from_path requires an int (issue 2970)
new_id_num = int(new_id[0])
# assign the new ID to an entity
new_key = db.Key.from_path('MyModel', new_id_num)
new_instance = MyModel(key=new_key)
...
new_instance.put()