我正在开发一个Django项目,它启动一个监视系统资源的异步线程,因为有些请求需要根据服务器的当前状态更改行为。设置监控线程的代码:
def monitor():
try:
f = open("file")
data = eval(f.read()) # raises SyntaxError!?
f.close()
except FileNotFoundError:
data = {
"cpu": [0 for _ in range(720)],
"ram": [0 for _ in range(720)],
"disk_capacity": [0 for _ in range(720)],
"disk_write": [0 for _ in range(720)],
"disk_read": [0 for _ in range(720)],
"network_sent": [0 for _ in range(720)],
"network_recv": [0 for _ in range(720)],
"uptime": 0
}
while True:
f = open("file", "w")
f.write(str(data))
f.close()
data = update_data(data) # Returns every full hour
class ServerStatusConfig(AppConfig):
...
def ready(self):
# Workaround for Django's process forking
try:
f = open("temp", "r")
f.close()
except FileNotFoundError:
f = open("temp", "w")
f.close()
thread = threading.Thread(target=monitor)
thread.start()
else:
os.remove("temp")
def update_data(data):
# Fetch cpu, ram, dskcap, dskw, dskr, netr, nets
# cpu scheduled to calculate average until next full hour,
# other stats are fetched immediately afterwards
...
data["cpu"] = data["cpu"][1:]+[cpu]
data["ram"] = data["ram"][1:]+[ram]
data["disk_capacity"] = data["disk_capacity"][1:]+[dskcap]
data["disk_write"] = data["disk_write"][1:]+[dskw]
data["disk_read"] = data["disk_read"][1:]+[dskr]
data["network_recv"] = data["network_recv"][1:]+[netr]
data["network_sent"] = data["network_sent"][1:]+[nets]
return data
基本上,从任何其他代码不读取或写入的文件中读取str(data)
会经常引发语法错误。语法文件中的错误始终由文件末尾的附加]}
引起。这意味着数据是可恢复的,并且这确实在技术上解决了问题:
except SyntaxError:
data = eval(f.read()[:-2])
但偶尔将不正确的数据写入文件可能是什么原因?
修改:更新了代码,以便在创建时显示data
字典内容。
修改:更新了代码以显示update_data
功能。