Unix服务器上Python调用Google Calendar API授权失败求助
按照官方教程配置Google Calendar API时,运行quickstart.py出现授权失败,控制台报错如下:
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=99236485634896-kkavoaib8mp8ert4eri2d5v6gicfln14i0k.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A42403%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar&state=XEqxqNSDNKfksdfgwUXw24JjK4EzA4G&access_type=offline
Traceback (most recent call last):
File "/home/calendar/quickstart.py", line 63, in
main()
File "/home/calendar/quickstart.py", line 33, in main
creds = flow.run_local_server(port=0)
File "/home/calendar/.local/lib/python3.10/site-packages/google_auth_oauthlib/flow.py", line 446, in run_local_server
authorization_response = wsgi_app.last_request_uri.replace("http", "https")
AttributeError: 'NoneType' object has no attribute 'replace'
点击授权链接完成账号选择和权限允许后,被重定向到http://localhost:42403/?state=XEkxqN2KMDSgXknqUXw24JjK4EzA4G&code=4/2AbUR2VOHwy3nuCXdumqaJejyAb8F0N7LXQ2JA48EGgtuzCm64uNc YJRb7wfTLgnVSA1C8g&scope=https://www.googleapis.com/auth/calendar,浏览器提示无法访问此网站。
附上quickstart.py代码:
from __future__ import print_function import datetime import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/calendar'] def main(): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ 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( 'client_secret_99236485634896-mlsfkvkldfmldfer34o3fiodfficfln14i0k.apps.googleusercontent.com.json', SCOPES) 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()) try: service = build('calendar', 'v3', credentials=creds) # Call the Calendar API now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: print('No upcoming events found.') return # Prints the start and name of the next 10 events for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) except HttpError as error: print('An error occurred: %s' % error) if __name__ == '__main__': main()
问题原因与修复方案
核心问题
Unix服务器为无GUI远程环境,run_local_server()方法依赖本地浏览器和本地端口接收授权回调,但远程服务器的localhost端口无法被本地浏览器访问,导致授权回调失败,进而触发AttributeError。
修复步骤
- 替换授权方式:将代码中
creds = flow.run_local_server(port=0)替换为creds = flow.run_console(),该方法专为无GUI环境设计,无需本地浏览器回调。 - 重新运行脚本:执行
quickstart.py后,控制台会输出授权URL,复制该URL到本地浏览器打开,完成授权后获取授权码。 - 输入授权码:将浏览器中得到的授权码粘贴回服务器控制台,脚本会自动生成
token.json文件。
额外注意事项
- 确认Google Cloud项目中,OAuth 2.0客户端ID的类型为桌面应用,而非Web应用,避免授权限制。
- 若之前生成过
token.json,需先删除该文件再重新运行脚本,防止旧凭证缓存干扰。
内容的提问来源于stack exchange,提问作者Konstantin Boev

