python - 如何在 Flask 的网页上读取用户输入
问题描述
我正在尝试创建一个在根登录页面上具有 HTML 表单的基本 Web 应用程序,然后在提交后,使用所需的输入运行 postgresql 查询,并将用户重定向到具有生成的 matplotlib 输入图表的页面。在我的主要功能中,我有以下内容:
@app.route('/', methods=['POST'])
def main():
return render_template("main.html")
因此,假设我的主 html 文件由烧瓶应用程序呈现。我在下面有另一条路线:
@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 端点呈现感到困惑。如果有人能详细说明这一点,我将不胜感激。前端不是我的强项。谢谢!
解决方案
如果我正确理解了您的问题,那么您将难以将表单信息从主函数传递到单独的 queryPage 函数进行渲染。这可以通过提供您希望作为关键字参数传递给 url_for 函数的值来轻松实现。然后可以从 queryPage 函数中的 request.args 检索这些。鉴于您从该函数返回 query.html 而不是图像,我假设您打算在 query.html 中的 img 标记内显示图表。在这种情况下,您将需要另一个视图函数来生成并返回图像本身。您可能还需要为此端点禁用浏览器缓存,以防止浏览器将您的动态图像视为静态图像https://stackoverflow.com/a/2068407/10548137。
@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
推荐阅读
- html - 弹性基础:自动在 IE11 中不起作用
- sql - 每次修改表时运行脚本
- node.js - 如何在 React 中使用使用“window”引用的组件与服务器端渲染?
- c# - 使用 Func 和 Expression Func 运行查询之间的差异
- javascript - 如何使用 HTML、CSS、Javascript 在可编辑字段中垂直键入文本...?
- jenkins - 詹金斯的 currentBuild()
- python - PIL 绘制没有灰色轮廓的文本
- intellij-idea - 默认在带有单词边界的路径中查找
- php - 在 Netbeans 8.2 中调试期间为空调用堆栈
- javascript - javascript forEach() 函数如何在 mongodb shell 中迭代文档?