0

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()?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank's for such a quick response, I was stuck on it for so long and you literally solved it in 2 minutes! Works perfectly, and makes sense.
1

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()

1 Comment

Thanks mike, works like a charm and i understand the concept now as well. Appreciate it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.