statusd.py now works with json modul

the deamon now uses the python modul json to read and write the api file. the
function replace_entry() is removed.
This commit is contained in:
Berhsi 2019-09-08 00:31:19 +02:00
parent cd1697a134
commit 5a6a236ebc

View file

@ -9,6 +9,7 @@
import socket
import os
import logging
import json
from time import time, ctime, sleep
from sys import exit, byteorder
@ -82,26 +83,6 @@ def bytes2int(raw_data):
return data
def replace_entry(line, new):
'''
The function becomes two strings and replaces the second part of the
first string from ":" until end with the second string. Than appends a
"," and returns the result.
!!! Todo: needs exception handling !!!
param 1: string
param 2: string
return: string
'''
array = line.split(':')
logging.debug('Replace {} with {}'.format(array[1], new))
array[1] = ''.join((new, ','))
line = ':'.join((array[0], array[1]))
return line
def change_status(raw_data, api):
'''
Becomes the received byte and the path to API file. Grabs the content of
@ -121,21 +102,13 @@ def change_status(raw_data, api):
logging.debug('API file is writable')
with open(api, 'w') as api_file:
logging.debug('API file open successfull')
for line in data.splitlines():
if line.strip().startswith('"state":'):
edit = True
elif edit == True and line.strip().startswith('"open":'):
line = replace_entry(line, status)
elif edit == True and line.strip().startswith('"lastchange":'):
line = replace_entry(line, timestamp)
edit = False
try:
api_file.write(line)
api_file.write('\n')
except Exception as e:
logging.error('Failed to write line to API file')
logging.error('Line: {}'.format(line))
logging.error('{}'.format(e))
data["state"]["open"] = status
data["state"]["lastchange"] = timestamp
try:
json.dump(data, api_file, indent=4)
except Exception as e:
logging.error('Failed to change API file')
logging.error('{}'.format(e))
logging.debug('API file changed')
else:
logging.error('API file is not writable. Wrong permissions?')
@ -158,12 +131,12 @@ def read_api(api):
with open(api, 'r') as api_file:
logging.debug('API opened successfull')
try:
api_data = api_file.read()
logging.debug('API read successfull')
api_json_data = json.load(api_file)
logging.debug('API file read successfull')
except Exception as e:
logging.error('Failed to read API file(): {}'.format(e))
return False
return (api_data)
return (api_json_data)
logging.error('Failed to read API file')
return False