Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

python - How to I get two inputs at same time in flask

from flask import Flask, render_template,  request
app = Flask(__name__)


@app.route('/', methods = ['GET', 'POST'])
@app.route('/', methods = ['GET', 'POST'])

def Input_1():
name1 = ""
if request.method == 'POST':
name1 = request.form.get("name1", "0")
return render_template('index.html', DataFromPython1 = name1)

def Input_2():
name2 = ""
if request.method == "POST":
name2 = request.form.get("name2", "0")
return render_template('index.html', DataFromPython2 = name2)

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

This is my code

First function works well, but second function dose not work as first function.

I gave input in second box but nothing happened

what do I have to do to get two inputs at same time?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that only Input_1() will run, for the / route.

The solution is to use one route and one function:

from flask import Flask
from flask import render_template
from flask import request
# ^^^ prefer one import per line


app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name1 = request.form.get('name1', '0')
        name2 = request.form.get('name2', '0')
        return render_template('index.html',
                               DataFromPython1=name1,
                               DataFromPython2=name2)
    else:
        return render_template('index.html')


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

If its a POST request, then retrieve all the values you want from the form, and pass them to be rendered.

Most likely, if its a GET request you want to just load index.html, so I've added that in as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...