Bigquery谷歌认证,无需浏览器提示



我使用OAuth 2.0方法通过python连接到bigquery来访问用户数据。但每次我进行查询时,它都会反复请求浏览器确认。如何取消此验证?当我将launch_browser值设置为False时,它会请求终端进行确认。我能用别的方法吗?我使用的是与文档中相同的示例代码https://cloud.google.com/bigquery/docs/authentication/end-user-installed

from google_auth_oauthlib import flow
from google.cloud import bigquery
launch_browser = True
appflow = flow.InstalledAppFlow.from_client_secrets_file(
"client_secrets.json", scopes=["https://www.googleapis.com/auth/bigquery"]
)
if launch_browser:
appflow.run_local_server()
else:
appflow.run_console()
credentials = appflow.credentials
project = 'user-project-id'
client = bigquery.Client(project=project, credentials=credentials)
query_string = """SELECT name, SUM(number) as total
FROM `bigquery-public-data.usa_names.usa_1910_current`
WHERE name = 'William'
GROUP BY name;
"""
query_job = client.query(query_string)
for row in query_job.result(): 
print("{}: {}".format(row["name"], row["total"]))

将凭据存储在一个文件中可以阻止谷歌不断请求它,但它只会持续一段时间。

creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_console()
#creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())

这是我用来加载凭据的东西(我通过控制台加载凭据,因为它在没有浏览器的Linux上(

您可能需要更改某些部分以适应您的代码,但这是一般的想法。

最新更新