
app.py
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.emriwmb.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca)
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_receive = request.form['comment_give']
doc = {
'name': name_receive,
'comment': comment_receive
}
db.homworks.insert_one(doc)
return jsonify({'msg': '저장완료!'})
@app.route("/homework", methods=["GET"])
def homework_get():
homework_list = list(db.homworks.find({}, {'_id': False}))
return jsonify({'homeworks': homework_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
index.html
<script>
$(document).ready(function () {
set_temp()
show_comment()
});
function set_temp() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function (response) {
$('#temp').text(response['temp'])
}
})
}
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()
}
})
}
function show_comment() {
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response['comments']
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)
}
});
}
</script>
왜 저장이 안될까요
