Bu eğitim, bir Google Analytics hesabına erişmek, Analytics API'lerini sorgulamak, API yanıtlarını işlemek ve sonuçları çıkarmak için gereken adımlarda size yol gösterir. Bu eğiticide Core Reporting API v3.0, Management API v3.0 ve OAuth2.0 kullanılmıştır.
1. Adım: Analytics API'yi etkinleştirin
Google Analytics API'yi kullanmaya başlamak için önce kurulum aracını kullanmanız gerekir. Bu araç, Google API Konsolu'nda proje oluşturma, API'yi etkinleştirme ve kimlik bilgileri oluşturma konusunda size rehberlik eder.
İstemci kimliği oluşturun
Kimlik bilgileri sayfasından:
- Kimlik Bilgileri Oluştur'u tıklayın ve OAuth istemci kimliği'ni seçin.
- UYGULAMA TÜRÜ için Diğer'i seçin.
- Kimlik bilgisini adlandırın.
- Create'i (Oluştur) tıklayın.
Oluşturduğunuz kimlik bilgisini seçin ve JSON'u indir'i tıklayın. İndirilen dosyayı client_secrets.json
olarak kaydedin. Eğiticide daha sonra bu dosyaya ihtiyacınız olacaktır.
2. Adım: Google İstemci Kitaplığı'nı yükleyin
Paket yöneticisi kullanabilir ya da Python istemci kitaplığını manuel olarak indirip yükleyebilirsiniz:
pip
Python paketlerini yüklemek için önerilen araç olan pip'i kullanın:
sudo pip install --upgrade google-api-python-client
Kurulum Araçları
setuptools paketinde bulunan easy_install aracını kullanın:
sudo easy_install --upgrade google-api-python-client
Manuel yükleme
python için istemci kitaplığının en son sürümünü indirin, kodu paketten çıkarın ve aşağıdaki komutu çalıştırın:
sudo python setup.py install
Python'u sisteme yüklemek için komutu süper kullanıcı (sudo
) ayrıcalıklarıyla çağırmanız gerekebilir.
3. Adım: Örneği oluşturun
Belirtilen örnek kodu içeren HelloAnalytics.py
adında tek bir dosya oluşturmanız gerekir.
- Aşağıdaki kaynak kodunu
HelloAnalytics.py
koduna kopyalayın veya indirin. - Daha önce indirilen
client_secrets.json
öğesini örnek kodla aynı dizine taşıyın.
"""A simple example of how to access the Google Analytics API.""" import argparse from apiclient.discovery import build import httplib2 from oauth2client import client from oauth2client import file from oauth2client import tools def get_service(api_name, api_version, scope, client_secrets_path): """Get a service that communicates to a Google API. Args: api_name: string The name of the api to connect to. api_version: string The api version to connect to. scope: A list of strings representing the auth scopes to authorize for the connection. client_secrets_path: string A path to a valid client secrets file. Returns: A service that is connected to the specified API. """ # Parse command-line arguments. parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) # Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets( client_secrets_path, scope=scope, message=tools.message_if_missing(client_secrets_path)) # Prepare credentials, and authorize HTTP object with them. # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to a file. storage = file.Storage(api_name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http=httplib2.Http()) # Build the service object. service = build(api_name, api_version, http=http) return service def get_first_profile_id(service): # Use the Analytics service object to get the first profile id. # Get a list of all Google Analytics accounts for the authorized user. accounts = service.management().accounts().list().execute() if accounts.get('items'): # Get the first Google Analytics account. account = accounts.get('items')[0].get('id') # Get a list of all the properties for the first account. properties = service.management().webproperties().list( accountId=account).execute() if properties.get('items'): # Get the first property id. property = properties.get('items')[0].get('id') # Get a list of all views (profiles) for the first property. profiles = service.management().profiles().list( accountId=account, webPropertyId=property).execute() if profiles.get('items'): # return the first view (profile) id. return profiles.get('items')[0].get('id') return None def get_results(service, profile_id): # Use the Analytics Service Object to query the Core Reporting API # for the number of sessions in the past seven days. return service.data().ga().get( ids='ga:' + profile_id, start_date='7daysAgo', end_date='today', metrics='ga:sessions').execute() def print_results(results): # Print data nicely for the user. if results: print 'View (Profile): %s' % results.get('profileInfo').get('profileName') print 'Total Sessions: %s' % results.get('rows')[0][0] else: print 'No results found' def main(): # Define the auth scopes to request. scope = ['https://www.googleapis.com/auth/analytics.readonly'] # Authenticate and construct service. service = get_service('analytics', 'v3', scope, 'client_secrets.json') profile = get_first_profile_id(service) print_results(get_results(service, profile)) if __name__ == '__main__': main()
4. Adım: Örneği çalıştırın
Analytics API'yi etkinleştirdikten sonra Python için Google API'leri istemci kitaplığını yükleyin ve örneğin çalışmaya hazır olduğu örnek kaynak kodunu ayarlayın.
Şunu kullanarak örneği çalıştırın:
python HelloAnalytics.py
- Uygulama, yetkilendirme sayfasını bir tarayıcıda yükler.
- Google hesabınıza giriş yapmadıysanız giriş yapmanız istenir. Birden fazla Google hesabına giriş yaptıysanız yetkilendirme için kullanılacak bir hesap seçmeniz istenir.
Bu adımları tamamladığınızda örnek, yetkili kullanıcının ilk Google Analytics görünümünün (profilinin) adını ve son yedi gündeki oturum sayısını verir.
Yetkili Analytics hizmet nesnesiyle artık Management API referans belgelerinde bulunan tüm kod örneklerini çalıştırabilirsiniz. Örneğin, kodu accountSummaries.list yöntemini kullanacak şekilde değiştirmeyi deneyebilirsiniz.
Sorun giderme
AttributeError: "Module_six_moves_urllib_parse" nesnesi "urlparse" özelliğine sahip değil
Bu hata, "altı" modülün (bu kitaplığın bağımlılığı) varsayılan yüklemesinin, pip'in yüklenen modülünden önce yüklendiği Mac OSX'te meydana gelebilir. Sorunu düzeltmek için pip'in yükleme konumunu PYTHONPATH
sistem ortamı değişkenine ekleyin:
-
Aşağıdaki komutla pip'in yükleme konumunu belirleyin:
pip show six | grep "Location:" | cut -d " " -f2
-
<pip_install_path>
kısmını yukarıda belirtilen değerle değiştirerek aşağıdaki satırı~/.bashrc
dosyanıza ekleyin:export PYTHONPATH=$PYTHONPATH:<pip_install_path>
-
Aşağıdaki komutu kullanarak açık terminal pencerelerinde
~/.bashrc
dosyanızı yeniden yükleyin:source ~/.bashrc