배움 __IL/TIL 0기

TIL - 4 POST & GET 하기

Mo_bi!e 2022. 10. 28. 16:37

<문제>

1주차의 과학5호기 방명록 완성하기

1. 응원 남기기(POST): 정보 입력 후 '응원 남기기' 버튼클릭 시 주문목록에 추가

2.응원 보기(GET): 페이지 로딩 후 하단 응원 목록이 자동으로 보이기

 

시작 이전에 차근차근 스텝을 밟아야한다.

Step 1. 클라이언트와 서버 확인할것

Step 2. post 확인

Setp 3. Get 확인

 

<app.py>

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://mo:jae@cluster0.joa3ijk.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
@app.route('/')
def home():
   return render_template('index.html')

@app.route("/homework", methods=["POST"])
def homework_post():
    nick_receive = request.form['nick_give']
    reple_receive = request.form['reple_give']

    doc = {
        'nick': nick_receive,
        'reple': reple_receive
    }
    db.kkk.insert_one(doc)

    return jsonify({'msg':'POST 연결 완료!'})

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

if __name__ == '__main__':
   app.run('0.0.0.0', port=5001, 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>초미니홈피 - 팬명록</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://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ7T1QSCYzk4IruFCvrMUS5lrqo2vuRbFSycg&usqp=CAU');
            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 nick = $('#nick').val()
            let reple = $('#reple').val()

            $.ajax({
                type: 'POST',
                url: '/homework',
                data: {nick_give : nick, reple_give :reple},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            })
        }
        function show_comment(){
            $.ajax({
                type: "GET",
                url: "/homework",
                data: {},
                success: function (response) {
                    console.log('you',response)

                    let rows = response['reple']
                    for (let i = 0 ; i<rows.length;i++){
                        let nick = rows[i]['nick']
                        let reple = rows[i]['reple']

                        console.log(nick,reple)

                        let temp_html = `<div class="card">
                                        <div class="card-body">
                                            <blockquote class="blockquote mb-0">
                                                <p>${reple}</p>
                                                <footer class="blockquote-footer">${nick}</footer>
                                            </blockquote>
                                        </div>
                                       </div>`

                        $('#reple-list').append(temp_html)

                    }
                }
            });
        }
    </script>
</head>
<body>
    <div class="mypic">
        <h1>과학 5호기 방명록</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="nick" placeholder="url">
            <label for="floatingInput">닉네임</label>

        </div>
        <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="reple"
                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="reple-list">
        <div class="card">
            <div class="card-body">
                <blockquote class="blockquote mb-0">
                    <p>새로운 앨범 너무 멋져요!</p>
                    <footer class="blockquote-footer">호빵맨</footer>
                </blockquote>
            </div>
        </div>
        <div class="card">
            <div class="card-body">
                <blockquote class="blockquote mb-0">
                    <p>새로운 앨범 너무 멋져요!</p>
                    <footer class="blockquote-footer">호빵맨</footer>
                </blockquote>
            </div>
        </div>
        <div class="card">
            <div class="card-body">
                <blockquote class="blockquote mb-0">
                    <p>새로운 앨범 너무 멋져요!</p>
                    <footer class="blockquote-footer">호빵맨</footer>
                </blockquote>
            </div>
        </div>
    </div>
</body>
</html>

호빵맨까지는 기본적으로 입력된 html이고, 그 아래부터는 서버로부터 post된 방명록들

 

<과정에서 문제 사항>

1

post가 되지 않았음

id값을 서로 올바르게 하지않아서 발생한 문제임

html이랑 자바스크립트 구조에대해서 다시 한번 더 이해하게되었음

 

append()가 되지안았음

# 을 붙이지 않았음

반복된 실수를 한거임

 

<느낀점>

문제를 해결하는 과정에서 반복실수와 그리고 구조를 더 잘 파악할수있게 된다는 이점이 있다.

프로그래밍은 실패는 필연적이고 실패를 해야 더 성장할 수있다는 것을 알 수있다.

 

이러한 연유로 스트레스를 받기보다 성장의 기회라고 다시 생각하게끔 하는 것이 좋다고 봄

'배움 __IL > TIL 0기' 카테고리의 다른 글

TIL - 자료표현과 변수 [221105]  (0) 2022.11.05
[TIL-5] AWS로 서버 구매부터 실행 후 최종 배포까지  (0) 2022.11.02
TIL-3 지니뮤직의 1~50위 곡을 스크래핑  (0) 2022.10.28
TIL - 2  (0) 2022.10.20
TIL - 1  (0) 2022.10.18