【问题标题】:HttpError 400 Precondition check failed during users().messages().list Gmail API call using service accountHttpError 400 在 users().messages().list 使用服务帐户调用 Gmail API 期间先决条件检查失败
【发布时间】:2020-10-31 22:33:48
【问题描述】:

我正在使用服务帐户在我的 gmail 邮箱中列出消息,但是在调用此 API service.users().messages().list(userId='me').execute()时出现以下错误

    HttpError                                 Traceback (most recent call last)
<ipython-input-44-da1dc3cccc81> in <module>
     27 
     28 apiservice = build('gmail', 'v1', credentials=service_cred)
---> 29 response = apiservice.users().messages().list(userId='me').execute()

~/opt/anaconda3/lib/python3.7/site-packages/googleapiclient/_helpers.py in positional_wrapper(*args, **kwargs)
    128                 elif positional_parameters_enforcement == POSITIONAL_WARNING:
    129                     logger.warning(message)
--> 130             return wrapped(*args, **kwargs)
    131         return positional_wrapper
    132 

~/opt/anaconda3/lib/python3.7/site-packages/googleapiclient/http.py in execute(self, http, num_retries)
    849       callback(resp)
    850     if resp.status >= 300:
--> 851       raise HttpError(resp, content, uri=self.uri)
    852     return self.postproc(resp, content)
    853 

HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages?alt=json returned "Precondition check failed.">

代码:

scopes = [
    "https://mail.google.com/",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.labels",
    "https://www.googleapis.com/auth/gmail.metadata",
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
]

service_cred = service_account.Credentials.from_service_account_info(
                credentials, scopes=scopes)

service = build('gmail', 'v1', credentials=service_cred)
response = service.users().messages().list(userId='me').execute()

【问题讨论】:

    标签: google-api gmail-api


    【解决方案1】:

    我在尝试从我的个人电子邮件中列出电子邮件时也遇到了这个问题。启用 Gmail API 时,Google 仪表板为我设置了服务帐户凭据,因此我认为这是我应该使用的。

    为了消除 400 错误,我必须添加:

    delegated_credentials = credentials.with_subject('my-email@gmail.com')
    

    https://developers.google.com/identity/protocols/oauth2/service-account#authorizingrequests

     

    但是,我随后收到错误消息,提示我的服务帐户未经授权代表我的个人电子邮件提出请求。如果您不使用 G Suite,我认为没有办法代表用户使用服务帐号。

    所以我的问题的最终解决方案是使用 OAuth 身份验证,就像在 Python Quickstart 中一样。

    【讨论】:

    • 非常感谢您抽出宝贵时间回复。是的,您是正确的使用with_subject 方法模拟用户帐户解决了这个问题。我在他们的文档中找到了它,这并不容易找到。 developers.google.com/identity/protocols/oauth2/…
    • And if you're not using G Suite, I don't think there's a way to use a service account on behalf of a user. 我想我正在努力学习这一点。不知道为什么他们没有在任何地方提到这一点。
    猜你喜欢
    • 1970-01-01
    • 2020-11-28
    • 2014-08-17
    • 2020-05-08
    • 2022-11-09
    • 2022-01-15
    • 2014-09-13
    • 2017-01-08
    • 2019-06-27
    相关资源
    最近更新 更多