Posts tagged with python

I am new to Google AdWords API.

Right now I am downloading the AD_PERFORMANCE_REPORT and I want to segment it by day, but I cant find the right example in their documentation

My code looks like this:

 def get_data(customer_id):     df = None     for item in customer_id:         report_query = (adwords.ReportQueryBuilder()                         .Select('AdGroupId', 'AdGroupName', 'AbsoluteTopImpressionPercentage', 'Impressions', 'Conversions')                         .From('AD_PERFORMANCE_REPORT')                         .During('LAST_7_DAYS')                         .Build())         # You can provide a file object to write the output to. For this         # demonstration we use sys.stdout to write the report to the screen.         report_downloader.DownloadReportWithAwql(             report_query,             'CSV',             output,             client_customer_id=item,  # denotes which adw account to pull from             skip_report_header=True,             skip_column_header=False,             skip_report_summary=True,             include_zero_impressions=False)         output.seek(0)         df = pd.read_csv(output)         if df is None:             df = pd.DataFrame(output)         else:             df = df.append(pd.DataFrame(output))     return df 

Thank you for your suggestions.

I am building an application that is using Google Adwords API. I am asking the user to sign in with his Google Account and grant me permission to use his adwords Accounts. When the user logs in with Google, I am getting his accounts using googleads.adwords

from googleads import oauth2, adwords client = adwords.AdWordsClient(developer_token, oauth2_client, 'test') offline_conversion_feed_service = client.GetService('CustomerService', version='v201809') customers = offline_conversion_feed_service.getCustomers() 

I need to find all the MCC accounts and their linked accounts.

In customers I have all the accounts and their client_customer_id, but I cannot determine which account is linked with which MCC.

My question is, how to determine which accounts are linked with which ?

I was trying to change the keyword status via Google Ads API the following code shows how to update the keyword bid... however, I was looking for a way to set the keyword status as paused, I haven't been able to find any info within the documentation to paused the keyword

from googleads import adwords AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' def main(client, ad_group_id, criterion_id):            # Initialize appropriate service.            ad_group_criterion_service = client.GetService(                                        'AdGroupCriterionService', version='v201809')            # Construct operations and update bids.            operations = [{                  'operator': 'SET',                  'operand': {                  'xsi_type': 'BiddableAdGroupCriterion',                  'adGroupId': ad_group_id,                  'criterion': {                  'id': criterion_id,                   },                 'biddingStrategyConfiguration': {                 'bids': [                      {                     'xsi_type': 'CpcBid',                     'bid': {                       'microAmount': '1000000'                       }                     }                   ]                 }               }             }]         ad_group_criteria = ad_group_criterion_service.mutate(operations)  # Display results.  if 'value' in ad_group_criteria:     for criterion in ad_group_criteria['value']:       if criterion['criterion']['Criterion.Type'] == 'Keyword':           print('Ad group criterion with ad group id "%s" and criterion id '                 '"%s" currently has bids:'                 % (criterion['adGroupId'], criterion['criterion']['id']))       for bid in criterion['biddingStrategyConfiguration']['bids']:          print('\tType: "%s", value: %s' % (bid['Bids.Type'],)               bid['bid']['microAmount']) else:     print('No ad group criteria were updated.') if __name__ == '__main__':      # Initialize client object.      adwords_client = adwords.AdWordsClient.LoadFromStorage()      main(adwords_client, AD_GROUP_ID, CRITERION_ID) 

Thanks in advance for the help...

I'm trying to fetch the audiences (Custom intent, Custom affinity) of all my enabled google display campaigns.

I thought I can get it through the CampaignCriterionService, but the returned data is empty.

     campaign_criterion_service = ADWORDS_CLIENT.GetService(         'CampaignCriterionService', version='v201809')     selector = {         'fields': ['CampaignId', 'Id', 'CriteriaType', "PlacementUrl",                    'KeywordText', "ChannelName", "AppId", "DisplayName", "CampaignStatus", "CampaignName"],         'predicates': [{             'field': 'CriteriaType',             'operator': 'IN',             'values': [                 'CUSTOM_AFFINITY',                 'CUSTOM_INTENT'             ]         },         {             'field': 'CampaignStatus',             'operator': 'IN',             'values': [                 'ENABLED'             ]         }         ],         'paging': {             'startIndex': 0,             'numberResults': 500         }     }     page = campaign_criterion_service.get(selector) 

Any clues?

I am trying to integrate Oauth2 into my Flask application, and am having some issues with keeping the flow persistent despite a redirect.

def account(): form = UpdateAccountForm() authorization_url = '' auth_code = request.args.get('code') if request.method == 'POST':     if request.form['submit_button'] == 'Test':         flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json',      scopes=['https://www.googleapis.com/auth'])         flow.redirect_uri = 'http://127.0.0.1:5000/account'         authorization_url, state = flow.authorization_url(access_type='offline',                  prompt='consent', include_granted_scopes='true')         print('Please go to this URL: {}'.format(authorization_url)) if auth_code != None:     flow.fetch_token(code=auth_code)     credentials = flow.credentials     print(credentials) 

Upon button click, the Oauth flow is initiated and the user is presented with a link to a Google page in which they grant my application access to some of their features. Then, the user is redirected back to the same page but with an authorization code attached to the request which is fed back into the flow and allows me to gain access the users credentials.

This part:

if auth_code != None:     flow.fetch_token(code=auth_code)     credentials = flow.credentials     print(credentials) 

When the page reloads I get:

UnboundLocalError: local variable 'flow' referenced before assignment

I assume this happens because the flow is no longer initialized when the page loads, and obviously I can't initialize a new flow the next time the page loads because the object would be different.

I am not sure how to approach this problem within Flask, what would be the best way to keep the flow consistent?

EDIT: This question is different from the suggested duplicate because this uses Oauthlibs Flow module as opposed to the previously suggested. The closest answer is here: https://developers.google.com/identity/protocols/OAuth2WebServer but still inadequate.