본문 바로가기
[스파르타 코딩클럽]/비개발자를 위한, 웹개발 종합반

화성땅 공동구매 -GET-

by 수민띠 2023. 2. 26.

주문 조회 API 만들기(GET)

페이지 로딩 시 자동으로 get 요청해 데이터 받게 구현

데이터 명세 

요청정보: URL: /mars, 요청방식 = GET

클라(fetch) → 서버(flask) : 없음

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

 

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

웹에 접속했을 때 서버로부터 메세지를 받는지 확인

 

서버 만들기

받을 것 없이 DB에서 찾은 데이터를 변수에 담아서 클라이언트한테 보낸다.

@app.route("/mars", methods=["GET"])
def mars_get():
    mars_data = list(db.mars.find({},{'_id':False}))
    return jsonify({'result': mars_data})

 

클라이언트 만들기

step1. 서버한테 받은 데이터 console에 확인해보기

step2. 받은 데이터 저장하기 ※서버한테 객체로 받은 점 유의

step3. forEach로 데이터 뽑기

step4. 추가할 요소 만들고 변수에 저장하기

step5. 요소 추가하기 - jQuery

step6. 새로고침 (기존 html코드를 지우는 용도)

$(document).ready(function () { //페이지 로딩 즉시
  show_order();
});
function show_order() {
  fetch('/mars').then((res) => res.json()).then((data) => {
    all_order = data['result'];
    $('#order-box').empty();
    all_order.forEach((a) => {
      let name = a['name'];
      let address = a['address'];
      let size = a['size'];

      temp_html = `<tr>
                  <td>${name}</td>
                  <td>${address}</td>
                  <td>${size}</td>
                </tr>`

      $('#order-box').append(temp_html);
    })
  })
}

 

동작 확인

화성땅 공동구매 app.py

더보기

app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('몽고db주소')
db = client.dbsparta

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

@app.route("/mars", methods=["POST"])
def mars_post():
    address_receive = request.form['address_give']
    name_receive = request.form['name_give']
    size_receive = request.form['size_give']

    doc = {
           'name': name_receive, 
           'address': address_receive,
           'size':size_receive ,                   
    }
    db.mars.insert_one(doc)
    return jsonify({'msg':'저장 완료!'})

@app.route("/mars", methods=["GET"])
def mars_get():
    mars_data = list(db.mars.find({},{'_id':False}))
    return jsonify({'result': mars_data})

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>

  <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() {
      fetch('/mars').then((res) => res.json()).then((data) => {
        all_order = data['result'];
        $('#order-box').empty();
        all_order.forEach((a) => {
          let name = a['name'];
          let address = a['address'];
          let size = a['size'];

          temp_html = `<tr>
                      <td>${name}</td>
                      <td>${address}</td>
                      <td>${size}</td>
                    </tr>`

          $('#order-box').append(temp_html);
        })
      })
    }
    function save_order() {
      let name = $('#name').val();
      let address = $('#address').val();
      let size = $('#size').val();


      let formData = new FormData();
      formData.append("name_give", name);
      formData.append("address_give", address);
      formData.append("size_give", size);

      fetch('/mars', { method: "POST", body: formData }).then((res) => res.json()).then((data) => {
        alert(data["msg"]);
        window.location.reload();
      });
    }
  </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 id="order-box">
        <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>