Self Code Review/(sparta) WEB plus - 나만의 단어장

[나만의 단어장] 7. 상세페이지 - 저장 & 삭제 기능 만들기

밍굥잉 2022. 5. 4. 14:20

1. 새 단어 / 기존 단어 구분

 

✅ url 예시

localhost:5000/detail/hello?status_give=new ⇒ 💾 버튼

localhost:5000/detail/hello?status_give=old ⇒ 🗑️버튼

status_receive = request.args.get("status_give", "new") 
# status_give 라는 파라미터를 status_receive 라는 이름으로 받음
# status_give 라는 파라미터를 주지 않을 경우를 대비해, 기본값을 "new"로 주도록 함.
return render_template("detail.html", word=keyword, result=result, status=status_receive)
# detail.html에 status 라는 이름으로 보냄
@app.route('/detail/')
def detail(keyword):
    # API에서 단어 뜻 찾아서 결과 보내기
    status_receive = request.args.get("status_give", "new")
    r = requests.get(f"<https://owlbot.info/api/v4/dictionary/{keyword}>",
                     headers={"Authorization": "Token [내 토큰]"})
    result = r.json()
    print(result)
    return render_template("detail.html", word=keyword, result=result, status=status_receive)
{% if status=="new" %} <!--status가 "new"이면 저장 버튼, 클릭하면 save_word() 함수 호출-->
    <button id="btn-save" class="btn btn-outline-sparta btn-lg" onclick="save_word()">
        <i class="fa fa-floppy-o"></i>
    </button>
{% else %} <!--아니면 삭제 버튼, 클릭하면 delete_word() 함수 호출-->
    <button id="btn-delete" class="btn btn-sparta btn-lg" onclick="delete_word()">
        <i class="fa fa-trash-o"></i>
    </button>
{% endif %}

 

2. 저장 기능 만들기

 

 서버 - 단어 저장 API

목록 페이지에서는 단어 당 뜻을 하나만 보여주기 때문에

단어와 첫 번째 정의만 POST 요청으로 보내고,

서버에서 단어와 뜻을 받아 words 컬렉션에 저장.

@app.route('/api/save_word', methods=['POST'])
def save_word(): # 단어 저장 함수
    word_receive = request.form['word_give'] 
    # 받을 단어를 저장할 변수 word_receive에 request의 form의 word_give라는 이름으로 보냄 
    # 즉, word_give로 클라이언트에서 보내준 데이터를 word_receive로 받음
    definition_receive = request.form['definition_give']
    # 받을 뜻을 저장할 변수 definition_receive에 request의 form의 definition_give라는 이름으로 보냄 
    # 즉, definition_give로 클라이언트에서 보내준 데이터를 definition_receive로 받음

    doc = {"word": word_receive, "definition": definition_receive}

    db.words.insert_one(doc)
    # db.컬렌션 이름.doc이라는 도큐먼트 하나를 보냄

    return jsonify({'result': 'success', 'msg': f'word "{word_receive}" saved'})

 

클라이언트 - 단어 저장 요청을 보낼 함수

클라이언트에서는 save_word API로 POST요청을 보내는데,

필요한 데이터(word_give, definition_give)들을 보내서

단어 저장엣 성공을 하면 메시지를 alert로 띄우고,

delete 버튼이 있는 status_give가 old인 페이지로 변경.

function save_word() {
    $.ajax({
        type: "POST",
        url: `/api/save_word`, 
        data: {
            word_give: "{{ word }}",
            definition_give: "{{ result.definitions[0].definition }}"
        },
        success: function (response) {
          alert(response["msg"])
          window.location.href = "/detail/{{ word }}?status_give=old"
        }
    });
}

 

3. 삭제 기능 만들기

 

 서버 - 단어 삭제 API

단어를 삭제할 때는 단어만 있으면 되므로 POST 요청으로 단어를 보내주고,

서버에서는 해당 단어를 찾아 삭제해줌.

@app.route('/api/delete_word', methods=['POST'])
def delete_word(): # 단어 삭제 함수
    word_receive = request.form['word_give']
		# word_receive로 클라이언트에서 보내준 데이터를 word_give로 받음
    db.words.delete_one({"word": word_receive})
		#db의 words에서 word_receive에 해당하는 word 하나를 지움
    db.examples.delete_many({"word": word_receive})
    return jsonify({'result': 'success', 'msg': f'word "{word_receive}" deleted'})

 

 클라이언트 - 단어 삭제 요청을 보낼 함수

delete_word API로 POST요청을 보내는데, 필요한 데이터(word)들을 보냄.

단어 삭제에 성공하면 더이상 보여줄 정보가 없으므로

메시지를 alert로 띄우고, 메인 페이지로 이동

function delete_word() {
    $.ajax({
        type: "POST",
        url: `/api/delete_word`,
        data: {
            word_give: "{{ word }}
        },
        success: function (response) {
            alert(response["msg"])
            window.location.href = "/"
        }
    });
}