简体   繁体   English

在web.py中打开和关闭文件的位置

[英]where to open and close file in web.py

A data file was getting corrupted when I terminated the program and realised that it was never properly closed. 当我终止程序并意识到它从未正确关闭时,数据文件已损坏。

It is quite critical that it does not get corrupted. 它不会被破坏是非常关键的。 So I added a statement to close the file. 所以我添加了一个声明来关闭文件。

Now, it seems like the file gets opened twice and then closed. 现在,似乎文件被打开两次然后关闭。 That's one operation too many. 这是一个太多的操作。 There are of course many read-write operations in-between but it should only open and close the files once. 当然中间有许多读写操作,但它应该只打开和关闭文件一次。

Here is what I have done to the standarize web.py template: 以下是我对标准web.py模板所做的操作:

import web
import pandas as pd

store = pd.HDFStore('data_file.h5')

urls = (
    '/', 'index'
)

class index:
    def __init__(self):
        self.__df = store['df']
    def GET(self):
        # several read-write, and modify operations on self.__df
        return "Hello, world!"

if __name__ == "__main__":
    try:
        app = web.application(urls, globals())
        app.run()
    finally:
        store.close()

Now, if I move the line which opens the store down inside the try statement at the bottom, it complains since it compiles the class but I can't find the variable store . 现在,如果我在底部的try语句中移动打开存储的行,它会抱怨,因为它编译了类但我找不到变量store

I tried initialising store with None at the top but it didn't work either. 我尝试在顶部初始化None store ,但它也没有用。 Then I tried putting that line up at the top in the function and calling it from the bottom, however, that didn't bring it into scope. 然后我尝试将该行放在函数的顶部并从底部调用它,然而,这并未将其纳入范围。

I was thinking of making it a global variable, which would probably do the trick, is that the right approach? 我想把它变成一个global变量,这可能就是诀窍,那是正确的方法吗?

See web.py running twice . 请参阅web.py运行两次 As mentioned there, avoid using globals as they don't do what you think they do... app.py runs twice, once on startup and a second time within web.appplication(urls, globals()) . 正如那里提到的那样,避免使用全局变量,因为它们没有按照你的想法去做... app.py运行两次,一次启动,第二次运行web.appplication(urls, globals()) If you set autoreload=False in web.applications() call, it won't load the file twice. 如果在web.applications()调用中设置autoreload=False ,则不会加载文件两次。

Another solution is to attach your store to web.config , which is globally available. 另一种解决方案是将您的store附加到全球可用的web.config

if __name__ == "__main__":
    try:
        web.config.store = pd.HDFStore('data_file.h5')
        app = web.application(urls, globals())
        app.run()
    finally:
        web.config.store.close()

...and reference that global in your __init__ ...并在__init__引用全局

class index:
    def __init__(self):
        self.__df = web.config.store['df']

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

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