【问题标题】:How to authorize a Google APIs without user interaction?如何在没有用户交互的情况下授权 Google API?
【发布时间】:2021-03-18 14:38:39
【问题描述】:

我正在尝试对 Google Analytics API 运行自动化的每日 API 调用

问题是当我运行命令建立连接时,我的浏览器中会弹出一个窗口 我必须单击以允许访问我的项目。

有什么办法可以避开这一步,因为这一步需要在我的浏览器中有一个可视界面和操​​作,我似乎无法让它每天在后台自动运行。

有什么建议吗?

【问题讨论】:

    标签: python google-api google-oauth google-analytics-api google-api-python-client


    【解决方案1】:

    您需要进入谷歌云控制台,启用 API,并使用正确的密钥设置服务帐户。 https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py

    【讨论】:

    • 我确实使用了服务帐户,但由于某种原因,我不断收到错误消息:用户没有分析帐户。我现在正在使用 oAuth
    • 您需要将该服务帐号添加到您尝试查询的 GA 媒体资源中。
    【解决方案2】:

    您应该考虑使用服务帐户。服务帐户就像虚拟用户,您可以预先授权服务帐户访问您的 Google 分析帐户,方法是获取服务帐户电子邮件地址并将其添加为您希望访问的帐户的用户。通过这样做,代码将不需要像您目前看到的那样由用户授权。

    服务帐户只能用于您开发者拥有的帐户,不应用于访问其他用户的帐户,因为您应该使用 Oauth2。

    官方教程可以在这里找到Hello Analytics Reporting API v4; Python quickstart for service accounts

    """Hello Analytics Reporting API V4."""
    
    from apiclient.discovery import build
    from oauth2client.service_account import ServiceAccountCredentials
    
    
    SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
    KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
    VIEW_ID = '<REPLACE_WITH_VIEW_ID>'
    
    
    def initialize_analyticsreporting():
      """Initializes an Analytics Reporting API V4 service object.
    
      Returns:
        An authorized Analytics Reporting API V4 service object.
      """
      credentials = ServiceAccountCredentials.from_json_keyfile_name(
          KEY_FILE_LOCATION, SCOPES)
    
      # Build the service object.
      analytics = build('analyticsreporting', 'v4', credentials=credentials)
    
      return analytics
    
    
    def get_report(analytics):
      """Queries the Analytics Reporting API V4.
    
      Args:
        analytics: An authorized Analytics Reporting API V4 service object.
      Returns:
        The Analytics Reporting API V4 response.
      """
      return analytics.reports().batchGet(
          body={
            'reportRequests': [
            {
              'viewId': VIEW_ID,
              'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
              'metrics': [{'expression': 'ga:sessions'}],
              'dimensions': [{'name': 'ga:country'}]
            }]
          }
      ).execute()
    
    
    def print_response(response):
      """Parses and prints the Analytics Reporting API V4 response.
    
      Args:
        response: An Analytics Reporting API V4 response.
      """
      for report in response.get('reports', []):
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
    
        for row in report.get('data', {}).get('rows', []):
          dimensions = row.get('dimensions', [])
          dateRangeValues = row.get('metrics', [])
    
          for header, dimension in zip(dimensionHeaders, dimensions):
            print(header + ': ', dimension)
    
          for i, values in enumerate(dateRangeValues):
            print('Date range:', str(i))
            for metricHeader, value in zip(metricHeaders, values.get('values')):
              print(metricHeader.get('name') + ':', value)
    
    
    def main():
      analytics = initialize_analyticsreporting()
      response = get_report(analytics)
      print_response(response)
    
    if __name__ == '__main__':
      main()
    

    您需要在 Google 开发者控制台上创建服务帐户凭据,您现在使用的凭据将不起作用。这是How to create Google Oauth2 Service account credentials.上的视频

    记得在库下启用 Google Analytics Reporting api。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多