【发布时间】:2019-02-20 10:19:20
【问题描述】:
我在下面有一个 python 代码:
def func1():
return x
def func2():
return y
x=func1()
y=func2()
z=x+y
products={} #its a nested dictionary containing product details
@app.route('/')
@app.route('/home')
def home():
return render_template('home.html', z=z, x=x, y=y)
@app.route('/product/<key>')
def product(key):
product = products.get(key)
if not product:
abort(404)
return render_template('product.html', product=product)
if __name__ == "__main__":
app.run(debug = True)
这是我的代码的基本结构。如果我运行这整个程序会执行两次。有没有办法先启动网页浏览器再运行python代码?
【问题讨论】:
-
“被执行两次”是什么意思? “启动网络浏览器”是什么意思? Flask 在服务器上运行,它在每次浏览器访问时提供一个请求,但它不知道也不关心该浏览器何时启动。
-
z=x+y只执行一次,因为它在 Python 第一次运行脚本时被评估,然后再也不会。 -
(当然,这段代码实际上不起作用,因为
x和y没有在模块范围内定义;如果您发布真实代码,也许我们可以提供更好的帮助?) -
@tripleee 所有函数都会执行两次。当我运行程序时,所有功能都会执行一次,并且服务器会在 Web 浏览器上启动。但是页面是空的。如果我按刷新整个代码再次运行,我会看到结果
-
@DanielRoseman 我不能在这里发布真正的代码,因为它超过 800 行。这就是我的代码花费大量时间运行两次的原因,我正在寻找是否有办法避免它
标签: python python-3.x flask jinja2