스파르타코딩클럽 내일배움단 웹개발 종합반 -10

몽슈뜨·2022년 10월 26일
0

웹개발 종합반

목록 보기
10/11
post-thumbnail

✨[버킷리스트] - 뼈대 준비하기

  • 프로젝트 준비 - index.html, app.py 준비하기

    • 버킷리스트 - app.py

      from flask import Flask, render_template, request, jsonify
      app = Flask(__name__)
      
      @app.route('/')
      def home():
       return render_template('index.html')
      
      @app.route("/bucket", methods=["POST"])
      def bucket_post():
        sample_receive = request.form['sample_give']
        print(sample_receive)
        return jsonify({'msg': 'POST(기록) 연결 완료!'})
      
      @app.route("/bucket/done", methods=["POST"])
      def bucket_done():
        sample_receive = request.form['sample_give']
        print(sample_receive)
        return jsonify({'msg': 'POST(완료) 연결 완료!'})
      
      @app.route("/bucket", methods=["GET"])
      def bucket_get():
        return jsonify({'msg': 'GET 연결 완료!'})
      
      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+Dodum&display=swap" rel="stylesheet">
      
        <title>인생 버킷리스트</title>
      
        <style>
            * {
                font-family: 'Gowun Dodum', sans-serif;
            }
            .mypic {
                width: 100%;
                height: 200px;
      
                background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://images.unsplash.com/photo-1601024445121-e5b82f020549?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1189&q=80');
                background-position: center;
                background-size: cover;
      
                color: white;
      
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
            }
            .mypic > h1 {
                font-size: 30px;
            }
            .mybox {
                width: 95%;
                max-width: 700px;
                padding: 20px;
                box-shadow: 0px 0px 10px 0px lightblue;
                margin: 20px auto;
            }
            .mybucket {
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: space-between;
            }
      
            .mybucket > input {
                width: 70%;
            }
            .mybox > li {
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: center;
      
                margin-bottom: 10px;
                min-height: 48px;
            }
            .mybox > li > h2 {
                max-width: 75%;
                font-size: 20px;
                font-weight: 500;
                margin-right: auto;
                margin-bottom: 0px;
            }
            .mybox > li > h2.done {
                text-decoration:line-through
            }
        </style>
        <script>
            $(document).ready(function () {
                show_bucket();
            });
            function show_bucket(){
                $.ajax({
                    type: "GET",
                    url: "/bucket",
                    data: {},
                    success: function (response) {
                        alert(response["msg"])
                    }
                });
            }
            function save_bucket(){
                $.ajax({
                    type: "POST",
                    url: "/bucket",
                    data: {sameple_give:'데이터전송'},
                    success: function (response) {
                        alert(response["msg"])
                    }
                });
            }
            function done_bucket(num){
                $.ajax({
                    type: "POST",
                    url: "/bucket/done",
                    data: {sameple_give:'데이터전송'},
                    success: function (response) {
                        alert(response["msg"])
                    }
                });
            }
        </script>
      </head>
      <body>
        <div class="mypic">
            <h1>나의 버킷리스트</h1>
        </div>
        <div class="mybox">
            <div class="mybucket">
                <input id="bucket" class="form-control" type="text" placeholder="이루고 싶은 것을 입력하세요">
                <button onclick="save_bucket()" type="button" class="btn btn-outline-primary">기록하기</button>
            </div>
        </div>
        <div class="mybox" id="bucket-list">
            <li>
                <h2>✅ 호주에서 스카이다이빙 하기</h2>
                <button onclick="done_bucket(5)" type="button" class="btn btn-outline-primary">완료!</button>
            </li>
            <li>
                <h2 class="done">✅ 호주에서 스카이다이빙 하기</h2>
            </li>
            <li>
                <h2>✅ 호주에서 스카이다이빙 하기</h2>
                <button type="button" class="btn btn-outline-primary">완료!</button>
            </li>
        </div>
      </body>
      </html>


