Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask return multiple variables?

Tags:

python

flask

I am learning Flash with Python. My python skills are okay, but I have no experience with web apps. I have a form that takes some information and I want to display it back after it is submitted. I can do that part, however I can only return one variable from that form even tho there are 3 variables in the form. I can return each one individually but not all together. If I try all 3, I get a 500 error. Here is the code I am working with:

from flask import Blueprint
from flask import render_template
from flask import request

simple_page = Blueprint('simple_page', __name__)

@simple_page.route('/testing', methods=['GET', 'POST'])
def my_form():
        if request.method=='GET':
            return render_template("my-form.html")
        elif request.method=='POST':
            firstname = request.form['firstname']
            lastname = request.form['lastname']
            cellphone = request.form['cellphone']
            return firstname, lastname, cellphone

If I change the last return line to:

return firstname

it works, or:

return lastname

or:

return cellphone

If I try two variables it will only return the first, once I add the 3rd I get the 500 error. I am sure I am doing something silly, but even with tons of googling I could not get it figured out. Any help would be great. Thank you.

like image 981
Christopher Nelson Avatar asked Sep 29 '16 14:09

Christopher Nelson


1 Answers

Flask requires either a str or Response to be return, in you case you are attempting to return a tuple.

You can either return your tuple as a formatted str

return  '{} {} {}'.format(firstname, lastname, cellphone)

Or you can pass the values into another template

return render_template('my_other_template.html', 
                       firstname=firstname,
                       lastname=lastname,
                       cellphone=cellphone)
like image 52
Wondercricket Avatar answered Sep 27 '22 21:09

Wondercricket