Merge pull request 'Добавление индексов БД; Фиксы' (#10) from dev into main
Reviewed-on: http://git.hronos.su:8080/sabron/repcofkk/pulls/10
This commit is contained in:
commit
8962e67462
@ -33,7 +33,11 @@ RUN mkdir -p /home/app
|
||||
|
||||
# create the app user
|
||||
RUN addgroup --system app && adduser --system --group app
|
||||
|
||||
|
||||
COPY ./entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
|
||||
# create the appropriate directories
|
||||
ENV HOME=/home/app
|
||||
ENV APP_HOME=/home/app/web
|
||||
@ -42,7 +46,7 @@ RUN mkdir $APP_HOME/static
|
||||
WORKDIR $APP_HOME
|
||||
|
||||
# install dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends netcat-traditional
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends
|
||||
COPY --from=builder /usr/src/app/wheels /wheels
|
||||
COPY --from=builder /usr/src/app/requirements.txt .
|
||||
RUN pip install --upgrade pip
|
||||
|
||||
@ -12,9 +12,10 @@ class ScalesControl(models.Model):
|
||||
class Meta:
|
||||
verbose_name = "Показание весов"
|
||||
verbose_name_plural = "Показания весов"
|
||||
indexes = [
|
||||
models.Index(fields=["name", "value"]),
|
||||
]
|
||||
indexes = (
|
||||
models.Index(fields=["name"]),
|
||||
models.Index(fields=["name", "time"])
|
||||
)
|
||||
|
||||
def json(self):
|
||||
return {
|
||||
|
||||
@ -27,5 +27,9 @@ class FabricWorkTime(models.Model):
|
||||
verbose_name = "Время работы фабрики"
|
||||
verbose_name_plural = "Отрезки времени работы фабрики"
|
||||
|
||||
indexes = (
|
||||
models.Index(fields=["time"]),
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.time}: {self.status}"
|
||||
|
||||
@ -28,7 +28,9 @@ class DashboardBaseService:
|
||||
def get_shift_start(now_date: datetime):
|
||||
start_shift = now_date.replace(hour=8, minute=0, second=0, microsecond=0)
|
||||
if now_date.hour < 8:
|
||||
start_shift = now_date.replace(hour=20, minute=0, second=0, microsecond=0) - relativedelta(days=1)
|
||||
start_shift = now_date.replace(
|
||||
hour=20, minute=0, second=0, microsecond=0
|
||||
) - relativedelta(days=1)
|
||||
elif now_date.hour > 20:
|
||||
start_shift = now_date.replace(hour=20, minute=0, second=0, microsecond=0)
|
||||
return start_shift
|
||||
|
||||
165
app/apps/main/services/redis_service/service.py
Normal file
165
app/apps/main/services/redis_service/service.py
Normal file
@ -0,0 +1,165 @@
|
||||
from typing import Union, Optional, Dict
|
||||
|
||||
import redis
|
||||
|
||||
from sabron.util import logging
|
||||
|
||||
REDIS_HOST = 'localhost'
|
||||
REDIS_PORT = '6379'
|
||||
|
||||
|
||||
class RedisBaseService:
|
||||
"""
|
||||
Сервис для работы с БД Redis
|
||||
"""
|
||||
|
||||
def __init__(self, host: str, port: int, db: str):
|
||||
"""
|
||||
Инициализация сервиса Redis.
|
||||
|
||||
:param host: Адрес сервера Redis.
|
||||
:param port: Порт сервера Redis.
|
||||
:param db: Номер базы данных Redis.
|
||||
"""
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.db = db
|
||||
self.connection = self.open_connection()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.close_connection()
|
||||
|
||||
def open_connection(self):
|
||||
"""
|
||||
Устанавливает соединение с сервером Redis.
|
||||
|
||||
:return: Объект соединения Redis.
|
||||
"""
|
||||
return redis.Redis(host=self.host, port=self.port, db=self.db)
|
||||
|
||||
def close_connection(self):
|
||||
"""
|
||||
Закрывает соединение с Redis
|
||||
Returns:
|
||||
|
||||
"""
|
||||
if self.connection:
|
||||
self.connection.close()
|
||||
|
||||
|
||||
class RedisSimpleService(RedisBaseService):
|
||||
"""Класс для работы с обычными Redis значениями (str)"""
|
||||
|
||||
def set_value(self, key: str, value: Union[bytes, str, int, float]):
|
||||
"""
|
||||
Устанавливает значение в Redis по ключу.
|
||||
|
||||
:param key: Ключ, под которым сохраняется значение.
|
||||
:param value: Значение, которое нужно сохранить.
|
||||
:return: True, если значение успешно сохранено.
|
||||
"""
|
||||
try:
|
||||
self.connection.set(key, value)
|
||||
return True
|
||||
except redis.RedisError as e:
|
||||
logging.error(f"Error setting value: {e}")
|
||||
return False
|
||||
|
||||
def get_value(self, key: str) -> Optional[str]:
|
||||
"""
|
||||
Получает значение из Redis по ключу.
|
||||
|
||||
:param key: Ключ, по которому нужно получить значение.
|
||||
:return: Значение в виде строки или None, если ключ не найден.
|
||||
"""
|
||||
try:
|
||||
value = self.connection.get(key)
|
||||
return value.decode('utf-8')
|
||||
except redis.RedisError as e:
|
||||
print(f"Error getting value: {e}")
|
||||
logging.error(e)
|
||||
return None
|
||||
|
||||
def delete_value(self, key: str):
|
||||
"""
|
||||
Удаляет значение в Redis по ключу.
|
||||
|
||||
:param key: Ключ, который нужно удалить.
|
||||
:return: True, если значение успешно удалено.
|
||||
"""
|
||||
try:
|
||||
self.connection.delete(key)
|
||||
return True
|
||||
except redis.RedisError as e:
|
||||
print(f"Error deleting value: {e}")
|
||||
logging.error(e)
|
||||
return False
|
||||
|
||||
|
||||
class RedisHashService(RedisBaseService):
|
||||
def hset_value(self, name: str, key: str, value: Union[bytes, str, int, float]) -> bool:
|
||||
"""
|
||||
Устанавливает значение в хэш по ключу.
|
||||
|
||||
:param name: Имя хэша.
|
||||
:param key: Ключ в хэше.
|
||||
:param value: Значение, которое нужно сохранить.
|
||||
:return: True, если значение успешно сохранено.
|
||||
"""
|
||||
try:
|
||||
self.connection.hset(name, key, value)
|
||||
return True
|
||||
except redis.RedisError as e:
|
||||
print(f"Error setting hash value: {e}")
|
||||
return False
|
||||
|
||||
def hget_value(self, name: str, key: str) -> Optional[str]:
|
||||
"""
|
||||
Получает значение из хэша по ключу.
|
||||
|
||||
:param name: Имя хэша.
|
||||
:param key: Ключ в хэше.
|
||||
:return: Значение в виде строки или None, если ключ не найден.
|
||||
"""
|
||||
try:
|
||||
value = self.connection.hget(name, key)
|
||||
return value.decode('utf-8') if value else None
|
||||
except redis.RedisError as e:
|
||||
print(f"Error getting hash value: {e}")
|
||||
return None
|
||||
|
||||
def hdel_value(self, name: str, key: str) -> bool:
|
||||
"""
|
||||
Удаляет значение из хэша по ключу.
|
||||
|
||||
:param name: Имя хэша.
|
||||
:param key: Ключ в хэше, который нужно удалить.
|
||||
:return: True, если значение успешно удалено.
|
||||
"""
|
||||
try:
|
||||
self.connection.hdel(name, key)
|
||||
return True
|
||||
except redis.RedisError as e:
|
||||
print(f"Error deleting hash value: {e}")
|
||||
return False
|
||||
|
||||
def hget_all(self, name: str) -> Optional[Dict[str, str]]:
|
||||
"""
|
||||
Получает все ключи и значения из хэша.
|
||||
|
||||
:param name: Имя хэша.
|
||||
:return: Словарь всех ключей и значений хэша или None, если хэш не найден.
|
||||
"""
|
||||
try:
|
||||
result = self.connection.hgetall(name)
|
||||
return {k.decode('utf-8'): v.decode('utf-8') for k, v in result.items()} if result else None
|
||||
except redis.RedisError as e:
|
||||
print(f"Error getting all hash values: {e}")
|
||||
return None
|
||||
|
||||
|
||||
class RedisService(RedisHashService, RedisSimpleService):
|
||||
pass
|
||||
@ -15,9 +15,6 @@ class WorkStatusService(DashboardBaseService):
|
||||
return {"last_status": "ND", "worktime": timedelta(0)}
|
||||
last_status = status_list[-1]
|
||||
if last_status["time"] < (self.get_current_time() - timedelta(minutes=5)):
|
||||
logging.message(
|
||||
f"Fabric Stopped {self.get_current_time()} ({self.get_current_time() - timedelta(minutes=5)})"
|
||||
)
|
||||
return {
|
||||
"last_status": "NW",
|
||||
"worktime": self.get_current_time() - last_status["time"],
|
||||
|
||||
@ -11,12 +11,8 @@ class FabricWorkTimeService(DashboardBaseService):
|
||||
@classmethod
|
||||
def calculate_work_time(cls, qs: list, return_duration: bool = False) -> dict:
|
||||
status_durations = {"WO": timedelta(0), "WA": timedelta(0), "NW": timedelta(0)}
|
||||
time_now = cls.get_current_time()
|
||||
if not qs:
|
||||
return {"WO": 0, "WA": 0, "NW": 0} if not return_duration else {"WO": "P0DT00H00M00S",
|
||||
"WA": "P0DT00H00M00S",
|
||||
"NW": time_now - cls.get_shift_start(
|
||||
time_now)}
|
||||
return
|
||||
|
||||
previous_time = qs[0]["time"]
|
||||
previous_status = qs[0]["status"]
|
||||
@ -34,7 +30,7 @@ class FabricWorkTimeService(DashboardBaseService):
|
||||
now_date = cls.get_current_time()
|
||||
duration = now_date - previous_time
|
||||
if duration.seconds // 60 > 5:
|
||||
status_durations['NW'] += duration
|
||||
status_durations["NW"] += duration
|
||||
else:
|
||||
status_durations[previous_status] += duration
|
||||
if return_duration:
|
||||
@ -59,13 +55,34 @@ class FabricWorkTimeService(DashboardBaseService):
|
||||
start_week = now_date - relativedelta(hours=168)
|
||||
start_shift = self.get_shift_start(now_date)
|
||||
monthly_qs = self.get_qs_by_range(start_month, now_date)
|
||||
monthly = self.calculate_work_time(list(monthly_qs), return_durations)
|
||||
if not monthly_qs:
|
||||
monthly = {"WO": 0, "WA": 0, "NW": 0} if not return_durations else {
|
||||
"WO": "P0DT00H00M00S",
|
||||
"WA": "P0DT00H00M00S",
|
||||
"NW": now_date - start_month,
|
||||
}
|
||||
else:
|
||||
monthly = self.calculate_work_time(list(monthly_qs), return_durations)
|
||||
|
||||
weekly_qs = self.get_qs_by_range(start_week, now_date)
|
||||
weekly = self.calculate_work_time(list(weekly_qs), return_durations)
|
||||
if not weekly_qs:
|
||||
weekly = {"WO": 0, "WA": 0, "NW": 0} if not return_durations else {
|
||||
"WO": "P0DT00H00M00S",
|
||||
"WA": "P0DT00H00M00S",
|
||||
"NW": now_date - start_week,
|
||||
}
|
||||
else:
|
||||
weekly = self.calculate_work_time(list(monthly_qs), return_durations)
|
||||
|
||||
shift_qs = self.get_qs_by_range(start_shift, now_date)
|
||||
daily = self.calculate_work_time(list(shift_qs), return_durations)
|
||||
if not shift_qs:
|
||||
daily = {"WO": 0, "WA": 0, "NW": 0} if not return_durations else {
|
||||
"WO": "P0DT00H00M00S",
|
||||
"WA": "P0DT00H00M00S",
|
||||
"NW": now_date - self.get_shift_start(now_date),
|
||||
}
|
||||
else:
|
||||
daily = self.calculate_work_time(list(shift_qs), return_durations)
|
||||
return {
|
||||
"monthly": monthly,
|
||||
"weekly": weekly,
|
||||
|
||||
@ -40,7 +40,7 @@ def create_worktime_data() -> int:
|
||||
.distinct("time_minute")
|
||||
)
|
||||
if not latest_records:
|
||||
return 'No scales records'
|
||||
return "No scales records"
|
||||
current_record = latest_records[0]
|
||||
for record in latest_records[1:]:
|
||||
delta = (record.time - current_record.time).seconds / 60
|
||||
@ -67,10 +67,10 @@ def create_worktime_data() -> int:
|
||||
status=status,
|
||||
)
|
||||
current_record = record
|
||||
return 'Success'
|
||||
return "Success"
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return 'Exception'
|
||||
return "Exception"
|
||||
|
||||
|
||||
@shared_task
|
||||
@ -84,21 +84,23 @@ def create_scales_control_data():
|
||||
def thin_out_scales():
|
||||
positions = Position.objects.all()
|
||||
for position in positions:
|
||||
pos_tags = [position.aver_smena_tag,
|
||||
position.aver_pred_smena_tag,
|
||||
position.smena_tag,
|
||||
position.pred_smena_tag,
|
||||
position.month_tag,
|
||||
position.sutki_tag]
|
||||
pos_tags = [
|
||||
position.aver_smena_tag,
|
||||
position.aver_pred_smena_tag,
|
||||
position.smena_tag,
|
||||
position.pred_smena_tag,
|
||||
position.month_tag,
|
||||
position.sutki_tag,
|
||||
]
|
||||
results = []
|
||||
for tag in pos_tags:
|
||||
try:
|
||||
res = thin_out_scale(tag)
|
||||
if not res:
|
||||
results.append({tag: 'No scales Data'})
|
||||
results.append({tag: "No scales Data"})
|
||||
results.append({tag: res})
|
||||
except Exception:
|
||||
logging.error(f'Celery: {traceback.format_exc()} \n on tag {tag}')
|
||||
logging.error(f"Celery: {traceback.format_exc()} \n on tag {tag}")
|
||||
results.append({tag: {traceback.format_exc()}})
|
||||
return results
|
||||
|
||||
@ -109,19 +111,20 @@ def thin_out_worktime():
|
||||
time__lt=timezone.now() - timedelta(hours=12)
|
||||
).order_by("time")
|
||||
if not worktime_qs:
|
||||
return 'No worktime'
|
||||
return "No worktime"
|
||||
prev = worktime_qs[0]
|
||||
for cur_obj in worktime_qs[1:]:
|
||||
if cur_obj.status == prev.status:
|
||||
cur_obj.delete()
|
||||
prev = cur_obj
|
||||
return f'Success. Deleted: {len(worktime_qs)} rows'
|
||||
return f"Success. Deleted: {len(worktime_qs)} rows"
|
||||
|
||||
|
||||
def thin_out_scale(tag) -> bool | int:
|
||||
qs = list(
|
||||
ScalesControl.objects.filter(
|
||||
name=tag, time__lte=DashboardBaseService.get_current_time() - timedelta(hours=12)
|
||||
name=tag,
|
||||
time__lte=DashboardBaseService.get_current_time() - timedelta(hours=12),
|
||||
).order_by("time")
|
||||
)
|
||||
|
||||
@ -143,7 +146,9 @@ def thin_out_scale(tag) -> bool | int:
|
||||
continue
|
||||
first_in_range = rang.first()
|
||||
last_in_range = rang.last()
|
||||
to_delete = rang.exclude(time=first_in_range.time).exclude(time=last_in_range.time)
|
||||
to_delete = rang.exclude(time=first_in_range.time).exclude(
|
||||
time=last_in_range.time
|
||||
)
|
||||
to_delete.delete()
|
||||
current_obj = last_in_range
|
||||
i += 1
|
||||
@ -153,11 +158,11 @@ def thin_out_scale(tag) -> bool | int:
|
||||
def get_scales_data() -> bool | list:
|
||||
try:
|
||||
with psycopg2.connect(
|
||||
dbname="vesi_db",
|
||||
user="ktp_user",
|
||||
password="rb,thrjl",
|
||||
host="192.168.10.2",
|
||||
port="5432",
|
||||
dbname="vesi_db",
|
||||
user="ktp_user",
|
||||
password="rb,thrjl",
|
||||
host="192.168.10.2",
|
||||
port="5432",
|
||||
) as conn_postgres:
|
||||
with conn_postgres.cursor() as cursor:
|
||||
cursor.execute(
|
||||
@ -176,14 +181,14 @@ def get_scales_data() -> bool | list:
|
||||
|
||||
def write_scales_data(data: list):
|
||||
if not data:
|
||||
return 'No scales data'
|
||||
return "No scales data"
|
||||
try:
|
||||
with psycopg2.connect(
|
||||
dbname=os.environ.get("POSTGRES_DB", "repcofkk_db"),
|
||||
user=os.environ.get("POSTGRES_USER", "repcofkk_user"),
|
||||
password=os.environ.get("POSTGRES_PASSWORD", "Angstrem*45"),
|
||||
host=os.environ.get("POSTGRES_HOST", "127.0.0.1"),
|
||||
port="5432",
|
||||
dbname=os.environ.get("POSTGRES_DB", "repcofkk_db"),
|
||||
user=os.environ.get("POSTGRES_USER", "repcofkk_user"),
|
||||
password=os.environ.get("POSTGRES_PASSWORD", "Angstrem*45"),
|
||||
host=os.environ.get("POSTGRES_HOST", "127.0.0.1"),
|
||||
port="5432",
|
||||
) as postgres_conn:
|
||||
with postgres_conn.cursor() as cursor: # TODO при настройке ОПС на запись в БД - убрать первое условие
|
||||
for row in data:
|
||||
@ -227,7 +232,7 @@ def write_scales_data(data: list):
|
||||
),
|
||||
)
|
||||
postgres_conn.commit()
|
||||
return 'Success'
|
||||
return "Success"
|
||||
except Exception:
|
||||
logging.error("CELERY: " + traceback.format_exc())
|
||||
return traceback.format_exc()
|
||||
|
||||
6
app/entrypoint.sh
Normal file
6
app/entrypoint.sh
Normal file
@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
|
||||
python manage.py makemigrations --noinput
|
||||
python manage.py migrate --noinput
|
||||
|
||||
exec "$@"
|
||||
@ -16,7 +16,7 @@ INSTALLED_APPS = [
|
||||
"""Информация о приложении """
|
||||
SITE_TITLE = "Система отчетов"
|
||||
SITE_TITLE_S = "СиО"
|
||||
APP_VERSION = "0.5.2"
|
||||
APP_VERSION = "0.5.3"
|
||||
APP_VEK = "2024 г"
|
||||
APP_COPPIRIGHT = "Система отчетов"
|
||||
|
||||
|
||||
@ -12,16 +12,18 @@ def get_scales_data() -> list:
|
||||
user="ktp_user",
|
||||
password="rb,thrjl",
|
||||
host="192.168.10.2",
|
||||
port="5432"
|
||||
port="5432",
|
||||
)
|
||||
|
||||
with conn_postgres.cursor() as cursor:
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT "Name", "Values", "Date", "Check"
|
||||
FROM public.vesi
|
||||
ORDER BY id DESC
|
||||
LIMIT 20000;
|
||||
""")
|
||||
"""
|
||||
)
|
||||
|
||||
data = cursor.fetchall()
|
||||
|
||||
@ -35,13 +37,14 @@ def write_scales_data(data: list):
|
||||
user="repcofkk_user",
|
||||
password="Angstrem*45",
|
||||
host="127.0.0.1",
|
||||
port="5432"
|
||||
port="5432",
|
||||
)
|
||||
try:
|
||||
with postgres_conn.cursor() as cursor:
|
||||
for row in data:
|
||||
name, value, date, check = row
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
DO $$
|
||||
DECLARE
|
||||
value_exists BOOLEAN;
|
||||
@ -62,11 +65,9 @@ def write_scales_data(data: list):
|
||||
VALUES (%s, %s, %s, %s);
|
||||
END IF;
|
||||
END $$;
|
||||
""", (
|
||||
name, value,
|
||||
date, name, value,
|
||||
name, value, date, check
|
||||
))
|
||||
""",
|
||||
(name, value, date, name, value, name, value, date, check),
|
||||
)
|
||||
postgres_conn.commit()
|
||||
except Exception:
|
||||
print(traceback.format_exc())
|
||||
@ -86,5 +87,5 @@ def main():
|
||||
time.sleep(120)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -1,37 +1,32 @@
|
||||
version: '3.9'
|
||||
|
||||
services:
|
||||
# web:
|
||||
# build: ./app
|
||||
# command: >
|
||||
# sh -c "
|
||||
# python manage.py makemigrations --noinput &&
|
||||
# python manage.py migrate --noinput &&
|
||||
# gunicorn --workers=2 repcofkk.wsgi:application --bind 0.0.0.0:8000
|
||||
# "
|
||||
# ports:
|
||||
# - '8000:8000'
|
||||
# expose:
|
||||
# - 8000
|
||||
# env_file:
|
||||
# - .env
|
||||
# depends_on:
|
||||
# postgres:
|
||||
# condition: service_healthy
|
||||
# volumes:
|
||||
# - static_volume:/home/app/web/static/
|
||||
# - code_volume:/home/app/web/
|
||||
#
|
||||
# nginx:
|
||||
# build: ./nginx/dev
|
||||
# volumes:
|
||||
# - static_volume:/home/app/web/static/
|
||||
# ports:
|
||||
# - "80:80"
|
||||
# - "443:443"
|
||||
# depends_on:
|
||||
# web:
|
||||
# condition: service_started
|
||||
web:
|
||||
build: ./app
|
||||
command: gunicorn --workers=2 repcofkk.wsgi:application --bind 0.0.0.0:8000
|
||||
ports:
|
||||
- '8000:8000'
|
||||
expose:
|
||||
- 8000
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- static_volume:/home/app/web/static/
|
||||
- code_volume:/home/app/web/
|
||||
|
||||
nginx:
|
||||
build: ./nginx/dev
|
||||
volumes:
|
||||
- static_volume:/home/app/web/static/
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
depends_on:
|
||||
web:
|
||||
condition: service_started
|
||||
|
||||
celery:
|
||||
build: ./app
|
||||
|
||||
@ -3,12 +3,7 @@ version: '3.9'
|
||||
services:
|
||||
web:
|
||||
build: ./app
|
||||
command: >
|
||||
sh -c "
|
||||
python manage.py makemigrations --noinput &&
|
||||
python manage.py migrate --noinput &&
|
||||
gunicorn --workers=2 repcofkk.wsgi:application --bind 0.0.0.0:8000
|
||||
"
|
||||
command: gunicorn --workers=2 repcofkk.wsgi:application --bind 0.0.0.0:8000
|
||||
ports:
|
||||
- '8000:8000'
|
||||
expose:
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user