[이노베이션캠프]웹개발 종합반 - 4주차(Flask, API)

Chaewon Yoon (Jamie)·2022년 7월 26일
0

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

로컬 개발 환경 + mongoDB 클라우드 서비스 이용할 것!

Flask 프레임워크: 서버를 구동시켜주는 편한 코드 모음. 서버를 구동하려면 필요한 복잡한 일들을 쉽게 가져다 쓸 수 있습니다.
    
    👉 프레임워크를 쓰지 않으면 태양초를 빻아서 고추장을 만드는 격!
    프레임워크는 3분 요리/소스 세트라고 생각하면 되겠습니다!
        

Flask 시작하기 - HTML파일 주기

- 1) Flask 기초: 기본 폴더구조 - 항상 이렇게 세팅하고 시작!
   
    👉 Flask 서버를 만들 때, 항상,
    
    프로젝트 폴더 안에,
     **ㄴstatic 폴더** (이미지, css파일을 넣어둡니다)
     **ㄴtemplates 폴더** (html파일을 넣어둡니다)
     **ㄴapp.py 파일**
    
    이렇게 세 개를 만들어두고 시작하세요!
    
    👉 **templates 폴더의 역할을 알아보겠습니다.**
    HTML 파일을 담아두고, 불러오는 역할을 하죠!
    
    
    👉 flask 내장함수 render_template를 이용합니다. 바로 이게 프레임워크의 위력!

    ```python
    from flask import Flask, render_template
    app = Flask(__name__)

    ## URL 별로 함수명이 같거나,
    ## route('/') 등의 주소가 같으면 안됩니다.

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

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

👉 GET, POST 방식

  • GET → 통상적으로! 데이터 조회(Read)를 요청할 때
    예) 영화 목록 조회
    데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달
    → 예: google.com?q=북극곰

  • POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때
    예) 회원가입, 회원탈퇴, 비밀번호 수정
    데이터 전달 : 바로 보이지 않는 HTML body에 key:value 형태로 전달

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!'})

GET 요청 확인 Ajax코드

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

POST 요청 API코드

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

POST 요청 확인 Ajax코드

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

[프로젝트 #1] - 화성땅 공동구매

http://spartacodingclub.shop/web/mars (완성작)

1. 프로젝트 설정 - flask 폴더 구조 만들기

👉 static, templates 폴더, app.py 만들기, templates 안에 index.html 만들기

2. 패키지 설치 - flask, pymongo, dnspython, certifi

3. 뼈대 준비: 화성땅 공동구매-app.py

    from flask import Flask, render_template, request, jsonify
    app = Flask(__name__)
    
    @app.route('/')
    def home():
       return render_template('index.html')
    
    @app.route("/mars", methods=["POST"])
    def web_mars_post():
        sample_receive = request.form['sample_give']
        print(sample_receive)
        return jsonify({'msg': 'POST 연결 완료!'})
    
    @app.route("/mars", methods=["GET"])
    def web_mars_get():
        return jsonify({'msg': 'GET 연결 완료!'})
    
    if __name__ == '__main__':
       app.run('0.0.0.0', port=5000, debug=True)

4. 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>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Batang:wght@400;700&display=swap" rel="stylesheet">

    <title>선착순 공동구매</title>

    <style>
        * {
            font-family: 'Gowun Batang', serif;
            color: white;
        }

        body {
            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://cdn.aitimes.com/news/photo/202010/132592_129694_3139.jpg');
            background-position: center;
            background-size: cover;
        }

        h1 {
            font-weight: bold;
        }

        .order {
            width: 500px;
            margin: 60px auto 0px auto;
            padding-bottom: 60px;
        }

        .mybtn {
            width: 100%;
        }

        .order > table {
            margin : 40px 0;
            font-size: 18px;
        }

        option {
            color: black;
        }
    </style>
    <script>
        $(document).ready(function () {
            show_order();
        });
        function show_order() {
            $.ajax({
                type: 'GET',
                url: '/mars',
                data: {},
                success: function (response) {
                    alert(response['msg'])
                }
            });
        }
        function save_order() {
            $.ajax({
                type: 'POST',
                url: '/mars',
                data: { sample_give:'데이터전송' },
                success: function (response) {
                    alert(response['msg'])
                }
            });
        }
    </script>
</head>
<body>
    <div class="mask"></div>
    <div class="order">
        <h1>화성에 땅 사놓기!</h1>
        <h3>가격: 평 당 500</h3>
        <p>
            화성에 땅을 사둘 수 있다고?<br/>
            앞으로 백년 간 오지 않을 기회. 화성에서 즐기는 노후!
        </p>
        <div class="order-info">
            <div class="input-group mb-3">
                <span class="input-group-text">이름</span>
                <input id="name" type="text" class="form-control">
            </div>
            <div class="input-group mb-3">
                <span class="input-group-text">주소</span>
                <input id="address" type="text" class="form-control">
            </div>
            <div class="input-group mb-3">
                <label class="input-group-text" for="size">평수</label>
                <select class="form-select" id="size">
                  <option selected>-- 주문 평수 --</option>
                  <option value="10평">10</option>
                  <option value="20평">20</option>
                  <option value="30평">30</option>
                  <option value="40평">40</option>
                  <option value="50평">50</option>
                </select>
              </div>
              <button onclick="save_order()" type="button" class="btn btn-warning mybtn">주문하기</button>
        </div>
        <table class="table">
            <thead>
              <tr>
                <th scope="col">이름</th>
                <th scope="col">주소</th>
                <th scope="col">평수</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>홍길동</td>
                <td>서울시 용산구</td>
                <td>20</td>
              </tr>
              <tr>
                <td>임꺽정</td>
                <td>부산시 동구</td>
                <td>10</td>
              </tr>
              <tr>
                <td>세종대왕</td>
                <td>세종시 대왕구</td>
                <td>30</td>
              </tr>
            </tbody>
          </table>
    </div>
</body>
</html>

5. mongoDB Atlas 창 띄우기

https://cloud.mongodb.com/

6. [화성땅 공동구매] - POST 연습(주문 저장)

- 1) API 만들고 사용하기 - 이름, 주소, 평수 저장하기(Create → **POST**)
    
    
    👉 1. 요청 정보 :  URL= `/mars`, 요청 방식 = `POST`
    2. 클라(ajax) → 서버(flask) : `name`, `address`, `size`
    3. 서버(flask) → 클라(ajax) : 메시지를 보냄 (주문 완료!)
    
    

- 1) 클라이언트와 서버 연결 확인하기

    [서버 코드 - `app.py`]
    
    ```python
    @app.route("/mars", methods=["POST"])
    def mars_post():
        sample_receive = request.form['sample_give']
        print(sample_receive)
        return jsonify({'msg': 'POST 연결 완료!'})
    ```
    
    [클라이언트 코드 - `index.html`]
    
    ```jsx
    function save_order() {
        $.ajax({
            type: 'POST',
            url: '/mars',
            data: { sample_give:'데이터전송' },
            success: function (response) {
                alert(response['msg'])
            }
        });
    }
    
    <button onclick="save_order()" type="button" class="btn btn-warning mybtn">주문하기</button>
    ```
    

- 2) 서버부터 만들기

    - `name`, `address`, `size` 정보를 받아서, 저장하면 되겠죠?
    - 우리가 일전에 만들어둔 `[dbtest.py](http://dbtest.py)` 파일을 불러와봅시다!
    
    ```python
    @app.route("/mars", methods=["POST"])
    def mars_post():
        name_receive = request.form['name_give']
        address_receive = request.form['address_give']
        size_receive = request.form['size_give']
    
        doc = {
            'name': name_receive,
            'address': address_receive,
            'size': size_receive
        }
    
        db.orders.insert_one(doc)
    
        return jsonify({'msg': '주문 완료!'})
    ```
    

- 3) 클라이언트 만들기

    - 이번엔 `name`, `address`, `size` 정보를 보내주면 되겠죠?
    
    ```jsx
    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()
            }
        });
    }
    ```
    

