1

我创建了一个 Python 程序,用于InstalledAppFlow.run_local_server弹出 Web 浏览器以让用户进行身份验证。快乐路径工作正常(用户进行身份验证,我得到凭据。)

但是,如果用户在没有进行身份验证的情况下关闭网页或者只是将其关闭,则程序将永远挂起,等待来自 run_local_server 的响应。

那么,两个问题...

  1. 有没有办法检测用户在没有验证的情况下关闭了网页?
  2. 有没有办法为 run_local_server 设置超时,这样如果没有响应,它将在 x 秒内返回?

我做了很多谷歌搜索,发现 run_local_server 在本地运行一个简单的 WSGI HTTP 服务器,但找不到任何关于如何解决上述两个问题的信息。

这是代码片段。

    flow = InstalledAppFlow.from_client_secrets_file(GOOGLE_CREDS_FILE, GOOGLE_API_SCOPES)
    google_credentials = flow.run_local_server(port=0)
    # Will hang here forever unless the user authenticates...

4

1 回答 1

0

如果有人仍在寻找它,请在此处查看一种解决方案。它使用pebble

以下示例是Teraskull使用我的Google Calendar Simple API库编写的:

from oauthlib.oauth2.rfc6749.errors import AccessDeniedError, MismatchingStateError
from gcsa.google_calendar import GoogleCalendar
from concurrent.futures import TimeoutError
from pebble import concurrent


@concurrent.process(timeout=60)  # Raise TimeoutError, if the function exceeds the given deadline (in seconds).
def create_process():
    return GoogleCalendar('primary', credentials_path='credentials.json')


def do_something():
    try:

        process = create_process()  # Return concurrent process.
        calendar = process.result()  # Wait for process result. Return calendar instance, or exceptions, if any were raised.

    # Catch exceptions, received from process result.
    except TimeoutError:  # If user did not log into Google Calendar on time.
        pass

    except AccessDeniedError:  # If user denied access to Google Calendar.
        pass

    except MismatchingStateError:  # If user attempted to login using an outdated browser window.
        pass
于 2021-02-27T15:15:49.383 回答