Here is my database code in flask and 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)
`
In your view function for /list
. Read your datas
from databse and accordingly render it in your template like below:
@app.route("/list")
def lists():
todolist = db.Student_list.find()
return render_template('snap17.html', todolist=todolist)
And In your template snap17.html
render it as
<html>
{% for elem in todolist %}
<li> {{elem['name']}}</li>
{% endfor %}
</html>
And to write into your database make a GET
request like this in your existing apllication:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.