Python 使用gcloud登录colab,不使用服务帐户
我正在尝试对colab文件进行身份验证,以便能够发出bigquery请求、访问驱动器等。我一直在使用:Python 使用gcloud登录colab,不使用服务帐户,python,gcloud,google-colaboratory,Python,Gcloud,Google Colaboratory,我正在尝试对colab文件进行身份验证,以便能够发出bigquery请求、访问驱动器等。我一直在使用: from google.colab import auth auth.authenticate_user() 它工作得很好,但是每次会话超时(我想每12小时)都会要求提供凭据,并且需要人工交互(单击链接,复制令牌,粘贴) 我知道我可以使用cli使用“服务帐户”进行身份验证。但在我工作的公司里,我无法访问它。但是,我可以从gcloud获得an和an 有没有一种方法可以使用这些令牌进行身份验证,
from google.colab import auth
auth.authenticate_user()
它工作得很好,但是每次会话超时(我想每12小时)都会要求提供凭据,并且需要人工交互(单击链接,复制令牌,粘贴)
我知道我可以使用cli使用“服务帐户”进行身份验证。但在我工作的公司里,我无法访问它。但是,我可以从gcloud获得an和an
有没有一种方法可以使用这些令牌进行身份验证,只需运行一个单元,而无需进一步交互?这些代币的用途是什么
附言:我对黑客解决方案没意见。我就是这样做的:
步骤1:手动登录一次
from google.colab import auth
auth.authenticate_user()
!pip install -U -q PyDrive
import httplib2
import json
from google.colab import auth
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI, client
from oauth2client.client import GoogleCredentials
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
auth_key = {
"client_id": "...",
"client_secret": "...",
"refresh_token": "..."
}
credentials = client.OAuth2Credentials(
access_token=None,
client_id=auth_key['client_id'],
client_secret=auth_key['client_secret'],
refresh_token=auth_key['refresh_token'],
token_expiry=None,
token_uri=GOOGLE_TOKEN_URI,
user_agent=None,
revoke_uri=GOOGLE_REVOKE_URI)
credentials.refresh(httplib2.Http())
credentials.authorize(httplib2.Http())
cred = json.loads(credentials.to_json())
cred['type'] = 'authorized_user'
with open('adc.json', 'w') as outfile:
json.dump(cred, outfile)
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = credentials
drive = GoogleDrive(gauth)
步骤2:转储密钥
!cat adc.json
然后复制以下密钥的值:client\u id
,client\u secret
,refresh\u token
步骤3:只要您想进行身份验证,就运行该代码
from google.colab import auth
auth.authenticate_user()
!pip install -U -q PyDrive
import httplib2
import json
from google.colab import auth
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI, client
from oauth2client.client import GoogleCredentials
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
auth_key = {
"client_id": "...",
"client_secret": "...",
"refresh_token": "..."
}
credentials = client.OAuth2Credentials(
access_token=None,
client_id=auth_key['client_id'],
client_secret=auth_key['client_secret'],
refresh_token=auth_key['refresh_token'],
token_expiry=None,
token_uri=GOOGLE_TOKEN_URI,
user_agent=None,
revoke_uri=GOOGLE_REVOKE_URI)
credentials.refresh(httplib2.Http())
credentials.authorize(httplib2.Http())
cred = json.loads(credentials.to_json())
cred['type'] = 'authorized_user'
with open('adc.json', 'w') as outfile:
json.dump(cred, outfile)
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = credentials
drive = GoogleDrive(gauth)
现在,您不必与浏览器进行任何交互,只需运行计算单元。我想,这个令牌将在24小时后过期。我使用了一个嵌入笔记本的服务帐户密钥。我更新了答案。现在正在刷新令牌。您是否有任何文章解释您的代码?我想知道每一行的工作原理和原因。不是真的,但我的意思是,
oauth2client
是一个谷歌库,所以我希望它能正常工作。你可以在这里找到一些文档