Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Key.to_legacy_urlsafe() #348

Merged
merged 4 commits into from
Mar 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion google/cloud/ndb/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,7 @@ def serialized(self):
return reference.SerializeToString()

def urlsafe(self):
"""A ``Reference`` protobuf encoded as urlsafe base 64.
"""A ``Reference`` protobuf serialized and encoded as urlsafe base 64.

.. doctest:: key-urlsafe

Expand All @@ -739,6 +739,33 @@ def urlsafe(self):
raw_bytes = self.serialized()
return base64.urlsafe_b64encode(raw_bytes).strip(b"=")

def to_legacy_urlsafe(self, location_prefix):
"""
A urlsafe serialized ``Reference`` protobuf with an App Engine prefix.

This will produce a urlsafe string which includes an App Engine
location prefix ("partition"), compatible with the Google Datastore
admin console.

Arguments:
location_prefix (str): A location prefix ("partition") to be
prepended to the key's `project` when serializing the key. A
typical value is "s~", but "e~" or other partitions are
possible depending on the project's region and other factors.

.. doctest:: key-legacy-urlsafe

>>> key = ndb.Key("Kind", 1337, project="example")
>>> key.to_legacy_urlsafe("s~")
b'aglzfmV4YW1wbGVyCwsSBEtpbmQYuQoM'
"""
return google.cloud.datastore.Key(
self._key.kind,
self._key.id,
namespace=self._key.namespace,
project=self._key.project,
).to_legacy_urlsafe(location_prefix=location_prefix)

@_options.ReadOptions.options
@utils.positional(1)
def get(
Expand Down
9 changes: 9 additions & 0 deletions tests/unit/test_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,15 @@ def test_urlsafe():
key = key_module.Key("d", None, app="f")
assert key.urlsafe() == b"agFmcgULEgFkDA"

@staticmethod
@pytest.mark.usefixtures("in_context")
def test_to_legacy_urlsafe():
key = key_module.Key("d", 123, app="f")
assert (
key.to_legacy_urlsafe(location_prefix="s~")
== b"agNzfmZyBwsSAWQYeww"
)

@staticmethod
@pytest.mark.usefixtures("in_context")
@mock.patch("google.cloud.ndb._datastore_api")
Expand Down