【问题标题】:googleapi python how to fetch / refresh access tokengoogle api python如何获取/刷新访问令牌
【发布时间】:2020-09-13 00:19:41
【问题描述】:

我正在尝试将 Google Analytics 设置到我的博客网站之一。我正在使用 google api 客户端库。如果我从站点手动获取访问令牌,则代码可以正常工作:https://developers.google.com/oauthplayground/。我发现刷新 access_token 很困难。有人可以指导我吗,因为我对 Google Analytics 很陌生。请分享python代码sn-p。

import httplib2
import httplib2 as lib2
import google.oauth2.credentials
# from google.auth.transport import requests
import requests
from google_auth_httplib2 import AuthorizedHttp
from oauth2client import client, GOOGLE_TOKEN_URI

from googleapiclient.discovery import build as google_build

# This is consistent for all Google services
token_uri = 'https://accounts.google.com/o/oauth2/token'

# WORKING CODE BUT REQUIRES VALID ACCESS_TOKEN
credentials = google.oauth2.credentials.Credentials(None,
                                                    refresh_token=refresh_token,
                                                  token_uri='https://accounts.google.com/o/oauth2/token',
                                                    client_id=client_id,
                                                    client_secret=client_secret)

credentials = google.oauth2.credentials.Credentials(access_token)
authorized = AuthorizedHttp(credentials=credentials)
print(access_token)

# API Name and Verison, these don't change until
# they release a new API version for us to play with.
api_name = 'analyticsreporting'
api_version = 'v4'

# Let's build the client
api_client = google_build(serviceName=api_name, version=api_version, http=authorized)

sample_request = {
    'viewId': 'xxxxxxxx',
    'dateRanges': {
        'startDate': datetime.strftime(datetime.now() - timedelta(days=120), '%Y-%m-%d'),
        'endDate': datetime.strftime(datetime.now(), '%Y-%m-%d')
    },
    'dimensions': [{'name': 'ga:date'}],
    'metrics': [{'expression': 'ga:sessions'}]
}

response = api_client.reports().batchGet(
    body={
        'reportRequests': sample_request
    }).execute()
print(response)

我已将 ACCESS_TOKEN 保留为 none 以获取初始访问令牌,当我打印它时,这似乎有效,但我无法使用此凭据 api 刷新此 access_token,因为它没有 expires_at 或 expiry属性也是如此。 URL 范围将是 'https://www.googleapis.com/auth/analytics.readonly'

运行上述代码刷新 ACCESS TOKEN 时,出现错误:

Traceback (most recent call last):
  File "E:/PyCharm_Workspace/MLPractices/GA3.py", line 78, in <module>
    'reportRequests': sample_request
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\googleapiclient\http.py", line 901, in execute
    headers=self.headers,
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\googleapiclient\http.py", line 177, in _retry_request
    resp, content = http.request(uri, method, *args, **kwargs)
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\google_auth_httplib2.py", line 213, in request
    self.credentials.refresh(self._request)
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\google\oauth2\credentials.py", line 172, in refresh
    "The credentials do not contain the necessary fields need to "
google.auth.exceptions.RefreshError: The credentials do not contain the necessary fields need to refresh the access token. You must specify refresh_token, token_uri, client_id, and client_secret.

提前致谢

尤瓦

【问题讨论】:

  • 在用户授权您的访问后,库应该为您刷新令牌。

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


【解决方案1】:

您将首次获得带有访问令牌的刷新令牌。您的刷新令牌是长期存在的。因此,您可以将其存储到数据库中的某个位置,以便以后使用。每当您需要访问令牌时,请使用该刷新令牌并生成新令牌。

Google API: getting Credentials from refresh token with oauth2client.client

上面的链接会对你有所帮助。

【讨论】:

  • 我之前尝试过,但由于 urllib 导致错误,urlencode 库不可用。谢谢
【解决方案2】:

谢谢大家。可以通过使用服务帐户凭据而不是 OAUTH - client_secrets 来获取 google 分析访问权限。使用服务帐户似乎很简单,因为现在我不需要刷新任何令牌。

但我正在考虑哪个更好,更安全,请有任何想法。这也是访问 Google Analytics V4 的最新参考,已于 2020 年发布参考:https://www.jcchouinard.com/google-analytics-api-using-python/

【讨论】:

    猜你喜欢
    • 2014-07-15
    • 2013-06-14
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2015-01-08
    相关资源
    最近更新 更多