python - 用简单的形式烧瓶 BadRequest
问题描述
嘿 !
使用来自获得 werkzeug.exceptions.BadRequestKeyError KeyError: 'first' 的简单表单的输入时遇到一些问题
HTML
<body>
<form id="inform" method="POST">
User name:<input name="first" type=text>
message:<input name="second" type=text>
<input id="sendBtn" type="button" value="send">
</form>
<pre id="chatbox">Loading...</pre>
</body>
Python
today=date.today()
app=Flask(__name__)
app.static_folder = 'static'
@app.route("/",methods=['GET'])
def first():
return render_template('index.html')
@app.route("/<room>",methods=['GET'])
def second(room):
return render_template('index.html')
@app.route("/chat/<room>",methods=['GET','POST'])
def third(room):
if request.method == "GET":
pass
elif request.method == "POST":
name = request.form["first"]
massage = request.form["second"]
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
f=open(f"chat room {room}", "w")
f.write(f"room number {room}\ndate and time {dt_string}\nusername {name} massage {massage}")
f.close()
return render_template('index.html')
if __name__=="__main__":
app.run(host="0.0.0.0",debug=True)
收到此错误:
10.0.0.4 - - [18/May/2021 11:03:02] "POST /api/chat/5454 HTTP/1.1" 404 -
谢谢您的帮助 !
解决方案
您的功能third
导致此错误。由于您同时允许GET
和POST
方法,因此您必须分别处理它们。GET
请求不包含任何表单变量,这正是它引发错误的原因。
因此,您可以使用条件对不同的方法执行不同的操作:
@app.route("/chat/<room>", methods=['GET', 'POST'])
def third(room):
if request.method == "GET":
# do something
elif request.method == "POST":
# do something else
return render_template('index.html')
您可以将当前third
函数的所有内容放在elif
此代码块中。
推荐阅读
- scikit-learn - 如何解决无法从“sklearn.datasets”导入名称“fetch_openml”
- php - 如何将变量值组合为常量值并作为常量输出
- wordpress - 每页重复菜单,想删除
- ios - 在 Alamofire 中使用 get 请求时如何快速修复无效的 JSON 响应?
- java - Junit:为从组中删除学生编写单元测试用例
- javascript - 计算 ReactJS 中父评论的线程数
- google-sheets - 搜索多列并返回顶部单元格值
- jquery - 如何使用轮播关闭 X 上的 Bootstrap 4 弹出窗口
- class - 修剪字符串的类和方法甚至没有开始
- python - Django Rest Framework 视图设置 url 过滤器错误