python - 我的代码有什么问题?我是 Flask 的新手
问题描述
我想使用 python、Flask 和 mongoDB 执行 INSERTION 操作。当我在服务器上运行我的代码时,它显示“在服务器上找不到请求的 URL。如果您手动输入了 URL,请检查您的拼写并重试”。我的代码有什么问题。请提前帮助和谢谢。
from flask import Flask,render_template,request
import pymongo
app=Flask(__name__)
app.secret_key = 'development key'
@app.route('/insert',methods=['POST','GET'])
def enter():
myclient=pymongo.MongoClient('mongodb://localhost:27017/')
mydb=myclient['student']
mycol=mydb['knit']
if request.method=='POST':
query={'name':request.form['name'],'age':request.form['age'],'city':request.form['city'],'company':request.form['company']}
x=mycol.insert_one(query)
print(x)
if __name__=='__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form method="post" action="/insert" required>
Username:<input type="text" name="name" required><br>
Age:<input type="text" name="age" required><br>
City:<input type="text" name="city" required><br>
Comapny:<input type="text" name="comapny" required><br>
<input type="submit" name="submit">
</form>
</body>
</html>
解决方案
问题是您没有从您的路线向浏览器返回任何内容。如果您不返回任何内容,则服务器对浏览器没有响应。
以下示例通过 GET 请求返回 insert.html 表单return render_template
,并在 POST 请求中返回 JSON 格式的表单字段(当您按下提交时)。确保 html 模板 ('insert.html) 位于与您的烧瓶 app.py 相同的目录中的文件夹 'templates' 中。
from flask import Flask,render_template,request
import json
app=Flask(__name__)
app.secret_key = 'development key'
@app.route('/insert',methods=['POST','GET'])
def enter():
if request.method == 'GET':
return render_template('insert.html')
if request.method == 'POST':
query={'name':request.form['name'],'age':request.form['age'],'city':request.form['city'],'company':request.form['company']}
print(query)
return json.dumps(query)
if __name__=='__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form method="post" action="/insert" required>
Username:<input type="text" name="name" required><br>
Age:<input type="text" name="age" required><br>
City:<input type="text" name="city" required><br>
Company:<input type="text" name="company" required><br>
<input type="submit" name="submit">
</form>
</body>
</html>
推荐阅读
- node.js - 猫鼬 findOne 返回未定义
- python - numpy:向量 x 矩阵 x 向量乘法
- c++ - 替换文件中的金额并将其保存到文件中
- scala - 是否可以在 Window 对象中进行模式检测?
- python - Django 视图,在 1 个视图中有 2 个重定向
- node.js - MongoDb mongoose 弃用警告 {useUnifiedTopology: true} 但它已设置为 true
- python - Python 中的 Azure 持久函数:为什么没有触发函数 2?
- javascript - 滚动视图中的映射使 React Native 中的水平列表垂直
- google-play - 谷歌播放卡在“内部测试”
- javascript - 在元素的多个实例上触发相同的滚动事件 - vanilla javascript