我正在我的窗口中使用以下代码,它可以工作,但是一旦我将它部署为GCP上的云函数,我就会得到这个错误?我该怎么绕过它呢?我想要做的是读取一个google表格,并在我的函数中使用它。
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject(EMAIL_FROM)
google函数日志显示以下错误
textPayload:"ModuleNotFoundError:没有名为‘oauth2client’的模块“ImportError: file_cache在使用oauth2client >= 4.0.0或google-auth时不可用
我该如何解决它?
发布于 2020-04-09 16:13:26
您必须更改您的依赖项oauth2client
,正如前面提到的here,它已被弃用
你可以选择google-auth==1.13.1
,它应该可以工作
那么,您的下一个问题将是:为什么它在我的本地环境中工作?我认为你已经全局安装了google-auth,你的代码接受这个依赖,即使它不在requirements.txt
中。我建议您使用虚拟环境,并仅在此venv中安装依赖项。
发布于 2020-04-10 11:02:44
希望这会有所帮助,顺便说一句,目标受众是你想要访问的url。
import argparse
import google.auth
import google.auth.app_engine
import google.auth.compute_engine.credentials
import google.auth.iam
from google.auth.transport.requests import Request
import google.oauth2.credentials
from google.oauth2 import service_account
class AuthenticationConstants:
AUTHENTICATION_SCOPES_URL = 'https://www.googleapis.com/auth/cloud-platform'
OAUTH_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'
class JWT(object):
def __init__(self, service_account_key_path):
self.service_account_key_path = service_account_key_path
self.credentials = service_account.Credentials.from_service_account_file(
self.service_account_key_path)
self.scoped_credentials = self.credentials.with_scopes(
[AuthenticationConstants.OAUTH_TOKEN_URI])
def get_google_open_id_connect_token(self, target_audience):
signer_email = self.scoped_credentials.service_account_email
signer = self.scoped_credentials.signer
service_account_credentials = google.oauth2.service_account.Credentials(
signer,
signer_email,
token_uri=AuthenticationConstants.OAUTH_TOKEN_URI,
additional_claims={
'target_audience': target_audience
}
)
service_account_jwt = service_account_credentials._make_authorization_grant_assertion()
request = google.auth.transport.requests.Request()
body = {
'assertion': service_account_jwt,
'grant_type': google.oauth2._client._JWT_GRANT_TYPE,
}
token_response = google.oauth2._client._token_endpoint_request(
request, AuthenticationConstants.OAUTH_TOKEN_URI, body)
return token_response['id_token']
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--service-account-path")
parser.add_argument("--target-audience")
result = parser.parse_args()
jwt = JWT(result.service_account_path)
print(jwt.get_google_open_id_connect_token(result.target_audience))
下面是我使用的requirements.txt:
google-api-python-client==1.7.11
https://stackoverflow.com/questions/61098412
复制相似问题