如何创建一个 class 将根据文件内容定期更新其变量

How to create a class which will periodically update its variables based on the file content

我正在尝试用 Flask 编写一个小的 REST API。由于暂时不想引入数据库,所以打算把客户端需要的信息全部存储在内存中。 现在,cron 作业从网络收集数据,对其进行分析并将结果写入文件。 REST API 的任务是将此数据部分(基于传入参数)提供给客户端。 这是一个代码示例,在我看来可以完成这项工作:

class DataAnalyzer:
    TYPE_DAY = 'day'
    TYPE_WEEK = 'week'

    def __init__(self):
        self.__daily_stats__ = []
        self.__weekly_stats__ = []

    def __load_stats__(self, daily_file, weekly_file, interval):
        while True:
            self.__daily_stats__ = [line.strip() for line in open(daily_file, 'r').readlines()]
            self.__weekly_stats__ = [line.strip() for line in open(weekly_file, 'r').readlines()]

            time.sleep(interval)

    def start(self, daily_file, weekly_file, interval):
        t = threading.Thread(target=self.__load_stats__, args=(daily_file, weekly_file, interval))
        t.daemon = True
        t.start()

    def get_stats(self, stats_type, skip, count):
        if stats_type == self.TYPE_WEEK:
            data_to_filter = self.__weekly_stats__
        elif stats_type == self.TYPE_DAY:
            data_to_filter = self.__daily_stats__
        else:
            raise ValueError("Unknown type of statistics: '" + stats_type + "'")

        result_list = itertools.islice(data_to_filter, skip, (skip + count))

        return list(result_list)

由于我的python经验很低,我很好奇现实世界应该怎么做。这种情况应该如何实现线程安全?

为确保您不会同时更新和获取数据您可以使用 Lock。

使用 python 锁定的很好的解释和示例您可以在这里找到: http://www.laurentluce.com/posts/python-threads-synchronization-locks-rlocks-semaphores-conditions-events-and-queues/

别担心。 GIL 帮助你 :) 如果你想要真正的多线程应用程序,你应该使用 multiprocessing module.

Global Interpreter Lock (GIL) is a mechanism used in computer language interpreters to synchronize the execution of threads so that only one thread can execute at a time. An interpreter which uses GIL will always allow exactly one thread to execute at a time, even if run on a multi-core processor.

您的线程将一个接一个地执行。不是同时。因此,您的 data_to_filter 将始终保持一致。 我认为你可以改变

result_list = itertools.islice(data_to_filter, skip, (skip + count))
return list(result_list)

return data_to_filter[skip, skip+count]