gpt4 book ai didi

python - 当我运行此 flask 代码时,什么也没有发生,值没有存储在 mongodb 数据库中

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:03 25 4
gpt4 key购买 nike

这是我在 Flask 和 mongodb 中的数据库代码 snadb.py

 from flask import Flask, render_template, request, redirect, url_for,request
from bson import ObjectId
from pymongo import MongoClient
import os

app = Flask(__name__)

client = MongoClient("mongodb://127.0.0.1:27017") #host uri
db = client.Student #Select the database
todos = db.Student_list #Select the collection name


def redirect_url():
return url_for('action')

@app.route("/list")
def lists ():
return render_template('snap17.html')


@app.route("/snap17", methods=['GET','POST'])
def action ():
#Adding a Task
name=request.values.get("firstname")
todos.insert({ "name":name})
return redirect("/list")

if __name__ == "__main__":
app.run(debug=True)

`

最佳答案

/list 的 View 函数中。从数据库读取您的数据并相应地将其呈现在您的模板中,如下所示:

@app.route("/list")  
def lists():
todolist = db.Student_list.find()
return render_template('snap17.html', todolist=todolist)

并在您的模板 snap17.html 中将其渲染为

<html>
{% for elem in todolist %}
<li> {{elem['name']}}</li>
{% endfor %}
</html>

要写入数据库,请在现有应用程序中发出如下 GET 请求:

http://localhost:5000/snap17?firstname="JaiSambhu"

关于python - 当我运行此 flask 代码时,什么也没有发生,值没有存储在 mongodb 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54359705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com