Cloud Storage'ı Kullanmaya Başlayın

Google Display & Video 360, Varlık Okuma Dosyaları'nı Google Cloud Storage'da otomatik olarak depolar. Bu dosyalara yalnızca erişim izni verilen hesaplar erişebilir.

Proje oluşturma

Aşağıdaki şekilde proje oluşturun ve yapılandırın:

  1. Google API Konsolu Etkin API'ler sayfasına gidin.

    Google'da henüz oturum açmadıysanız oturum açmanız istenir.

  2. Proje açılır menüsünden mevcut bir projeyi seçin veya yeni bir proje oluşturun.
    • Mevcut birden fazla projeniz varsa Google Cloud Storage'ı etkinleştirmek istediğiniz projeyi seçtiğinizden emin olun, ardından Devam'ı seçin.
    • Projeniz yoksa Yeni proje oluştur'u seçin, bir proje adı girin ve Oluştur'u seçin.

      Not: Bazı kaynak tanımlayıcılarının (proje kimlikleri gibi) projenizin ömrü boyunca saklanabileceğini unutmayın. Bu nedenle, hassas bilgileri kaynak tanımlayıcılarda depolamaktan kaçının.

  3. Etkin API'ler listesinde, Google Cloud Storage bileşeninin listelendiğinden emin olun. Listede yoksa Google API'leri sekmesini tıklayın, Google Cloud Storage bileşenini bulup seçin ve API'yi etkinleştir'i tıklayın.

    Çoğu projede Google Cloud Storage bileşeninin zaten etkin olduğunu unutmayın. Google Cloud Storage'a JSON API kullanarak erişmeyi planlıyorsanız Google Cloud Storage JSON API'nin etkin olduğunu da doğrulamanız gerekir.

  4. Proje için faturalandırmayı etkinleştirin.

    Google Cloud Storage'ı kullanabilmeniz için henüz yapmadıysanız projenizde faturalandırmayı etkinleştirmeniz gerekir. Faturalandırmanın etkinleştirilmesi mutlaka ücretlendirileceğiniz anlamına gelmez. Daha fazla bilgi edinmek için Fiyatlandırma'ya göz atın.

    1. Yine Cloud Storage projesindeyken, sol üst köşedeki galeri menüsünü tıklayın ve ardından Faturalandırma'yı seçin.
    2. Henüz faturalandırma hesabınız yoksa yeni faturalandırma hesabı oluşturma talimatlarını uygulayın.
    3. Mevcut bir faturalandırma hesabınız varsa bu hesabı seçip Hesap belirle'yi seçin.

Google API Konsolu'nda aynı projede kalın ve sonraki bölüme geçin.

Cloud Storage'a erişimi ayarlama

  1. Gerekli projedeki Google API Konsolu'ndayken sol üst köşedeki galeri menüsünü tıklayın, API'ler ve Hizmetler'i seçin ve ardından Kimlik bilgileri'ni tıklayın. Kimlik bilgileri sayfasında Hizmet hesabı anahtarları'nı bulun.

    Hizmet hesabı anahtarı e-posta adresini bulun:

    1. Hizmet Hesaplarını Yönet bağlantısını seçin (Hizmet hesabı anahtarları bölümünün sağında).
    2. E-posta adresi, açılan İzinler sayfasında görüntülenebilir.

    Hizmet hesabı anahtarı yoksa yeni bir hizmet hesabı oluşturun:

    1. Kimlik bilgisi oluştur açılır menüsünü, ardından Hizmet hesabı anahtarı'nı seçin.
    2. Hizmet hesabı açılır menüsünden Yeni hizmet hesabı'nı seçin.
    3. Hizmet hesabı için bir Ad girin. Hizmet hesabı kimliği, addan ve proje adından otomatik olarak oluşturulur.
    4. Hizmet hesabı kimliği gserviceaccount.com e-posta adresini not edin. Oluştur'u seçtikten sonra Kimlik Bilgileri sayfasında görünmez.
    5. Anahtar türü bölümünde JSON'yi seçin.
    6. Create'i (Oluştur) tıklayın. Hesabın herkese açık/özel anahtar çiftini içeren JSON dosyası İndirilenler klasörünüze kaydedilir. Bu anahtar, uygulamanızın API'de kimliğini doğrulamak ve API'ye gönderdiği tüm istekleri imzalamak için kullanılır. Oluşturulan JSON dosyasını, uygulamanızın erişebileceği güvenli bir yerde depolayın.
  2. Varlık Okuma dosyalarının ve/veya Google Bid Manager API'sinin etkinleştirilmesini istemek için Display & Video 360 Destek Ekibi ile iletişime geçin.

    Destek Ekibi erişimi onayladıktan sonra özel bir Google Grubu (veya gruplar) oluşturun ve Display & Video 360 iş ortağı ayrıntılarında aşağıdaki alanları güncelleyin (yalnızca iş ortağı seviyesinde erişimi olan kullanıcıların bu güncellemeleri yapabileceğini unutmayın):

    • Günlük Okuma Google Grubu
      Salt okunur grup yalnızca depolama paketlerinin dosyalarını okuma ve içeriğini listeleme iznine sahiptir.
    • Günlük Yönetimi Google Grubu
      Yönetim grubu salt okuma grubunun tüm izinlerine sahiptir ancak paketlerdeki dosyaların EKL'lerini de değiştirebilir. Yönetim grubunun bile paket EKL'lerini değiştirme ve dosya oluşturma, değiştirme ya da silme izni olmadığını unutmayın.

    Google Grubu eklendikten sonra, Display & Video 360 destek ekibinin başka bir müdahalesine gerek olmadan, gerektiğinde Google Grubunuza kullanıcı ekleyip çıkarabilirsiniz. Yalnızca grubunuzdaki kullanıcılar verilerinize erişebilir.

