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: "))
def get_token(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'C:\\client_secret.json', scopes=[oauth2.GetAPIScope('adwords')]) flow.redirect_uri = 'https://achedescontos.online/oauth2callback' authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') print(authorization_url, state) context = {'authorization_url': authorization_url} return render(request, 'index.html', context)
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 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
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']))
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']
def get_adwords_client(self, request): client_id = settings.ADWORDS_CLIENT_ID client_secret = settings.ADWORDS_SECRET_KEY redirect_uri = request.build_absolute_uri( reverse('accounts_oauth_callback')) return client.OAuth2WebServerFlow( client_id=client_id, client_secret=client_secret, scope=oauth2.GetAPIScope('adwords'), user_agent='Test', prompt='consent', redirect_uri=redirect_uri, )
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']))
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']
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)
from flask import Flask import locale import cPickle as pickle import json # get this object from flask import Response, send_from_directory locale.setlocale(locale.LC_ALL, 'en_US') client_id = "563744622690-ae6klrpf57gmugf4b8kdh4thsudd0hco.apps.googleusercontent.com" client_secret = "oKMnHv0aGzec42-OL6MIASmB" flow = client.OAuth2WebServerFlow(client_id=client_id, client_secret=client_secret, scope=oauth2.GetAPIScope('adwords'), user_agent='Test', redirect_uri="http://localhost:8082") auth_uri = flow.step1_get_authorize_url() # print auth_uri auth_code = "4/OnrImjz9Yd3oq8kE-qgzcOKQ-5YABAtOsx_2e10WH8Y#" # credentials = flow.step2_exchange(auth_code) # # pprint(vars(credentials)) access_token = "ya29.GlsmBCJdOWhwEULh0O_IeTMPAhCkCgL1cbkrol-acHVqiyeOSbDYWSIeQM0hxtMWPOduBhO5XbW7RtSm0aKfnHtMHinkuFJpeZE0_mhcPZjNdrvdxsM9RtDdgItN" refresh_token = "1/I1aqrBRCI9u8lKLUm0Aj3dNjY8gTsamf2Qtf0ezkpKI"
_JINJA_ENVIRONMENT = jinja2.Environment( autoescape=True, extensions=['jinja2.ext.autoescape'], loader=jinja2.FileSystemLoader(_TEMPLATES_PATH)) _CLIENT_ID, _CLIENT_SECRET = RetrieveAppCredential() # set timeout to 10 s socket.setdefaulttimeout(10) # initialize flow object _HOSTNAME = app_identity.get_default_version_hostname() _FLOW = client.OAuth2WebServerFlow( client_id=_CLIENT_ID, client_secret=_CLIENT_SECRET, scope=oauth2.GetAPIScope('ad_manager'), user_agent='DFP Playground', redirect_uri=( ('https://' + _HOSTNAME) if _HOSTNAME else 'http://localhost:8008') + '/oauth2callback', access_type='offline', approval_prompt='force') class MainPage(webapp2.RequestHandler): """View that displays the DFP Playground's homepage.""" @oauth2required def get(self): """Handle get request.""" user = users.get_current_user() user_email = user.email()
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)
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)
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))
##os.chdir('/home/sabeiro/lav/media') key_file = os.environ['LAV_DIR'] + '/credenza/dfp-intertino-861da83250a9.json' key_file2 = os.environ['LAV_DIR'] + '/credenza/dfp-intertino.json' cred = [] with open(key_file) as f: cred = json.load(f) cred2 = [] with open(key_file2) as f: cred2 = json.load(f) DEFAULT_CLIENT_ID = cred2['client_id'] DEFAULT_CLIENT_SECRET = cred2['client_secret'] ##cred2['refresh_token'] flow = client.OAuth2WebServerFlow(client_id=cred2['client_id'],client_secret=cred2['client_secret'],scope=oauth2.GetAPIScope('adwords'),user_agent='Test',redirect_uri=cred2['redirect_uri']) auth_uri = flow.step1_get_authorize_url() # from oauth2client.client import flow_from_clientsecrets # flow = flow_from_clientsecrets('credenza/dfp-intertino.json',scope='https://www.googleapis.com/auth/calendar',redirect_uri='http://analisi.ad.mediamond.it') # The DFP API OAuth2 scope. SCOPE = u'https://www.googleapis.com/auth/dfp' parser = argparse.ArgumentParser(description='Generates a refresh token with ' 'the provided credentials.') parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID, help='Client Id retrieved from the Developer\'s Console.') parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET, help='Client Secret retrieved from the Developer\'s '
_JINJA_ENVIRONMENT = jinja2.Environment( autoescape=True, extensions=['jinja2.ext.autoescape'], loader=jinja2.FileSystemLoader(_TEMPLATES_PATH)) _CLIENT_ID, _CLIENT_SECRET = RetrieveAppCredential() # set timeout to 10 s socket.setdefaulttimeout(10) # initialize flow object _HOSTNAME = app_identity.get_default_version_hostname() _FLOW = client.OAuth2WebServerFlow( client_id=_CLIENT_ID, client_secret=_CLIENT_SECRET, scope=oauth2.GetAPIScope('dfp'), user_agent='DFP Playground', redirect_uri=( ('https://' + _HOSTNAME) if _HOSTNAME else 'http://localhost:8008') + '/oauth2callback', access_type='offline', approval_prompt='force') class MainPage(webapp2.RequestHandler): """View that displays the DFP Playground's homepage.""" @oauth2required def get(self): """Handle get request.""" user = users.get_current_user() user_email = user.email()