iustin
iustin

Reputation: 66

How to use flask variables from outside the function to later use in javascript?

Running routes.py

@app.route('/articles', methods=['GET', 'POST'])
def articles():
    upload()
    return render_template('articles.html')

And this function that saves an image and processes its information

def upload():
    if request.method == 'POST':
        # Save the file to static/uploads
    
        label = "some string from process above"
        probability = "another string"

        return None

    return None

How do I make use of the variables label and probability in rendering the template? Some people use something close to:

return render_template('articles.html', label=label, probability=probability)

This would be done to make a reference to variables using js. But how do I make a reference to that variable if it is computed inside of upload()? Any need for global variables?

Upvotes: 2

Views: 1608

Answers (1)

ParthS007
ParthS007

Reputation: 2689

You can return those variables from the function.

You have to unpack the variable you are sending from upload function.

First, you have to return them from upload and then unpack it to send it to render_template.

@app.route('/articles', methods=['GET', 'POST'])
def articles():
    label, probability = upload()
    return render_template('articles.html', label=label, probability=probability)
def upload():
    if request.method == 'POST':
        # Save the file to static/uploads
    
        label = "some string from process above"
        probability = "another string"

        return (label, probability)

    return (None, None)

Upvotes: 2

Related Questions