Повышение устойчивости web-приложений к SQL-инъекциям на примере мессенджера Telegram
Заказать уникальную курсовую работу- 84 84 страницы
- 3 + 3 источника
- Добавлена 18.07.2023
- Содержание
- Часть работы
- Список литературы
set_loc_num(message.text, DataBase.get_location_user(message.from_user.id))bot.send_message(message.chat.id, "Добавлен")bot.set_state(message.from_user.id, adminStates.admin_choice)@bot.message_handler(state = adminStates.report_)def report_call(message): if (message.text == conf.admin_button['report_moth']):bot.send_message(message.chat.id, "Напишитеполныймесяц (01-12)")elif (message.text == conf.admin_button['report_all']): temp = DataBase.report_all(DataBase.get_location_user(message.from_user.id)) msg = "Количество заказов: " + str(temp[0])msg += "\nСумма: " + str(temp[1])msg += "\nСредний чек: " + str(temp[2])bot.send_message(message.chat.id, msg)elif (message.text == conf.admin_button['menu']):admin_menu(message) else: temp = DataBase.report_moth(message.text, DataBase.get_location_user(message.chat.id)) msg = "Количество заказов: " + str(temp[0][0])msg += "\nСумма: " + str(temp[0][1])msg += "\nСредний чек: " + str(temp[0][2])msg += "\n\nТоп-5 продуктов:\n"for i in enumerate(temp[1]): if (i[0] == 5): break msg += str(i[0] + 1) + "." + str(i[1][0]) + " " + str(i[1][1]) + " шт.\n"bot.send_message(message.chat.id, msg)@bot.message_handler(state = adminStates.date)def set_new_date(message): DataBase.set_time_loc(DataBase.get_location_user(message.chat.id), message.text)bot.send_message(message.chat.id, "okok")bot.set_state(message.chat.id, adminStates.admin_menu)@bot.message_handler(state = adminStates.spam)def spam_all(message): if (message.text == conf.admin_button['menu']):bot.set_state(id, adminStates.admin_menu)admin_menu(message) else: temp = DataBase.get_all_id_clients() for i in temp:send_message_user(i, message.text)bot.set_state(message.chat.id, adminStates.admin_menu)admin_menu(message)@bot.message_handler(state = adminStates.admin_choice)def get_admin(message): id = message.from_user.id if (message.text == conf.admin_button['menu']):bot.set_state(id, adminStates.admin_menu)admin_menu(message)elif (message.text == conf.admin_button['prod']):bot.set_state(id, adminStates.prod_ad)prod_menu(message)elif (message.text == conf.admin_button['prod_add']):#Меня заставили!! Это стыдно НЕ ЧИТАЙТЕtemp = [None,None]list_category = DataBase.get_category_in_location(DataBase.get_location_user(message.from_user.id)) markup = types.ReplyKeyboardMarkup(resize_keyboard = True)markup.add(conf.buttons['back']) for row in enumerate(list_category): if (row[0]%3 == 2):markup.add(temp[0], temp[1], row[1][0], row_width=3)temp[0] = Nonetemp[1] = None else: temp[row[0]%3] = row[1][0] if (temp[1] is not None):markup.add(temp[0], temp[1], row_width=2)elif (temp[0] is not None):markup.add(temp[0])bot.send_message(id, "Выберитекатегорию", reply_markup= markup)bot.set_state(id, adminStates.prod_ad_category)elif (message.text == conf.admin_button['prod_update_count']):bot.send_message(id, conf.admin['prod_update_count'])bot.set_state(id, adminStates.prod_upcount)elif (message.text == conf.admin_button['prod_update_cost']):bot.send_message(id, conf.admin['prod_update_cost'])bot.set_state(id, adminStates.prod_upcost)elif (message.text == conf.admin_button['prod_delete']):id_prod_print(message)bot.set_state(id, adminStates.prod_delete)elif (message.text == conf.admin_button['prod_add_new_category']): markup = types.ReplyKeyboardMarkup(resize_keyboard = True)markup.add(conf.buttons['back'])bot.send_message(id, "Введитеновуюкатегорию", reply_markup= markup)bot.set_state(message.chat.id, adminStates.prod_add_new_category)elif (message.text == conf.admin_button['order']):bot.set_state(id, adminStates.order_menu)order_menu(message)elif (message.text == conf.admin_button['active_order']):id_order_print(message)bot.set_state(id, adminStates.order_info)elif (message.text == conf.admin_button['cancel_order']):id_order_print(message)bot.set_state(id, adminStates.order_cancel)elif (message.text == conf.admin_button['complete_order']):id_order_print(message)bot.set_state(id, adminStates.order_complete)elif (message.text == conf.admin_button['raffle']):raffle_menu(message)elif (message.text == conf.admin_button['raffle_start']):DataBase.new_raffle()bot.send_message(id, conf.admin_button['raffle_start'])raffle_menu(message)elif (message.text == conf.admin_button['raffle_info']): temp = DataBase.get_all_ticket() msg = "" for row in temp: msg += "@" + row[0] + " - " + str(row[1]) + "\n" if (msg == ""):msg = "Участников нету"bot.send_message(id, msg)elif (message.text == conf.admin_button['raffle_end']):DataBase.close_raffle()bot.send_message(id, conf.admin_button['raffle_end'])raffle_menu(message)elif (message.text == conf.admin_button['raffle_delete']):DataBase.delete_raffle()bot.send_message(id, conf.admin_button['raffle_delete'])elif(message.text == conf.admin_button['loc_num']):bot.send_message(message.chat.id, "Введитеновыйтелефондлялокации")bot.set_state(id, adminStates.loc_num)elif (message.text == conf.admin_button['report']):report_menu(message)elif (message.text == conf.admin_button['date']):bot.send_message(message.from_user.id, "Введитеновоевремядоставки в формате 00-00")bot.set_state(message.from_user.id, adminStates.date)elif (message.text == conf.admin_button['spam']):markup_reply = types.ReplyKeyboardMarkup(resize_keyboard = True)markup_reply.add(conf.admin_button['menu'])bot.send_message(message.chat.id, "Введитетекстрассылки", reply_markup=markup_reply)bot.set_state(message.chat.id, adminStates.spam)@bot.message_handler(state = MyStates.choice_)def get_text(message): if (message.text == conf.buttons['products']):show_products(message)elif (message.text == conf.buttons['buy']):orders_user = DataBase.get_bot_complete(message.from_user.id) for row in orders_user: if row[0] is not None:bot.send_message(message.chat.id, conf.botMessage['one_active_order']) else:bot.set_state(message.chat.id, MyStates.buy)buy_menu(message)elif (message.text == conf.buttons['account']):bot.set_state(message.chat.id, MyStates.account)account_menu(message)elif (message.text == conf.buttons['menu']):bot.set_state(message.chat.id, state = MyStates.main_menu) menu(message)elif (message.text == conf.buttons['select_location']):DataBase.delete_location_user(message.from_user.id)select_location(message)elif (message.text == conf.buttons['continue']):bot.set_state(message.chat.id, state=MyStates.buy)buy_menu(message)elif (message.text == conf.buttons['end_buy']):bot.set_state(message.chat.id, state= MyStates.new_num_name)num_name(message)elif (message.text == conf.buttons['order_info']):order_info_client(message)elif (message.text == conf.buttons['call']): temp = DataBase.get_num_loc(DataBase.get_location_user(message.from_user.id)) if (temp is None):bot.send_message(message.chat.id, conf.botMessage['er']) else:bot.send_message(message.chat.id, temp)elif (message.text == conf.buttons['cancel_order']): temp = DataBase.get_bot_complete(message.from_user.id) for row in temp:DataBase.client_cancel_odrer(row[0])DataBase.cancel_order(row[0]) DataBase.increase_cancel_order(message.from_user.id)account_menu(message)elif (message.text == conf.buttons['raffle_join'] and DataBase.check_ticket(message.from_user.username)): if (DataBase.check_ticket(message.from_user.username)):DataBase.add_new_ticket(message.from_user.username)bot.send_message(message.chat.id, conf.botMessage['raffle_join']%(DataBase.get_ticket(message.from_user.username))) else:bot.send_message(message.chat.id, conf.botMessage['error'])@bot.message_handler(content_types=['text'])def get_state(message): if (message.text == conf.buttons['products']):show_products(message)elif (message.text == conf.buttons['account']):bot.set_state(message.chat.id, MyStates.account)account_menu(message) else: bot.send_message(message.chat.id, conf.botMessage['error_state'])start_user(message)def select_location(msg): markup=types.ReplyKeyboardMarkup(one_time_keyboard= True,resize_keyboard=True)list_location = DataBase.get_all_location() for row in list_location: if (not(row[0] is None)):markup.add(row[0])bot.send_message(msg.chat.id,conf.botMessage['location'],reply_markup=markup)bot.set_state(msg.from_user.id, MyStates.main_menu)def report_menu(msg): markup=types.ReplyKeyboardMarkup(resize_keyboard=True)markup.add(conf.admin_button['report_moth'], conf.admin_button['report_all'], conf.admin_button['menu'], row_width=2)bot.send_message(msg.chat.id, "Выберитеотчёт", reply_markup=markup)bot.set_state(msg.from_user.id, adminStates.report_)def show_products(msg): location = DataBase.get_location_user(msg.from_user.id)list_products = DataBase.get_location_products(location)message_bot = "" #[0]-id,[1]-name,[2]-count,[3]-type,[4]-loc, [5]-cost temp = "" for row in list_products: temp = row[3].title()message_bot += temp + ":\n" break for row in list_products: if (temp != row[3].title()):message_bot += "\n" + row[3].title() + ":\n" temp = row[3].title()message_bot += conf.botMessage['prod_list']%(row[1], row[5]) + "\n" if (message_bot == ""):message_bot = conf.botMessage['empty_products']bot.send_message(msg.chat.id, message_bot)def tranc(text):i = 0 row = []row.append("") for c in text: if (c == '-'):i += 1row.append("") else: row[i] += c return rowdef send_message_user(id, msg):bot.send_message(id, msg)def id_order_print(message):markup_reply = types.ReplyKeyboardMarkup(one_time_keyboard=True,resize_keyboard = True)list_active_orders = DataBase.get_active_orders(DataBase.get_location_user(message.from_user.id)) for row in list_active_orders: if (row[0] is None and row[1] is None): breakmarkup_reply.add(str(row[0]))bot.send_message(message.from_user.id, conf.admin['id_order'], reply_markup=markup_reply)def id_prod_print(message):markup_reply = types.ReplyKeyboardMarkup(one_time_keyboard=True,resize_keyboard = True)list_active_prod = DataBase.get_all_location_products(DataBase.get_location_user(message.from_user.id))markup_reply.add(conf.buttons['back']) for row in list_active_prod: if (row[0] is None and row[1] is None): breakmarkup_reply.add(str(row[0]))bot.send_message(message.from_user.id, conf.admin['id_prod'], reply_markup=markup_reply)bot.add_custom_filter(custom_filters.StateFilter(bot))bot.add_custom_filter(custom_filters.IsDigitFilter())bot.infinity_polling(skip_pending=True)conf.pypersent_bonus = 0.02configure = { 'token': '5284765764:AAFsASMMUfq-4HwXFfFuaQKtXZa5ZVWVZyU', #5179373973:AAEt5nTmx8K0I9-JAjKTvZ-XOgKcF_ZBeNM 'adminKey': "39020ae13d2b79ce6489477436a6e472d713b35da8d0643015659245c0d35c0da4c49279d501b1e3249d070c7f198334842c30cab76c6586af21132d987e9f46"}botMessage = { 'welcome': "Добропожаловать!",'location': "Выберите удобную вам локацию", 'category': "Выберите категорию товара", 'product': "Выберите товар", 'count': "Выберите количество товара", 'empty': "Категории которые сейчас недоступны в данной локации:", 'failed_category': "Выбрана неверная категория!", 'failed_location': "Данной локации либо нету товара, либо мы там не работаем!", 'cancel': "Вы очистили свои данные!\nНапишите или нажмите /start ", 'menu': "Главное меню", 'accept_order': "Ваш заказ принят, желаете продолжить покупки?", 'accept_cart': "Ваш заказ сформирован", 'num_name': 'Введите номер телефона и как к вам обращаться.', 'comm': 'Укажите адрес доставки', 'error': 'Данные введены неверно', 'er' : "В данный момент не указан", 'account': "Информация о вас:\nБонусы: %d\nВсего сделанных закaзов: %d", 'active_order': "\n\nАктивный заказ: %d на сумму %d руб.\nПродавец свяжется в скором времени", 'not_active_order': "\n\nАктивных заказов нету.", 'not_info_orders': "У вас ещё нету заказов", 'info_order': "%s: Стоимость заказа %drub. - %s", 'raffle_join': "Теперь вы участвуете в розыгрыше под номером %d", 'raffle_ticket': "\nВаш билет в розыгрыше: %d",'prod_list': "%s - %d руб/шт",'one_active_order': "У вас уже есть активный заказ!", 'empty_products': "Товаров нет в наличие", 'raffle_error': "Для того, чтобы участвовать в розыгрыше, выставите в настройках телеграма 'Имя пользователя'", 'empty_orders': "Вы ещё не совершили заказ", 'order_date': "Доставка производится с ", 'complete_order' : "Заказ выполнен! Вам начисленно %d бонусов", 'cancel_order': "Ваш заказ отменён по причине: ", 'error_start': "Для продолжения работы укажите в настройках телеграма 'Имя пользователя'\nИ напишите снова /start", 'error_state': "Извините случились неполадки, мы это исправим в скором времени.\n", 'delete_order': "Ваш незаконченный заказ удалён. Простите за неудобства"}buttons = { 'products': "💵Товары", 'buy': "🛒Купить", 'account': "🗂Личный кабинет", 'menu': "Главная", 'select_location': "🌏Сменить локацию", 'call': "📞Связь с продавцом", 'back': "Назад", 'continue': "Продолжить покупки", 'end_buy': "Закончить покупку", 'no': "Не указывать", 'yes': "Уже указано", #1 - id, 2 - name 3 - count 4-cost #Если захотие, удалить одну из %s то надо залезать в код'prod': "%s %d руб./шт. [%d]", 'order_info': "🗃Историязаказов", 'cancel_order': "🚫Отменитьзаказ",'raffle_join': "🎟Участвовать в розыгрыше"}admin = { 'entry': "Введите пароль для входа", 'admin_menu': "Админ меню", 'prod_add': "Название-Количество-Стоимость\nВсё через тире, а не отдельными сообщениями", 'prod_update_count': "id-Новое количество",'prod_update_cost': "id-Новаяцена", 'accept': "Принято", 'id_order': "Введите id заказа",'id_prod': "Введите id продукта",'active_order': "%d: Суммазаказа - %d"}admin_button = { 'menu': "Меню", 'prod': "🍍Продукты",'prod_add': "Добавить продукт", 'prod_update_count': "Изменить количество",'prod_update_cost': "Изменитьцену", 'prod_delete': "Удалить", 'prod_add_new_category':"Добавитьновуюкатегорию",'order': "Заказы", 'active_order': "Подробности заказа", 'cancel_order': "Отменить заказ", 'complete_order': "Выполнить заказ", 'raffle': "Розыгрыш", 'raffle_start': 'Начать розыгрыш', 'raffle_info': "Информация об участниках", 'raffle_end': "Закончить розыгрыш", 'raffle_delete': "Очистить розыгрыш", 'loc_num': "📞Изменить номер телефона локации",'report': "💼Отчёт", 'report_moth': "Замесяц",'report_all': "За всё время", 'report_all_moth': "За всё время по месяцам", 'date': "Изменить время доставки", 'spam': "Рассылка"}#не редактироватьid_cancel_order = 0id_client = 0DataBase.pyimport sqlite3import confdb = sqlite3.connect('DataBase.db', check_same_thread=False)sql = db.cursor()status = {0 : "Обрабатывается",1 : "Обработан",2 : "Принят",3 : "Выполнен",4 : "Отклонён",5 : "Отменён", 'not_like': "Обр%" # = 1-3 буквам 0-1 статусу}# adddef add_new_Client(id:int, username:str): if username is None: username = "Empty" username = "@"+usernamesql.execute("INSERT INTO clients(id, username) VALUES (?, ?)", (id, username))db.commit()def add_new_Order(id_product,id_client:int, cost:int, location:str, counts:int): max_id = sql.execute("SELECT MAX(id_order) FROM orders").fetchone() for row in max_id: if (not(row is None)): TEMP = rowmax_id = TEMP + 1sql.execute("INSERT INTO orders(id_order, id_client, id_product, cost, location, date, counts) VALUES(?, ?, ?, ?, ?, date('now'), ?)", (max_id, id_client, id_product, cost, location, counts))db.commit() return max_iddef add_plus_Order(id_order, id_client, id_prod, cost,location, counts):sql.execute("INSERT INTO orders(id_order, id_client, id_product, cost, location, date, counts) VALUES(?, ?, ?, ?, ?, date('now'), ?)", (id_order, id_client, id_prod, cost*counts, location, counts))db.commit()def add_new_Product(name:str, count:int, type_prod:str, location:str, cost:int): max_id = sql.execute("SELECT MAX(id) FROM products").fetchone()max_id = int(max_id[0]) + 1sql.execute("INSERT INTO products VALUES(?, ?, ?, ?, ?, ?)", (max_id, name, count, type_prod, location, cost))db.commit()def add_new_category(location, category):add_new_Product("Новаякатегория", 0, category, location, 0)def add_comm(id, comm):sql.execute("INSERT INTO order_comm VALUES(?, ?)", (id, comm))db.commit()# setdef increase_order(id:int):sql.execute("UPDATE clients SET count_orders = count_orders + 1 WHERE id = ?", (id,))db.commit()def increase_cancel_order(id:int):sql.execute("UPDATE clients SET count_cancel_orders = count_cancel_orders + 1 WHERE id = ?", (id,))db.commit()def update_count_product(id:int, sign:int):sql.execute("UPDATE products SET count = count + ? WHERE id = ?", (sign, id))db.commit()def set_count_product(id,sign):sql.execute("UPDATE products SET count = ? WHERE id = ?", (sign, id))db.commit()def set_cost_product(id,sign):sql.execute("UPDATE products SET cost = ? WHERE id = ?", (sign, id))db.commit()def set_location_user(id:int, location:str):sql.execute("UPDATE clients SET location = ? WHERE id = ?", (location,id,))db.commit()def update_num_and_name(id:int, num_name:str):sql.execute("UPDATE clients SET num_name = ? WHERE id = ?", (num_name,id,))db.commit()def set_loc_num(numberPhone, location): temp = sql.execute("SELECT * FROM loc_num WHERE loc LIKE ?", (location,)).fetchone() if (temp is None):sql.execute("INSERT INTO loc_num(loc) VALUES (?)", (location,))db.commitsql.execute("UPDATE loc_num SET num = ? WHERE loc LIKE ?", (numberPhone, location))db.commit()#updatedef bot_complete_order(id:int):sql.execute("UPDATE orders SET status = ? WHERE id_order= ?", (status[1], id))db.commit()def accept_order(id:int):sql.execute("UPDATE orders SET status = ? WHERE id_order= ?", (status[2], id))db.commit()def complete_order(id:int):sql.execute("UPDATE orders SET status = ? WHERE id_order= ?", (status[3], id))db.commit()def cancel_order(id:int):sql.execute("UPDATE orders SET status = ? WHERE id_order= ?", (status[4], id))db.commit() temp = get_id_product_in_order(id) for row in temp: if (not row[0] is None):update_count_product(row[0], row[1])def client_cancel_odrer(id:int):sql.execute("UPDATE orders SET status = ? WHERE id_order= ?", (status[5], id))db.commit()def client_add_bonusese(id:int): temp = get_order_(id)id_client = 0 bonuses = 0 for row in temp: if (not(row[0] is None and row[1] is None)):id_client = row[1] bonuses = row[0] * conf.persent_bonussql.execute("UPDATE clients SET bonuses = bonuses + ? WHERE id = ?", (bonuses, id_client))db.commit() return id_client, bonusesdef increase_bonuses(id_client:int, sign:int):sql.execute("UPDATE clients SET bonuses = bonuses + ? WHERE id = ?", (sign, id_client))db.commit()def update_product(id:int, count:int):sql.execute("UPDATE products SET count = ? WHERE id = ?", (count, id))db.commit()def delete_prod (id:int):sql.execute("DELETE FROM products WHERE id = ?", (id,))db.commit()def delete_location_user(id:int):sql.execute("UPDATE clients SET location = NULL WHERE id = ?", (id,))db.commit()def delete_orders_0():list_id_orders = sql.execute("SELECT id_order FROM orders WHERE status like ?", (status[0],)).fetchall()rtn = [] for id in list_id_orders:rtn.append(get_id_user(id[0])) temp = get_id_product_in_order(id[0]) for row in temp: if (not row[0] is None):update_count_product(row[0], row[1])sql.execute("DELETE FROM orders WHERE status LIKE ?", (status[0],))db.commit() return rtndef set_state_user(id, state):sql.execute("UPDATE clients SET state = ? WHERE id = ?", (state, id))db.commit()def set_time_loc(location, times):sql.execute("UPDATE loc_num SET time = ? WHERE loc like ?", (times, location))db.commit()#Геттерыdef get_username_client(id:int): temp = sql.execute("SELECT username FROM clients WHERE id = (?)", (id,)).fetchone() if (temp is None): return None for row in temp: return rowdef get_location_user(id:int): temp = sql.execute("SELECT location FROM clients WHERE id = (?)", (id,)).fetchone() if (temp is None): return None for row in temp: return rowdef get_all_products(): return sql.execute("SELECT * FROM products").fetchall()def get_location_products(location): return sql.execute("SELECT * FROM products WHERE location LIKE ? AND count > 0 ORDER BY type", (location,)).fetchall()def get_all_location_products(location): return sql.execute("SELECT * FROM products WHERE location LIKE ?", (location,)).fetchall()def get_count_orders_client(id:int): return sql.execute("SELECT count_orders, count_cancel_orders FROM clients WHERE id = ?", (id,))def get_product(id:int): return sql.execute("SELECT * FROM products WHERE id = ?", (id,)).fetchone()def get_products_category_location(category, location): return sql.execute("SELECT * FROM products WHERE type LIKE ? AND location LIKE ? AND count>0", (category, location)).fetchall()def get_positive_category_in_location(location): return sql.execute("SELECT DISTINCT type FROM products WHERE location LIKE '" + location + "' AND count > 0").fetchall()def get_category_in_location(location): return sql.execute("SELECT DISTINCT type FROM products WHERE location LIKE '" + location + "'").fetchall()def get_empty_category_in_location(location): return sql.execute("SELECT type FROM products WHERE count = 0 AND type != (SELECT type FROM products WHERE location LIKE '" + location + "' AND count > 0);")def get_orders(id:int): return sql.execute("SELECT id_order, SUM(cost),status , date FROM orders WHERE id_client = ? AND status NOT LIKE ? GROUP BY id_order", (id, status['not_like'])).fetchall()def get_active_orders(location): return sql.execute("SELECT id_order, SUM(cost) FROM orders WHERE location LIKE ? and status LIKE ? GROUP BY id_order", (location, status[1])).fetchall()def get_order_(id:int): return sql.execute("SELECT SUM(cost), id_client FROM orders WHERE id_order = ?", (id,))def get_all_location(): return sql.execute("SELECT DISTINCT location FROM products").fetchall()def get_id_admins(location): temp = sql.execute("SELECT id FROM clients WHERE state LIKE 'admin' and location LIKE ?", (location,)).fetchall()rtn = [] for row in temp:rtn.append(row[0]) return rtndef get_comm_order(id:int): temp = sql.execute("SELECT comm FROM order_comm WHERE id_order = ?", (id,)).fetchone() if (temp is None): return None for row in temp: return rowdef get_active_product_order(id:int): return sql.execute("SELECT name, counts FROM orders, products WHERE id = id_product and id_order = ?", (id,)).fetchall()def get_num_name(id:int):sql.execute("SELECT num_name FROM clients WHERE id = ?", (str(id),)) temp = sql.fetchone() if (temp is None): return None for row in temp: return rowdef get_id_user(id): temp = sql.execute("SELECT id_client FROM orders WHERE id_order = ?", (id,)).fetchone() if (temp is None): return None for row in temp: return rowdef get_info_client(id:int): return sql.execute("SELECT bonuses, count_orders FROM clients WHERE id = (?)", (id,)).fetchall()def get_bot_complete(id:int): return sql.execute("SELECT id_order, SUM(cost) FROM orders WHERE id_client = ? AND status = ?", (id, status[1])).fetchall()def get_num_loc(location:str): temp = sql.execute("SELECT num FROM loc_num WHERE loc LIKE ?", (location,)) temp = sql.fetchone() if (temp is None): return None for row in temp: return rowdef get_time_loc(location): temp = sql.execute("SELECT time FROM loc_num WHERE loc like ?", (location,)).fetchone() return temp[0]def get_id_product_in_order(id:int): return sql.execute("SELECT id_product, counts FROM orders WHERE id_order = ?", (id,)).fetchall()def get_all_id_clients(): temp = sql.execute("SELECT id FROM clients").fetchall()rtn = [] for i in temp:rtn.append(i[0]) return rtn#booldef new_user(id:int): temp = sql.execute("SELECT id FROM clients WHERE id = " + str(id)).fetchone() if temp is None: return True else: return Falsedef check_location_user(id:int):temp =get_location_user(id) if (temp is None): return True return Falsedef check_order(id:int): temp = sql.execute("SELECT id_order FROM orders WHERE id_order = (?)", (id,)).fetchone() if (temp is None): return True return Falsedef check_num(id:int): temp = sql.execute("SELECT num_name FROM clients WHERE id = (?)", (id,)).fetchone() for row in temp: if row is None: return True else: return False#raffledef get_ticket(first_name): temp = sql.execute("SELECT ticket FROM raffle WHERE user LIKE ?", (first_name,)) for c in temp: return int(c[0])def add_new_ticket(last_name): temp = 0max_id = sql.execute("SELECT MAX(ticket) FROM raffle").fetchone() for row in max_id: if (not(row is None)): temp = rowmax_id = temp + 1sql.execute("INSERT INTO raffle VALUES(?, ?)", (last_name, max_id))db.commit()def check_ticket(last_name): temp = sql.execute("SELECT ticket FROM raffle WHERE user = ?", (last_name,)).fetchone() if (temp is None): return True else: return Falsedef get_all_ticket(): return sql.execute("SELECT * FROM raffle").fetchall()def new_raffle():sql.execute("UPDATE booling SET raffle = 1")db.commit()def close_raffle():sql.execute("UPDATE booling SET raffle = 0")db.commit()def delete_raffle():sql.execute("DELETE FROM raffle")db.commit()def check_raffle(): temp = sql.execute("SELECT raffle FROM booling").fetchone() for i in temp: if (temp[0]): return True else: return Falsedef report_moth(date, location): date = "2022-" + date + "%"rtn = [sql.execute("SELECT SUM(cnt), SUM(pr), AVG(vg) FROM (SELECT COUNT(DISTINCT id_order) as cnt, SUM(cost) as pr, AVG(cost) as vg FROM orders WHERE date LIKE ? and status LIKE ? and location LIKE ? GROUP BY date ) as a", (date, status[3], location)).fetchone()] rtn.append(sql.execute("SELECT name, SUM(counts) as top FROM orders, products WHERE id = id_product and date like ? and orders.location like ? and status like ? GROUP BY id_product ORDER BY top DESC", (date, location, status[3]))) return rtndef report_all(location): return sql.execute("SELECT SUM(cnt), SUM(pr), AVG(vg) FROM (SELECT COUNT(DISTINCT id_order) as cnt, SUM(cost) as pr, AVG(cost) as vg FROM orders WHERE status LIKE ? and location LIKE ? GROUP BY date ) as a", (status[3], location)).fetchone()#Testsid_cl = 470070588id_pr = 4cnt = 100num = 540long_str = "Juja, Puja, Check"one_str = ["One", "Two", "Three"]Список литературыhttps://clck.ru/3467Sj - web-сервер глазами хакера 3-е издание Михаил Фленовhttps://otherreferats.allbest.ru/programming/00135445_0.html - хороший курсачhttps://owasp.org/www-pdf-archive/WPstats_fall09_8th.pdf
https://otherreferats.allbest.ru/programming/00135445_0.html - хороший курсач
https://owasp.org/www-pdf-archive/WPstats_fall09_8th.pdf