python - 无法从 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>
解决方案
将 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="" 属性中添加或删除它。
还:
- 添加路由以显示搜索表单
- 检查请求是否是 post 方法,因为您同时接受 get 和 post
- 您可以使用
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>
推荐阅读
- node.js - 如何通过 API 获取 YouTube 视频?
- javascript - 有没有办法获取用户上次在 Google Workspace 中更改密码的日期和时间
- python - 为什么在 windows 中使用 python 进行多处理时出现运行时错误?
- node.js - 通过 mongoose 对 mongodb 中的多个字段进行排序
- php - 碳场,未定义的元素数量
- sql-server - 唯一约束和索引
- c++ - 你如何在 Windows vscode MinGW 上编译 ImGui?
- excel-formula - 除了拖动之外,我如何到达列的底部以应用公式
- python - 如何使用 python 更改 docx 文件中的图像
- python - python tkinter canvas打印到打印机