2017-05-26 90 views
2

我意識到使用全局變量不是一種好的編程習慣。我需要在啓動時加載機器學習模型,以便我不需要在每次請求時處理它。我有Flask來處理請求。不過,我無法理解在Python中啓動時初始化變量的良好做法。在Java中我想我的辦法是通過以下方式使用一類具有一個靜態變量:在Python中啓動時避免全局變量和加載模型

Class A{ 
    private ClassB classB; 
    A() { 
     //Load some file into memory 
     classB = new ClassB(); 
     classB.x = //set from file 
    } 

    public static getClassB() { 
    return classB; 
    } 
} 


Is this something which is a good practice to follow in Python as well? I could then probably do something like 

@app.route('/', methods=['GET']) 
    def main(): 
    b = getClassB() ; //this time it shouldn't load 
    score = b.predict() 
    return score 

if __name__ == 'app': 
    try: 
     getClassB() //this will load once at startup 
    except Exception,e : 
     print 'some error' 
+0

如何在'before_first_request'中加載模型並將其存儲在'g'中? – stamaimer

+0

@stamaimer在這裏看到https://stackoverflow.com/questions/15083967/when-should-flask-g-be-used - 我不認爲g的作品你的想法 – cal97g

回答

0

這將是很難做到這一點沒有某種形式的全球 - 除非你想加載一個模型每個請求的基礎,這顯然是不高效的。

flask.g實際上是一個每個請求的上下文。

只需將其設置爲init文件或主文件中的變量即可。 Ala:

app = Flask(__name__) 
learning_model = load_learning_model() 


@app.route('/', methods=['GET']) 
def home(): 
    #here you can use the learning model however you like 

學習模型可以是類或其他類型的實例。