티스토리 뷰

반응형
@app.route('/api/list', methods=['GET'])
def show_stars():
    sample_receive = request.args.get('sample_give')
    print(sample_receive)
    return jsonify({'msg': 'list 연결되었습니다!'})

 

받을 데이터가 없기 때문에 지우고 dbprac에서 찾기를 붙인다

# API 역할을 하는 부분
@app.route('/api/list', methods=['GET'])
def show_stars():
    movie_star = list(db.mystar.find({'age': 21}, {'_id': False}))
    return jsonify({'movie_stars': movie_star})

문제는 정렬을 해서 내려줘야함

pymongo에 정렬해서 뽑는 기능이 있음

'pymongo 정렬' 구글링

→ 'pymongo sort w3school' 구글링

# API 역할을 하는 부분
@app.route('/api/list', methods=['GET'])
def show_stars():
    movie_Star = list(db.mystar.find({}, {'_id': False}).sort('like', -1))
    return jsonify({'movie_stars': movie_Star})

이제 서버쪽은 끝났고 html쪽에선 우선 movie_star가 들어오는지 찍어봄

function showStar() {
    $.ajax({
        type: 'GET',
        url: '/api/list?sample_give=샘플데이터',
        data: {},
        success: function (response) {
            let mystars = response['movie_stars']
            console.log(mystars)
        }
    });
}

잘 나왔으면 for 문으로 돌려보기

 $.ajax({
        type: 'GET',
        url: '/api/list?sample_give=샘플데이터',
        data: {},
        success: function (response) {
            let mystars = response['movie_stars']
            for (let i = 0; i < mystars.length; i++){
                let name = mystars[i]['name']
                let img_url = mystars[i]['img_url']
                let recent = mystars[i]['recent']
                let url = mystars[i]['url']
                let like = mystars[i]['like']

                let temphtml = `<div class="card">
                                    <div class="card-content">
                                        <div class="media">
                                            <div class="media-left">
                                                <figure class="image is-48x48">
                                                    <img
                                                            src="${img_url}"
                                                            alt="Placeholder image"
                                                    />
                                                </figure>
                                            </div>
                                            <div class="media-content">
                                                <a href="#" target="_blank" class="star-name title is-4">${name} (좋아요: ${like})</a>
                                                <p class="subtitle is-6">${recent}</p>
                                            </div>
                                        </div>
                                    </div>
                                    <footer class="card-footer">
                                        <a href="${url}" onclick="likeStar('${name}')" class="card-footer-item has-text-info">
                                            위로!
                                            <span class="icon">
                                  <i class="fas fa-thumbs-up"></i>
                                </span>
                                        </a>
                                        <a href="#" onclick="deleteStar('${name}')" class="card-footer-item has-text-danger">
                                            삭제
                                            <span class="icon">
                                  <i class="fas fa-ban"></i>
                                </span>
                                        </a>
                                    </footer>
                                </div>`
            }
        }
    });
}

다 완성한 후에 라이크가 역순으로 잘나오는지 확인

robo3t로 들어가서 edit으로 숫자를 수정한 후 맨위로 올라가나 확인

 

완성

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title>마이 페이보릿 무비스타 | 프론트-백엔드 연결 마지막 예제!</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css"/>
        <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
        <style>
            .center {
                text-align: center;
            }

            .star-list {
                width: 500px;
                margin: 20px auto 0 auto;
            }

            .star-name {
                display: inline-block;
            }

            .star-name:hover {
                text-decoration: underline;
            }

            .card {
                margin-bottom: 15px;
            }
        </style>
        <script>
            $(document).ready(function () {
                showStar();
            });

            function showStar() {
                $.ajax({
                    type: 'GET',
                    url: '/api/list?sample_give=샘플데이터',
                    data: {},
                    success: function (response) {
                        let mystars = response['movie_stars']
                        for (let i = 0; i < mystars.length; i++){
                            let name = mystars[i]['name']
                            let img_url = mystars[i]['img_url']
                            let recent = mystars[i]['recent']
                            let url = mystars[i]['url']
                            let like = mystars[i]['like']

                            let temp_html = `<div class="card">
                                                <div class="card-content">
                                                    <div class="media">
                                                        <div class="media-left">
                                                            <figure class="image is-48x48">
                                                                <img
                                                                        src="${img_url}"
                                                                        alt="Placeholder image"
                                                                />
                                                            </figure>
                                                        </div>
                                                        <div class="media-content">
                                                            <a href="#" target="_blank" class="star-name title is-4">${name} (좋아요: ${like})</a>
                                                            <p class="subtitle is-6">${recent}</p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <footer class="card-footer">
                                                    <a href="${url}" onclick="likeStar('${name}')" class="card-footer-item has-text-info">
                                                        위로!
                                                        <span class="icon">
                                              <i class="fas fa-thumbs-up"></i>
                                            </span>
                                                    </a>
                                                    <a href="#" onclick="deleteStar('${name}')" class="card-footer-item has-text-danger">
                                                        삭제
                                                        <span class="icon">
                                              <i class="fas fa-ban"></i>
                                            </span>
                                                    </a>
                                                </footer>
                                            </div>`
                            $('#star-box').append(temp_html)
                        }
                    }
                });
            }

            function likeStar(name) {
                $.ajax({
                    type: 'POST',
                    url: '/api/like',
                    data: {sample_give:'샘플데이터'},
                    success: function (response) {
                        alert(response['msg']);
                    }
                });
            }

            function deleteStar(name) {
                $.ajax({
                    type: 'POST',
                    url: '/api/delete',
                    data: {sample_give:'샘플데이터'},
                    success: function (response) {
                        alert(response['msg']);
                    }
                });
            }

        </script>
    </head>
    <body>
        <section class="hero is-warning">
            <div class="hero-body">
                <div class="container center">
                    <h1 class="title">
                        마이 페이보릿 무비스타😆
                    </h1>
                    <h2 class="subtitle">
                        순위를 매겨봅시다
                    </h2>
                </div>
            </div>
        </section>
        <div class="star-list" id="star-box">

        </div>
    </body>
</html>
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
링크
글 보관함