Verilerinize erişin

gsutil aracını kullanarak verilere erişme

gsutil aracı, Google Cloud Storage verilerinize herhangi bir programlama deneyimi olmadan kolayca erişmenizi sağlayan bir komut satırı uygulamasıdır. Örneğin, gsutil'i özel uygulamalar oluşturmak yerine bir komut dosyasının veya toplu dosyanın parçası olarak kullanabilirsiniz.

gsutil'i kullanmaya başlamak için gsutil dokümanlarını okuyun. Önceden olduğu gibi OAuth 2 kullanarak kimlik doğrulaması yapmanız gerekir ancak gsutil'in kendisi ilk kez kimlik bilgilerinizi ister ve daha sonra kullanmak üzere saklar.

Verilere programatik olarak erişme

Google Cloud Storage, verilerinize programatik olarak erişmenize olanak tanıyan birçok programlama dili için API'lere sahiptir. Aşağıdaki örnekte, Google Cloud Storage'daki Varlık Okuma Dosyaları'ndan birini basit bir şekilde nasıl indirebileceğiniz gösterilmektedir. gdbm-public paketinde yalnızca herkese açık Varlık Okuma Dosyaları'nın depolandığını unutmayın. Özel Varlık Okuma Dosyalarınız, İş Ortağı ve Reklamverene özel paketlerde depolanır.

Java

Aşağıdaki örnekte, Google Cloud Storage'da tutulan verilere erişimi kolaylaştıran Java için Google API'leri İstemci Kitaplığı kullanılmıştır. Ana genel Google API'leri İstemci Kitaplığı'na ek olarak, ayrı Cloud Storage API kitaplığını da indirmeniz gerekir.

Verilerinize erişim yetkisi almak için öncelikle API ile iletişim kurarken kullanılacak kimlik bilgilerini ayarlamanız gerekir. Bu işlem, ServiceAccountId olarak Hizmet Hesabının developer.gserviceaccount.com e-posta adresini kullanan ve Hizmet Hesabı oluşturulurken Google API Konsolu'ndan indirilen özel anahtar dosyasını yükleyen bir Credential nesnesi oluşturarak yapılır. Bu, API'ye yönelik gelecekteki tüm isteklerin Hizmet Hesabının özel anahtarıyla imzalanmasını sağlar:

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 nesnesini oluşturduktan sonra bu nesneyi, gelecekteki tüm Google Cloud Storage API isteklerinde kullanabileceğiniz yeni bir Storage nesnesi oluşturmak için kullanabilirsiniz:

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

Artık yeni bir Storage nesneniz olduğuna göre API'ye istekte bulunmaya hazırsınız. Burada, bucket paketinden belirli bir öğeyi (bucketObjectName) almak için istekte bulunuyorsunuz. Kitaplık, dosyanın Google Cloud Storage'dan HTTP indirme işlemini gerçekleştirir, ardından içerikleri konsola yazdırın:

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

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

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

bucket ve bucketObjectName değerleriniz, API'nin hangi bölümüne eriştiğinize bağlı olarak değişiklik gösterir. Adlandırma kurallarıyla ilgili bölüme bakın.

C#

Aşağıdaki örnekte, Google Cloud Storage'da tutulan verilere erişimi basit ve kolay hale getiren .NET için Google API'leri İstemci Kitaplığı kullanılmıştır.

İlk olarak, verilerinize erişim yetkisi almak üzere API ile iletişim kurarken kullanılacak kimlik bilgilerini ayarlamanız gerekir. Bu işlem, ServiceAccountId olarak Hizmet Hesabı'nın developer.gserviceaccount.com e-posta adresini kullanan ve Hizmet Hesabı oluşturulurken Google API Konsolu'ndan indirilen özel anahtar dosyasını yükleyen bir AssertionFlowClient nesnesi oluşturarak yapılır.

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 nesnesini oluşturduktan sonra, bu yeni OAuth2Authenticator nesnesini örneklendirmek için kullanabilirsiniz. Bu nesneyi Google Cloud Storage API'ye gelecekteki tüm isteklerde yeni bir Storage örneği oluşturmak için kullanabilirsiniz:

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

Artık yeni bir Storage nesneniz olduğuna göre API'ye istekte bulunmaya hazırsınız. Burada, bucket paketinden belirli bir öğeyi (bucketObjectName) almak için istekte bulunuyorsunuz. Google Cloud Storage'dan yapılan HTTP indirme işlemini işlemek için standart .NET istemci kitaplığı sınıflarını kullanırız ancak istekte her zaman doğru Authorization üst bilgisinin bulunduğundan emin olmak için yönlendirmenin olduğu durumu manuel olarak ele almanız gerekir:

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();
}

Yanıtın içeriği daha sonra her zamanki gibi GetResponseStream aracılığıyla HttpWebResponse nesnesinden okunabilir. bucket ve bucketObjectName değerleriniz, API'nin hangi bölümüne eriştiğinize bağlı olarak değişiklik gösterir. Adlandırma kurallarıyla ilgili bölüme bakın.

Ek: Tam Örnekler

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;
        }

    }
}