开发者

Key generation in Google App Engine

If you guys ever used Google App Engine. It generates a key for every single instan开发者_StackOverflowce of a model created. It's pretty neat.

I'm looking into building something like that. Do they do it so that the key is based on the content? Or do they just take a random choice from a-zA-Z0-9 for like 50 times and build a string out of it? That sounds reasonable because the chances that 2 key would be the same would be lower than 1/10^89.


Just using random values is not going to cut it. While the chance of two keys being the same is very slim the chances increase rapidly with the number of keys generated. See the birthday paradox.

In most cases such keys are generated in a way that guarantees uniqueness by containing several values like MAC address or some serial number of the server that generated it, a time stamp, the value of an special counter.


You can find more information about how universal unique identifier is being constructed here.

If you want to create it from the php side of code you can use uniqid function. More information here.


Keys in App Engine are based on:

  1. The keys of the ancestor entities of the entity, if any.

  2. The kind name of the entity.

  3. Either an auto-generated integer id or a user-assigned key_name. The integer IDs are allocated in generally-increasing blocks to various instances of the application, so that they can be guaranteed to be unique but are not guaranteed to actualy get assigned to entities in a monotonically increasing fashion.

The keys do not use anything like a universally unique ID.


May be not 100% unique, but I use something like this:

def get_unique_id_str():
    import binascii
    import uuid
    table = ''.join(chr(i) for i in xrange(256))
    return binascii.b2a_base64(uuid.uuid4().bytes).translate(table, '/+=\n')

key_name = get_unique_id_str()
instance = MyModel(key_name=key_name, ...)
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