首页 > 解决方案 > 我的代码有什么问题?我是 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>

标签: pythonmongodbflask

解决方案


问题是您没有从您的路线向浏览器返回任何内容。如果您不返回任何内容,则服务器对浏览器没有响应。

以下示例通过 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>

推荐阅读