Jaegool_'s log

웹개발 종합반 4주차 내용 [스파르타 코딩] <Flask, POST, GET> 본문

Development Log/Web Development

웹개발 종합반 4주차 내용 [스파르타 코딩] <Flask, POST, GET>

Jaegool 2022. 5. 23. 23:16

https://teamsparta.notion.site/4-0056714b522240a68f7c778237525282

 

[스파르타코딩클럽] 웹개발 종합반 - 4주차

매 주차 강의자료 시작에 PDF파일을 올려두었어요!

teamsparta.notion.site

 

<Lecture goals>

1. Make  API, using Flask framework.

2. Make API and connect to clients.

 

 

<flask 시작 코드>

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

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

 

<Jquery import>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<GET 요청 API코드>

@app.route('/test', methods=['GET'])
def test_get():
   title_receive = request.args.get('title_give')
   print(title_receive)
   return jsonify({'result': 'success', 'msg': '이 요청은 GET!'})

<POST 요청 API코드>

@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '요청을 잘 받았어요'})

<GET 요청 확인 Ajax코드>

<script>
    function hey() {
        $.ajax({
            type: "GET",
            url: "/test?title_give=봄날은간다",
            data: {},
            success: function (response) {
                console.log(response)
            }
        })
    }
</script>

 

<POST 요청 확인 Ajax코드>

<script>
    function hey() {
        $.ajax({
            type: "POST",
            url: "/test",
            data: {title_give: '봄날은간다'},
            success: function (response) {
                console.log(response['msg'])
            }
        })
    }
</script>

 

 

<Keep>

1. 프로젝트 새로 시작할 때

- 폴더안에 디렉토리(static, templates)와 파일(app.py) 만들고 시작하기.

- flask, db 연결 패키지(flask, pymongo, dnspython) + crawling 패키지(requests, bs4) 설치

 

<Problem>

function save_order() {
    let name = $('#name').val()
    let address = $('#address').val()
    let size = $('#size').val()


    $.ajax({
        type: 'POST',
        url: '/mars',
        data: { name_give: name, address_give: address, size_give: size},
        success: function (response) {
            alert(response['msg'])
            window.location.reload()
        }
    });
}
data: { name_give: name, address_give: address, size_give: size},

name, address, size를 할당해 줄 때 'name', 'address', 'size'이런 식으로 주는 바람에 문자열 그대로 들어가는 일이 발생.

>>>>> 주의하기!

 

 

<크롤링 기본 코드>

import requests
from bs4 import BeautifulSoup

url = 'https://movie.naver.com/movie/bi/mi/basic.naver?code=191597'

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(url,headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

<POST>

1. 요청정보: URL=/movie, 요청 방식 = POST

2. 클라(ajax) >>> 서버(flask): url, star, comment 정보를 DB에 저장

3. 서버(flask) >>> 클라(ajax): 메시지를 보냄(포스팅 완료!)

<GET>

1. 요청정보: URL=/movie, 요청 방식 =GET

2. 클라(ajax) >>> 서버(flask): 없음

3. 서버(flask) >>> 클라(ajax): 전체 영화(쌓인 데이터)를 보내주기

 

<< homework >>

<app.py>

from flask import Flask, render_template, request, jsonify
from pymongo import MongoClient
import certifi

ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.l0equ.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta

app = Flask(__name__)

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

@app.route("/homework", methods=["POST"])
def homework_post():
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']

    doc = {
        'name':name_receive,
        'comment':comment_receive
    }
    db.homework.insert_one(doc)

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

@app.route("/homework", methods=["GET"])
def homework_get():
    comment_list = list(db.homework.find({}, {'_id': False}))
    return jsonify({'comments':comment_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>초미니홈피 - 팬명록</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://www.somagnews.com/wp-content/uploads/2020/03/39-6-e1585327776334.jpg');
            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 name = $('#name').val()
            let comment = $('#comment').val()

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

        function show_comment() {
            $('#comment-list').empty()
            $.ajax({
                type: "GET",
                url: "/homework",
                data: {},
                success: function (response) {
                    console.log(response)
                    let rows = response['comments']

                    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)
                    }
                }
            });
        }
    </script>
</head>
<body>
<div class="mypic">
    <h1>코난 그레이(Conan Gray) 팬명록</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 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>

<Keep>

이 코드를 사용하면

$('#comment-list').empty()

웹에서는 필요없는 내용을 비워 주지만 파일에서는 기존의 코드 형태를 알 수 있도록 보존할 수 있다.

 

<Problem>

숙제를 해결할 때 아무것도 없는 상태에서 혼자는 못할 것 같다는 생각이 든다.

기존에 내가 했던 작업을 보면서 어디에 무엇이 들어가야할 지 유추하면서 어떻게 작동하는 지 조금씩 조금씩 이해해가는 중이다.

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

코드를 다 작성하고 이 부분(POST로 데이터를 DB에 저장하고 GET으로 클라이언트에 보여주는 마지막 작업)에서 '#'을 빠뜨려서 코드를 다시 확인해야 하는 일이 생겼다.

 

<Try>

오히려 이런 실수가 나옴으로 앞으로 주의 해줄 수 있게 해주니 오류를 많이 남겨서 발전해야겠다.

오류가 나더라도 그냥 지나가면 금새 잊어버릴 것이다.