编辑代码


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:
                    # 处理格式不符合“key = value”的行
                    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

    # 检查record列表长度
    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]  # 直接获取查询结果的第一个元素,即最大id值
        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]  # 直接获取查询结果的第一个元素,即最大id值
        # 将最大id值赋给类属性config['investing']
        self.config['calendar'] = max_id
        cursor.close()
        return 


    def get_investing(self):
        cursor = self.conn.cursor()
        # sql = f"SELECT ID,sub_title,time_label,date,detail from investing where id > {self.config['investing']}"
        sql = "SELECT MAX(id) AS max_id FROM investing"
        cursor.execute(sql)
        max_id = cursor.fetchone()[0]  # 直接获取查询结果的第一个元素,即最大id值
        # 将最大id值赋给类属性config['investing']
        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()