사전 스터디(웹개발 종합반 4주차)

[수업 목표]
1. Flask 프레임워크를 활용해서 API를 만들 수 있다.
2. '화성에 땅사기' API를 만들고 클라이언트에 연결한다.
3. '스파르타피디아' API를 만들고 클라이언트와 연결한다.

✍️새로 학습한 내용


1.Flask 프레임워크(서버 만들기)

서버를 직접 만들어서 구동시키기 위해서는 굉장히 복잡한 일들을 해야하는데, Flask 프레임워크를 활용하여 서버를 쉽게 구축하고 구동할 수 있게해준다.
flask 패키지 설치
  • app.py 파일 flask 시작 코드
#app.py 파일

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) # port 5000번으로 연결

app.py 파일을 수행한 후 브라우저를 통해서 http://localhost:5000/으로 접속

👉 내 PC에서 서버를 구동 시 localhost로 접속

👉 5000번 포트로 접속

👉 / (루트경로,최상위경로) , /mypage와 같이 루트경로에 추가적으로 경로를 주어 URL을 나눌 수 있다.

 

  • Flask 기본 폴더구조
프로젝트 폴더 안에,
👉 static폴더(이미지,css파일을 넣어둔다.)
👉 templates(html파일을 넣어둔다.)
👉 app.py 파일

 

  • 요청한 클라이언트에 HTML파일 내려주기
flask 내장함수 render_template를 이용하면 쉽게 원하는 요청에 따른 해당 html을 보내줄 수 있다.
from flask import Flask, render_template
app = Flask(__name__)

## URL 별로 함수명이 같거나,
## route('/') 등의 주소가 같으면 안됩니다.
@app.route('/') # '/'로 요청 시
def home():
	return render_template('index.html') # templates/index.html파일 내려주기

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

 

  • 클라이언트-서버 통신
클라이언트 : Jquery.Ajax를 활용하여 서버로 요청을 보내고 응답을 받는다.
서버 : Flask 프레임워크를 활용하여 클라이언트로부터 요청을 받아서 원하는 기능을 수행 후 결과를 전달한다.
         : 데이터를 추가,검색,수정,삭제와 같은 기능을 수행 시 연결된 DB와 통신하여 데이터조작관련 기능 수행
         : 요청을 받기 위한 request, 응답을 위한 jsonify 내장함수를 임포트해준다.
  • GET 요청 통신
# 서버쪽
from flask import Flask, render_template, request, jsonify

@app.route('/test', methods=['GET']) #url: /test, 요청방식 : GET
def test_get():
	title_receive = request.args.get('title_give') #get요청 시 넘어오는 값 받기
	print(title_receive)
	return jsonify({'result':'success', 'msg': '이 요청은 GET!'})


--------------------------------------------------------------------------------------------
# 클라이언트쪽

$.ajax({
    type: "GET",
    url: "/test?title_give=봄날은간다", //get요청 시 데이터 전달
    data: {},
    success: function(response){
    console.log(response)
    }
})

 

  • POST 요청 통신
# 서버쪽
from flask import Flask, render_template, request, jsonify

@app.route('/test', methods=['POST'])
def test_post():
    title_receive = request.form['title_give'] # POST 시 데이터 받는방법
    print(title_receive)
    return jsonify({'result':'success', 'msg': '이 요청은 POST!'})



--------------------------------------------------------------------------------------------
# 클라이언트쪽

$.ajax({
    type: "POST",
    url: "/test",
    data: { title_give:'봄날은간다' }, //POST 시 데이터 전달 방식
    success: function(response){
    console.log(response)
)}

 

  • import oo , from oo import xx 차이
예를들어 oo라는 모듈에 xx()라는 함수를 사용하려고 한다.

import oo로 선언 시 → oo.xx() [모듈명.함수명( )] 식으로 사용해야한다.
from oo import xx로 선언시  → xx() [함수명( )]식으로 바로 함수사용가능하다.

💻과제


  • 1주차에  팬명록에 다음 기능 추가!
  • 응원 남기기(POST): 정보 입력 후 '응원 남기기' 버튼클릭 시 주문목록에 추가
  • 응원 보기(GET): 페이지 로딩 후 하단 응원 목록이 자동으로 보이기
app.py 코드
from flask import Flask, render_template, request, jsonify
from pymongo import MongoClient
client = MongoClient('db정보')
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.fans.insert_one(doc)
    return jsonify({'msg':'등록 완료!'})

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

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://cdn.newsculture.press/news/photo/202209/511072_621954_2920.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() {
            $.ajax({
                type: "GET",
                url: "/homework",
                data: {},
                success: function (response) {
                    let rows = response['comment']

                    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>이영지 팬명록</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="name">닉네임</label>
    </div>
    <div class="form-floating">
<textarea class="form-control" placeholder="Leave a comment here" id="comment"
          style="height: 100px"></textarea>
        <label for="comment">응원댓글</label>
    </div>
    <button onclick="save_comment()" type="button" class="btn btn-dark">응원 남기기</button>
</div>
<div class="mycards" id="comment-list">
</div>
</body>
</html>

 


🖊 회고


 

어느덧 4주차 강의까지 모두 수강하였다.  크게 어렵거나 이해가 안되거나 하는 부분은 없었으며, 도움이 되었던 것은 1주차부터해서 갑자기 확확 바뀌는 것이 아니라 그 전에 했던 것에서 추가추가 이런식으로 진행이 되다보니 전반적으로 부담도 덜하고 클라이언트-서버간 통신에 대해서 정리가 되는 듯 했다.

 

기존에 django 프레임워크로 했었는데, 그 당시 사실 맛보기 식으로 잠깐해본 것이라 거의 깡통이었고, flask가 있다는 것은 들었는데 이번에 실제로 해보면서 조금이나마 체험을 해 본것이 충분히 좋은 경험이 되었다고 생각한다.

 

추가적으로 통신을 위해서 ajax도 계속 실습해보고 사용해보면서 강의를 듣기 전보다 많이 친숙해진 것 같다. 

 

마지막으로 강의를 들으면서 1,2주차 때는 직접 내 pc에 있는 html파일을 브라우저로 열었는데, 이 부분에 대해서 서버에서 주는 것과 차이점을 잠시 알려주신 부분에 대해서 아~하~ 맞지! 하면서 뭔가 정리되는 느낌도 받았다.