웹개발종합반

(항해 사전스터디) 웹개발종합반 5주차 정리

JAVABOZA 2023. 4. 12. 13:25

1주차 - html css javascript
2주차 - jquery , ajax ,api
3주차 - python , 크롤링 , mongoDB
4주차 - 미니프로젝트1, 미니프로젝트2
5주차 - 미니프로젝트3.4 ,  AWS

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

5주차 - 미니프로젝트3.4 ,  AWS

 

AWS를 통한 서버에 내 프로젝트 올리기

여기서 AWS란?

  • Amazon Web Service 의 앞글자만 따서 AWS 라 부른다
  • 서버 네트워크 등 인프라를 전체적으로 빌려주는 서비스이다.
  • 다양한 서비스를 제공하고 있어서 요즘은 AWS에서 제공하는 서비스로도 대부분 구축이 가능 ex) EC2, S3..

 

<미니프로젝트 3>

👉왼쪽은 결과물 / 오른쪽은 MongoDB에 넣은 데이터값

 

 

04.BUCKET -> app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.eam3qp6.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta

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


#api만들기
@app.route("/bucket", methods=["POST"])
def bucket_post():
    bucket_receive = request.form['bucket_give']
    doc = {
        'bucket': bucket_receive
    }
    db.bucket.insert_one(doc)

    return jsonify({'msg': '저장 완료!'})

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

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

 

