Oma*_*lak 4 python gcloud google-colaboratory
我正在尝试对 colab 文件进行身份验证,以便能够发出 bigquery 请求、访问驱动器等。我一直在使用:
from google.colab import auth
auth.authenticate_user()
Run Code Online (Sandbox Code Playgroud)
效果很好,但每次会话超时(我认为每 12 小时)时都会要求提供凭据,并且需要人工交互(单击链接、复制令牌、粘贴)。
我知道我可以使用gcloudcli 使用“服务帐户”进行身份验证。但是我无法在我工作的组织中访问它。但是,我可以从 gcloud获取access-token和identity-token。
有没有办法使用这些令牌进行身份验证,只需运行一个单元,而无需进一步交互?无论如何,这些令牌的目的是什么?
PS:我对hacky解决方案没意见。
Oma*_*lak 11
这就是我所做的:
第 1 步:手动登录一次
from google.colab import auth
auth.authenticate_user()
Run Code Online (Sandbox Code Playgroud)
第 2 步:转储密钥
!cat adc.json
Run Code Online (Sandbox Code Playgroud)
然后复制以下键的值:client_id, client_secret,refresh_token
第 3 步:每当您想进行身份验证时运行该代码
!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)
Run Code Online (Sandbox Code Playgroud)
现在您无需与浏览器进行任何交互,只需运行单元格即可。
| 归档时间: |
|
| 查看次数: |
1804 次 |
| 最近记录: |