92 lines
2.8 KiB
Python
92 lines
2.8 KiB
Python
import time
|
|
import traceback
|
|
from datetime import datetime
|
|
|
|
import psycopg2
|
|
from psycopg2 import OperationalError
|
|
|
|
|
|
# Подключение к первой базе данных
|
|
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:
|
|
return None
|
|
|
|
|
|
def write_scales_data(data: list):
|
|
postgres_conn = psycopg2.connect(
|
|
dbname="repcofkk_db",
|
|
user="repcofkk_user",
|
|
password="Angstrem*45",
|
|
host="127.0.0.1",
|
|
port="5432",
|
|
)
|
|
try:
|
|
with postgres_conn.cursor() as cursor:
|
|
for row in data:
|
|
name, value, date, check = row
|
|
cursor.execute(
|
|
"""
|
|
DO $$
|
|
DECLARE
|
|
value_exists BOOLEAN;
|
|
BEGIN
|
|
|
|
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 $$;
|
|
""",
|
|
(name, value, date, name, value, name, value, date, check),
|
|
)
|
|
postgres_conn.commit()
|
|
except Exception:
|
|
print(traceback.format_exc())
|
|
print(row)
|
|
postgres_conn.close()
|
|
finally:
|
|
postgres_conn.close()
|
|
|
|
|
|
def main():
|
|
while True:
|
|
print(f"Task started at {datetime.now()}")
|
|
scales_data = get_scales_data()
|
|
print(f"Task: selected data at {datetime.now()}")
|
|
write_scales_data(scales_data)
|
|
print(f"Task performed at {datetime.now()}")
|
|
time.sleep(120)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|