Запись для виджета весов в redis
This commit is contained in:
parent
7b2b651f23
commit
dbcce9e737
@ -32,11 +32,7 @@ FROM python:3.10
|
||||
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"]
|
||||
RUN addgroup --system app && adduser --system --group app
|
||||
|
||||
# create the appropriate directories
|
||||
ENV HOME=/home/app
|
||||
|
||||
@ -1,165 +0,0 @@
|
||||
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
|
||||
@ -1,3 +1,5 @@
|
||||
import logging
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from django.db.models import QuerySet
|
||||
@ -5,9 +7,12 @@ from django.db.models import QuerySet
|
||||
from apps.main.services.base_service import DashboardBaseService
|
||||
from apps.util.redis_api import RedisService
|
||||
|
||||
from repcofkk.settings import REDIS_HOST, REDIS_PORT
|
||||
|
||||
|
||||
class RedisRepository(DashboardBaseService):
|
||||
def __init__(self, fabric_goal: str, control_conveyor_month: str, service: RedisService):
|
||||
def __init__(self, control_conveyor_month: str, fabric_goal: str,
|
||||
service: RedisService = RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1)):
|
||||
self.fabric_goal = fabric_goal
|
||||
self.control_conveyor_month = control_conveyor_month
|
||||
self.service = service
|
||||
@ -19,15 +24,150 @@ class RedisRepository(DashboardBaseService):
|
||||
latest_date = None
|
||||
with self.service as redis_service:
|
||||
for position in positions:
|
||||
position_value = redis_service.hget_value(f'{position.tag}.{interval}', 'Value')
|
||||
position_date_str = redis_service.hget_value(f'{position.tag}.{interval}', 'Date')
|
||||
position_date = datetime.strptime(position_date_str, "%Y-%m-%d %H:%M:%S.%f")
|
||||
try:
|
||||
if position.tag == 'SIEMENSPLC.AZG01.ReportProdDB.ProdPos13':
|
||||
pass
|
||||
position_value = redis_service.hget_value(f'{position.tag}.{interval}', 'Value')
|
||||
if position_value is None:
|
||||
position_value = "0"
|
||||
position_date_str = redis_service.hget_value(f'{position.tag}.{interval}', 'Date')
|
||||
if position_date_str is not None:
|
||||
position_date = datetime.strptime(position_date_str, "%Y-%m-%d %H:%M:%S.%f")
|
||||
|
||||
scales[position.title] = position_value if position_value >= 0 else 0
|
||||
|
||||
if latest_date:
|
||||
if latest_date < position_date:
|
||||
scales[position.title] = int(float(position_value)) if int(float(position_value)) >= 0 else 0
|
||||
if latest_date:
|
||||
if latest_date < position_date:
|
||||
latest_date = position_date
|
||||
else:
|
||||
latest_date = position_date
|
||||
else:
|
||||
latest_date = position_date
|
||||
except KeyError:
|
||||
scales[position.position.title] = '0'
|
||||
try:
|
||||
res["scales"] = scales
|
||||
res["percent_values"] = self.get_percent_values(
|
||||
scales["Поз. 13"], scales["Поз. 22"], scales["Поз. 4"]
|
||||
)
|
||||
res["latest_date"] = latest_date
|
||||
except AttributeError:
|
||||
res["latest_date"] = None
|
||||
finally:
|
||||
return res
|
||||
|
||||
def get_scales_value_by_shifts(self, positions: QuerySet, interval: str) -> dict:
|
||||
res = {}
|
||||
current_work_shift = {}
|
||||
previous_work_shift = {}
|
||||
latest_previous_shift_date = None
|
||||
latest_current_shift_date = None
|
||||
percent_values = {}
|
||||
with self.service as redis_service:
|
||||
for position in positions:
|
||||
previous_shift_tag = self.get_shift_tag(
|
||||
position, interval, is_current=False
|
||||
)
|
||||
try:
|
||||
previous_value = int(float(redis_service.hget_value(previous_shift_tag, 'Value')))
|
||||
previous_date_str = redis_service.hget_value(previous_shift_tag, 'Date')
|
||||
previous_date = datetime.strptime(previous_date_str, "%Y-%m-%d %H:%M:%S.%f")
|
||||
previous_work_shift[position.title] = previous_value
|
||||
except KeyError:
|
||||
previous_work_shift[position.title] = '0'
|
||||
logging.error(traceback.format_exc())
|
||||
|
||||
if latest_previous_shift_date:
|
||||
if previous_date and latest_previous_shift_date < previous_date:
|
||||
latest_previous_shift_date = previous_date
|
||||
else:
|
||||
latest_previous_shift_date = previous_date
|
||||
|
||||
try:
|
||||
current_shift_tag = self.get_shift_tag(position, interval, is_current=True)
|
||||
current_value = int(float(redis_service.hget_value(current_shift_tag, 'Value')))
|
||||
current_date_str = redis_service.hget_value(current_shift_tag, 'Date')
|
||||
current_date = datetime.strptime(current_date_str, "%Y-%m-%d %H:%M:%S.%f")
|
||||
current_work_shift[position.title] = current_value
|
||||
except KeyError:
|
||||
current_work_shift[position.title] = '0'
|
||||
logging.error(traceback.format_exc())
|
||||
if latest_current_shift_date:
|
||||
if current_date and latest_current_shift_date < current_date:
|
||||
latest_current_shift_date = current_date
|
||||
else:
|
||||
latest_current_shift_date = current_date
|
||||
|
||||
percent_values["current_shift"] = self.get_percent_values(
|
||||
current_work_shift["Поз. 13"],
|
||||
current_work_shift["Поз. 22"],
|
||||
current_work_shift["Поз. 4"],
|
||||
)
|
||||
percent_values["previous_shift"] = self.get_percent_values(
|
||||
previous_work_shift["Поз. 13"],
|
||||
previous_work_shift["Поз. 22"],
|
||||
previous_work_shift["Поз. 4"],
|
||||
)
|
||||
|
||||
res["percent_values"] = percent_values
|
||||
|
||||
res["previous_work_shift"] = previous_work_shift
|
||||
res["current_work_shift"] = current_work_shift
|
||||
|
||||
if latest_previous_shift_date and latest_current_shift_date:
|
||||
res["latest_date"] = (
|
||||
latest_current_shift_date
|
||||
if latest_previous_shift_date < latest_current_shift_date
|
||||
else latest_previous_shift_date
|
||||
)
|
||||
else:
|
||||
res["latest_date"] = (
|
||||
latest_current_shift_date
|
||||
if latest_current_shift_date
|
||||
else None
|
||||
)
|
||||
|
||||
return res
|
||||
|
||||
def get_scales_value_with_plan(self):
|
||||
with self.service as redis_service:
|
||||
try:
|
||||
scales_value = int(float(redis_service.hget_value(self.control_conveyor_month, 'Value')))
|
||||
except KeyError:
|
||||
return {"value": 0, "percent": 0, "goal": 0}
|
||||
planned_value = int(self.fabric_goal)
|
||||
percent = str(round(scales_value * 100 / int(planned_value))) + "%"
|
||||
return {"value": scales_value, "percent": percent, "goal": planned_value}
|
||||
|
||||
@staticmethod
|
||||
def get_percent_values(pos13_value: int, pos22_value: int, pos4_value: int) -> dict:
|
||||
"""
|
||||
Формула для вычисления Y отсева:
|
||||
Поз.13 * 100 / Поз.4
|
||||
|
||||
Формула для вычисления Y концентрата:
|
||||
Поз.22 * 100 / Поз.4
|
||||
"""
|
||||
try:
|
||||
concentrate = round(int(pos22_value) * 100 / int(pos4_value))
|
||||
except ZeroDivisionError:
|
||||
concentrate = 0
|
||||
try:
|
||||
dropout = round(int(pos13_value) * 100 / int(pos4_value))
|
||||
except ZeroDivisionError:
|
||||
dropout = 0
|
||||
return {
|
||||
"Y к-та": concentrate,
|
||||
"Y отсева": dropout,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def get_shift_tag(position, interval, is_current):
|
||||
"""
|
||||
Получает тег смены для заданной позиции в зависимости от интервала и типа смены.
|
||||
"""
|
||||
if is_current:
|
||||
return position.aver_smena_tag if interval == "Aver" else position.smena_tag
|
||||
else:
|
||||
return (
|
||||
position.aver_pred_smena_tag
|
||||
if interval == "Aver"
|
||||
else position.pred_smena_tag
|
||||
)
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
from django.http import JsonResponse
|
||||
|
||||
from apps.main.models.scales_control import ScalesControl, Position
|
||||
from apps.main.services.scales_control.redis_repository import RedisRepository
|
||||
from apps.main.services.scales_control.service import ScalesControlService
|
||||
from apps.util.base_view import base_view
|
||||
from sabron.util.sabronmodule import get_settings
|
||||
@ -10,7 +11,7 @@ from sabron.util.sabronmodule import get_settings
|
||||
def get_scales_data(request):
|
||||
control_conveyor_month = get_settings("conveyor_month")
|
||||
fabric_goal = get_settings("fabric_goal")
|
||||
service = ScalesControlService(control_conveyor_month, fabric_goal)
|
||||
service = RedisRepository(control_conveyor_month, fabric_goal)
|
||||
positions = Position.objects.order_by("id")
|
||||
monthly = service.get_scales_value(positions, "Month")
|
||||
average = service.get_scales_value_by_shifts(positions, "Aver")
|
||||
|
||||
@ -15,6 +15,8 @@ from psycopg2 import OperationalError
|
||||
from apps.main.models.scales_control import ScalesControl, Position
|
||||
from apps.main.models.worktime import FabricWorkTime
|
||||
from apps.main.services.base_service import DashboardBaseService
|
||||
from apps.util.redis_api import RedisService
|
||||
from repcofkk.production_settings import REDIS_HOST, REDIS_PORT
|
||||
from sabron.util import logging
|
||||
from sabron.util.sabronmodule import get_settings
|
||||
|
||||
@ -68,18 +70,32 @@ def create_worktime_data() -> int:
|
||||
)
|
||||
current_record = record
|
||||
return "Success"
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logging.error(traceback.format_exc())
|
||||
return "Exception"
|
||||
return f"Exception: {e}"
|
||||
|
||||
|
||||
@shared_task
|
||||
def create_scales_control_data():
|
||||
scales_data = get_scales_data()
|
||||
scales_data = get_scales_data(1500)
|
||||
res = write_scales_data(scales_data)
|
||||
return res
|
||||
|
||||
|
||||
@shared_task
|
||||
def write_scale_control_data_to_redis():
|
||||
try:
|
||||
data = get_scales_data(1000)
|
||||
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service:
|
||||
for row in data:
|
||||
redis_service.hset_value(row[0], key='Value', value=str(row[1]))
|
||||
redis_service.hset_value(row[0], key='Date', value=str(row[2]))
|
||||
return 'Success'
|
||||
except Exception as e:
|
||||
logging.error('CELERY' + traceback.format_exc())
|
||||
return str(e)
|
||||
|
||||
|
||||
@shared_task
|
||||
def thin_out_scales():
|
||||
positions = Position.objects.all()
|
||||
@ -155,14 +171,14 @@ def thin_out_scale(tag) -> bool | int:
|
||||
return len(to_delete)
|
||||
|
||||
|
||||
def get_scales_data() -> bool | list:
|
||||
def get_scales_data(limit: int = 20000) -> 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(
|
||||
@ -170,9 +186,9 @@ def get_scales_data() -> bool | list:
|
||||
SELECT "Name", "Values", "Date", "Check"
|
||||
FROM public.vesi
|
||||
ORDER BY id DESC
|
||||
LIMIT 1000;
|
||||
LIMIT %s;
|
||||
"""
|
||||
)
|
||||
, (limit,))
|
||||
data = cursor.fetchall()
|
||||
return data[::-1]
|
||||
except OperationalError:
|
||||
@ -184,11 +200,11 @@ def write_scales_data(data: list):
|
||||
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:
|
||||
|
||||
@ -1,14 +1,9 @@
|
||||
import datetime
|
||||
from typing import Union, Optional, Dict
|
||||
|
||||
import redis
|
||||
|
||||
from create_scale_control_data import get_scales_data
|
||||
from sabron.util import logging
|
||||
|
||||
REDIS_HOST = 'localhost'
|
||||
REDIS_PORT = '6379'
|
||||
|
||||
|
||||
class RedisBaseService:
|
||||
"""
|
||||
@ -70,7 +65,7 @@ class RedisSimpleService(RedisBaseService):
|
||||
logging.error(f"Error setting value: {e}")
|
||||
return False
|
||||
|
||||
def get_value(self, key: str) -> Optional[str]:
|
||||
def get_value(self, key: str) -> str | None:
|
||||
"""
|
||||
Получает значение из Redis по ключу.
|
||||
|
||||
@ -79,8 +74,10 @@ class RedisSimpleService(RedisBaseService):
|
||||
"""
|
||||
try:
|
||||
value = self.connection.get(key)
|
||||
if value is None:
|
||||
raise KeyError
|
||||
return value.decode('utf-8')
|
||||
except redis.RedisError as e:
|
||||
except (redis.RedisError, AttributeError) as e:
|
||||
print(f"Error getting value: {e}")
|
||||
logging.error(e)
|
||||
return None
|
||||
@ -165,11 +162,3 @@ class RedisHashService(RedisBaseService):
|
||||
|
||||
class RedisService(RedisHashService, RedisSimpleService):
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
data = get_scales_data(1000)
|
||||
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service:
|
||||
for row in data:
|
||||
redis_service.hset_value(row[0], key='Value', value=str(row[1]))
|
||||
redis_service.hset_value(row[0], key='Date', value=str(row[2]))
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
python manage.py makemigrations --noinput
|
||||
python manage.py migrate --noinput
|
||||
|
||||
exec "$@"
|
||||
@ -3,27 +3,32 @@ import traceback
|
||||
from datetime import datetime
|
||||
|
||||
import psycopg2
|
||||
from psycopg2 import OperationalError
|
||||
|
||||
|
||||
# Подключение к первой базе данных
|
||||
def get_scales_data(limit: int = 20000) -> list:
|
||||
conn_postgres = psycopg2.connect(
|
||||
dbname="vesi_db",
|
||||
user="ktp_user",
|
||||
password="rb,thrjl",
|
||||
host="192.168.10.2",
|
||||
port="5432",
|
||||
)
|
||||
|
||||
with conn_postgres.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT "Name", "Values", "Date", "Check"
|
||||
FROM public.vesi
|
||||
ORDER BY id DESC
|
||||
LIMIT %s;
|
||||
"""
|
||||
, (limit,))
|
||||
try:
|
||||
with psycopg2.connect(
|
||||
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(
|
||||
"""
|
||||
SELECT "Name", "Values", "Date", "Check"
|
||||
FROM public.vesi
|
||||
ORDER BY id DESC
|
||||
LIMIT %s;
|
||||
"""
|
||||
, (limit,))
|
||||
data = cursor.fetchall()
|
||||
return data[::-1]
|
||||
except OperationalError:
|
||||
return None
|
||||
|
||||
|
||||
def write_scales_data(data: list):
|
||||
|
||||
@ -30,7 +30,7 @@ services:
|
||||
|
||||
celery:
|
||||
build: ./app
|
||||
command: celery -A repcofkk worker -l info
|
||||
command: celery -A repcofkk worker --autoscale=10,3 -l info
|
||||
volumes:
|
||||
- code_volume:/home/app/web/
|
||||
env_file:
|
||||
|
||||
@ -3,7 +3,12 @@ version: '3.9'
|
||||
services:
|
||||
web:
|
||||
build: ./app
|
||||
command: gunicorn --workers=2 repcofkk.wsgi:application --bind 0.0.0.0:8000
|
||||
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:
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user