본문 바로가기

js 공부(ft. sparta)/5주차

5-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("/bucket", methods=["POST"])
def bucket_post():
    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
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />
    <script
      integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
      crossorigin="anonymous"
    ></script>

    <link
      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)
          ),
        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() {
        fetch('/bucket').then(res => res.json()).then(data => {
                console.log(data)
                                alert(data["msg"]);
            })
      }

      function save_bucket() {
        let formData = new FormData();
        formData.append("sample_give", "샘플데이터");

        fetch('/bucket', {method: "POST",body: formData,}).then((response) => response.json()).then((data) => {
            alert(data["msg"]);
            window.location.reload();
          });
      }

    </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>
      </li>
    </div>
  </body>
</html>

그리고 mongoDB에 들어가있는다.

https://cloud.mongodb.com/

 

MongoDB Cloud

MongoDB Cloud is a unified data platform for modern applications and includes a global cloud database, search, data lake, mobile, and application services.

www.mongodb.com

가서 확인해보면 아래 사진과 같이 나온다.

그리고 다시 vscode로 가서 모두 저장해주고 app.py를 실행해주면 아래와 같이 연결된다.

 

기록하기를 누르면 post도 연결이 잘 되있는걸 확인할 수 있다.

어떻게 연결되있는지 간단히 보겠다.(html)

    <script>
      $(document).ready(function () {
        show_bucket();
      });
      function show_bucket() {
        fetch('/bucket').then(res => res.json()).then(data => {
                console.log(data)
                                alert(data["msg"]);
            })
      }

      function save_bucket() {
        let formData = new FormData();
        formData.append("sample_give", "샘플데이터");

        fetch('/bucket', {method: "POST",body: formData,}).then((response) => response.json()).then((data) => {
            alert(data["msg"]);
            window.location.reload();
          });
      }

    </script>

위 코드를 보면 우선

$(document).ready(function () {
        show_bucket();
      });

연결하면 show_bucekt()을 보여준다.

function show_bucket() {
        fetch('/bucket').then(res => res.json()).then(data => {
                console.log(data)
                                alert(data["msg"]);
            })
      }

그리고 show_bucket()에서는 fetch로 api에 요청을 날린다.

그럼 그걸 받아와서 data에 저장후 alert을 띄워준다.

 

그리고 /bucket이 어찌 생겼는지 app.py에 가서 보면 아래 코드와 같다.

@app.route("/bucket", methods=["GET"])
def bucket_get():
    return jsonify({'msg': 'GET 연결 완료!'})

이렇게 get을 불러온다.

 

이번엔 save_bucket()을 한번 봐보자.

function save_bucket() {
        let formData = new FormData();
        formData.append("sample_give", "샘플데이터");

 

        fetch('/bucket', {method: "POST",body: formData,}).then((response) => response.json()).then((data) => {
            alert(data["msg"]);
            window.location.reload();
          });
      }

sample_give라는 샘플데이터를 담아서 보낸다. /bucket 포켓에다가 보낸다.

app.py를 보면

@app.route("/bucket", methods=["POST"])
def bucket_post():
    sample_receive = request.form['sample_give']
    print(sample_receive)
    return jsonify({'msg': 'POST 연결 완료!'})

sample_receive에 값을 넣어주고 print 해준 다음 메세지를 html파일 alert에 보내준다.

 

다음시간엔 API 만들러 가보도록 한다.

먼저 데이터를 넣는것을 만들어준다.