Esempio n. 1
0
    def connect(self, key_dict, network_code):
        """Takes a dictionary containing GAM login information,
            along with a Network code and returns a GAM connection object

        Arguments:
            key_dict {dict} -- Login dict.
                            private_key,
                            client_email,
                            and token_uri are required
            network_code {str} -- GAM network to connect to

        Returns:
            AdmanagerClient -- GAM connection client
        """

        key_file = self._create_tmp_file(json.dumps(key_dict).encode('utf-8'),
                                         return_path=True)
        try:
            oauth2_client = oauth2.GoogleServiceAccountClient(
                key_file, scope=oauth2.GetAPIScope('ad_manager'))
            return ad_manager.AdManagerClient(oauth2_client,
                                              self.name,
                                              network_code=network_code)
        except (
                AccessTokenRefreshError,
                binascii.Error,
        ) as exc:
            print(f"Connection error, {exc}")
            return False
    def _oauth2_client(self, credentials_file, network_code, application_name):
        """
        Create a client given a Google API Keyfile.
        """

        #NOTE: created this function to move things out of the constructor, but
        #NOTE: (cont) we may want to move all of the client functions here.
        oauth2_client = oauth2.GoogleServiceAccountClient(credentials_file, oauth2.GetAPIScope('ad_manager'))
        ad_client = ad_manager.AdManagerClient(oauth2_client, application_name, network_code)
        return ad_client
def main(access_token, token_expiry, application_name):
    oauth2_client = oauth2.GoogleAccessTokenClient(access_token, token_expiry)

    ad_manager_client = ad_manager.AdManagerClient(oauth2_client,
                                                   application_name)

    networks = ad_manager_client.GetService('NetworkService').getAllNetworks()
    for network in networks:
        print(
            'Network with network code "%s" and display name "%s" was found.' %
            (network['networkCode'], network['displayName']))
Esempio n. 4
0
def main(key_file, application_name):
    oauth2_client = oauth2.GoogleServiceAccountClient(
        key_file, oauth2.GetAPIScope('ad_manager'))

    client = ad_manager.AdManagerClient(oauth2_client, application_name,
                                        NETWORK_CODE)

    #networks = ad_manager_client.GetService('NetworkService').getAllNetworks()
    #for network in networks:
    #  print('Network with network code "%s" and display name "%s" was found.'
    #        % (network['networkCode'], network['displayName']))

    # Initialize a DataDownloader.
    report_downloader = client.GetDataDownloader(version='v201911')

    # Create report job.
    report_job = {
        'reportQuery': {
            'dimensions': ['DATE', 'AD_UNIT_NAME'],
            'adUnitView':
            'HIERARCHICAL',
            'columns': [
                'AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
                'ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS',
                'ADSENSE_LINE_ITEM_LEVEL_CLICKS',
                'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS',
                'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'
            ],
            'dateRangeType':
            'LAST_WEEK'
        }
    }

    try:
        # Run the report and wait for it to finish.
        report_job_id = report_downloader.WaitForReport(report_job)
    except errors.AdManagerReportError as e:
        print('Failed to generate report. Error was: %s' % e)

# Change to your preferred export format.
    export_format = 'CSV_DUMP'

    report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)

    # Download report data.
    report_downloader.DownloadReportToFile(report_job_id, export_format,
                                           report_file)

    report_file.close()

    # Display results.
    print('Report job with id "%s" downloaded to:\n%s' %
          (report_job_id, report_file.name))
def main(client_id, client_secret, refresh_token, application_name):
    oauth2_client = oauth2.GoogleRefreshTokenClient(client_id, client_secret,
                                                    refresh_token)

    ad_manager_client = ad_manager.AdManagerClient(oauth2_client,
                                                   application_name)

    networks = ad_manager_client.GetService('NetworkService').getAllNetworks()
    for network in networks:
        print(
            'Network with network code "%s" and display name "%s" was found.' %
            (network['networkCode'], network['displayName']))
def main(key_file, application_name):
    oauth2_client = oauth2.GoogleServiceAccountClient(
        key_file, oauth2.GetAPIScope('ad_manager'))

    ad_manager_client = ad_manager.AdManagerClient(oauth2_client,
                                                   application_name)

    networks = ad_manager_client.GetService('NetworkService').getAllNetworks()
    for network in networks:
        print(
            'Network with network code "%s" and display name "%s" was found.' %
            (network['networkCode'], network['displayName']))
