禁用模拟 google.cloud.storage 时的 Google 云身份验证 Python。

huangapple go评论74阅读模式
英文:

Disable google cloud authentication python when mocking google.cloud.storage

问题

以下是您要翻译的部分:

从以下的Google Cloud Storage模拟开始

```python
from google.cloud import storage


class MockBlob:
    def download_as_string(self) -> bytes:
        return bytes("\n".join(INPUT_IDS), "utf-8")


class MockBucket:
    def get_blob(self, path: str) -> MockBlob:
        return MockBlob()


class MockStorageClient(storage.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def _require_client_info(self, client_info=None):
        pass

    def _require_virtual(self):
        pass

    def get_bucket(self, bucket_or_name: str):
        return MockBucket()

我收到以下错误消息

.venv/lib/python3.8/site-packages/google/cloud/storage/client.py:173: in __init__
    super(Client, self).__init__(
.venv/lib/python3.8/site-packages/google/cloud/client/__init__.py:320: in __init__
    _ClientProjectMixin.__init__(self, project=project, credentials=credentials)
.venv/lib/python3.8/site-packages/google/cloud/client/__init__.py:268: in __init__
    project = self._determine_default(project)
.venv/lib/python3.8/site-packages/google/cloud/client/__init__.py:287: in _determine_default
    return _determine_default_project(project)
.venv/lib/python3.8/site-packages/google/cloud/_helpers/__init__.py:152: in _determine_default_project
    _, project = google.auth.default()
.venv/lib/python3.8/site-packages/google/auth/_default.py:615: in default
    credentials, project_id = checker()
.venv/lib/python3.8/site-packages/google/auth/_default.py:608: in <lambda>
    lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id),
.venv/lib/python3.8/site-packages/google/auth/_default.py:228: in _get_explicit_environ_credentials
    credentials, project_id = load_credentials_from_file(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

filename = '', scopes = None, default_scopes = None, quota_project_id = None, request = None

    def load_credentials_from_file(
        filename, scopes=None, default_scopes=None, quota_project_id=None, request=None
    ):
        """Loads Google credentials from a file.
    
        The credentials file must be a service account key, stored authorized
        user credentials, external account credentials, or impersonated service
        account credentials.
    
        Args:
            filename (str): The full path to the credentials file.
            scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
                specified, the credentials will automatically be scoped if
                necessary
            default_scopes (Optional[Sequence[str]]): Default scopes passed by a
                Google client library. Use 'scopes' for user-defined scopes.
            quota_project_id (Optional[str]):  The project ID used for
                quota and billing.
            request (Optional[google.auth.transport.Request]): An object used to make
                HTTP requests. This is used to determine the associated project ID
                for a workload identity pool resource (external account credentials).
                If not specified, then it will use a
                google.auth.transport.requests.Request client to make requests.
    
        Returns:
            Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
                credentials and the project ID. Authorized user credentials do not
                have the project ID information. External account credentials project
                IDs may not always be determined.
    
        Raises:
            google.auth.exceptions.DefaultCredentialsError: if the file is in the
                wrong format or is missing.
        """
        if not os.path.exists(filename):
>           raise exceptions.DefaultCredentialsError(
                "File {} was not found.".format(filename)
            )
E           google.auth.exceptions.DefaultCredentialsError: File  was not found.

.venv/lib/python3.8/site-packages/google/auth/_default.py:116: DefaultCredentialsError

测试的目的是查看是否使用存储桶的代码是否正常工作。获取的Blob包含一个由"\n"分隔的文本文件中的ID,这就是下载函数返回静态字节字符串的原因。
如何禁用凭据以避免出现问题。

英文:

With the following mock of google cloud storage

from google.cloud import storage


class MockBlob:
    def download_as_string(self) -> bytes:
        return bytes("\n".join(INPUT_IDS), "utf-8")


class MockBucket:
    def get_blob(self, path: str) -> MockBlob:
        return MockBlob()


class MockStorageClient(storage.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def _require_client_info(self, client_info=None):
        pass

    def _require_virtual(self):
        pass

    def get_bucket(self, bucket_or_name: str):
        return MockBucket()

i get the error displayed below

.venv/lib/python3.8/site-packages/google/cloud/storage/client.py:173: in __init__
    super(Client, self).__init__(
.venv/lib/python3.8/site-packages/google/cloud/client/__init__.py:320: in __init__
    _ClientProjectMixin.__init__(self, project=project, credentials=credentials)
.venv/lib/python3.8/site-packages/google/cloud/client/__init__.py:268: in __init__
    project = self._determine_default(project)
.venv/lib/python3.8/site-packages/google/cloud/client/__init__.py:287: in _determine_default
    return _determine_default_project(project)
.venv/lib/python3.8/site-packages/google/cloud/_helpers/__init__.py:152: in _determine_default_project
    _, project = google.auth.default()
.venv/lib/python3.8/site-packages/google/auth/_default.py:615: in default
    credentials, project_id = checker()
.venv/lib/python3.8/site-packages/google/auth/_default.py:608: in <lambda>
    lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id),
.venv/lib/python3.8/site-packages/google/auth/_default.py:228: in _get_explicit_environ_credentials
    credentials, project_id = load_credentials_from_file(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

filename = '', scopes = None, default_scopes = None, quota_project_id = None, request = None

    def load_credentials_from_file(
        filename, scopes=None, default_scopes=None, quota_project_id=None, request=None
    ):
        """Loads Google credentials from a file.
    
        The credentials file must be a service account key, stored authorized
        user credentials, external account credentials, or impersonated service
        account credentials.
    
        Args:
            filename (str): The full path to the credentials file.
            scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If
                specified, the credentials will automatically be scoped if
                necessary
            default_scopes (Optional[Sequence[str]]): Default scopes passed by a
                Google client library. Use 'scopes' for user-defined scopes.
            quota_project_id (Optional[str]):  The project ID used for
                quota and billing.
            request (Optional[google.auth.transport.Request]): An object used to make
                HTTP requests. This is used to determine the associated project ID
                for a workload identity pool resource (external account credentials).
                If not specified, then it will use a
                google.auth.transport.requests.Request client to make requests.
    
        Returns:
            Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
                credentials and the project ID. Authorized user credentials do not
                have the project ID information. External account credentials project
                IDs may not always be determined.
    
        Raises:
            google.auth.exceptions.DefaultCredentialsError: if the file is in the
                wrong format or is missing.
        """
        if not os.path.exists(filename):
>           raise exceptions.DefaultCredentialsError(
                "File {} was not found.".format(filename)
            )
E           google.auth.exceptions.DefaultCredentialsError: File  was not found.

.venv/lib/python3.8/site-packages/google/auth/_default.py:116: DefaultCredentialsError

The purpose of the test is to see if the code utilizing the bucket is working. The blob that is fetched contains a text file of ids that are separated by "\n", which is why the download function returns a static byte string.
How do i disable the credentials, such that it is not an issue.

答案1

得分: 1

以下是翻译好的部分:

您可以简单地覆盖失败的函数如下所示

```python
from google.auth import credentials
import google.auth._default


def load_credentials_from_file(
    filename, scopes=None, default_scopes=None, quota_project_id=None, request=None
) -> Tuple[credentials.Credentials, Optional[str]]:
    return (credentials.AnonymousCredentials(), "test-project")


google.auth._default.load_credentials_from_file = load_credentials_from_file

<details>
<summary>英文:</summary>
You can simply override the function that fails as 
```python
from google.auth import credentials
import google.auth._default
def load_credentials_from_file(
filename, scopes=None, default_scopes=None, quota_project_id=None, request=None
) -&gt; Tuple[credentials.Credentials, Optional[str]]:
return (credentials.AnonymousCredentials(), &quot;test-project&quot;)
google.auth._default.load_credentials_from_file = load_credentials_from_file

huangapple
  • 本文由 发表于 2023年5月24日 18:55:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定