1

'NoneType' object is not subscriptable после выполнения удаления

Вот функция из бота

def del_cat(message):
    try:
        conn = sqlite3.connect("base_ts.sqlite")
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM catalog')
        row = cursor.fetchall()
        cursor.close()
        conn.close()

        name = row[int(message.text)][1]
        category = func.AddCategory(name)
        cat_dict[message.chat.id] = category

        conn = sqlite3.connect("base_ts.sqlite")
        cursor = conn.cursor()
        cursor.execute(f'SELECT * FROM "{name}"')
        row = cursor.fetchall()
        cursor.close()
        conn.close()

        text = ''
        num = 0

        for i in row:
            text = text + '№ ' + str(num) + '   |  ' + str(i[0]) + '\n'
            num += 1

        msg = bot.send_message(chat_id=message.chat.id,
                               text='Выберите номер товара который хотите удалить\n\n'
                                    f'{text}')
        bot.register_next_step_handler(msg, del_cat_2)
    except Exception as e:
        print(e)
        bot.send_message(chat_id=message.chat.id,
                         text='Упсс, что-то пошло не по плану')


def del_cat_2(message):
    try:
        category = cat_dict[message.chat.id]

        conn = sqlite3.connect("base_ts.sqlite")
        cursor = conn.cursor()
        cursor.execute(f"SELECT * FROM '{category.section}'")
        row = cursor.fetchall()

        name_category = row[int(message.text)][2]
        category.category = name_category

        markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
        markup.add('Yes', 'No')

        msg = bot.send_message(chat_id=message.chat.id,
                               text='❕Удалить ⬇️\n'
                                    f'❕{category.category}\n\n'
                                    '❕из раздела ⬇️\n'
                                    f'❕{category.section}  ?',
                               reply_markup=markup)
        bot.register_next_step_handler(msg, del_cat_3)
    except Exception as e:
        print(e)
        bot.send_message(chat_id=message.chat.id,
                         text='Упсс, что-то пошло не по плану')


def del_cat_3(message):
    try:
        if message.text == 'Yes':
            category = cat_dict[message.chat.id]

            func.del_cat_to_section(category.category, category.section)
            bot.send_message(
                chat_id=message.chat.id,
                text=f'✅Товар: {category.category}\n'
                     f'✅Успешно удален из раздела',
                reply_markup=menu.admin_menu
            )
        if message.text == 'No':
            bot.send_message(chat_id=message.chat.id,
                             text='Вы вернулись в меню админа',
                             reply_markup=menu.admin_menu)
    except Exception as e:
        print(e)
        bot.send_message(chat_id=message.chat.id,
                         text='Упсс3, что-то пошло не по плану')

И это с импорта файла как функции ,я подозреваю что проблема в классах но как верно будет

class AddCategory:
    def __init__(self, section):
        self.section = section
        self.cat = None
        self.category = None

class Category:
    def __init__(self, category):
        self.category = category

def del_cat_to_section(section, name_category):
    # Connection
    conn = sqlite3.connect("base_ts.sqlite")
    cursor = conn.cursor()

    # del
    category = cursor.execute(f'SELECT * FROM "{section}" WHERE list = "{name_category}"').fetchone()

    cursor.execute(f"DELETE FROM '{section}' WHERE list = '{name_category}'")
    conn.commit()

    cursor.execute(f"DROP TABLE '{category[2]}'")

    # Close connection
    cursor.close()
    conn.close()

дохожу до 3го делита и 'NoneType' object is not subscriptable

И вот полный трейсбек

Traceback (most recent call last):
  File "C:/Users/Бодянич/Desktop/newbot/main.py", line 732, in del_cat_3
    func.del_cat_to_section(category.category, category.section)
  File "C:\Users\Бодянич\Desktop\newbot\functions.py", line 227, in del_cat_to_section
    cursor.execute(f"DROP TABLE '{category[2]}'")
TypeError: 'NoneType' object is not subscriptable
2
  • оффтоп, но если не сложно скажите., вы используете прокси для запросов к телеграм апи?
    – finally
    21 мая 2020 в 23:13
  • Нет, не нуждаюсь
    – NHide
    21 мая 2020 в 23:15

2 ответа 2

1

Команда

category = cursor.execute(f'SELECT * FROM "{section}" WHERE list = "{name_category}"').fetchone()

не была неудачна (нет такой строки), потому значение переменной category будет None и — следовательно — в команде

cursor.execute(f"DROP TABLE '{category[2]}'")

the expression category[2] raises the exception

TypeError: 'NoneType' object is not subscriptable

Мне не хочет разбираться в том, что вы хотели сделать, но самой ошибки возможно избавиться так, что вместо

cursor.execute(f"DROP TABLE '{category[2]}'")

используете

if cursor:
    cursor.execute(f"DROP TABLE '{category[2]}'")
6
  • Thanks. Can y help me, how i can fix this? My sqlite base consists are catalog table (section,code), category(cat, section,code), how i can drop the table what created after
    – NHide
    22 мая 2020 в 9:09
  • def add_cat_to_section(name_category, name_saction): # Connection conn = sqlite3.connect("base_ts.sqlite") cursor = conn.cursor() code = random.randint(11111, 99999) cursor.execute(f"INSERT INTO '{name_saction}' VALUES ('{name_category}', '{name_saction}', '{code}')") conn.commit() cursor.execute(f"INSERT INTO 'category' VALUES ('{name_category}', '{name_saction}', '{code}')") conn.commit() # Create table product cursor.execute(f"CREATE TABLE '{code}' (list text, price text, code text)") cursor.close() conn.close()
    – NHide
    22 мая 2020 в 9:13
  • Я что-то добавил в мой ответ.
    – MarianD
    22 мая 2020 в 9:19
  • Не понял о if cursor: ( можете немного пояснить ? Пожалуйста
    – NHide
    22 мая 2020 в 9:35
  • if cursor: в том контексте то же самое как if cursor is not None:
    – MarianD
    22 мая 2020 в 10:07
1

Вместо

category = cursor.execute(f'SELECT * FROM "{section}" WHERE list = "{name_category}"').fetchone()

напишите эту команду без присваивания, так:

cursor.execute(f'SELECT * FROM "{section}" WHERE list = "{name_category}"').fetchone()

чтобы не переписать переменную category.

2
  • Спасибо вам огромное за помощь 😇
    – NHide
    22 мая 2020 в 15:09
  • @NHide, не стоит.
    – MarianD
    22 мая 2020 в 15:14

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.