✨[버킷리스트] - POST연습(기록하기)

  • API 만들고 사용하기 - 버킷리스트 기록 API (Create→ POST)
  1. 요청 정보 : URL= /bucket, 요청 방식 = POST
  2. 클라(ajax) → 서버(flask) : bucket
  3. 서버(flask) → 클라(ajax) : 메시지를 보냄 (기록 완료!)
    💡 서버에서 한 가지 일을 더 해야합니다.
    → 번호를 만들어 함께 넣어주는 것. 그래야 업데이트가 가능하겠죠!
  • 클라이언트와 서버 연결 확인하기

    • 서버 코드 - app.py

      @app.route("/bucket", methods=["POST"])
      def bucket_post():
        sample_receive = request.form['sample_give']
        print(sample_receive)
        return jsonify({'msg': 'POST(기록) 연결 완료!'})
    • 클라이언트 코드 - index.html

      function save_bucket(){
        $.ajax({
            type: "POST",
            url: "/bucket",
            data: {sample_give:'데이터전송'},
            success: function (response) {
                alert(response["msg"])
            }
        });
      }
      
      <button onclick="save_bucket()" type="button" class="btn btn-outline-primary">기록하기</button>
  • 서버부터 만들기
    bucket 정보를 받아서, 저장하면 되겠죠?
    💡 한 가지 일이 더 있답니다. → 네, 버킷 번호완료여부 를 함께 넣어주는 것!

    count = list(db.bucket.find({},{'_id':False}))
    num = len(count) + 1
    
    vs
    
    count = db.bucket.find({},{'_id':False}).count()
    num = count + 1
    @app.route("/bucket", methods=["POST"])
    def bucket_post():
      bucket_receive = request.form["bucket_give"]
    
      count = db.bucket.find({},{'_id':False}).count()
      num = count + 1
    
      doc = {
          'num':num,
          'bucket': bucket_receive,
          'done':0
      }
    
      db.bucket.insert_one(doc)
      return jsonify({'msg':'등록 완료!'})
  • 클라이언트 만들기

    • bucket 정보만 보내주기
      function save_bucket(){
       let bucket = $('#bucket').val()
       $.ajax({
           type: "POST",
           url: "/bucket",
           data: {bucket_give:bucket},
           success: function (response) {
               alert(response["msg"])
               window.location.reload()
           }
       });
      }
  • 완성 확인하기

    • DB에 잘 들어갔는지 확인


✨[버킷리스트] - GET연습(보여주기)

  • API 만들고 사용하기 - 버킷리스트 조회 API (Read→ GET)

    1. 요청 정보 : URL= /bucket, 요청 방식 = GET
    2. 클라(ajax) → 서버(flask) : (없음)
    3. 서버(flask) → 클라(ajax) : 전체 버킷리스트를 보여주기

  • 서버부터 만들기

    • 받을 것 없이 buckets에 주문정보를 담아서 내려주기만 하면 됩니다!
      @app.route("/bucket", methods=["GET"])
      def bucket_get():
       buckets_list = list(db.bucket.find({},{'_id':False}))
       return jsonify({'buckets':buckets_list})
  • 클라이언트 만들기

    • 응답을 잘 받아서 for 문으로 !

      function show_bucket(){
       $('#bucket-list').empty()
       $.ajax({
           type: "GET",
           url: "/bucket",
           data: {},
           success: function (response) {
               let rows = response['buckets']
               for (let i = 0; i < rows.length; i++) {
                   let bucket = rows[i]['bucket']
                   let num = rows[i]['num']
                   let done = rows[i]['done']
      
                   let temp_html = ``
                   if (done == 0) {
                       temp_html = `<li>
                                       <h2>✅ ${bucket}</h2>
                                       <buttontoken interpolation">${num})" type="button" class="btn btn-outline-primary">완료!</button>
                                   </li>`
                   } else {
                       temp_html = `<li>
                                       <h2 class="done">✅ ${bucket}</h2>
                                   </li>`
                   }
                   $('#bucket-list').append(temp_html)
               }
           }
       });
      }


✨[버킷리스트] - POST연습(완료하기)

  • API 만들고 사용하기 - 버킷리스트 완료 API (Update→ POST)

    1. 요청 정보 : URL= /bucket/done, 요청 방식 = POST
    2. 클라(ajax) → 서버(flask) : num (버킷 넘버)
    3. 서버(flask) → 클라(ajax) : 메시지를 보냄 (버킷 완료!)

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

    • 서버 코드 - app.py

      @app.route("/bucket/done", methods=["POST"])
      def bucket_done():
       sample_receive = request.form['sample_give']
       print(sample_receive)
       return jsonify({'msg': 'POST(완료) 연결 완료!'})
    • 클라이언트 코드 - index.html

      function done_bucket(num){
       $.ajax({
           type: "POST",
           url: "/bucket/done",
           data: {sameple_give:'데이터전송'},
           success: function (response) {
               alert(response["msg"])
           }
       });
      }
      
      <button onclick="done_bucket(5)" type="button" class="btn btn-outline-primary">완료!</button>

  • 서버부터 만들기
    버킷 번호를 받아서, 업데이트 하면 됩니다!
    num_receive 는 문자열로 들어오니까, 숫자로 바꿔주는 것이 중요

     @app.route("/bucket/done", methods=["POST"])
    def bucket_done():
       num_receive = request.form["num_give"]
       db.bucket.update_one({'num': int(num_receive)}, {'$set': {'done': 1}})
       return jsonify({'msg': '버킷 완료!'})
  • 클라이언트 만들기
    버킷 넘버를 보여주면 됩니다!

     function done_bucket(num){
       $.ajax({
           type: "POST",
           url: "/bucket/done",
           data: {'num_give':num},
           success: function (response) {
               alert(response["msg"])
               window.location.reload()
           }
       });
    }
  • 완성 확인하기

profile
개발자되면 맥북사줄께

0개의 댓글