from flask import Flask, render_template, request, jsonify
import pymysql
app = Flask(__name__)
# database에 접근
db = pymysql.connect( host='localhost',
port=3306,
user='root',
passwd='changmin94!',
db='project',
charset='utf8')
# database를 사용하기 위한 cursor를 세팅합니다.
cursor = db.cursor()
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
# GET 구현
@app.route("/comment", methods=["GET"])
def comment_get():
sql = '''SELECT * FROM test_table'''
cursor.execute(sql)
data_list = cursor.fetchall()
return jsonify({'data_list': data_list})
$(document).ready(function () {
reload_comment();
});
// GET - 댓글 불러오기
function reload_comment() {
$.ajax({
type: "GET",
url: "/comment",
data: {},
success: function (response) {
doc = response['data_list']
for (let i = 0; i < doc.length; i++) {
let id = doc[i][0]
let name = doc[i][1]
let comment = doc[i][2]
let note = doc[i][3]
let 템플릿 = `<tr>
<th>${id}</th>
<th>${name}</th>
<th>${comment}</th>
<th>${note}</th>
</tr>`
$('#comment-list').append(템플릿)
}
}
});
}
$('.btn-write').on('click', () => $('.post-write').fadeIn(1000) ) // 글쓰기 버튼 클릭 시 write창 보여짐
$('.close').on('click', () => $('.post-write').fadeOut(1000) ) // 닫힘 버튼 클릭 시 write창 사라짐
글쓰기 버튼 클릭 시 fadein
닫힘 버튼 클릭 시 fadeout
# POST 구현
@app.route("/save_comment", methods=["POST"])
def comment_post():
name_receive = request.form['name_give']
comment_receive = request.form['comment_give']
print(name_receive)
sql =f'''INSERT INTO test_table(name, comment, note)
VALUES('{name_receive}', '{comment_receive}', '비고');'''
cursor.execute(sql)
db.commit()
return jsonify({'msg':'댓글 입력 완료!'})
// POST - 댓글 저장하기
function save_comment() {
let name = $('#name').val()
let comment = $('#comment').val()
$.ajax({
type: 'POST',
url: '/save_comment',
data: {name_give: name, comment_give: comment},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}