【问题标题】:Getting HttpError 401 while generating google Admob network report using python script使用 python 脚本生成 google Admob 网络报告时获取 HttpError 401
【发布时间】:2020-02-11 15:02:14
【问题描述】:

下面是我用来生成 Admob 网络报告的代码

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import os


base_path=os.path.dirname(os.path.realpath(__file__))
scopes=['https://www.googleapis.com/auth/admob.report']
key_file_location = base_path+'/config/service_account.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file_location, scopes)



account_id='accounts/pub-XXXXXXXXXXXXXXXX'
network_report_filter = {
  'dateRange': {
    'startDate': {'year': 2020, 'month': 1, 'day': 1},
    'endDate': {'year': 2020, 'month': 2, 'day': 10}
  },
  'dimensions': ['DATE', 'APP', 'COUNTRY'],
  'metrics': ['CLICKS', 'ESTIMATED_EARNINGS'],
  'dimensionFilters': [
    {
      'dimension': 'COUNTRY',
      'matchesAny': {'values': [{'value': 'US', 'value': 'CN'}]}
    }
  ],
  'sortConditions': [
    {'dimension':'APP', 'order': 'ASCENDING'},
    {'metric':'CLICKS', 'order': 'DESCENDING'}
  ],
  'localizationSettings': {
    'currencyCode': 'USD',
    'languageCode': 'en-US'
  }
}


# Build the service object.
admob = build('admob', 'v1', credentials=credentials)

admob._resourceDesc=network_report_filter
accounts=admob.accounts()
network_report=accounts.networkReport().generate(parent=account_id)
data=network_report.execute()

它会抛出以下错误

*** HttpError: https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/networkReport:generate?alt=json 返回“请求缺少所需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie或其他有效的身份验证凭据。请参阅https://developers.google.com/identity/sign-in/web/devconsole-project。">

我已在启用 Admob API 的情况下生成服务帐户凭据。 但无法弄清楚为什么会出现身份验证错误。

【问题讨论】:

    标签: python-3.x admob


    【解决方案1】:

    主要问题是,上面的代码尝试使用服务帐户来查询 api。但是,它不受支持。可以通过OAuth2.0 Client Id查询。

    OAth2.0 Client ID生成步骤:

    以下内容对我很有效:

    库:

    pip3 install --upgrade google-api-python-client --user
    pip3 install --upgrade oauth2client --user
    

    代码示例:

    import csv
    import sys
    
    from googleapiclient import discovery
    from googleapiclient.http import build_http
    from oauth2client import tools
    from oauth2client.file import Storage
    from oauth2client.client import OAuth2WebServerFlow
    
    
    class AdMobAPI:
    
        def __init__(self):
            scope = 'https://www.googleapis.com/auth/admob.report'
            name = 'admob'
            version = 'v1'
    
            flow = OAuth2WebServerFlow(client_id='<todo: replace with a client_id from the secret json>',
                                       client_secret='<todo: replace with a secret from the secret json>',
                                       scope=scope)
            storage = Storage(name + '.dat')
            credentials = storage.get()
            if credentials is None or credentials.invalid:
                credentials = tools.run_flow(flow, storage)
            http = credentials.authorize(http=build_http())
            self.admob = discovery.build(name, version, http=http)
    
        # Convert to the list of dictionaries
        def report_to_list_of_dictionaries(self, response):
            result = []
    
            for report_line in response:
                if report_line.get('row'):
                    print(report_line)
                    row = report_line.get('row')
                    dm = {}
                    if row.get('dimensionValues'):
                        for key, value in row.get('dimensionValues').items():
                            if value.get('value') and value.get('displayLabel'):
                                dm.update({key: value.get('value')})
                                dm.update({key + '_NAME': value.get('displayLabel')})
                            else:
                                dm.update({key: next(filter(None, [value.get('value'), value.get('displayLabel')]))})
                    if row.get('metricValues'):
                        for key, value in row.get('metricValues').items():
                            dm.update({key: next(filter(None, [value.get('value'), value.get('microsValue'), value.get('integerValue')]))})
                    result.append(dm)
            return result
    
        def generate_report(self, publisher_id):
            date_range = {'startDate': {'year': 2020, 'month': 4, 'day': 1},
                          'endDate': {'year': 2020, 'month': 4, 'day': 1}}
            dimensions = ['DATE', 'APP', 'PLATFORM', 'COUNTRY']
            metrics = ['ESTIMATED_EARNINGS', 'IMPRESSIONS', 'CLICKS',
                       'AD_REQUESTS', 'MATCHED_REQUESTS']
            sort_conditions = {'dimension': 'DATE', 'order': 'DESCENDING'}
            report_spec = {'dateRange': date_range,
                           'dimensions': dimensions,
                           'metrics': metrics,
                           'sortConditions': [sort_conditions]}
    
            request = {'reportSpec': report_spec}
            return self.admob.accounts().networkReport().generate(
                    parent='accounts/{}'.format(publisher_id),
                    body=request).execute()
    
    api = AdMobAPI()
    raw_report = api.generate_report('<todo: replace with publisher id, smth like pub-[0-9]+>')
    report_as_list_of_dictionaries = api.report_to_list_of_dictionaries(raw_report)
    
    # Convert to CSV
    dict_writer = csv.DictWriter(sys.stdout, report_as_list_of_dictionaries[0].keys())
    dict_writer.writeheader()
    dict_writer.writerows(report_as_list_of_dictionaries)
    

    【讨论】:

    • 对于任何阅读此内容的人,因为他们试图获取自动脚本/任务来收集 AdMob 数据,上述解决方案要求有权访问 AdMob 帐户的人在浏览器中使用 Google 登录。该脚本将为您打开浏览器到正确的 URI,但您仍然需要有人输入他们的详细信息。这意味着它并不是该自动数据收集用例的服务帐户流的真正替代方案。
    【解决方案2】:

    目前,google admob api 不支持服务帐号

    更多详情,请看这里enter link description here

    【讨论】:

    • 我不确定这是否会给现有答案添加任何内容,现有答案已经表明不支持服务帐户,然后继续展示如何使用不同的身份验证方法来完成?
    • 我只是觉得这个答案来自官方论坛,会更有说服力,也提供了各种建议
    猜你喜欢
    • 2023-03-11
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 2015-05-27
    • 2016-05-14
    • 1970-01-01
    相关资源
    最近更新 更多