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

2022. 4. 28. 20:033층 1구역 - 개발의 장/웹개발 일지(풀스택)

4주차는 이제까지 만들어둔 HTML과 데이터베이스인 mongoDB를 연동해서 서버를 만들게 된다.

(낯부끄러운 사이트 하나가 어쩌면 누군가 보게 될 수도 있다..)

 

우리는 Flask 라는 프레임워크를 통해 서버 구동을 시도해 보는데, 서버를 구동하기 위해선 꽤 복잡한 일들을

이거 하나로 간편하게 해결 가능하다.

 

굳이 따지자면 프레임워크를 쓰느냐 안쓰느냐 차이는

우리가 카레를 만드는데 강황, 우유, 기타 속 재료를 손질하고 씻을 건 씻고, 풍미를 위해 굽고 찌고 뭐하는 과정이

프레임워크를 안 쓰는 과정이며, 프레임워크를 사용한다는 것은 3분카레를 뎁혀서 밥에 뿌려먹는 정도로 생각하면 될 거 같다.

 

Flask 서버를 만들 땐,

Project 폴더 안에

venv

static 폴더 << 이미지, css파일을 넣어두는 곳

templates 폴더 << html 파일을 넣어두는 곳

app.py 파일

3가지를 만들어두고 시작하도록 하자. (venv는 가상환경을 구축해주는 파일이라 안보인다 라고 생각하도록 하자.)

 

3주차에 GET,POST방식에 대해 짧게 배운 것이 있다.

GET방식은 데이터조회(Read)를 요청할 때

POST방식은 생성(Create), 변경(Update), 삭제(Delete)를 요청할 때

 

숙제인 기존에 만들었던 팬명록을 통해 자세히 알아보도록 하자.

프로젝트 기본환경 구축

앞서 언급한 프로젝트 기본 폴더 및 파이썬파일을 만들어주고,

프로젝트의 가상환경을 구축해줘야 한다.

프로젝트 기본환경 구축 2

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

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

Flask 임폴트 및 mongoDB를 사용하기 위한 pymongo임폴트 관한 코드

 

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

첫번째 줄 @app.route('/') : 따로 url루트를 나눠주는 코드인데 지금 할 필요 없다.

만약 url를 나눠줄 필요가 있다면

@app.route('/mypage')

def home():

     return '블라블라블라' 

이런 식으로 나눠주면 '기본 주소/mypage' 라고 입력하면 '블라블라블라' 라고 써있는 페이지로 진입하게 된다.

 

두번째,세번째 줄

def home():

     return render_template('index.html')

위에 코드에서 설명했듯 홈페이지가 있으면 그 페이지에 무엇을 보여줄거냐 라고 묻는 것이라고 생각하면 될 것이다.

위에서 return '블라블라블라' 라고 써져 있으면 그 페이지에 '블라블라블라' 가 출력되고, 지금 코드는

templates 폴더에 있는 index.html 파일 있잖아? 그거 보여 줘! 라는 느낌이다.

 

포스트(POST)방식에 관하여

 

 

app

@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':'응원 감사합니다!'})

 

index

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 save_comment() {
    let name = $('#name').val()
    let comment = $('#comment').val()

홈페이지에서 닉네임(name), 한줄 평(comment)을 입력하면

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

1. ajax콜을 하는데

2. POST타입이며,

3. index에서 url은 '/homework'이고, (app에서 @app.route("/homework", methods=["POST"]) 이부분)

4. 닉네임은 name_give라는 데이터로, 한줄 평은 comment_give라는 데이터로 이동한 후,

5. 성공했으면 response하고 'msg'를 띄어라

6. 그 후 window.location.reload() (새로고침) 해라.

 

그러면 app 쪽에선

@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':'응원 감사합니다!'})

1. OK! url과 POST 방식인 거 확인했어.

2. 닉네임(name_give), 한줄 평(comment_give) 데이터 가져왔지?

각각 name_receive, comment_receive 창구로 가져가

3. 그러면 데이터베이스(mongoDB)에서 각 창구의 데이터를 기록해 줄게

4. 그 후 홈페이지에서 '응원 감사합니다!' 라는 메세지를 띄어줄게

 

이런 흐름으로 흘러가게 된다.

POST방식의 결과 값
데이터베이스에 저장된 기록

 

GET방식에 관하여

 

 

app

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

 

index

function show_comment() {
    $.ajax({
        type: "GET",
        url: "/homework",
        data: {},
        success: function (response) {
            let rows = response['homework']
            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)

 

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

1. url은 homework이고, GET방식이다.

2. homework_list는 데이터베이스에 있는 homework 카테고리에서 찾아주고 id값은 필요없다.

3. 다 찾았으면 데이터를 조회하고자 homework를 입력하면 homework_list를 보여주면 된다.

 

function show_comment() {
    $.ajax({
        type: "GET",
        url: "/homework",
        data: {},
        success: function (response) {
            let rows = response['homework']
            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)

1. ajax콜을 할 것이다.

2. url은 homework이고 GET방식이다.

3. 데이터는 전부

4. 성공하면 homework 관련을 보여주는데

i = 0부터 rows.length만큼 도는데 i에 하나씩 추가해라.(i++)

5. name은 rows[i]['name']값을 보여주고, comment는 rows[i]['comment']의 값을 보여준다.

6. 이걸 종합해서 temp_html을 만들건데,

comment는 코멘트 칸에(<p>${comment}</p>)

name은 (<footer class="blockquote-footer">${name}</footer>)

이후 id=comment-list인 곳에 temp_html 결과를 보여줘라.

 

데이터베이스에 있던 값

POST, GET방식에 대한 흐름이다. 아직 용어에 대해 완벽히 이해 한것이 아니라 해석에 있어서 어색함이 있을거지만

내가 알아보면 장땡이지

 

4주차를 접하면서 3주차까지 '내가 잘하고 있는게 맞나?' 라고 생각했던 게 조금씩 '잘하고 있는 거 같다' 라고 바뀌는 듯 하다. 튜터님 께서 이번껀 2분이면 되겠다, 3분이면 되겠다 하면서 개인적으로 해결할 시간을 주시는데 10분이 되도 모르겠고, 30분이 되도 몰라 결국 강의 해답을 보고 '이렇구나' 해서 '여기는 나랑 안 맞는다' 라고 생각했는데

한 번 보고 나중에 복습으로 강의 들으며 실습해보면 좀 더 이해가 잘 되더라..

 

아직 내가 프론트엔드인지 백엔드인지 5주차 강의도 들어봐야 알겠지만 지금은 뭐든 이해가 조금씩 되기 시작하니

다 재미있다.