如果我定义两个函数:
def atesting():
a = 2
return a
def btesting():
b = a+ 3
return b
但是在Flask中,如果尚未定义“ a”,则在运行以下命令时会收到“内部服务器错误”。尽管如果我在应用程序外部定义“ a”,即说a = 2,则它可以工作并且得到5。
app = Flask(__name__)
@app.route('/')
def index():
results = {}
a = atesting()
results = btesting()
return render_template('index.html', results=results)
if __name__ == '__main__':
app.run()
Index.html:
<html>
<h1>{{ results }}</h1>
</html>
但是通常在Python中运行此命令时我得到5:
a = atesting()
btesting()
为什么Flask在计算btesting()时不使用a = atesting()作为输入?
答案 0 :(得分:1)
烧瓶错误是正确的。
在此用例中,没有全局 a 。 (它设置在 index 函数内部,因此其他函数看不到)
如果您在 正常程序。
如果要让函数btesting看到a变量, 将其作为参数传递。
app = Flask(__name__)
@app.route('/')
def index():
results = {}
a = atesting()
results = btesting(a)
return render_template('index.html', results=results)
if __name__ == '__main__':
app.run()
和
def btesting(a):
b = a + 3
return b
答案 1 :(得分:1)
btesting
的书写方式无法看到a
。您需要了解 scope 。尝试使用此功能-请注意,我们通过将btesting
的值作为参数传递来告诉a
:
def atesting():
a = 2
return a
def btesting(a):
b = a+ 3
return b
然后,像这样调用它(将值传递给函数)
app = Flask(__name__)
@app.route('/')
def index():
results = {}
a = atesting()
results = btesting(a)
return render_template('index.html', results=results)
if __name__ == '__main__':
app.run()