尝试将 google OAuth2 与 Docker 一起使用时,没有名为 "requests" 的模块

No module named "requests" when trying to use google OAuth2 with Docker

我正在尝试为我的网络应用程序使用 google OAuth。为此,我在我的 venv 中和 Docker 构建期间(来自 requirements.txt).尽管如此,当我 运行 我的应用程序找不到请求模块时,抱怨说:

flask.cli.NoAppException: While importing "debateit", an ImportError was raised:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/google/auth/transport/requests.py", line 23, in <module>
    import requests
ImportError: No module named 'requests'

导入如下:

from google.auth.transport import requests

并像这样使用:

idinfo = id_token.verify_oauth2_token(token, requests.Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"])

其他导入,例如 id_token。verify_oauth2_token 工作正常。

我检查了我的 docker 构建,它说我已经正确包含 google-auth:

Installing collected packages: ... google-auth, httplib2, google-auth-httplib2, google-api-python-client
Successfully installed ... google-api-python-client-1.7.3 google-auth-1.5.0 google-auth-httplib2-0.0.3 httplib2-0.11.3 ...

我在 venv 中可以清楚地看到 google.auth.transport.requests 模块,它在应用程序本身中不起作用。

我错过了什么?什么会导致找不到此模块?

the documentation 中所报告,它应该更像是:

import google.auth.transport.requests
import requests

request = google.auth.transport.requests.Request()

credentials.refresh(request)

但为了您的目的,我建议:

from google.auth.transport.requests import Request

然后更改以下内容:

idinfo = id_token.verify_oauth2_token(token, requests.Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"])

至:

idinfo = id_token.verify_oauth2_token(token, Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"])

这是一个错误,因为在路径 google.auth.transport.requests 中没有名为 requests.

的函数或 class

我的建议是基于

idinfo = id_token.verify_oauth2_token(token, requests.Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"])

这告诉我们您使用了一个名为 Requests() 的 class,它存在于 google.auth.transport.requests 中,正如您在 the documentation.

中看到的那样

所以我发现了问题 - 在 google.auth.transport.requests 模块中,他们试图导入库 "requests"。我没有安装这个库。我已经这样做了,现在可以使用了。

我遵循的指南:https://developers.google.com/identity/sign-in/web/backend-auth 没有提到您需要安装这个库。我误解了请求模块中请求的导入应该做什么。

我知道这已得到解答,但您可以通过 运行 命令快速全局安装这些库:

pip install google-auth

如果有人不想全局安装它们,这里是如何在本地虚拟环境中安装 pip 或安装库: https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

pip install requests

似乎 google.auth.transport.requests 使用 requests