繁体   English   中英

如何仅运行一次Python方法,从而缩短程序生命周期?

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

我建立了一个Python Flask REST API,该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():
    file_content = None

    def inner():
        nonlocal file_content

        if file_content is None:
            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
    return inner
read_file = read_file()

第一次调用read_file()file_content值为None ,文件被读取,数据被分配给file_content 对于后续的方法调用,内部函数仅返回file_content的值。

在最后一行中,变量read_fileinner函数替换。 调用read_file调用inner

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM