【问题标题】:gmail python api authenticationgmail python api认证
【发布时间】:2023-03-16 02:17:01
【问题描述】:

我在 Google Developer 仪表板中创建了一个项目,授予它对 Gmail API 的访问权限,并将我的凭据下载为 JSON 文件。

然后我在这里更改了 JSON 凭证文件路径并尝试运行快速入门示例,但失败:

In [2]: run quickstart.py
---------------------------------------------------------------------------
InvalidClientSecretsError                 Traceback (most recent call last)
/Users/me/Code/gmail/quickstart.py in <module>()
     19 
     20 # Start the OAuth flow to retrieve credentials
---> 21 flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
     22 http = httplib2.Http()
     23 

/Users/me/.virtualenvs/nlp/lib/python2.7/site-packages/oauth2client/util.pyc in positional_wrapper(*args, **kwargs)
    130         else: # IGNORE
    131           pass
--> 132       return wrapped(*args, **kwargs)
    133     return positional_wrapper
    134 

/Users/me/.virtualenvs/nlp/lib/python2.7/site-packages/oauth2client/client.pyc in flow_from_clientsecrets(filename, scope, redirect_uri, message, cache, login_hint, device_uri)
   1987   """
   1988   try:
-> 1989     client_type, client_info = clientsecrets.loadfile(filename, cache=cache)
   1990     if client_type in (clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED):
   1991       constructor_kwargs = {

/Users/me/.virtualenvs/nlp/lib/python2.7/site-packages/oauth2client/clientsecrets.pyc in loadfile(filename, cache)
    141 
    142   if not cache:
--> 143     return _loadfile(filename)
    144 
    145   obj = cache.get(filename, namespace=_SECRET_NAMESPACE)

/Users/me/.virtualenvs/nlp/lib/python2.7/site-packages/oauth2client/clientsecrets.pyc in _loadfile(filename)
    104   except IOError:
    105     raise InvalidClientSecretsError('File not found: "%s"' % filename)
--> 106   return _validate_clientsecrets(obj)
    107 
    108 

/Users/me/.virtualenvs/nlp/lib/python2.7/site-packages/oauth2client/clientsecrets.pyc in _validate_clientsecrets(obj)
     71 def _validate_clientsecrets(obj):
     72   if obj is None or len(obj) != 1:
---> 73     raise InvalidClientSecretsError('Invalid file format.')
     74   client_type = tuple(obj)[0]
     75   if client_type not in VALID_CLIENT:

InvalidClientSecretsError: Invalid file format.

代码如下:

#!/usr/bin/python

import httplib2

from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run


# Path to the client_secret.json file downloaded from the Developer Console
CLIENT_SECRET_FILE = 'gmail-api-eeac5a33ec79.json'

# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'

# Location of the credentials storage file
STORAGE = Storage('gmail.storage')

# Start the OAuth flow to retrieve credentials
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
http = httplib2.Http()

# Try to retrieve credentials from storage or run the flow to generate them
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
  credentials = run(flow, STORAGE, http=http)

# Authorize the httplib2.Http object with our credentials
http = credentials.authorize(http)

# Build the Gmail service from discovery
gmail_service = build('gmail', 'v1', http=http)

# Retrieve a page of threads
threads = gmail_service.users().threads().list(userId='me').execute()

# Print ID for each thread
if threads['threads']:
  for thread in threads['threads']:
    print 'Thread ID: %s' % (thread['id'])

我没有更改 JSON 文件——只是从开发者控制台下载了它。我真的很反感 Gmail 的 API 很难上手——有人知道我做错了什么吗?

【问题讨论】:

  • 卡在同一个地方。希望有人回答这个问题。如果您找到解决方案,请提供更新。谢谢!

标签: python json gmail


【解决方案1】:

在创建新的客户端 ID 时,请确保您选择 Web 应用程序已安装的应用程序

如果您选择了服务帐户,那么收到的 JSON 格式不同,必须遵循另一个过程:

服务帐号

Google API(例如 Prediction API 和 Google Cloud Storage)可以代表您的应用程序执行操作,而无需访问用户信息。在这些情况下,您的应用程序需要向 API 证明自己的身份,但无需用户同意。同样,在企业场景中,您的应用程序可以请求对某些资源的委派访问。

对于这些类型的服务器到服务器交互,您需要一个服务帐户,该帐户属于您的应用程序而不是单个最终用户。您的应用程序代表服务帐户调用 Google API,无需用户同意。 (在非服务帐户场景中,您的应用程序代表最终用户调用 Google API,有时需要用户同意。)

注意:这些服务帐户方案需要应用程序创建 JSON Web 令牌 (JWT) 并对其进行加密签名。我们强烈建议您使用库来执行这些任务。如果您在不使用抽象令牌创建和签名的库的情况下编写此代码,则可能会出现严重影响应用程序安全性的错误。有关支持此方案的库列表,请参阅服务帐户文档。 您从 Google Developers Console 获得的服务帐户凭据包括生成的唯一电子邮件地址、客户端 ID 和至少一个公钥/私钥对。您使用客户端 ID 和一个私钥来创建签名的 JWT 并以适当的格式构造访问令牌请求。然后,您的应用程序将令牌请求发送到 Google OAuth 2.0 授权服务器,该服务器返回访问令牌。应用程序使用令牌来访问 Google API。当令牌过期时,应用程序会重复该过程。

来自google's dev pages

【讨论】:

    【解决方案2】:

    首先进入网站,我生成了我的身份验证 在我告知我的身份验证文件的完整路径后

    CLIENT_SECRET_FILE = '''C:\Python27\Lib\site-packages\oauth2client\client_secret_777909171445-9umvr7m509u4aabvujt5dofia5d8jlmb.apps.googleusercontent.com.json'''

    【讨论】:

      猜你喜欢
      • 2015-08-08
      • 1970-01-01
      • 2013-08-08
      • 2021-06-29
      • 1970-01-01
      • 2016-12-01
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多