import mysql
def read_config():
"""
从指定的文本文件中读取配置信息,转换成字典格式。
:param filepath: 文件的路径
:return: 包含配置信息的字典
"""
filepath = "/www/pachong/spider/filesave.txt"
update_record = {}
try:
with open(filepath, 'r') as file:
for line in file:
parts = line.strip().split('=')
if len(parts) == 2:
key, value = parts[0].strip(), parts[1].strip()
try:
update_record[key] = int(value)
except ValueError:
print(f"Warning: 键'{key}'的值'{value}'无法转换为整数。")
else:
print(f"Warning: 行格式错误,跳过:'{line.strip()}'")
except FileNotFoundError:
print(f"错误:文件'{filepath}'未找到。")
except IOError:
print(f"错误:无法读取文件'{filepath}'。")
except Exception as e:
print(f"未知错误:{e}")
return update_record
def update_config(record):
"""
更新配置文件的参数值。
:param filepath: 配置文件的路径
:param record: 一个包含三个数字的列表,分别对应更新的参数值
"""
filepath = "/www/pachong/spider/filesave.txt"
try:
with open(filepath, 'r') as file:
lines = file.readlines()
except FileNotFoundError:
print(f"错误:文件'{filepath}'未找到。")
return
except IOError:
print(f"错误:无法读取文件'{filepath}'。")
return
if len(record) != 3:
print("错误:record列表必须包含三个元素。")
return
updated_lines = []
for line, new_value in zip(lines, record):
parts = line.strip().split('=')
if len(parts) == 2:
key = parts[0].strip()
updated_lines.append(f"{key} = {new_value}\n")
else:
print(f"Warning: 行格式错误,跳过:'{line.strip()}'")
updated_lines.append(line)
try:
with open(filepath, 'w') as file:
file.writelines(updated_lines)
except IOError:
print(f"错误:无法写入文件'{filepath}'。")
class FileUpdate():
def __init__(self, conn):
self.config = read_config()
self.conn = conn
def get_news(self):
cursor = self.conn.cursor()
sql = "SELECT MAX(id) AS max_id FROM followin"
cursor.execute(sql)
max_id = cursor.fetchone()[0]
self.config['news'] = max_id
cursor.close()
return
def get_calendar(self):
cursor = self.conn.cursor()
sql = "SELECT MAX(id) AS max_id FROM coinmarket"
cursor.execute(sql)
max_id = cursor.fetchone()[0]
self.config['calendar'] = max_id
cursor.close()
return
def get_investing(self):
cursor = self.conn.cursor()
sql = "SELECT MAX(id) AS max_id FROM investing"
cursor.execute(sql)
max_id = cursor.fetchone()[0]
self.config['investing'] = max_id
cursor.close()
return
def run():
conn = mysql.get_db_conn()
file_update = FileUpdate(conn)
news = file_update.get_news()
investing = file_update.get_investing()
calendar = file_update.get_calendar()
conn.close()
record = [file_update.config['news'], file_update.config['calendar'], file_update.config['investing']]
update_config(record)
if __name__ == '__main__':
run()