首页 > 解决方案 > 无法从 html 表单获取值到我的 python 代码

问题描述

我无法从我的 html 表单获取信息到我的 python 代码。我检查了很多次代码,但似乎没有问题。请检查我的代码并告诉我出了什么问题。谢谢你。

@app.route("/search",methods=["POST","GET"]) 
def search1():                                #python code
    var=request.form.get("search2")
    sear=str(var)
    print(var,sear)
    return " "
<html>                      <!--html code-->
<head>
    <title>hi there</title>
</head>
<body>
    <h1 style="font-family:verdana; font-style:italic;">Welcome to the book sea !!!....</h1>
    <form action="{{ url_for('search1') }}" method="get" align:"center">
        <input type="text" name="search2" placeholder="enter details">
        <button>search</button>
    </form>
    
</body>

标签: python

解决方案


将 HTML 中的“get”更改为“post”。因为您的 Flask 路由的设置方式,它不允许使用 get 请求传递变量。

<form action="{{ url_for('search1') }}" method="get" align:"center">

至:

<form action="{{ url_for('search1') }}" method="post" align:"center">

此外,您可能想要删除或编辑align:"center",因为它不是正确的 html。在 style="" 属性中添加或删除它。

还:

  1. 添加路由以显示搜索表单
  2. 检查请求是否是 post 方法,因为您同时接受 get 和 post
  3. 您可以使用var=request.form["search2"]而不是var=request.form.get("search2")

============================================

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("search.html")

@app.route("/search",methods=["POST","GET"])
def search1():                                #python code
    if request.method == 'POST':
        var=request.form["search2"]
        sear=str(var)
        print(var,sear)
    return " "

if __name__ == "__main__":
    app.run(debug=True)

==== search.html .. 应该放在项目的模板文件夹中 ===

<html>                      <!--html code-->
<head>
    <title>hi there</title>
</head>
<body>
<h1 style="font-family:verdana; font-style:italic;">Welcome to the book sea !!!....</h1>
<form action="{{ url_for('search1') }}" method="post">
    <input type="text" name="search2" placeholder="enter details">
    <button>search</button>
</form>

</body>

</html>

推荐阅读