108 lines
5.6 KiB
Python
108 lines
5.6 KiB
Python
import sqlite3
|
||
import logging
|
||
from threading import Lock
|
||
|
||
db_lock = Lock()
|
||
|
||
# Инициализируем логгер
|
||
logger = logging.getLogger(__name__)
|
||
logger.setLevel(logging.DEBUG) # Устанавливаем уровень логирования
|
||
|
||
|
||
class RegionAPI:
|
||
def __init__(self, db_path):
|
||
self.db_path = db_path
|
||
|
||
def add_region(self, region_id: int, region_name: str):
|
||
logger.info(f"Запрос на добавление региона: id={region_id}, name={region_name}")
|
||
|
||
# Проверка валидности region_id
|
||
if not str(region_id).isdigit():
|
||
logger.error(f"region_id {region_id} не является числом.")
|
||
return {"status": "failure", "message": "Region_id must be digit only"}
|
||
|
||
with db_lock, sqlite3.connect(self.db_path) as conn:
|
||
cursor = conn.cursor()
|
||
logger.debug(f"Проверка существования региона с id={region_id}")
|
||
cursor.execute('SELECT COUNT(*) FROM regions WHERE region_id = ?', (region_id,))
|
||
count = cursor.fetchone()[0]
|
||
|
||
if count == 0:
|
||
# Добавляем новый регион
|
||
cursor.execute('INSERT INTO regions (region_id, region_name, active) VALUES (?, ?, 1)',
|
||
(region_id, region_name))
|
||
conn.commit()
|
||
logger.info(f"Регион с id={region_id} успешно добавлен.")
|
||
return {"status": "success", "message": "Region added successfully"}
|
||
else:
|
||
logger.warning(f"Регион с id={region_id} уже существует.")
|
||
return {"status": "error", "message": "Region already exists"}
|
||
|
||
def remove_region(self, region_id):
|
||
logger.info(f"Запрос на удаление региона: id={region_id}")
|
||
|
||
with db_lock, sqlite3.connect(self.db_path) as conn:
|
||
cursor = conn.cursor()
|
||
logger.debug(f"Проверка существования региона с id={region_id}")
|
||
cursor.execute('SELECT COUNT(*) FROM regions WHERE region_id = ?', (region_id,))
|
||
count = cursor.fetchone()[0]
|
||
|
||
if count == 0:
|
||
logger.warning(f"Регион с id={region_id} не найден.")
|
||
return {"status": "error", "message": "Region not found"}
|
||
else:
|
||
cursor.execute('DELETE FROM regions WHERE region_id = ?', (region_id,))
|
||
conn.commit()
|
||
logger.info(f"Регион с id={region_id} успешно удалён.")
|
||
return {"status": "success", "message": "Region removed successfully"}
|
||
|
||
def get_regions(self):
|
||
logger.info("Запрос на получение списка регионов.")
|
||
|
||
with db_lock, sqlite3.connect(self.db_path) as conn:
|
||
cursor = conn.cursor()
|
||
logger.debug("Извлечение данных из таблицы regions.")
|
||
cursor.execute('SELECT region_id, region_name, active FROM regions')
|
||
regions = cursor.fetchall()
|
||
logger.info(f"Получено {len(regions)} регионов.")
|
||
return [{"region_id": r[0], "region_name": r[1], "regions_active": r[2]} for r in regions]
|
||
|
||
def change_region_status(self, region_id, active):
|
||
logger.info(f"Запрос на изменение статуса региона: id={region_id}, статус={active}")
|
||
|
||
with db_lock, sqlite3.connect(self.db_path) as conn:
|
||
cursor = conn.cursor()
|
||
logger.debug(f"Проверка существования региона с id={region_id}")
|
||
cursor.execute('SELECT COUNT(*) FROM regions WHERE region_id = ?', (region_id,))
|
||
count = cursor.fetchone()[0]
|
||
|
||
if count == 0:
|
||
logger.warning(f"Регион с id={region_id} не найден.")
|
||
return {"status": "error", "message": "Region not found"}
|
||
else:
|
||
cursor.execute('UPDATE regions SET active = ? WHERE region_id = ?', (active, region_id))
|
||
conn.commit()
|
||
logger.info(f"Статус региона с id={region_id} успешно изменён.")
|
||
return {"status": "success", "message": "Region status updated successfully"}
|
||
|
||
def update_region_status(self, region_id, active):
|
||
logger.info(f"Запрос на обновление статуса региона: id={region_id}, активность={active}")
|
||
|
||
with db_lock, sqlite3.connect(self.db_path) as conn:
|
||
cursor = conn.cursor()
|
||
|
||
# Проверяем существование региона
|
||
logger.debug(f"Проверка существования региона с id={region_id}")
|
||
cursor.execute("SELECT region_name FROM regions WHERE region_id = ?", (region_id,))
|
||
result = cursor.fetchone()
|
||
if not result:
|
||
logger.warning(f"Регион с id={region_id} не найден.")
|
||
return {"status": "error", "message": "Регион не найден"}
|
||
|
||
# Обновляем статус активности региона
|
||
cursor.execute("UPDATE regions SET active = ? WHERE region_id = ?", (int(active), region_id))
|
||
conn.commit()
|
||
action = "Активирован" if active else "Отключён"
|
||
logger.info(f"Регион с id={region_id} {action}.")
|
||
return {"status": "success", "message": f"Регион {region_id} {action}"}
|