Cloud Storage 使用入门

Google Display & Video 360 会自动将实体读取文件存储在 Google Cloud Storage 中。只有已被授予访问权限的帐号才能访问这些文件。

创建项目

按如下方式创建和配置项目:

  1. 前往 Google API 控制台中的“已启用的 API”页面

    如果您尚未登录 Google,系统会提示您登录。

  2. 从项目下拉菜单中,选择一个现有项目或创建一个新项目。
    • 如果您有多个现有项目,请务必选择要激活 Google Cloud Storage 的项目,然后选择继续
    • 或者,如果您没有项目,请选择创建新项目,输入项目名称,然后选择创建

      注意:请注意,某些资源标识符(例如项目 ID)的保留期可能比项目的生命周期更长。因此,请避免将敏感信息存储在资源标识符中。

  3. 已启用的 API 列表中,确保已列出 Google Cloud Storage 组件。 如果未列出,请点击 Google API 标签页,搜索并选择 Google Cloud Storage 组件,然后点击启用 API

    请注意,对于大多数项目,已启用 Google Cloud Storage 组件。如果您打算使用 JSON API 访问 Google Cloud Storage,则还应验证是否已启用 Google Cloud Storage JSON API。

  4. 为项目启用结算功能。

    您需要为项目启用结算功能(如果尚未启用结算功能)才能使用 Google Cloud Storage。启用结算功能不一定意味着您需要付费。如需了解详情,请参阅价格

    1. 还是在 Cloud Storage 项目中,点击左上角的图库菜单,然后选择结算
    2. 如果您还没有结算帐号,请按照说明创建新的结算帐号
    3. 如果您已有结算帐号,请选择该帐号,然后选择设置帐号

在 Google API 控制台中,保持同一项目并转到下一部分。

设置对 Cloud Storage 的访问权限

  1. 还是在 Google API 控制台的所需项目中,点击左上角的图库菜单,选择 API 和服务,然后点击凭据。在“凭据”页面上,查找服务帐号密钥

    找到服务账号密钥电子邮件地址:

    1. 选择管理服务帐号链接(位于“服务帐号密钥”部分右侧)。
    2. 您可以在随即显示的权限页面中查看该电子邮件地址

    如果没有服务账号密钥,请创建一个新的服务账号:

    1. 选择创建凭据下拉列表,然后选择服务帐号密钥
    2. 服务帐号下拉列表中,选择新建服务帐号
    3. 为该服务帐号输入一个名称。系统会根据名称和项目名称自动生成服务帐号 ID
    4. 记下 ID 为 gserviceaccount.com 的服务帐号的电子邮件地址。 选择创建后,此凭据不会显示在“凭据”页面上。
    5. 密钥类型部分中,选择 JSON
    6. 点击创建。包含帐号的公钥/私钥对的 JSON 文件会保存到您的“下载内容”文件夹中。此密钥用于向 API 验证您的应用,并签署它向 API 发送的所有请求。将生成的 JSON 文件存储在安全的位置,也就是您的应用可以访问的位置。
  2. 请与 Display & Video 360 支持团队联系,请求启用实体读取文件和/或 Google Bid Manager API。

    支持团队确认访问权限后,创建一个(或多个)专用 Google 群组,并更新 Display & Video 360 合作伙伴详细信息中的以下字段(请注意,只有拥有合作伙伴级访问权限的用户才能进行这些更新):

    • 日志读取 Google 群组
      只读群组仅具有读取文件和列出存储分区内容的权限。
    • 日志管理 Google 群组
      管理群组拥有只读群组的所有权限,但也可以更改存储分区中文件的 ACL。请注意,管理群组也没有权限更改存储分区 ACL,也无权创建、修改或删除文件。

    添加 Google 群组后,您可以根据需要向 Google 群组添加用户以及从中移除用户,而无需 Display & Video 360 支持团队进一步协助;只有位于您的群组中的用户才能访问您的数据。

访问您的数据

使用 gsutil 访问数据

gsutil 工具是一个命令行应用,您无需任何编程经验,即可轻松访问 Google Cloud Storage 数据。例如,您可以将 gsutil 用作脚本或批处理文件的一部分,而不是创建自定义应用。

要开始使用 gsutil,请阅读 gsutil 文档。 您仍然需要像以前一样使用 OAuth 2 进行身份验证,但 gsutil 本身会在您首次使用时提示您输入凭据,然后存储凭据以供日后使用。

