Как исправить постоянные ошибки при реализации входа в систему Google OAuth с помощью Django

Я решил внедрить метод google sign in в свой Django-сайт, но столкнулся с ошибками, связанными с библиотекой social_auth_app_django. Например, сначала я получил ошибку ValueError (Expected 2 got 1) из одного из файлов utils.py в коде библиотеки. Обратите внимание, что я новичок в добавлении google sign in в Django-приложение.

Вот мои спецификации версии:

  • Django версии 4.2.13
  • Python версии 3.10.5
  • Библиотека social_auth_app_django версии 5.4.1

Вот мой settings.py (обратите внимание, что ключи API будут скрыты в целях безопасности)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "games.apps.GamesConfig",
    "account.apps.AccountConfig",
    "forums.apps.ForumsConfig",
    "play.apps.PlayConfig",
    "make_game.apps.MakeGameConfig",
    "administration.apps.AdministrationConfig",
    "bootstrap5",
    "payments.apps.PaymentsConfig",
    "social_django"
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'account.middleware.DeviceDetectionMiddleware',
    # "django.middleware.debug.DebugMiddleware",
    'social_django.middleware.SocialAuthExceptionMiddleware',
]

ROOT_URLCONF = 'superstarstudios.urls'



SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "my-google-key"
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "my-google-secret"
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    "email",
]
AUTHENTICATION_BACKENDS = (
    'social_core.backends.google.GoogleOAuth2'
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / "templates"
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'account.context_processors.device_type',
                "social_django.context_processors.backends",
                'social_django.context_processors.login_redirect'
            ],
        },
    },
]

LOGIN_REDIRECT_URL = "/games"
LOGOUT_REDIRECT_URL = "/"

SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.social_details', 
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username', 
    'social_core.pipeline.user.create_user',
    'account.pipeline.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
)

Вот функция, в которой возникает основная ошибка ValueError:

def module_member(name):
    try:
        mod, member = name.rsplit(".", 1)
        module = import_module(mod)
        return getattr(module, member)
    except (ValueError, AttributeError, ImportError) as e:
        print(f"Couldn't import {name}: {e}")

** Вот функция, в которой возникает ошибка TypeError (issubclass() arg 1 must be a class) **

def load_backends(backends, force_load=False):
    """
    Load backends defined on SOCIAL_AUTH_AUTHENTICATION_BACKENDS, backends will
    be imported and cached on BACKENDSCACHE. The key in that dict will be the
    backend name, and the value is the backend class.

    Only subclasses of BaseAuth (and sub-classes) are considered backends.

    Previously there was a BACKENDS attribute expected on backends modules,
    this is not needed anymore since it's enough with the
    AUTHENTICATION_BACKENDS setting. BACKENDS was used because backends used to
    be split on two classes the authentication backend and another class that
    dealt with the auth mechanism with the provider, those classes are joined
    now.

    A force_load boolean argument is also provided so that get_backend
    below can retry a requested backend that may not yet be discovered.
    """
    global BACKENDSCACHE
    if force_load:
        BACKENDSCACHE = OrderedDict()
    if not BACKENDSCACHE:
        for auth_backend in backends:
            backend = module_member(auth_backend)
            if issubclass(backend, BaseAuth):
                BACKENDSCACHE[backend.name] = backend
    return BACKENDSCACHE

Я пробовал разные методы, например, менял rsplit с (".", 1) на (".", 2), а также много задавал вопросов AI о помощи, но ни один из них не помог. Как было сказано выше, я просто продолжал получать ошибки снова и снова. Вот подробное (очень подробное) сообщение об ошибке:

Couldn't import s: not enough values to unpack (expected 2, got 1)
Internal Server Error: /account-sys/login/google-oauth2/
Traceback (most recent call last):
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\utils.py", line 49, in get_backend
    return BACKENDSCACHE[name]
KeyError: 'google-oauth2'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapper_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 63, in wrapper
    return func(request, backend, *args, **kwargs)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 44, in wrapper
    request.backend = load_backend(
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 27, in load_backend
    return strategy.get_backend(name, redirect_uri=redirect_uri)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\strategy.py", line 176, in get_backend
    Backend = self.get_backend_class(name)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\strategy.py", line 172, in get_backend_class
    return get_backend(self.get_backends(), name)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\utils.py", line 52, in get_backend
    load_backends(backends, force_load=True)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\utils.py", line 35, in load_backends
    if issubclass(backend, BaseAuth):
TypeError: issubclass() arg 1 must be a class

Спасибо за любую возможную помощь.

Я исправил свою ошибку: Имя бэкенда было неверным.

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