Esempio n. 7
0
def list_network_codes(oauth2_client):
    """List network codes and print them so that the user can select.

    Arguments:
        oauth2_client {oauth2.client} -- Logged client
    """
    ad_manager_client = ad_manager.AdManagerClient(
        oauth2_client, APPLICATION_NAME, cache=ZeepServiceProxy.NO_CACHE)

    network_service = ad_manager_client.GetService("NetworkService",
                                                   version=API_VERSION)
    networks = network_service.getAllNetworks()
    print("=" * 15)
    print("Listing available networks:")
    for network in networks:
        print("Network code: {} (network name: {})".format(
            network["networkCode"], network["displayName"]))
    print("=" * 15)
    print("Copy selected network's code to extractor's configuration.")
Esempio n. 8
0
    def __init__(self, dfp_version='v202002', code=None):
        # login
        content_file = tempfile.NamedTemporaryFile(suffix='.json',
                                                   delete=False,
                                                   mode='w')
        json.dump(settings.DFP, content_file)
        content_file.flush()

        oauth2_client = GoogleServiceAccountClient(
            content_file.name, oauth2.GetAPIScope('ad_manager'))
        code = code or '108073772'
        self.dfp_client = dfp.AdManagerClient(oauth2_client,
                                              settings.DFP['name'], code)
        v = dfp_version
        self.inventory_service = self.dfp_client.GetService('InventoryService',
                                                            version=v)
        self.li_service = self.dfp_client.GetService('LineItemService',
                                                     version=v)
        self.placement_service = self.dfp_client.GetService('PlacementService',
                                                            version=v)
        self.creative_service = self.dfp_client.GetService('CreativeService',
                                                           version=v)
        self.order_service = self.dfp_client.GetService('OrderService',
                                                        version=v)
Esempio n. 9
0
from googleads import ad_manager
from googleads import oauth2

# Initialize the GoogleRefreshTokenClient using the credentials you received
# in the earlier steps.
oauth2_client = oauth2.GoogleServiceAccountClient(
    'client_secret_773664483695-tp6q1ditrsl96fm0a1f6ir8sg75ftod6.apps.googleusercontent.com.json',
    oauth2.GetAPIScope('ad_manager'))

# Initialize the Ad Manager client.
ad_manager_client = ad_manager.AdManagerClient(oauth2_client, application_name)
Esempio n. 10
0
def report(key_file, application_name,startDate,endDate):
  oauth2_client = oauth2.GoogleServiceAccountClient(
      key_file, oauth2.GetAPIScope('ad_manager'))

  client = ad_manager.AdManagerClient(
      oauth2_client, application_name, NETWORK_CODE)

  #networks = ad_manager_client.GetService('NetworkService').getAllNetworks()
  #for network in networks:
  #  print('Network with network code "%s" and display name "%s" was found.'
  #        % (network['networkCode'], network['displayName']))

  # Initialize a DataDownloader.
  report_downloader = client.GetDataDownloader(version='v201911')
  # Set the start and end dates of the report to run (past 0 days, you can change to what u need).
  end_date = datetime.strptime( startDate, "%Y-%m-%d").date()
  
  start_date = datetime.strptime( endDate, "%Y-%m-%d").date()
  
  print ('start_date: ', start_date)
  print ('end_date: ', end_date)
  
  report_filename_prefix='report_example_using_service_account_with_date_range'
  
 # Create report job.
  report_job = {
      'reportQuery': {
          'dimensions': ['DATE', 'AD_UNIT_NAME'],
          'adUnitView': 'HIERARCHICAL',
          'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
                      'ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS',
                      'ADSENSE_LINE_ITEM_LEVEL_CLICKS',
                      'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS',
                      'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'],
          'dateRangeType': 'CUSTOM_DATE',
          'startDate': start_date,
          'endDate': end_date
      }
  }


  try:
    # Run the report and wait for it to finish.
    report_job_id = report_downloader.WaitForReport(report_job)
  except errors.AdManagerReportError as e:
    print('Failed to generate report. Error was: %s' % e)
 
 # Change to your preferred export format.
  export_format = 'CSV_DUMP'

  report_file = tempfile.NamedTemporaryFile(suffix='_'+report_filename_prefix+'_'+startDate+'__'+endDate+'.csv.gz', delete=False)

  # Download report data.
  report_downloader.DownloadReportToFile(
      report_job_id, export_format, report_file)

  report_file.close()
  
    # Display results.
  print('Report job with id "%s" downloaded to:\n%s' % (
      report_job_id, report_file.name))
