问题描述
我创建了一个Python程序,该程序使用InstalledAppFlow.run_local_server
来打开Web浏览器以使用户进行身份验证。幸福的道路工作正常(用户进行身份验证,我获得了凭据。)
但是,如果用户关闭网页而不进行身份验证或只是将其保留,程序将永远挂起,等待来自run_local_server的响应。
所以,有两个问题...
我做了很多谷歌搜索,发现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...
解决方法
如果有人仍在寻找它,请参阅一种解决方案 here。它使用 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