Beispiel #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 main(service_account_email, key_file, application_name):
  oauth2_client = oauth2.GoogleServiceAccountClient(
      oauth2.GetAPIScope('dfp'), service_account_email, key_file)

  dfp_client = dfp.DfpClient(oauth2_client, application_name)

  networks = dfp_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 _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 __init__(self, service_account_email, key_file, application_name):
        oauth2_client = oauth2.GoogleServiceAccountClient(
            oauth2.GetAPIScope('dfp'), service_account_email, key_file)

        self.dfp_client = dfp.DfpClient(oauth2_client, application_name,
                                        NETWORK)
        self.custom_targeting_service = self.dfp_client.GetService(
            'CustomTargetingService', version='v201505')

        self.search_for_order(raw_input("Search for the order: "))
Beispiel #5
0
def load_client():
    global _client

    if not _client:
        oauth2_client = oauth2.GoogleServiceAccountClient(
            oauth2.GetAPIScope("dfp"),
            g.dfp_service_account_email,
            KEY_FILE,
        )

        _client = dfp.DfpClient(oauth2_client, g.dfp_project_id)
        _client.network_code = g.dfp_test_network_code if g.debug else g.dfp_network_code
Beispiel #6
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(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']))
Beispiel #8
0
def main(service_account_email, key_file, service_account_user,
         developer_token, user_agent, client_customer_id):
    oauth2_client = oauth2.GoogleServiceAccountClient(
        oauth2.GetAPIScope('adwords'),
        service_account_email,
        key_file,
        sub=service_account_user)

    adwords_client = adwords.AdWordsClient(developer_token, oauth2_client,
                                           user_agent, client_customer_id)

    customer = adwords_client.GetService('CustomerService').get()
    print 'You are logged in as customer: %s' % customer['customerId']
Beispiel #9
0
def main(service_account_email, key_file, service_account_user,
         user_profile_name, application_name):
    oauth2_client = oauth2.GoogleServiceAccountClient(
        oauth2.GetAPIScope('dfa'),
        service_account_email,
        key_file,
        sub=service_account_user)

    dfa_client = dfa.DfaClient(user_profile_name, oauth2_client,
                               application_name)

    campaign_service = dfa_client.GetService(
        'campaign', server='https://advertisersapitest.doubleclick.net')
    results = campaign_service.getCampaignsByCriteria({})
    if results['records']:
        for campaign in results['records']:
            print('Campaign with name \'%s\' and ID \'%s\' was found.' %
                  (campaign['name'], campaign['id']))
Beispiel #10
0
def main(service_account_email, key_file, service_account_user,
         developer_token, user_agent, client_customer_id):
  oauth2_client = oauth2.GoogleServiceAccountClient(
      oauth2.GetAPIScope('adwords'), service_account_email, key_file,
      sub=service_account_user)

  adwords_client = adwords.AdWordsClient(
      developer_token, oauth2_client, user_agent,
      client_customer_id=client_customer_id)

  customer_service = adwords_client.GetService('CustomerService',
                                               version='v201702')
  customers = customer_service.getCustomers()

  print 'You are logged in as a user with access to the following customers:'

  for customer in customers:
    print '\t%s' % customer['customerId']
Beispiel #11
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)
Beispiel #12
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))
Beispiel #13
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)
Beispiel #14
0
path = 'C:/Users/christopher.brossman/Documents/Projects/work/newDFP/python/'
keyName = 'DFP service Account-ec3f20e59362.p12'
key_file_path = path + keyName
passwd = 'notasecret'
serviceAccountId = '*****@*****.**'

application_name = 'brossmanPython'


from googleads import dfp
from googleads import oauth2


# Initialize the GoogleRefreshTokenClient using the credentials you received
# in the earlier steps.
oauth2_client = oauth2.GoogleServiceAccountClient(oauth2.GetAPIScope('dfp'), serviceAccountId, key_file_path)

# Initialize the DFP client.
dfp_client = dfp.DfpClient(
   oauth2_client, application_name)