def handle(self, *args, **options): if len(args) != 1: raise CommandError("Usage: <product.id>") product_id = args product = Product.objects.get(pk=product_id) campaign_name = 'PLA - %s' % product.category_tree client = AdWordsClient(path=os.path.join('..', '..', '..', '..', '..')) campaign_service = client.GetCampaignService(version='v201306') selector = { 'fields': ['Id', 'Name', 'Status'], 'paging': { 'startIndex': str(0), 'numberResults': str(10) }, 'predicates': [{ 'field': 'Name', 'operator': 'EQUALS', 'values': ['PLA - Animals and Pets > Houses and Kennels > Houses'] }] }
def setUp(self): """Prepare unittest.""" client = AdWordsClient(headers={ 'authToken': ' ', 'userAgent': ' ', 'developerToken': ' ' }) self.service = client.GetReportDownloader()
def setUp(self): """Prepare unittest.""" client = AdWordsClient(headers={ 'oauth2credentials': 'cr3d3n7i415', 'userAgent': 'USER AGENT', 'developerToken': 'DEV TOKEN' }, path='/tmp/') self.service = client.GetReportDownloader()
def setUp(self): """Prepare unittest.""" with mock.patch( 'adspygoogle.adwords.util.XsdToWsdl.CreateWsdlFromXsdUrl'): credentials = OAuth2Credentials('ACCESS_TOKEN', 'client_id', 'client_secret', 'refresh_token', None, 'uri', 'user_agent') self.oauth2_headers = { 'oauth2credentials': credentials, 'userAgent': 'USER AGENT', 'developerToken': 'DEV TOKEN', 'clientCustomerId': 'client customer id' } client = AdWordsClient(self.oauth2_headers, path='/tmp/') self.service = client.GetReportDownloader()
def _RunTestWithBuffer(self, buffer_): """Tests error parsing using the given AdWordsSoapBuffer.""" client = AdWordsClient(headers={ 'userAgent': 'USER_AGENT', 'developerToken': 'DEVELOPER_TOKEN', 'clientCustomerId': 'CLIENT_CUSTOMER_ID', 'oauth2credentials': OAuth2Credentials('ACCESS_TOKEN', 'client_id', 'client_secret', 'refresh_token', None, 'uri', 'user_agent') }, path='/tmp/') with mock.patch('adspygoogle.SOAPpy.WSDL.Proxy'): service = client.GetCampaignService() buffer_.write(open(BUFFER_FILE_LOCATION).read()) try: service._HandleLogsAndErrors(buffer_, '', '', {'data': 'datum'}) except AdWordsRequestError, e: self.assertEqual(-1, e.code) self.assertEqual(1, len(e.errors)) error_detail = e.errors[0] self.assertEqual( 'Please correct the capitalization in the following ' 'phrase(s): \'AAAAAAAAAAAAAAAAAAAAA\'', error_detail.externalPolicyDescription) self.assertEqual('[Capitalization] Excessive capitalization', error_detail.externalPolicyName) self.assertEqual(None, error_detail.externalPolicyUrl) self.assertEqual('true', error_detail.isExemptable) self.assertEqual('operations[0].operand.ad.headline', error_detail.fieldPath) self.assertEqual('PolicyViolationError', error_detail.type) self.assertEqual(None, error_detail.trigger) self.assertEqual( { 'policyName': 'capitalization', 'violatingText': 'AAAAAAAAAAAAAAAAAAAAA' }, error_detail.key) self.assertEqual({ 'index': '0', 'length': '21' }, error_detail.violatingParts)
def setUp(self): """Prepare unittest.""" with mock.patch( 'adspygoogle.adwords.util.XsdToWsdl.CreateWsdlFromXsdUrl'): client = AdWordsClient( headers={ 'authToken': 'AUTH TOKEN', 'userAgent': 'USER AGENT', 'developerToken': 'DEV TOKEN', 'email': '*****@*****.**', 'password': '******' }) self.service = client.GetReportDownloader() credentials = OAuth2Credentials('ACCESS_TOKEN', 'client_id', 'client_secret', 'refresh_token', None, 'uri', 'user_agent') client_oauth2 = AdWordsClient( headers={ 'oauth2credentials': credentials, 'userAgent': 'USER AGENT', 'developerToken': 'DEV TOKEN' }) self.service_oauth2 = client_oauth2.GetReportDownloader()
'id': AGE_RANGE_UNDETERMINED } } ] # Create operations. operations = [] for criterion in ad_group_criteria: operations.append({'operator': 'ADD', 'operand': criterion}) response = ad_group_criterion_service.Mutate(operations)[0] if response and response['value']: criteria = response['value'] for ad_group_criterion in criteria: criterion = ad_group_criterion['criterion'] print( 'Ad group criterion with ad group ID %s, criterion ID %s and ' 'type \'%s\' was added.' % (ad_group_criterion['adGroupId'], criterion['id'], criterion['type'])) else: print 'No criteria were returned.' if __name__ == '__main__': # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..', '..')) main(client, ad_group_id)
if link['clientCustomerId'] not in parent_links: parent_links[link['clientCustomerId']] = [] parent_links[link['clientCustomerId']].append(link) # Create map from customerID to account and find root account. accounts = {} root_account = None for account in graph['entries']: accounts[account['customerId']] = account if account['customerId'] not in parent_links: root_account = account # Display account tree. if root_account: print 'Login, CustomerId, Name' DisplayAccountTree(root_account, None, accounts, child_links, 0) else: print 'Unable to determine a root account' else: print 'No serviced accounts were found' print print('Usage: %s units, %s operations' % (client.GetUnits(), client.GetOperations())) if __name__ == '__main__': # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..', '..')) client.use_mcc = True main(client)
# Create map from customerID to account and find root account. accounts = {} root_account = None for account in graph['accounts']: accounts[account['customerId']] = account if account['customerId'] not in parent_links: root_account = account # Display account tree. if not root_account and len(child_links) > 0: # Sandbox doesn't handle parent links properly, so use a fake account. root_account = {'customerId': child_links.items()[0][0], 'login': '******'} if root_account: print 'Login, CustomerId (Status)' DisplayAccountTree(root_account, None, accounts, child_links, 0) else: print 'Unable to determine a root account' else: print 'No serviced accounts were found' print print ('Usage: %s units, %s operations' % (client.GetUnits(), client.GetOperations())) if __name__ == '__main__': # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..', '..')) client.use_mcc = True main(client)
print('Log in to your AdWords account and open the following URL: \n%s\n' % authorize_url) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() credential = None try: credential = flow.step2_exchange(code) except FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e) # Create the AdWordsUser and set the OAuth2 credentials. client = AdWordsClient( headers={ 'developerToken': '%s++USD' % email, 'clientCustomerId': client_customer_id, 'userAgent': 'OAuth2 Example', 'oauth2credentials': credential }) # OAuth2 credentials objects can be reused credentials = client.oauth2credentials print 'OAuth2 authorization successful!' # OAuth2 credential objects can be refreshed via credentials.refresh() - the # access token expires after 1 hour. credentials.refresh(httplib2.Http()) # Note: you could simply set the credentials as below and skip the previous # steps once access has been granted. client.oauth2credentials = credentials
code = raw_input('Code: ').strip() try: credential = flow.step2_exchange(code) except client.FlowExchangeError, e: print 'Authentication has failed: %s' % e sys.exit(1) else: print( 'OAuth 2.0 authorization successful!\n\n' 'Your access token is:\n %s\n\nYour refresh token is:\n %s\n' % (credential.access_token, credential.refresh_token)) # Create an AdWordsClient try: AdWordsClient( headers={ 'clientCustomerId': client_customer_id, 'developerToken': developer_token, 'oauth2credentials': credential, 'userAgent': user_agent }) print 'Successfully created AdWordsClient!' except Exception, e: print 'Failed to create AdWordsClient with error:\n %s' % e if __name__ == '__main__': main(CLIENT_CUSTOMER_ID, CLIENT_ID, CLIENT_SECRET, DEVELOPER_TOKEN, SCOPE, USER_AGENT)
print ('Log in to your AdWords account and open the following URL: \n%s\n' % authorize_url) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() credential = None try: credential = flow.step2_exchange(code) except FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e) # Create the AdWordsUser and set the OAuth2 credentials. client = AdWordsClient(headers={ 'developerToken': '%s++USD' % email, 'clientCustomerId': client_customer_id, 'userAgent': 'OAuth2 Example', 'oauth2credentials': credential }) # OAuth2 credentials objects can be reused credentials = client.oauth2credentials print 'OAuth2 authorization successful!' # OAuth2 credential objects can be refreshed via credentials.refresh() - the # access token expires after 1 hour. credentials.refresh(httplib2.Http()) # Note: you could simply set the credentials as below and skip the previous # steps once access has been granted. client.oauth2credentials = credentials
def main(sandbox_email, client_customer_id): # Set the OAuth consumer key and secret. Anonymous values can be used for # testing, and real values can be obtained by registering your application: # http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html credentials = { 'oauth_consumer_key': 'anonymous', 'oauth_consumer_secret': 'anonymous' } # Create the AdWordsUser and set the OAuth credentials. client = AdWordsClient(headers={ 'developerToken': '%s++USD' % sandbox_email, 'clientCustomerId': client_customer_id, 'userAgent': 'OAuth Example', 'oauth_credentials': credentials }) # Now set the handler - you can define your own if needed. client.oauth_handler = PythonOAuth2OAuthHandler() # Request a new OAuth token. Web applications should pass in a callback URL to # redirect the user to after authorizing the token. client.RequestOAuthToken('https://adwords-sandbox.google.com', applicationname='OAuth Example') # Get the authorization URL for the OAuth token. authorizationurl = client.GetOAuthAuthorizationUrl() # In a web application you would redirect the user to the authorization URL # and after approving the token they would be redirected back to the # callback URL with the URL parameter "oauth_verifier" added. For desktop or # server applications, spawn a browser to the URL and then have the user enter # the verification code that is displayed. print ('Log in to your AdWords account and open the following URL: %s\n' % authorizationurl) print 'After approving the token enter the verification code (if specified).' verifier = raw_input('Verifier: ').strip() # Upgrade the authorized token. client.UpgradeOAuthToken(verifier) # An upgraded token does not expire and should be stored and reused for # every request to the API. credentials = client.oauth_credentials print ('OAuth authorization successful. Store these credentials to reuse' + ' until revoked: %s' % credentials) # Note: you could simply set the crendentials as below and skip the previous # steps once access has been granted. client.oauth_credentials = credentials campaign_service = client.GetCampaignService( 'https://adwords-sandbox.google.com', 'v201206') # Get all campaigns. # Construct selector and get all campaigns. selector = { 'fields': ['Id', 'Name', 'Status'] } campaigns = campaign_service.Get(selector)[0] # Display results. if 'entries' in campaigns: for campaign in campaigns['entries']: print ('Campaign with id \'%s\', name \'%s\' and status \'%s\' was found.' % (campaign['id'], campaign['name'], campaign['status'])) else: print 'No campaigns were found.' # Initialize appropriate service. report_downloader = client.GetReportDownloader( 'https://adwords-sandbox.google.com', 'v201206') # Create report definition. report = { 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', 'dateRangeType': 'LAST_7_DAYS', 'reportType': 'CRITERIA_PERFORMANCE_REPORT', 'downloadFormat': 'CSV', 'selector': { 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', 'Criteria', 'Impressions', 'Clicks', 'Cost'] }, # Enable to get rows with zero impressions. 'includeZeroImpressions': 'false' } print report_downloader.DownloadReport(report)