Generate ndb.Key.urlsafe Compatible, or Convert urlsafe String to Key (Python)

June 7, 2019

I was developing on App Engine Python 2.7 for a long time and using ndb.Key.urlsafe() quite a lot (including storing these keys on external app like Android).

Since App Engine Python 3.7 and Google Cloud Functions, NDB is no longer available and we have to access Datastore via google-cloud-datastore Python client libraries.

Luckily the following functions are available to generate and parse ndb.Key.urlsafe() Key.

google.cloud.datastore.key.Key.from_legacy_urlsafe()

This is intended to work with the “legacy” representation of a datastore “Key” used within Google App Engine (a so-called “Reference”). This assumes that urlsafe was created within an App Engine app via something like ndb.Key(…).urlsafe().

google.cloud.datastore.key.Key.to_legacy_urlsafe()

Convert to a base64 encode urlsafe string for App Engine.

This is intended to work with the “legacy” representation of a datastore “Key” used within Google App Engine (a so-called “Reference”). The returned string can be used as the urlsafe argument to ndb.Key(urlsafe=…). The base64 encoded values will have padding removed.

The string returned by to_legacy_urlsafe is equivalent, but not identical, to the string returned by ndb. The location prefix may need to be specified to obtain identical urlsafe keys.

location_prefix (str) – The location prefix of an App Engine project ID. Often this value is ‘s~’, but may also be ‘e~’, or other location prefixes currently unknown.

You will notice the by default, the urlsafe string generated by Key.to_legacy_urlsafe() differ from those of ndb.Key.urlsafe(). I was using datastore at us-central, so using Key.to_legacy_urlsafe('s~') will generate exactly the same string as ndb.Key.urlsafe().

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.