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: add signed url to gcs #23

Merged
merged 16 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
21 changes: 21 additions & 0 deletions cloud/google/storage.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import datetime
from typing import Any

from google import auth
from google.cloud import storage


Expand All @@ -15,10 +17,29 @@ def download(self, bucket_name: str, source_filename: str, destination_filename:
blob = self.client.bucket(bucket_name).blob(source_filename)
blob.download_to_filename(destination_filename)

def generate_presigned_url(
self,
bucket_name: str,
source_filename: str,
expiration: int,
) -> str:
credentials, _ = auth.default()
client = storage.Client(credentials=credentials)
blob = client.bucket(bucket_name).blob(source_filename)
leonardoc-lima marked this conversation as resolved.
Show resolved Hide resolved

url = blob.generate_signed_url(
expiration=datetime.timedelta(seconds=expiration),
)
return url


class Uploader(Client):
pass


class Downloader(Client):
pass


class URLSigner(Client):
pass
28 changes: 27 additions & 1 deletion tests/google/test_storage.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import datetime
import unittest
from unittest import mock

from cloud.google.storage import Downloader, Uploader
from cloud.google.storage import Downloader, Uploader, URLSigner
from cloud.protocols import StorageDownloader, StorageUploader


Expand Down Expand Up @@ -51,3 +52,28 @@ def test_storage_downloader(self, client_mock):

blob = bucket.blob.return_value
blob.download_to_filename.assert_called_once_with(destination)


class TestStorageURLSigner(unittest.TestCase):
@mock.patch("google.cloud.storage.Client")
def test_storage_urlsigner(self, client_mock):
urlsigner = URLSigner()

client_mock.assert_called_once_with()

bucket_name = "test-bucket"
object_name = "test.txt"
expiration = 3600

urlsigner.generate_presigned_url(bucket_name, object_name, expiration)

cli = client_mock.return_value
cli.bucket.assert_called_once_with(bucket_name)

bucket = cli.bucket.return_value
bucket.blob.assert_called_once_with(object_name)

blob = bucket.blob.return_value
blob.generate_signed_url.assert_called_once_with(
expiration=datetime.timedelta(seconds=expiration),
)
Loading