본문 바로가기
💻 개발블로그/웹개발

4주차 웹개발 강의: 팬명록만들기 예제(개발일지)

by August.J 2021. 12. 17.

* 항상 DB(MongoDB사용)를 준비한다.

* 새 프로젝트를 열고, static 과 templates 디렉토리 생성

* app.py생성, templates 안에 index.html 생성

* 패키지설치: flask, BS4, dnspython, pymongo, requests

 

POST연결

1. 요청정보: URL=/homework, 요청방식=POST2. 클라이언트(Ajax) >> 서버(Flask): name, comment3. 서버(Flask) >> 클라이언트(Ajax): 메시지보냄(입력완료)

 

GET연결

1. 요청정보: URL=/homework, 요청방식=GET2. 클라이언트(Ajax)>>서버(Flask): 없음3. 서버(Flask)>>클라이언트(Ajax): 전체데이터보내주기

 

-서버 만들기: 여러개 찾기 코드 활용

all_users = list(db.users.find({},{'_id':False}))

-클라이언트 만들기: 클라이언트는 가져갈 데이터가 없음


app.py


@app.route('/')
def home():
    return render_template('index.html')

@app.route("/homework", methods=["POST"])
def homework_post():
    nickname_receive = request.form['nickname_give']
    mycomment_receive = request.form['mycomment_give']

    doc = {'nickname':nickname_receive, 'mycomment':mycomment_receive}
    db.homework.insert_one(doc)

    return jsonify({'msg':'**입력완료**'})

@app.route("/homework", methods=["GET"])
def homework_get():
    fan_list = list(db.homework.find({}, {'_id': False}))
    return jsonify({'fan':fan_list})

if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>BTS팬명록</title>

    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Noto Serif KR', serif;
        }
        .mypic {
            width: 100%;
            height: 300px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://img.buzzfeed.com/buzzfeed-static/static/2021-05/21/15/asset/e6dd9f2189d1/sub-buzz-1688-1621612188-25.png?downsize=1600:*&output-format=auto&output-quality=auto');
            background-position: center 30%;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 20px auto;

            box-shadow: 0px 0px 3px 0px black;
            padding: 20px;
        }

        .mypost > button {
            margin-top: 15px;
        }

        .mycards {
            width: 95%;
            max-width: 500px;
            margin: auto;
        }

        .mycards > .card {
            margin-top: 10px;
            margin-bottom: 10px;
        }
    </style>
    <script>
        $(document).ready(function(){
            set_temp()
            show_comment()
        });
        function set_temp(){
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                data: {},
                success: function (response) {
                    $('#temp').text(response['temp'])
                }
            })
        }
        function save_comment(){
            let nickname = $('#name').val()
            let mycomment = $('#comment').val()

            $.ajax({
                type: 'POST',
                url: '/homework',
                data: {nickname_give: nickname, mycomment_give: mycomment},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            })
        }
        function show_comment(){
            $.ajax({
                type: "GET",
                url: "/homework",
                data: {},
                success: function (response) {
                    let rows = response['fan']
                    for (let i = 0; i < rows.length; i++){
                        let nickname = rows[i]['nickname']
                        let mycomment = rows[i]['mycomment']

                        let temp_html = `<div class="card">
                                            <div class="card-body">
                                                <blockquote class="blockquote mb-0">
                                                    <p>${mycomment}</p>
                                                    <footer class="blockquote-footer">${nickname}</footer>
                                                </blockquote>
                                            </div>
                                        </div>`
                        $('#comment-list').append(temp_html)
                    }
                }
            });
        }
    </script>
</head>
<body>
<div class="mypic">
    <h1>BTS팬명록</h1>
    <p>현재기온: <span id="temp">36</span>도</p>
</div>
<div class="mypost">
    <div class="form-floating mb-3">
        <input type="text" class="form-control" id="name" placeholder="url">
        <label for="floatingInput">닉네임</label>
    </div>
    <div class="form-floating">
<textarea class="form-control" placeholder="Leave a comment here" id="comment"
          style="height: 100px"></textarea>
        <label for="floatingTextarea2">응원댓글</label>
    </div>
    <button onclick="save_comment()" type="button" class="btn btn-dark">응원 남기기</button>
</div>
<div class="mycards" id="comment-list">
</div>
</body>
</html>

*나의 실수

 

-value값 여러개 나열시, 쉼표사용하지 않기let name = $('#name').val()let commnet = $('#comment').val()

 

-새로고침기능window.location.reload()

 

-for문에 해당 괄호 사용할 것 ()