如何在程序生命周期内只执行一次运行 Python方法?

How to run Python method only once, durning the program life cycle?

我构建了一个 Python Flask REST API,它对 POST 请求作出反应。每次调用端点时,都会从服务器读取文件。请问有什么办法可以让文件只读一次吗?

我想要它,以便仅在程序启动后才从文件中读取。目前,每次调用“/test”端点时都会读入文件。

这是控制器的一个例子:

@app.route('/test', methods=['POST'])
def test(data):
    file_content = Data.readFile()
    ...
    "Here do something with the file content and data"

这里是Data.py的内容:

def readFile():
    with open(os.getcwd() + '/csv_files/' + config.WORDS, encoding="utf-8-sig", mode='r') as f:
        csv_reader = csv.reader(f, delimiter=';')
        file_content = [row[0] for row in csv_reader]
    return file_content

我知道在 Java Spring 中您可以使用@PostConstruct 或@Configuration。 Python中有类似的东西吗?

更改控制器,使文件数据已在函数外读取。

pre_file_content = Data.readFile()
@app.route('/test', methods=['POST'])
def test(data):
    file_content = pre_file_content
    ...
    "Here do something with the file content and data"

您可以为此创建一个闭包函数。

# Data.py
def read_file():
    # the variable `read_file` is being modified inside the function
    # ignoring the global declaration will create a local variable read_file
    global read_file

    with open(os.getcwd() + '/csv_files/' + config.WORDS, encoding="utf-8-sig", mode='r') as f:
        csv_reader = csv.reader(f, delimiter=';')
        file_content = [row[0] for row in csv_reader]

    def inner():
        return file_content

    # read file is a global variable 
    # because it is declared as a function in the global scope
    # we are modifying it here and monkey patching it with `inner`
    # subsequent calls to `read_file` will inherently call `inner`
    read_file = inner

    # for the first time the function is called
    return file_content

第一次调用 read_file() 时,文件被打开,file_content 被加载到变量中,变量 read_fileinner 函数替换。
对于后续方法调用,file_content 的值仅由 inner 函数返回。