正在使用Flask初始化路由中使用的对象



我正在使用Flask服务器,我想初始化一些对象,并使它们对路由可见。

在进口和路线的定义之间不要有太多的代码,那就太好了。

最好的方法是什么?下面是一个名为Object的对象的示例。这个例子有效,但我相信还有更好的方法。

也许给Flask(__name__)一些论据是有效的,但不确定如何做到这一点。

from flask import Flask
# Could I give some references of the object o here?
app = Flask(__name__) 

class Object:
def __init__(self):
self.value = 2

# I would like to avoid stuffing too much code between 
# the imports and the definitions of the routes.
o = Object() 

@app.route('/')
def hello_world():
# I need the object to be in this scope. 
# Maybe with app.o or something similar?
return f'Hello, World! {o.value}'

if __name__ == '__main__':
# Ideally the definition of o = Object() goes here and app exposes it.
app.run()

当我启动Flask应用程序时,你目前的方式正是我要做的。只要应用程序不是太大,就把它简单地放在一个文件中。

根据您需要o的位置,您可以直接在路由中实例化它。

如果你的应用程序增长,你可以移动你的";数据提供者";进入一个单独的模块并从中导入。

关于您的在线问题/评论:

# Could I give some references of the object o here?
app = Flask(__name__) 

没有。您可以传入一个单独的模板目录或类似的目录,但不传入路由的数据。

# I would like to avoid stuffing too much code between 
# the imports and the definitions of the routes.
o = Object() 

正如建议的那样,这目前还可以,如果它得到了太多的代码,请将其移动到另一个模块并从那里导入。

@app.route('/')
def hello_world():
# I need the object to be in this scope. 
# Maybe with app.o or something similar?
return f'Hello, World! {o.value}'

您也可以实例化";数据源";对象。

if __name__ == '__main__':
# Ideally the definition of o = Object() goes here and app exposes it.
app.run()

不要在这里再放任何代码,因为测试非常困难(如果你开始写测试(。

最新更新