Flask mongodb crud 삭제기능(팬명록 작성하기!)

youngsung·2023년 2월 8일
0

python

목록 보기
1/2

공부를 하면서 생성하는 기능은 많이 써봤지만, 삭제기능과 수정기능을 사용해보지 못하여서 나혼자 만들어보기로했다. 일단 삭제기능부터 만들었다.

// delete(삭제 기능!!)
@app.route("/homework2/delete", methods=["POST"])
def delete_post():
    name_receive = request.form['name_give']
    db.homework2.delete_one({'name': name_receive})
    return jsonify({'result': 'success','msg':'삭제 완료!'})
$.ajax({
                type: "GET",
                url: "/homework2",
                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" id="writer">${name}</footer>
                                                    <button onclick="modify_comment('${name}')" type="button" class="btn btn-dark">수정</button>
                                                    <button onclick="delete_comment('${name}')" type="button" class="btn btn-dark">삭제</button>
                                                </blockquote>
                                            </div>
                                        </div>`
                        $('#comment-list').append(temp_html)
                    }
                }
            });
// delete(삭제 버튼!!)
function delete_comment() {
            let name = $('.writer').text()
            console.log(name)
            $.ajax({
                    type: 'POST',
                    url: '/homework2/delete',
                    data: {'name_give':name},
                    success: function (response) {
                        alert(response['msg'])
                        window.location.reload()
                    }
                })
            }

이런식으로 작성을 하고나니 일단 삭제는 잘 되긴했다.. 여기서 또 문제점이 나온다. 내가 원하는걸 지우고싶은데 순차적으로 지워진다는것이었다. 알고보니, writer의 값이 너무 많은 값을 가져가다보니 제일 먼저있는 값이 지워진다는것이었다. 이 문제를 해결하기위해 writer의 고유의 값을 정해줘야한다 생각했다.
여러가지 시도중에있다. writer 값에 해당 번호를 주면 될거라 생각해서 코드를 작성하였다.
수많은 고민끝에 writer값에 번호를 주는것보다 데이터마다 번호를 달면 되는문제였다..아주쉽고 간단한 생각을 나는 몇시간을 이렇게 허비한지 모르겠다..ㅠㅠ아무튼 새로 코드를 작성하여

@app.route("/homework2", methods=["POST"])
def homework2_post():
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']
    comment_list = list(db.homework2.find({}, {'_id': False}))
    count = len(comment_list) + 1

    doc = {
        'name': name_receive,
        'comment': comment_receive,
        'num': count
    }
    db.homework2.insert_one(doc)
    return jsonify({'msg':'응원 완료!'})

이런식으로 해당 데이터마다 count를 주었고,

@app.route("/homework2/delete", methods=["POST"]) # delete(삭제 기능!!)
def delete_post():
    num_receive = request.form['num_give']
    db.homework2.delete_one({'num': int(num_receive)})
    return jsonify({'result': 'success','msg':'삭제 완료!'})
            $.ajax({
                type: "GET",
                url: "/homework2",
                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 num = rows[i]['num'] //고유 num을 줘서 데이터를 구분을 하기위함.

                        let temp_html = `<div class="card">
                                            <div class="card-body">
                                                <blockquote class="blockquote mb-0">
                                                    <p>${comment}</p>
                                                    <footer class="blockquote-footer" id="writer">${name}</footer>
                                                    <button onclick="modify_comment('${num}')" type="button" class="btn btn-dark">수정</button>
                                                    <button onclick="delete_comment('${num}')" type="button" class="btn btn-dark">삭제</button>
                                                </blockquote>
                                            </div>
                                        </div>`
                        $('#comment-list').append(temp_html)
                    }
                }
            });
         function delete_comment(num) {
            $.ajax({
                    type: 'POST',
                    url: '/homework2/delete',
                    data: {'num_give':num},
                    success: function (response) {
                        alert(response['msg'])
                        window.location.reload()
                    }
                })
            }

이런식으로 해당 데이터에 번호를 주니 쉽게 해결되었다..내가 너무 어렵게 생각한듯하다. 아직 구글링 연습도 많이 필요하다

profile
To Infinity and Beyond

0개의 댓글