Ralph
Ralph

Reputation: 319

Can't return multiple values from this Flask view

The following view will return the smead but will not return the second string. When I try to return variable john, I get a 500 error. How do I fix my view to return the right thing?

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def homepage():
    return render_template("main.html")

@app.route('/test/', methods=["GET","POST"])
def test():
    import re
    text = "testereread"
    john = re.findall(r'test(.*)$', text)
    smead = "testererere"
    return smead
    return "i swear it no workiez"

if __name__ == "__main__":
    app.run()

Upvotes: 0

Views: 3174

Answers (2)

davidism
davidism

Reputation: 127190

The first issue is that you can only return once from a function, so as soon as you return smead the function ends and doesn't return the next string.

The second issue is that re.findall returns a list. Flask doesn't know what to do with a list returned from a view, so it throws an error. You can only return a string or Response from a view.

What you probably want to do is render a template that does something with those values.

return render_template('test', smead=smead, other='it works', john=john)
<p>{{ smead }}: {{ other }}</p>
<ul>{% for item in john %}
    <li>{{ item }}</li>
{% endfor %}

Upvotes: 1

xyres
xyres

Reputation: 21744

That is happening because on the first return statement i.e. return smead, the function exits without checking for the next return statement or any other code below.

Try this:

return smead + " i swear it no workiez"

Upvotes: 1

Related Questions