Esempio n. 11
0
def main():
    """Main function encapsulating everything this extractor does
    """

    config_path = sys.argv[1] if len(sys.argv) == 2 else "/data/config.json"

    if not os.path.exists(config_path):
        raise Exception(
            "Configuration not specified, was expected at '{}'".format(
                config_path))

    with open(config_path, encoding="utf-8") as conf_file:
        conf = json.load(conf_file)["parameters"]

    basicConfig(format="[{asctime}] [{levelname}]: {message}",
                style="{",
                level=DEBUG if conf["debug"] else INFO)

    logger = getLogger(__name__)

    logger.debug("Running in DEBUG mode")

    logger.debug("Dumping service account")
    # Store credentials in a file
    with open("./service.json", "w", encoding="utf-8") as service_file:
        json.dump(json.loads(conf["#service_account"]), service_file)

    # OAuth2 credential info
    key_file = "./service.json"

    logger.info("Proceeding with OAuth2 authentication")
    oauth2_client = oauth2.GoogleServiceAccountClient(
        key_file, oauth2.GetAPIScope('ad_manager'))

    if conf["list_network_codes"]:
        logger.warning(
            "Running in 'List Network Codes' mode, nothing will be downloaded."
        )
        list_network_codes(oauth2_client)
        sys.exit(0)

    ad_manager_client = ad_manager.AdManagerClient(
        oauth2_client,
        APPLICATION_NAME,
        network_code=conf["network_code"],
        cache=ZeepServiceProxy.NO_CACHE)

    downloader = ad_manager_client.GetDataDownloader(version=API_VERSION)

    # test report job
    report_job = {"reportQuery": conf["report_job"]}

    if report_job["reportQuery"]["dateRangeType"] != "CUSTOM_DATE":
        if "startDate" in report_job["reportQuery"]:
            del report_job["reportQuery"]["startDate"]
        if "endDate" in report_job["reportQuery"]:
            del report_job["reportQuery"]["endDate"]
    else:
        datetime_from = datetime.strptime(
            report_job["reportQuery"]["startDate"], "%Y-%m-%d")
        datetime_to = datetime.strptime(report_job["reportQuery"]["endDate"],
                                        "%Y-%m-%d")
        report_job["reportQuery"]["startDate"] = {
            "year": datetime_from.year,
            "month": datetime_from.month,
            "day": datetime_from.day
        }
        report_job["reportQuery"]["endDate"] = {
            "year": datetime_to.year,
            "month": datetime_to.month,
            "day": datetime_to.day
        }

    logger.info("Waiting for job completion")
    job = downloader.WaitForReport(report_job)

    output_path = OUTPUT_DIRECTORY
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    logger.info("Job completed, downloading")

    output_filename = slugify(conf["report_name"])
    output_file = os.path.join(output_path, "{}.csv".format(output_filename))

    # download
    with open(output_file, "wb") as fid:
        downloader.DownloadReportToFile(job,
                                        "CSV",
                                        fid,
                                        use_gzip_compression=False,
                                        include_totals_row=False)

    # add date range type, add corresponding dates for "CUSTOM_DATE" date range
    tmp_file = os.path.join(output_path,
                            "{0}{1}.csv".format(output_filename, "_tmp"))

    with open(output_file,
              "r", encoding="utf-8") as fid, open(tmp_file,
                                                  "w",
                                                  encoding="utf-8") as tmpf:
        report_reader = csv.reader(fid)
        report_writer = csv.writer(tmpf, dialect=csv.unix_dialect)
        for i, row in enumerate(report_reader):
            if i == 0:
                row.append("DATE_RANGE_TYPE")
                row.append("CUSTOM_DATE.from")
                row.append("CUSTOM_DATE.to")
            else:
                row.append(report_job["reportQuery"]["dateRangeType"])
                if report_job["reportQuery"]["dateRangeType"] == "CUSTOM_DATE":
                    row.append(datetime_from)
                    row.append(datetime_to)
                else:
                    row.append(None)
                    row.append(None)
            report_writer.writerow(row)

    os.replace(tmp_file, output_file)