以编程方式访问数据

Google Cloud Storage 提供许多编程语言的 API,支持您以程序化方式访问数据。以下示例展示了如何从 Google Cloud Storage 执行一个简单的实体读取文件下载操作。请注意,只有公开的实体读取文件存储在 gdbm-public 存储分区中;您的私有 实体读取文件将存储在合作伙伴专用存储分区和广告客户专用存储分区中。

Java

以下示例使用了适用于 Java 的 Google API 客户端库,以便轻松访问保存在 Google Cloud Storage 中的数据。除了主要的常规 Google API 客户端库之外,您还需要下载单独的 Cloud Storage API 库

您首先需要设置与该 API 通信时要使用的凭据,以获取数据访问权限。方法是创建一个 Credential 对象,该对象会将服务帐号的 developer.gserviceaccount.com 电子邮件地址用作 ServiceAccountId,并加载在创建服务帐号时从 Google API 控制台下载的私钥文件。这可确保以后向该 API 发出的所有请求均使用服务帐号的私钥进行签名:

NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JacksonFactory JSON_FACTORY = new JacksonFactory();

...

Credential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
   .setJsonFactory(JSON_FACTORY)
   .setServiceAccountId("...@developer.gserviceaccount.com")
   .setServiceAccountScopes(StorageScopes.DEVSTORAGE_READ_ONLY)
   .setServiceAccountPrivateKeyFromP12File(new File("...-privatekey.p12"))
   .build();

创建 Credential 对象后,您可以使用它来实例化一个新的 Storage 对象,以用于将来向 Google Cloud Storage API 发出的所有请求:

Storage storage = new Storage(HTTP_TRANSPORT, JSON_FACTORY, credential);

现在,您已经有了新的 Storage 对象,可以开始向 API 发出请求了。您正在发出请求,以便从存储分区 bucket 中检索特定项 bucketObjectName。该库会处理从 Google Cloud Storage 进行文件的 HTTP 下载,然后您只需将内容输出到控制台即可:

Get bucketObject = storage.objects().get(bucketName, bucketObjectName);

ByteArrayOutputStream output = new ByteArrayOutputStream();
bucketObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
bucketObject.executeAndDownloadTo(output);

System.out.println(output.toString());

bucketbucketObjectName 的值因您要访问的 API 部分而异;请参阅关于命名惯例的相应部分。

C#

以下示例使用了 .NET 版 Google API 客户端库,该库可以轻松访问保存在 Google Cloud Storage 中的数据。

您首先需要设置与 API 通信时要使用的凭据,以获取访问您数据的授权。为此,请创建一个 AssertionFlowClient 对象,该对象会将服务帐号的 developer.gserviceaccount.com 电子邮件地址用作 ServiceAccountId,并加载在创建服务帐号时从 Google API 控制台下载的私钥文件。

string keyPath = @"...-privatekey.p12";
X509Certificate2 certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
    ServiceAccountId = "...@developer.gserviceaccount.com",
    Scope = StorageService.Scopes.DevstorageRead_only.GetStringValue()
};

创建 AssertionFlowClient 对象后,您可以使用它来实例化一个新的 OAuth2Authenticator 对象,以用来实例化新的 Storage 实例,以用于将来向 Google Cloud Storage API 发出的所有请求:

var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
StorageService service = new StorageService(auth);

现在,您已经有了新的 Storage 对象,可以开始向 API 发出请求了。您正在发出请求,以便从存储分区 bucket 中检索特定项 bucketObjectName。我们使用标准 .NET 客户端库类来处理从 Google Cloud Storage 下载的 HTTP 请求,但您必须手动处理存在重定向的情况,以确保请求中存在正确的 Authorization 标头:

var results = service.Objects.Get(bucketName, bucketObjectName).Fetch();

HttpWebRequest request = createRequest(results.Media.Link, auth);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Handle redirects manually to ensure that the Authorization header is present if
// your request is redirected.
if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
{
    request = createRequest(response.Headers["Location"], auth);
    response = (HttpWebResponse)request.GetResponse();
}

然后,可以照常通过 GetResponseStreamHttpWebResponse 对象读取响应的内容。bucketbucketObjectName 的值因您要访问的 API 部分而异;请参阅关于命名惯例的相应部分。

