Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 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?

question from:https://stackoverflow.com/questions/65855055/how-to-i-get-two-inputs-at-same-time-in-flask

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...