웹개발 종합반_homework_4주차

Hyeyeong·2022년 8월 7일
0

웹개발 종합반

목록 보기
11/13

🛠 팬명록 DB연결

👉 output


📍 준비 사항

  • MongoDB 로그인과 폴더 셋팅 및 서버 구축 관련(flask), mongoDB 관련(pymongo, dnspython, certifi) 패키지 설치
  • 구현할 기능 : 팬명록 작성과 작성 리스트 보여주기

1) 팬명록 저장하기

(1) API 만들고 사용하기 - 닉네임, 응원댓글 (Create → POST)

  • 요청 정보 : URL= /homework, 요청 방식 = POST
  • 클라(ajax) → 서버(flask) : name, comment
  • 서버(flask) → 클라(ajax) : 메시지를 보냄 (응원 완료!)

❗️ 작업 순서
① 클라이언트와 서버 연결 확인하기
② 서버부터 만들기
③ 클라이언트 만들기
④ 확인하기

① 클라이언트와 서버 연결 확인하기

  • app.py 실행해서 index.html 와의 연결 확인

② 서버부터 만들기

  • app.py 파일에 DB 연결 및 데이터 추가 코드 기입
@app.route("/fanrecord", methods=["POST"])
def fanrecord_post():
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']

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

③ 클라이언트 만들기

  • index.html 파일에 input에 기입되는 값을 데이터로 만든 후 app.py 파일과 연결 및 새로고침 기능 추가
function save_comment(){
            let name = $('#name').val()
            let comment = $('#comment').val()

            $.ajax({
                type: 'POST',
                url: '/fanrecord',
                data: { name_give : name, comment_give : comment },
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            })
        }

④ 확인하기
👉 output


2) 팬명록 보여주기

(1) API 만들고 사용하기 - 저장된 팬명록을 화면에 보여주기(Read → GET)

  • 요청 정보 : URL= /homework, 요청 방식 = GET
  • 클라(ajax) → 서버(flask) : (없음)
    ➟ 로딩이 되자마자 모든 데이터를 가져오기만 하면 됨
  • 서버(flask) → 클라(ajax) : 전체 팬명록을 보내주기

❗️ 작업 순서
① 클라이언트와 서버 연결 확인하기
② 서버부터 만들기
③ 클라이언트 만들기
④ 확인하기

① 클라이언트와 서버 연결 확인하기

  • app.py 실행해서 index.html 와의 연결 확인(app.py파일의 def web_homework_get(): 부분과 index.html파일의 ajax get 부분)

② 서버부터 만들기

  • app.py 파일에 데이터 가져오는 코드 기입
@app.route("/fanrecord", methods=["GET"])
def fanrecord_get():
    fan_list = list(db.fanrecords.find({}, {'_id' : False}))
    return jsonify({'lists' : fan_list})

③ 클라이언트 만들기

  • index.html 파일에 로딩 시 DB의 리스트를 조건문으로 가져오고, DB 값을 태그 내 탬플릿으로 붙이기
    ❗️ 추가된 데이터를 DB에서 확인할 수 있음
function show_comment(){
            $.ajax({
                type: "GET",
                url: "/fanrecord",
                data: {},
                success: function (response) {

                    let rows = response['lists']
                    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)
                    }
                }
            });
        }

④ 확인하기

  • 완성본 👀
profile
코딩입문 코린이

0개의 댓글