04.BUCKET -> templates -> 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" />

    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
    integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
    crossorigin="anonymous"></script>


  <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 => {
        let rows = data['result']
        $('#bucket-list').empty()
        rows.forEach((a) => {
          let bucket = a['bucket']

          let temp_html = `<li>
                            <h2>✅ ${bucket}</h2>
                           </li>`
          $('#bucket-list').append(temp_html)
        })

      })
    }

    function save_bucket() {
      let bucket = $('#bucket').val()

      let formData = new FormData();

      formData.append("bucket_give", bucket);

      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>

 

 

제일 먼저 서버 데이터베이스를 연결 (사전에 터미널에 pip install pymongo 설치함 )

from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.eam3qp6.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta

 

 

후에 서버작업 진행

 

@app.route("/bucket", methods=["POST"])
def bucket_post():
    bucket_receive = request.form['bucket_give']
    doc = {
        'bucket': bucket_receive
    }
    db.bucket.insert_one(doc)

    return jsonify({'msg': '저장 완료!'})

프론트단 작업 진행

 - let bucket = $('#bucket').val() 로 bucket 값 보내주기

 - formData.append("bucket_give", bucket); 로 데이터를 넣고  fetch 로 데이터 보내기

 - window.location.reload(); 는 클라이언트가 원하는 정보를 넣고 저장이되면 새로고침이 되서 보여주는 기능

 

    function save_bucket() {
      let bucket = $('#bucket').val()

      let formData = new FormData();

      formData.append("bucket_give", bucket);

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

 

 

 

 

다음은 API를 조회(GET) 

 

<백엔드 작업>

all_buckets = list(db.bucket.find({},{'_id' : False}))               // all_buckets에 bucket 디비에 있는 값을 찾아 리스트해서 담기

result는 담은 all_buckets를 json 타입으로 리턴

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

 

<프론트작업>

서버에서 가져온 result값을 rows 변수에 담아

forEach문으로 반복해서 돌려 원하는 값가져오기

 

temp_html로 가져온 html 틀에 jquery로 담아 append() 사용

   function show_bucket() {
      fetch('/bucket').then(res => res.json()).then(data => {
        let rows = data['result']
        $('#bucket-list').empty()
        rows.forEach((a) => {
          let bucket = a['bucket']

          let temp_html = `<li>
                            <h2>✅ ${bucket}</h2>
                           </li>`
          $('#bucket-list').append(temp_html)
        })

      })
    }

 

append() 후에 기존 html 코드는 지워지는 걸 구현하기 위한 empty() 사용

 


👉왼쪽은 결과물 / 오른쪽은 MongoDB에 넣은 데이터값

 

05.FAN -> app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.eam3qp6.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta

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

@app.route("/guestbook", methods=["POST"])
def guestbook_post():
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']

    doc = {
        'name' : name_receive,
        'comment' : comment_receive
    }
    db.fan.insert_one(doc)

    return jsonify({'msg': '저장완료!'})

@app.route("/guestbook", methods=["GET"])
def guestbook_get():
    all_comments = list(db.fan.find({},{'_id':False}))
    return jsonify({'result': all_comments})

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

 

 

05.FAN -> templates -> 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" />

    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
    integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
    crossorigin="anonymous"></script>

  <title>초미니홈피 - 팬명록</title>


  <meta property="og:title" content="BTS 팬명록" />
  <meta property="og:description" content="아티스트에게 응원 한마디" />

    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)),
      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() {
      fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then((res) => res.json()).then((data) => {

        let temp = data['temp']

        $('#temp').text(temp)

      });
    }
    function save_comment() {
      let name = $('#name').val()
      let comment = $('#comment').val()

      let formData = new FormData();
      formData.append("name_give", name);
      formData.append("comment_give", comment);

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

        let rows = data['result']
        $('#comment-list').empty()
        rows.forEach((a) => {
          let name = a['name']
          let comment = a['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>BTS 팬명록</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="floatingInput">닉네임</label>
    </div>
    <div class="form-floating">
      <textarea class="form-control" placeholder="Leave a comment here" id="comment" style="height: 100px"></textarea>
      <label for="floatingTextarea2">응원댓글</label>
    </div>
    <button onclick="save_comment()" type="button" class="btn btn-dark">
      댓글 남기기
    </button>
  </div>
  <div class="mycards" id="comment-list">
    <div class="card">
      <div class="card-body">
        <blockquote class="blockquote mb-0">
          <p>새로운 앨범 너무 멋져요!</p>
          <footer class="blockquote-footer">호빵맨</footer>
        </blockquote>
      </div>
    </div>
    <div class="card">
      <div class="card-body">
        <blockquote class="blockquote mb-0">
          <p>새로운 앨범 너무 멋져요!</p>
          <footer class="blockquote-footer">호빵맨</footer>
        </blockquote>
      </div>
    </div>
    <div class="card">
      <div class="card-body">
        <blockquote class="blockquote mb-0">
          <p>새로운 앨범 너무 멋져요!</p>
          <footer class="blockquote-footer">호빵맨</footer>
        </blockquote>
      </div>
    </div>
  </div>
</body>

</html>

 

미니프로젝트4에서는 전반적으로 구현 했던 모든 기능을 했다

추가로 사용 했던 기능은 og태그인데 아래의 이미지처럼 URL만 전송하면 image, title, content를 같이 불러올 수 있다.

 

 

 

og태그 예시

위의 이미지는 05.FAN프로젝트의 index.html의 <head>영역이며 여기에 표시된 <meta>태그를 넣고 url을 전송할 때

보여질 title, desription, image 값을 넣었다.

 

작업을 완료 후 AWS Elastic Beanstalk 등록

※AWS에 등록하는 것도 외우지말자 어떻게 진행되는 지 알고 필요한거는 그때 그때 검색해서 찾아 해결하는 습관을 갖자

 

등록된 url을 SNS등에 전송하면 설정한거 확인 가능!

👉결과물


 

5주차 소감

전반적으로 웹페이지를 다뤄보았다.

처음에는 블로그도 어색하고 무지성으로 공부만 했다면 블로그를 통해서 배운것들을 한번 더 체크를 하게 되는거 같다.

또 이제 공부할 자바도 한 챕터를 진행하고 이렇게 같은 개념으로 정리를 해보려 한다.

 

이제 웹에 대한 기초를 배워서 한층 더 깊은 공부를 해야할 듯하다