Reputation: 61
If I define two functions:
def atesting():
a = 2
return a
def btesting():
b = a+ 3
return b
But in Flask I get an "Internal Server Error" when running the following if "a" hasn't been defined already. Although if I define "a" outside the app ie say a =2, then it works and I get 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>
But just normally in Python I get 5 when i run this:
a = atesting()
btesting()
Why won't Flask use a = atesting() as an input when computing btesting()?
Upvotes: 0
Views: 2255
Reputation: 8362
The flask error is correct.
For this usecase there is no global a. (It is set inside the index function, so other functions can't see it)
This is different, if you define a globally in a normal program.
If you want to let function btesting seen the a variable, pass it as a parameter.
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()
and
def btesting(a):
b = a + 3
return b
Upvotes: 1
Reputation: 11267
The way you have it written, btesting
cannot see a
. You need to understand scope. Try this for your functions - note that we are telling btesting
the value of a
by passing it as an argument:
def atesting():
a = 2
return a
def btesting(a):
b = a+ 3
return b
Then, call it like this (pass the value to the function)
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()
Upvotes: 1