我想使用python,Flask和mongoDB执行插入操作。 当我在服务器上运行代码时,它显示“在服务器上找不到请求的URL。如果您手动输入URL,请检查拼写,然后重试”。我的代码有什么问题。请提前帮助并thnx。
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>
答案 0 :(得分:0)
问题是您没有从路线返回任何东西给浏览器。如果不返回任何内容,则服务器对浏览器没有响应。
以下示例通过return render_template
对GET请求返回insert.html表单,而对POST请求则返回JSON格式的表单字段(按提交时)。确保html模板('insert.html)位于与flask 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>