TypeError: объект типа «NoneType» не имеет len()

"""API."""
from __future__ import print_function

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/spreadsheets.readonly']


def get_links_from_spreadsheet(id: str, token_file_name: str) -> list:
    """
    Возвращает список строк из первого столбца электронной таблицы Google с заданным идентификатором.
Пример ввода с https://docs.google.com/spreadsheets/d/1WrCzu4p5lFwPljqZ6tMQEJb2vSJQSGjyMsqcYt-yS4M
    get_links_from_spreadsheet('1WrCzu4p5lFwPljqZ6tMQEJb2vSJQSGjyMsqcYt-yS4M', 'token.json')

Returns
    ['https://www.youtube.com/playlist?list=PLPszdKAlKCXUhU3r25SOFgBxwCEr-JHVS', ... and so on]
        """
        SAMPLE_SPREADSHEET_ID = id
        SAMPLE_RANGE_NAME = 'A1:E'
        creds = None
        if os.path.exists(token_file_name):
            creds = Credentials.from_authorized_user_file(token_file_name, SCOPES)
        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(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)
    
            with open(token_file_name, 'w') as token:
                token.write(creds.to_json())
    
        try:
            service = build('sheets', 'v4', credentials=creds)
    
            sheet = service.spreadsheets()
            result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                        range=SAMPLE_RANGE_NAME).execute()
            values = result.get('values', [])

        if not values:
            return

        final_links = []
        for x in values:
            final_links.append(x.pop())
        print(final_links)

    except HttpError as err:
        print(err)


if __name__ == '__main__':
    get_links_from_spreadsheet('1WrCzu4p5lFwPljqZ6tMQEJb2vSJQSGjyMsqcYt-yS4M', 'token.json')

При проверке выдает правильный ответ ['https://www.youtube.com/playlist?list=PLPszdKAlKCXUhU3r25SOFgBxwCEr-JHVS', 'https://www.youtube.com/playlist?list=PLH2l6uzC4UEW0s7-KewFLBC1D0l6XRfye', 'https://www.youtube.com/playlist?list=PLFt_AvWsXl0ehjAfLFsp1PGaatzAwo0uK', 'https://www.youtube.com/playlist?list=PLMOpZvQB55bfp6ykOLayLqLrjcpv_Sw3P']

Но при отправке на тест выдает ошибку: TypeError: object of type 'NoneType' has no len()

Я поставил

if not values:
            return

но видимо дело не в этом. К сожалению доступа к тесту нет, поэтому не могу прислать данные теста. Проводить тесты можно сколько угодно раз.


Ответы (1 шт):

Автор решения: koljumba
"""API."""
from __future__ import print_function

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/spreadsheets.readonly']


def get_links_from_spreadsheet(id: str, token_file_name: str) -> list:
    """
    Возвращает список строк из первого столбца электронной таблицы Google с заданным идентификатором.
Пример ввода с https://docs.google.com/spreadsheets/d/1WrCzu4p5lFwPljqZ6tMQEJb2vSJQSGjyMsqcYt-yS4M
    get_links_from_spreadsheet('1WrCzu4p5lFwPljqZ6tMQEJb2vSJQSGjyMsqcYt-yS4M', 'token.json')

Returns
    ['https://www.youtube.com/playlist?list=PLPszdKAlKCXUhU3r25SOFgBxwCEr-JHVS', ... and so on]
        """
        SAMPLE_SPREADSHEET_ID = id
        SAMPLE_RANGE_NAME = 'A1:E'
        creds = None
        if os.path.exists(token_file_name):
            creds = Credentials.from_authorized_user_file(token_file_name, SCOPES)
        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(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)
    
            with open(token_file_name, 'w') as token:
                token.write(creds.to_json())
    
        try:
            service = build('sheets', 'v4', credentials=creds)
    
            sheet = service.spreadsheets()
            result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                        range=SAMPLE_RANGE_NAME).execute()
            values = result.get('values', [])

        if not values:
            return

        final_links = []
        for x in values:
            final_links.append(x.pop())
        return final_links

    except HttpError as err:
        return err


if __name__ == '__main__':
    get_links_from_spreadsheet('1WrCzu4p5lFwPljqZ6tMQEJb2vSJQSGjyMsqcYt-yS4M', 'token.json')
→ Ссылка