Skip to content

Commit 8feb90d

Browse files
Chris Rossichmoder
andauthored
feat: Key.to_legacy_urlsafe() (#348)
* #264 Create method `legacy_urlsafe` to include location prefix in a urlsafe key * Update docstring, rename to match Datastore for consistency. * Fix test. * Make suggested changes from code review. Co-authored-by: Thomas Cross <tom.bz2@gmail.com>
1 parent d156d3e commit 8feb90d

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

packages/google-cloud-ndb/google/cloud/ndb/key.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -728,7 +728,7 @@ def serialized(self):
728728
return reference.SerializeToString()
729729

730730
def urlsafe(self):
731-
"""A ``Reference`` protobuf encoded as urlsafe base 64.
731+
"""A ``Reference`` protobuf serialized and encoded as urlsafe base 64.
732732
733733
.. doctest:: key-urlsafe
734734
@@ -739,6 +739,33 @@ def urlsafe(self):
739739
raw_bytes = self.serialized()
740740
return base64.urlsafe_b64encode(raw_bytes).strip(b"=")
741741

742+
def to_legacy_urlsafe(self, location_prefix):
743+
"""
744+
A urlsafe serialized ``Reference`` protobuf with an App Engine prefix.
745+
746+
This will produce a urlsafe string which includes an App Engine
747+
location prefix ("partition"), compatible with the Google Datastore
748+
admin console.
749+
750+
Arguments:
751+
location_prefix (str): A location prefix ("partition") to be
752+
prepended to the key's `project` when serializing the key. A
753+
typical value is "s~", but "e~" or other partitions are
754+
possible depending on the project's region and other factors.
755+
756+
.. doctest:: key-legacy-urlsafe
757+
758+
>>> key = ndb.Key("Kind", 1337, project="example")
759+
>>> key.to_legacy_urlsafe("s~")
760+
b'aglzfmV4YW1wbGVyCwsSBEtpbmQYuQoM'
761+
"""
762+
return google.cloud.datastore.Key(
763+
self._key.kind,
764+
self._key.id,
765+
namespace=self._key.namespace,
766+
project=self._key.project,
767+
).to_legacy_urlsafe(location_prefix=location_prefix)
768+
742769
@_options.ReadOptions.options
743770
@utils.positional(1)
744771
def get(

packages/google-cloud-ndb/tests/unit/test_key.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,15 @@ def test_urlsafe():
567567
key = key_module.Key("d", None, app="f")
568568
assert key.urlsafe() == b"agFmcgULEgFkDA"
569569

570+
@staticmethod
571+
@pytest.mark.usefixtures("in_context")
572+
def test_to_legacy_urlsafe():
573+
key = key_module.Key("d", 123, app="f")
574+
assert (
575+
key.to_legacy_urlsafe(location_prefix="s~")
576+
== b"agNzfmZyBwsSAWQYeww"
577+
)
578+
570579
@staticmethod
571580
@pytest.mark.usefixtures("in_context")
572581
@mock.patch("google.cloud.ndb._datastore_api")

0 commit comments

Comments
 (0)