附录:完整示例

Java

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.bidmanager.api.samples;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.Storage.Objects.Get;
import com.google.api.services.storage.StorageScopes;

/**
 * A simple class that demonstrates how to download a specific object from a bucket using a
 * service account
 */
public class ServiceDownload {

  /**
   * This is the HTTP Transport object used for automatically refreshing access tokens.
   */
  static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /**
   * This is the JSON factory used for parsing refresh token responses.Your first requirement
   */
  static final JacksonFactory JSON_FACTORY = new JacksonFactory();

  /**
   * The main method will attempt to download a specific named object from the gdbm-public bucket
   * using a service account.
   *
   * @param args Not used.
   */
  public static void main(String[] args) {

    try {
      // Prompt the user for the details of the object to download.
      System.out.print("Name of object to download, e.g. entity/20130430.0.Browser.json:");
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String bucketObjectName = in.readLine();
      in.close();
      String bucketName = "gdbm-public";

      Credential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
           .setJsonFactory(JSON_FACTORY)
           .setServiceAccountId("...@developer.gserviceaccount.com")
           .setServiceAccountScopes(StorageScopes.DEVSTORAGE_READ_ONLY)
           .setServiceAccountPrivateKeyFromP12File(
               new File("...-privatekey.p12"))
           .build();

      Storage storage = new Storage(HTTP_TRANSPORT, JSON_FACTORY, credential);

      Get bucketObject = storage.objects().get(bucketName, bucketObjectName);

      ByteArrayOutputStream output = new ByteArrayOutputStream();
      bucketObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
      bucketObject.executeAndDownloadTo(output);
      System.out.println(output.toString());

    } catch (Exception e) {
      System.err.println("Unexpected exception caught: " + e.getMessage());
      e.printStackTrace();
    }

  }


}

C#

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;

using DotNetOpenAuth.OAuth2;

using Google.Apis;
using Google.Apis.Requests;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Storage.v1beta1;
using Google.Apis.Storage.v1beta1.Data;
using Google.Apis.Util;

namespace ApiSamples
{
    /// <summary>
    /// A simple class that demonstrates how to download a specific object from a bucket using a
    /// service account
    /// </summary>
    class ServiceDownload
    {
        /// <summary>
        /// The main method will attempt to download a specific named object from the
        /// gdbm-public bucket using a service account.
        /// </summary>
        /// <param name="args">Not used.</param>
        public static void Main(string[] args)
        {

            // Prompt the user for the details of the object to download
            Console.WriteLine("Name of object to download, e.g. entity/20130430.0.Browser.json:");
            string bucketObjectName = Console.ReadLine();
            string bucketName = "gdbm-public";

            try
            {
                string keyPath = @"...-privatekey.p12";
                X509Certificate2 certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
                var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
                {
                    ServiceAccountId = "...@developer.gserviceaccount.com",
                    Scope = StorageService.Scopes.DevstorageRead_only.GetStringValue()
                };
                var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

                StorageService service = new StorageService(auth);
                var results = service.Objects.Get(bucketName, bucketObjectName).Fetch();

                HttpWebRequest request = createRequest(results.Media.Link, auth);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // Handle redirects manully to ensure that the Authorization header is present if
                // our request is redirected.
                if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
                {
                    request = createRequest(response.Headers["Location"], auth);
                    response = (HttpWebResponse)request.GetResponse();
                }

                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                String data = reader.ReadToEnd();
                Console.Write(data);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception caught: " + e.Message);
                Console.Write(e.StackTrace);
            }
            Console.ReadKey();
        }

        /// <summary>
        /// Generate a HttpWebRequest for the given URL with the appropriate OAuth2 authorization
        /// header applied.  The HttpWebRequest object returned has its AllowAutoRedirect option
        /// disabled to allow us to manually handle redirects.
        /// </summary>
        /// <param name="url">URL that is to be requested with this object</param>
        /// <param name="auth">The OAuth2Authenticator instance that contains the appropriate keys.</param>
        /// <returns>HttpWebRequest object ready to be used to make requests to the API</returns>
        private static HttpWebRequest createRequest(string url, OAuth2Authenticator<AssertionFlowClient> auth)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Bearer " + auth.State.AccessToken);
            request.AllowAutoRedirect = false;
            return request;
        }

    }
}