当前位置: 首页 > 知识库问答 >
问题:

使用服务帐户使用独立的Python脚本连接到Google Cloud Storage

唐利
2023-03-14

我正在尝试使用一个服务帐户从一个独立的python脚本连接到Google Cloud Storage。我正在从本地系统运行此脚本。我还使用gcloud身份验证激活了服务帐户,并添加了“google_application_credentials”来指向client_secrets.json文件。



    Uploading object..
    Traceback (most recent call last):
      File "quickstart.py", line 122, in 
        main(args.bucket, args.filename, args.reader, args.owner)
      File "quickstart.py", line 16, in main
        resp = upload_object(bucket, filename, readers, owners)
      File "quickstart.py", line 43, in upload_object
        service = create_service()
      File "quickstart.py", line 39, in create_service
        return discovery.build('storage', 'v1', http=http_auth)
      File "build/bdist.macosx-10.12-intel/egg/oauth2client/util.py", line 137, in positional_wrapper
      File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 214, in build
      File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 261, in _retrieve_discovery_doc
      File "build/bdist.macosx-10.12-intel/egg/oauth2client/transport.py", line 153, in new_request
      File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 765, in _refresh
      File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 797, in _do_refresh_request
      File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1609, in request
        (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
      File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1351, in _request
        (response, content) = self._conn_request(conn, request_uri, method, body, headers)
      File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1272, in _conn_request
        conn.connect()
      File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1036, in connect
        self.disable_ssl_certificate_validation, self.ca_certs)
      File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 80, in _ssl_wrap_socket
        cert_reqs=cert_reqs, ca_certs=ca_certs)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 911, in wrap_socket
        ciphers=ciphers)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 520, in __init__
        self._context.load_verify_locations(ca_certs)
    IOError: [Errno 13] Permission denied



    import oauth2client
    from oauth2client.service_account import ServiceAccountCredentials
    from httplib2 import Http
    from googleapiclient import discovery
    import argparse
    import filecmp
    import json
    import tempfile
    import logging

    logging.basicConfig(filename='debug.log',level=logging.DEBUG)


    def main(bucket, filename, readers=[], owners=[]):
        print('Uploading object..')
        resp = upload_object(bucket, filename, readers, owners)
        print(json.dumps(resp, indent=2))


    def create_service():
        scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
        credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', scopes)
        http_auth = credentials.authorize(Http())
        return discovery.build('storage', 'v1', http=http_auth)


    def upload_object(bucket, filename, readers, owners):
        service = create_service()

        # This is the request body as specified:
        # http://g.co/cloud/storage/docs/json_api/v1/objects/insert#request
        body = {
            'name': filename,
        }

        # If specified, create the access control objects and add them to the
        # request body
        if readers or owners:
            body['acl'] = []

        for r in readers:
            body['acl'].append({
                'entity': 'user-%s' % r,
                'role': 'READER',
                'email': r
            })
        for o in owners:
            body['acl'].append({
                'entity': 'user-%s' % o,
                'role': 'OWNER',
                'email': o
            })

        # Now insert them into the specified bucket as a media insertion.
        # http://g.co/dv/resources/api-libraries/documentation/storage/v1/python/latest/storage_v1.objects.html#insert
        with open(filename, 'rb') as f:
            req = service.objects().insert(
                bucket=bucket, body=body,
                # You can also just set media_body=filename, but for the sake of
                # demonstration, pass in the more generic file handle, which could
                # very well be a StringIO or similar.
                media_body=http.MediaIoBaseUpload(f, 'application/octet-stream'))
            resp = req.execute()

        return resp

共有1个答案

艾泉
2023-03-14

从错误来看,这似乎是一个简单的权限问题。你用根Priviges运行这个程序了吗?如果没有,则从命令行开始使用sudo运行该文件。

注意:IDLE不使用root运行它。

 类似资料:
  • 我正在尝试使用API将成员添加到组中。我在谷歌脚本工具中编写代码,但是,我收到了错误消息: 我已经在G套件域中添加了作用域,我已经创建了服务帐户、API密钥、OAuth 2.0密钥。我的要求是: 遗漏了什么,或者我做错了什么?我已经阅读了所有的文档,仍然不知道出了什么问题。

  • 我已经在本地下载了wiremock独立jar。我使用下面的命令启动独立服务器。java-jar wiremock-jre8-standalone-2.26.3.jar--端口8089 我需要一个可以连接到我的wiremock服务器并显示所有映射的用户界面。如果UI能够提供永久编辑、删除和添加新文件的特征,这将是有利的。

  • 我授予所有特权。这是脚本: 我在浏览器中看到以下消息: 警告:mysqli::mysqli():(HY000/1045):在C:\xampp\htdocs\web-datos\connect\u-mysql中,用户“username”@“localhost”(使用密码:YES)的访问被拒绝。php第11行 拒绝访问用户“username”@“localhost”(使用密码:YE 我试图联系但没有成

  • 问题内容: 在python中,我有变量和。我想把它们串联起来获得。但是在Windows下,我应该使用和用于POSIX 。 如何使该平台独立? 问题答案: 您要为此使用os.path.join()。 使用此方法而不是使用字符串连接等方法的优势在于,它知道各种特定于OS的问题,例如路径分隔符。例子: 在 Windows 7下 : 在 Linux下 : 所述OS模块包含目录,路径操纵并找出OS特定信息许

  • 问题内容: 我正在尝试使用Python中的Selenium用我的GMail帐户自动登录,但出现此错误: 我的代码如下所示: 我该如何解决我的问题? 问题答案: 尝试更改网址。使用代替。 确保使用原始电子邮件和密码。并更改到每个元素。 您的代码将是:

  • 我试图使用Python Twisted Authobhan websocket客户端打开客户端(每台机器有60K端口限制)的并发websocket连接。但是我无法使用下面的代码打开不超过20K的连接: 我在一个循环中使用了“reactor.connecttcp”,使用Twisted打开并发websocket连接是否正确? 让我知道。