from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.prwfiap.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/homework", methods=["POST"])
def homework_post():
name_receive = request.form['name_give']
comment = request.form['comment_give']
doc = {
'name':name_receive,
'comment':comment
}
db.homework.insert_one(doc)
return jsonify({'msg':'저장 완료!'})
index.html 에서 name_give,comment_give 데이터를 가져와서 homework라는 db에 insert(저장)한다.
function save_comment() {
let name = $('#name').val()
let comment = $('#comment').val()
$.ajax({
type: 'POST',
url: '/homework',
data: {name_give: name,comment_give:comment},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
index.html #name, #comment 의 값을 가져와서 name_give라는 이름과 comment_give라는 이름으로 ajax를 통해서 서버로 데이터를 보낸다.
window.location.reload() = 새로고침을 말한다.
@app.route("/homework", methods=["GET"])
def homework_get():
homework_list = list(db.homework.find({}, {'_id': False}))
return jsonify({'homework':homework_list})
function show_comment() {
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response['homework']
for(let i=0; i<rows.length;i++){
let name = rows[i]['name']
let comment = rows[i]['comment']
let temp_html = `
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment}</p>
<footer class="blockquote-footer">${name}</footer>
</blockquote>
</div>
</div>
`
$('#comment-list').append(temp_html)
}
}
});
}