From dd8c9cd0bb33145117347964a3e554d95c65fc45 Mon Sep 17 00:00:00 2001 From: zakhy Date: Wed, 18 Sep 2024 13:04:42 +0700 Subject: [PATCH] =?UTF-8?q?=D0=BE=D0=B1=D1=89=D0=B8=D0=B9=20=D1=80=D0=B5?= =?UTF-8?q?=D1=84=D0=B0=D0=BA=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../services/scales_control/orm_repository.py | 0 app/apps/main/tasks.py | 211 ++++++++++-------- app/apps/main/urls.py | 2 +- 3 files changed, 123 insertions(+), 90 deletions(-) delete mode 100644 app/apps/main/services/scales_control/orm_repository.py diff --git a/app/apps/main/services/scales_control/orm_repository.py b/app/apps/main/services/scales_control/orm_repository.py deleted file mode 100644 index e69de29..0000000 diff --git a/app/apps/main/tasks.py b/app/apps/main/tasks.py index f8990b9..1c9b774 100644 --- a/app/apps/main/tasks.py +++ b/app/apps/main/tasks.py @@ -22,17 +22,125 @@ except ModuleNotFoundError: from repcofkk.production_settings import REDIS_HOST, REDIS_PORT -def get_scales_data_from_redis(tag: str = get_settings('control_conveyor')): - with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service: - # Получение объекта из Redis с последней актуальной записью по управляющему конвейеру - value = redis_service.hget_value(tag, 'Value') - date_str = redis_service.hget_value(tag, 'Date') - try: # В случае если нет миллисекунд - date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S.%f') - except ValueError: - date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') +class RedisScales: + def get_scales_data_from_redis(tag: str = get_settings('control_conveyor')): + with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service: + # Получение объекта из Redis с последней актуальной записью по управляющему конвейеру + value = redis_service.hget_value(tag, 'Value') + date_str = redis_service.hget_value(tag, 'Date') + try: # В случае если нет миллисекунд + date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S.%f') + except ValueError: + date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') - return {'value': value, 'date': date} + return {'value': value, 'date': date} + + +class PostgresScales: + @staticmethod + def fetch_scales_data_by_range(start: datetime, end: datetime) -> list: + control_conveyor = get_settings('control_conveyor') + 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 DISTINCT ON (date_trunc('minute', "Date")) + "Name", + "Values", + "Date", + "Check" + FROM public.vesi + WHERE + "Name" = %s AND + "Date" BETWEEN %s AND %s + LIMIT 10000; + """, (control_conveyor, start, end)) + return cursor.fetchall() + + @staticmethod + 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', + ) 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: + logging.error(traceback.format_exc()) + return None + + @staticmethod + def write_scales_data(data: list): + if not 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', + ) as postgres_conn: + with postgres_conn.cursor() as cursor: + for row in data: + name, value, date, check = row + cursor.execute( + """ + DO $$ + DECLARE + value_exists BOOLEAN; + BEGIN + IF %s LIKE '%%Smena' OR %s LIKE '%%Month' THEN + SELECT EXISTS ( + SELECT 1 + FROM public.main_scalescontrol + WHERE "Name" = %s AND "Values" = %s + ) INTO value_exists; + + IF value_exists THEN + UPDATE public.main_scalescontrol + SET "Date" = %s + WHERE "Name" = %s AND "Values" = %s; + ELSE + INSERT INTO public.main_scalescontrol ("Name", "Values", "Date", "Check") + VALUES (%s, %s, %s, %s); + END IF; + END IF; + END $$; + """, + (name, name, name, value, date, name, value, name, value, date, check,), + ) + postgres_conn.commit() + return 'Success' + except Exception: + logging.error('CELERY: ' + traceback.format_exc()) + return traceback.format_exc() + finally: + postgres_conn.close() + + +@shared_task +def create_worktime_data_from_scales_db(start, stop): + pass @shared_task @@ -48,7 +156,7 @@ def create_worktime_data(): now_date = DashboardBaseService.get_current_time() - obj_from_redis = get_scales_data_from_redis(get_settings('control_conveyor')) + obj_from_redis = RedisScales.get_scales_data_from_redis(get_settings('control_conveyor')) delta_now_and_redis = (now_date - obj_from_redis['date']).total_seconds() / 60 @@ -81,8 +189,8 @@ def create_scales_control_data(): try: if not cache_value: cache.set_cache_value('create_scales_control_data', '1') - scales_data = get_scales_data(300) - res = write_scales_data(scales_data) + scales_data = PostgresScales.get_scales_data(300) + res = PostgresScales.write_scales_data(scales_data) cache.delete_cache_value('create_scales_control_data') return res return 'Skip' @@ -94,7 +202,7 @@ def create_scales_control_data(): @shared_task def write_scale_control_data_to_redis(): try: - data = get_scales_data(300) + data = PostgresScales.get_scales_data(300) 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])) @@ -105,81 +213,6 @@ def write_scale_control_data_to_redis(): return str(e) -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', - ) 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: - logging.error(traceback.format_exc()) - return None - - -def write_scales_data(data: list): - if not 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', - ) as postgres_conn: - with postgres_conn.cursor() as cursor: - for row in data: - name, value, date, check = row - cursor.execute( - """ - DO $$ - DECLARE - value_exists BOOLEAN; - BEGIN - IF %s LIKE '%%Smena' OR %s LIKE '%%Month' THEN - SELECT EXISTS ( - SELECT 1 - FROM public.main_scalescontrol - WHERE "Name" = %s AND "Values" = %s - ) INTO value_exists; - - IF value_exists THEN - UPDATE public.main_scalescontrol - SET "Date" = %s - WHERE "Name" = %s AND "Values" = %s; - ELSE - INSERT INTO public.main_scalescontrol ("Name", "Values", "Date", "Check") - VALUES (%s, %s, %s, %s); - END IF; - END IF; - END $$; - """, - (name, name, name, value, date, name, value, name, value, date, check,), - ) - postgres_conn.commit() - return 'Success' - except Exception: - logging.error('CELERY: ' + traceback.format_exc()) - return traceback.format_exc() - finally: - postgres_conn.close() - - @shared_task def create_shift_report(): control_conveyor_month = get_settings('conveyor_month') diff --git a/app/apps/main/urls.py b/app/apps/main/urls.py index f1504fd..1816084 100644 --- a/app/apps/main/urls.py +++ b/app/apps/main/urls.py @@ -10,5 +10,5 @@ urlpatterns = [ path('scale/', scales, name='concentrate_and_dropout'), path('aspiration/', aspiration, name='aspiration'), - path('administration/', administration, name='administration') + path('administration/', administration, name='administration'), ]