【问题标题】:Bigquery google auth without browser promptBigquery google auth 没有浏览器提示
【发布时间】:2022-10-06 03:23:38
【问题描述】:

我通过使用 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\"]))
  • 您能否提供您所指的browser confirmation 的屏幕截图?

标签: python google-bigquery


【解决方案1】:

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

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 上)

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

希望这可以帮助!

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 2014-09-08
    相关资源
    最近更新 更多