Google Calendar API на EC2 (AWS) - webbrowser.Error: could not locate runnable browser

Я разрабатываю Django App, в котором пользователь может получить доступ к своему Google Calendar с помощью этого скрипта

credentials = None
token = os.path.join(folder, "token.pickle")

if os.path.exists(token):
        with open(token, 'rb') as tk:
                credentials = pickle.load(tk)

if not credentials or not credentials.valid:
    if credentials and credentials.expired and credentials.refresh_token:
         credentials.refresh(Request())
    else: 
        credentials = os.path.join(folder, "credentials.json")
        flow = InstalledAppFlow.from_client_secrets_file( credentials, scopes=['openid', 'https://www.googleapis.com/auth/calendar'] )
        flow.authorization_url(
            # Recommended, enable offline access so that you can refresh an access token without
            # re-prompting the user for permission. Recommended for web server apps.
            access_type='offline',
            # Optional, enable incremental authorization. Recommended as a best practice.
            include_granted_scopes='true',
            # # Optional, if your application knows which user is trying to authenticate, it can use this
            # # parameter to provide a hint to the Google Authentication Server.
            login_hint=useremail,
            # Optional, set prompt to 'consent' will prompt the user for consent
            prompt='consent')

        flow.run_local_server()
        credentials = flow.credentials

    with open(token, 'wb') as tk:
        pickle.dump(credentials, tk)

service = build('calendar', 'v3', credentials = credentials)

Когда я тестирую его на своей локальной машине, все работает нормально. Однако, запустив его на экземпляре EC2 на AWS, я получаю следующую ошибку:

flow.run_local_server()
  File "/home/ubuntu/webapp/lib/python3.12/site-packages/google_auth_oauthlib/flow.py", line 447, in run_local_server
    webbrowser.get(browser).open(auth_url, new=1, autoraise=True)
    ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/webbrowser.py", line 66, in get
    raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser

Он обрывается на строке flow.run_local_server(). Есть идеи, что я делаю не так?

Спасибо!!!

The issue occurs because flow.run_local_server() tries to open a browser for authentication which is not possible on an ec2 instance since it typically runs without a GUI.

use run_console() Instead of run_local_server()

since ec2 is a headless environment, use run_console() instead of run_local_server() to manually copy and paste the authentication URL and code:

flow.run_console()

this will prompt you with a url in the console. open it in your local machine's browser complete the authentication and paste the provided code into the terminal.

Вернуться на верх