- 4) 완성 확인하기

    - DB에 잘 들어갔는지 확인해보면 되겠죠?
    
    ![Untitled](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ca518454-e8db-440b-9a22-aca38bcf6907/Untitled.png)
    

7. [화성땅 공동구매] - GET 연습(주문 보여주기)

  • 1) API 만들고 사용하기 - 저장된 주문을 화면에 보여주기(Read → GET) <asid<aside> 💡 1. 요청 정보 : URL= /mars, 요청 방식 = GET`
    1. 클라(ajax) → 서버(flask) : (없음)

    2. 서버(flask) → 클라(ajax) : 전체 주문을 보내주기

    • 1) 클라이언트와 서버 확인하기 [서버 코드 - app.py]
      @app.route("/mars", methods=["GET"])
      def mars_get():
          return jsonify({'msg': 'GET 연결 완료!'})
      [클라이언트 코드 - index.html]
      $(document).ready(function () {
          show_order();
      });
      function show_order() {
          $.ajax({
              type: 'GET',
              url: '/mars',
              data: {},
              success: function (response) {
                  alert(response['msg'])
              }
          });
      }
    • 2) 서버부터 만들기
      • 받을 것 없이 orders 에 주문정보를 담아서 내려주기만 하면 됩니다!

        @app.route("/mars", methods=["GET"])
        def mars_get():
            orders_list = list(db.orders.find({},{'_id':False}))
            return jsonify({'orders':orders_list})
    • 3) 클라이언트 만들기
      • 응답을 잘 받아서 for 문으로! 붙여주면 끝이겠죠!

        function show_order() {
            $('#order-box').empty()
            $.ajax({
                type: 'GET',
                url: '/mars',
                data: {},
                success: function (response) {
                    let rows = response['orders']
                    for (let i = 0; i < rows.length; i++) {
                        let name = rows[i]['name']
                        let address = rows[i]['address']
                        let size = rows[i]['size']
        
                        let temp_html = `<tr>
                                            <td>${name}</td>
                                            <td>${address}</td>
                                            <td>${size}</td>
                                          </tr>`
                        $('#order-box').append(temp_html)
                    }
        
                }
            });
        }
    • 4) 완성 확인하기 👉 **동작 테스트:** 화면을 새로고침 했을 때, DB에 저장된 리뷰가 화면에 올바르게 나타나는지 확인합니다.
profile
keep growing as a web developer!🧃

0개의 댓글