नमस्ते Analytics API: इंस्टॉल किए गए ऐप्लिकेशन के लिए Python क्विकस्टार्ट

इस ट्यूटोरियल में, Google Analytics खाता ऐक्सेस करने, Analytics एपीआई से क्वेरी करने, एपीआई के रिस्पॉन्स को मैनेज करने, और नतीजे देने के लिए ज़रूरी चरणों के बारे में बताया गया है. इस ट्यूटोरियल में, Core Reporting API v3.0, Management API v3.0, और OAuth2.0 का इस्तेमाल किया गया है.

पहला चरण: Analytics API चालू करना

Google Analytics API का इस्तेमाल शुरू करने से पहले, सेटअप टूल का इस्तेमाल करें. यह आपको Google API कंसोल में प्रोजेक्ट बनाने, एपीआई चालू करने, और क्रेडेंशियल बनाने के बारे में जानकारी देता है.

क्लाइंट आईडी बनाना

क्रेडेंशियल पेज से:

  1. क्रेडेंशियल बनाएं पर क्लिक करें और OAuth क्लाइंट आईडी चुनें.
  2. APPLICATION TYPE के लिए, अन्य चुनें.
  3. क्रेडेंशियल को नाम दें.
  4. बनाएं पर क्लिक करें.

अभी-अभी बनाया गया क्रेडेंशियल चुनें और JSON डाउनलोड करें पर क्लिक करें. डाउनलोड की गई फ़ाइल को client_secrets.json के तौर पर सेव करें. आपको बाद में, ट्यूटोरियल में इसकी ज़रूरत पड़ेगी.

दूसरा चरण: Google क्लाइंट लाइब्रेरी इंस्टॉल करना

पैकेज मैनेजर का इस्तेमाल किया जा सकता है या Python क्लाइंट लाइब्रेरी को मैन्युअल तरीके से डाउनलोड और इंस्टॉल किया जा सकता है:

pip

Python पैकेज इंस्टॉल करने के लिए, सुझाया गया टूल pip इस्तेमाल करें:

sudo pip install --upgrade google-api-python-client

सेटअपटूल

setuptools पैकेज में शामिल easy_install टूल का इस्तेमाल करें:

sudo easy_install --upgrade google-api-python-client

मैन्युअल तरीके से इंस्टॉल करना

Python के लिए क्लाइंट लाइब्रेरी का सबसे नया वर्शन डाउनलोड करें. इसके बाद, कोड को अनपैक करें और यह चलाएं:

sudo python setup.py install

सिस्टम Python पर इंस्टॉल करने के लिए, आपको सुपर उपयोगकर्ता (sudo) के खास अधिकारों वाले निर्देश को शुरू करना पड़ सकता है.

तीसरा चरण: सैंपल सेटअप करना

आपको HelloAnalytics.py नाम की एक फ़ाइल बनानी होगी, जिसमें दिया गया सैंपल कोड शामिल होगा.

  1. इस सोर्स कोड को HelloAnalytics.py में कॉपी करें या डाउनलोड करें.
  2. पहले डाउनलोड किए गए client_secrets.json को उसी डायरेक्ट्री में ले जाएं जिसमें सैंपल कोड है.
"""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()

चौथा चरण: सैंपल चलाना

Analytics एपीआई चालू करने के बाद, Python के लिए Google API क्लाइंट लाइब्रेरी इंस्टॉल करें. और सैंपल सोर्स कोड सेट अप करें, ताकि सैंपल चलाने के लिए तैयार हो.

इसका इस्तेमाल करके सैंपल चलाएं:

python HelloAnalytics.py
  1. यह ऐप्लिकेशन, ब्राउज़र में अनुमति देने वाले पेज को लोड कर देगा.
  2. अगर आप पहले से अपने Google खाते में लॉग इन नहीं हैं, तो आपको लॉग इन करने के लिए कहा जाएगा. अगर आपने एक से ज़्यादा Google खातों में लॉग इन किया हुआ है, तो आपसे अनुमति के लिए एक खाता चुनने के लिए कहा जाएगा.

इन चरणों को पूरा करने के बाद, सैंपल में, अनुमति वाले उपयोगकर्ता के पहले Google Analytics व्यू (प्रोफ़ाइल) का नाम और पिछले सात दिनों के सेशन की संख्या दिखती है.

अनुमति वाले Analytics सेवा ऑब्जेक्ट की मदद से, अब Management API के रेफ़रंस दस्तावेज़ में मिले किसी भी कोड सैंपल को चलाया जा सकता है. उदाहरण के लिए, आपके पास accountSummaries.list तरीके का इस्तेमाल करने के लिए, कोड को बदलने का विकल्प है.

समस्या हल करना

विशेषता गड़बड़ी: 'मॉड्यूल_six_moves_urllib_parse' ऑब्जेक्ट में कोई विशेषता नहीं 'urlparse' है

यह गड़बड़ी Mac Nexus में हो सकती है, जहां "छह" मॉड्यूल (इस लाइब्रेरी पर निर्भरता) का डिफ़ॉल्ट इंस्टॉलेशन, पीआईपी (पिक्चर में पिक्चर) इंस्टॉल किए जाने से पहले लोड होता है. इस समस्या को ठीक करने के लिए, PYTHONPATH सिस्टम के एनवायरमेंट वैरिएबल में पीआईपी की इंस्टॉल करने की जगह की जानकारी जोड़ें:

  1. नीचे दिए गए निर्देश की मदद से, पीआईपी (पिक्चर में पिक्चर) की इंस्टॉल करने की जगह का पता लगाएं:

    pip show six | grep "Location:" | cut -d " " -f2
    

  2. <pip_install_path> को ऊपर तय की गई वैल्यू से बदलें और अपनी ~/.bashrc फ़ाइल में नीचे दी गई लाइन जोड़ें:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. इस निर्देश का इस्तेमाल करके, अपनी ~/.bashrc फ़ाइल को किसी भी खुली टर्मिनल विंडो में फिर से लोड करें:

    source ~/.bashrc