【问题标题】:What's wrong in my code?I am new to Flask [duplicate]我的代码有什么问题?我是 Flask 的新手 [重复]
【发布时间】:2019-08-26 14:52:42
【问题描述】:

我想使用 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>

【问题讨论】:

  • 默认使用 IP 127.0.0.1,这意味着它不能从其他计算机访问。您可能必须使用app.run(host='0.0.0.0', debug=True)
  • 在“0.0.0.0”处显示 =====“无法访问此站点0.0.0.0 处的网页可能暂时关闭,或者它可能已永久移动到新网址.ERR_ADDRESS_INVALID"
  • 我解决了问题。谢谢先生。弗拉斯

标签: python mongodb flask


【解决方案1】:

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

以下示例在通过return render_template 的 GET 请求中返回 insert.html 表单,在 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>

【讨论】:

  • 如何在模板“success.html”上打印我的 mongodb 数据后使用此...return render_template('success.html',body=x)。我应该使用什么来打印数据就像 1-body.name(我要打印的表单字段)或任何其他方式。
猜你喜欢
  • 2018-08-19
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多