Python 如何在Flask中读取网页上的用户输入
我正在尝试创建一个在根登录页上具有HTML表单的基本web应用程序,然后在提交后,使用所需的输入运行postgresql查询,并将用户重定向到一个包含其输入的生成matplotlib图表的页面。在我的主要职能中,我有以下几点:Python 如何在Flask中读取网页上的用户输入,python,python-3.x,matplotlib,flask,Python,Python 3.x,Matplotlib,Flask,我正在尝试创建一个在根登录页上具有HTML表单的基本web应用程序,然后在提交后,使用所需的输入运行postgresql查询,并将用户重定向到一个包含其输入的生成matplotlib图表的页面。在我的主要职能中,我有以下几点: @app.route('/', methods=['POST']) def main(): return render_template("main.html") 假设我的主html文件由flask应用程序呈现。我还有另一条路线: @app.route('/qu
@app.route('/', methods=['POST'])
def main():
return render_template("main.html")
假设我的主html文件由flask应用程序呈现。我还有另一条路线:
@app.route('/query', methods=['POST'])
def queryPage():
# code to execute query with information
# passed from the main.html template
# then generate chart via matplotlib via returned information
return render_template("query.html")
我不知道如何从main.html中的表单获取输入,以便将信息发送回应用程序,以便在/query端点进行渲染。如果有人能详细解释一下,我将不胜感激。前端不是我的强项。谢谢 您需要main.html上的表单。。。可能是这样(注意表单操作): 然后用户名变量将出现在
query.html
页面上
请记住,我只传递了一个变量。您可以传递多个变量、列表、字典等
还请记住,返回query.html的任何变量都可以使用Jinja模板变得非常动态。你可以循环浏览列表,打印不同的html标签等,并在html中使用逻辑。。。可能的情况取决于返回到页面的值。如果我正确理解了您的问题,则您很难将表单信息从主函数传递到单独的查询页面函数进行呈现。这可以通过提供希望作为关键字参数传递给函数url_的值来轻松实现。然后,可以从queryPage函数中的request.args检索这些参数。鉴于您是从这个函数返回query.html而不是图像,我假设您打算在query.html中的img标记中显示图表。在这种情况下,您将需要另一个view函数来生成并返回图像本身。您可能还需要为此端点禁用浏览器缓存,以防止浏览器将动态图像视为静态图像
<form action = /query method="POST">
<label for="username">USERNAME:</label>
<input type="text" name="username" id="username" size="15">
<input type="submit" name="submit" id="submit"/>
</form>
return render_template('query.html, username=username)
@app.route('/', methods=['GET', 'POST'])
def main():
form = MyForm(request.form)
if request.method == "POST" and form.validate():
return redirect(url_for("queryPage", **form.data))
return render_template("main.html", form=form)
@app.route('/query', methods=['GET'])
def queryPage():
arguments = request.args.to_dict()
image_url = url_for("make_chart", **arguments)
return render_template("query.html", image_url=image_url)
@app.route('/make_chart', methods=['GET'])
def make_chart():
arguments = request.args.to_dict()
# perform postgres query here using arguments
# generate matplotlib chart here using query results
# ? save chart in BytesIO buffer in png format
response = send_file(file_pointer, mimetype="image/png")
# just return response here if don't need to alter headers
response = make_response(response)
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response