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'
如何在'before_first_request'中加載模型並將其存儲在'g'中? – stamaimer
@stamaimer在這裏看到https://stackoverflow.com/questions/15083967/when-should-flask-g-be-used - 我不認爲g的作品你的想法 – cal97g