본문 바로가기

IT/스파르타코딩클럽(웹개발종합반)

웹개발 종합반 (5주차) (스파르타코딩클럽)

반응형

 

 

드디어 마지막 주인 5주차!!

이번 게시글이 웹개발 종합반의 마지막 게시물이 될 예정이다 ㅎㅎ..

 

 

<버킷리스트 프로젝트>

프로젝트 세팅

프로젝트 세팅은 저번 게시글과 동일하다. 

그동안 쭉 해왔던 대로  폴더 열고, app.py 파일 만든 후 venv 가상환경 잡아주고 라이브러리 설치하고 templates 폴더만들어서 index.html 파일 만들어 주면 된다.

(필요한 라이브러리는 flask, pymongo, dnspython )

 

 

 

뼈대 준비

[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
      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() {
        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>

페이지 로딩이 완료되면 show_bucker()이라는 함수를 부름.

show_bucket 함수는 fetch를 이용하여 /bucket API에 요청을 날리고 가져온 데이터의 msg값을 alert을 통해 보여주게 한다. ('POST 연결 완료!')

기록하기 버튼을 누르게 되면 샘플데이터를 app.py쪽으로 보내고 데이터의 msg를 alert으로 뜨도록 한다. ('GET 연결 완료!')

 

 

이렇게 코드를 입력하고 localhost:5000으로 접속하면

이러한 화면을 확인할 수 있다.

 

 

 

POST 구현하기 (기록하기)

[app.py]

맨 윗줄에 pymongo를 사용하기 위한 3줄을 추가하고

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

post 부분을 수정하면 된다.

@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': '저장 완료'})

받은 'bucket_give'를 변수 bucket_receive에 담고 딕셔너리 형태로 저장한다.

 

 

[index.html]

save_bucket() 함수를 변경해주어야 한다.

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();
          });
      }

bucket  변수에 bucket이라는 id를 가진 input의 값을 넣는다.

그리고 이 값을 bucket_give라는 이름으로 app.py로 넘겨주는 것이다.

 

 

결과

이렇게 입력하여 기록하기 버튼을 누르면

 

저장완료 alert이 뜨고

 

db에 잘 저장된 것을 확인할 수 있다.

 

 

 

GET 구현하기 (저장된 데이터 보여주기)

[app.py]

GET 부분을 고쳐주면 된다.

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

all_bucket이라는 변수에 list 형식으로 가져온 data를 넣은 후 return 하여 result라는 이름으로 html에 보내준다.

 

[index.html]

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

받은 result 값을 row에 넣고 list이기 때문에 for문을 돌려 값들을 append를 통해 html에 붙인다.

 

 

결과

새로고침을 하면 저장되어 있는 데이터들만 보이게 된다!!

 

 

최종 전체코드

[app.py]

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

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

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

@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_bucket = list(db.bucket.find({},{'_id':False}))
    return jsonify({'result': all_bucket})

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() {
            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 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>

 

 

 

 

 

<팬명록 프로젝트>

프로젝트 세팅

프로젝트 세팅은 위의 프로젝트와 동일함.

 

 

뼈대 준비하기

[app.py]

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

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

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

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

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

POST 부분에서 sample_give라는 데이터를 받아서 프린트 해주고있다.

 

[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>

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

    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap"
        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)),
                url("https://cdn.topstarnews.net/news/photo/201807/456143_108614_510.jpg");
            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) => {
                console.log(data)
            });
        }
        function save_comment() {
            let formData = new FormData();
            formData.append("sample_give", "샘플데이터");

            fetch('/guestbook', { method: "POST", body: formData, }).then((res) => res.json()).then((data) => {
                //console.log(data)
                alert(data["msg"]);
            });
        }
        function show_comment() {
            fetch('/guestbook').then((res) => res.json()).then((data) => {
                alert(data["msg"])
            })
        }
    </script>
</head>

<body>
    <div class="mypic">
        <h1>십센치(10cm) 팬명록</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>

document가 로딩이 다 되면 set_temp() 함수와 show_comment() 함수가 호출된다.

set_temp()는 온도 붙여주는 함수이고, 

show_comment()는 받아온 데이터의 msg를 alert으로 띄워주고 있다.

save_commen() 함수는 받아온 form 데이터를 append로 index.html에 보내준다.

 

 

 

결과

이렇게 화면이 잘 나온다.

 

 

 

 

날씨 API 적용하기 (조각기능)

set_temp()의 url을 보면

function set_temp() {
            fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then((res) => res.json()).then((data) => {
                console.log(data)
            });
        }

이러한 데이터들이 들어있다. 우리가 필요한 것은 이중에서 temp 데이터이기 때문에 temp 데이터를 추출하면 된다.

 

 

function set_temp() {
            fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then((res) => res.json()).then((data) => {

                let temp = data['temp']
                $('#temp').text(temp)
            });
        }

set_temp() 함수를 이렇게 수정해준다.

data의 temp값을 temp라는 변수에 넣어 id가 temp인 곳에 temp값을 text로 붙여주었다.

 

결과적으로

이렇게 온도가 바뀐 것을 확인할 수 있다.

 

 

 

 

POST 구현하기 (응원 등록하기)

[app.py]

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

from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.q7rbruf.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():
    return jsonify({'msg': 'GET 연결 완료!'})

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

 

db와의 연결을 위해 윗부분에 pymongo 3줄 추가해 주었고 post 부분을 수정하였다.

넘어온 name_give와 comment_give 데이터를 각각 name_recieve, commect_receive 변수에 담았고

doc 딕셔너리 형태로 담아 db에 넣어주었다.

 

[index.html]

<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) => {
                alert(data["msg"])
            })
        }
    </script>

save_comment() 함수를 고쳐주었다. form의 id 값을 가져와서 name, comment 변수에 넣어주었고 이 값들을 append로 app.py로 보내주었다.

 

 

결과

이렇게 댓글을 남기면 위에 alert이 정상적으로 뜨게되고 페이지가 새로고침된다.

 

그리고 db에 정상적으로 저장된 것을 확인할 수 있다.

 

 

 

 

GET 구현하기 (응원 보여주기)

[app.py]

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

from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.q7rbruf.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)

get 부분을 변경해 주면 된다. 

db에서 가져온 데이터를 리스트 형식으로 all_comments 변수에 담아 result 라는 이름을 index.html로 return한다.

 

[index.html]

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

받은 result 라는 이름을 가진 db 데이터를 rows 라는 변수에 담고, 리스트 형식이기 때문에 forEach 문을 돌려서 name과 comment에 저장해준 후 html로 붙여주면 된다.

 

 

 

결과

이렇게 저장된 데이터가 잘 보이는 것을 확인할 수 있다.

 

 

 

<프로젝트 서버에 올리기>

AWS에 프로그램을 올려야 하지만 해외 결제가 되는 카드가 없는 관계로 실습하지 못했다..

대신 강의는 다 보았음!

 

AWS Elastic Beanstalk을 이욯해서 빠르고 쉽게 배포할 수 있다.

 

https://ap-northeast-2.console.aws.amazon.com/elasticbeanstalk/home?region=ap-northeast-2#/welcome

로 들어가서 로그인을 하고 오른쪽 위 클릭하고 보안 자격 증명으로 들어간다.

그리고 액세스 키를 눌러서 새 액세스 키를 만들어 준다. 

그 ID 와 키를 메모장에 적어두고 닫기를 누른다.

 

- 터미널 준비하기 - 
mkdir deploy
cp app.py deploy/application.py
cp -r templates deploy/templates
pip freeze > deploy/requirements.txt
cd deploy

- appication.py 세팅하기 - 
application = app = Flask(__name__)
app.run()

- 패키지 설치하기 - 
pip install awsebcli

- 보안 자격증명 - 
eb init

- 초기 설정 - 
eb create myweb

- 코드 수정 & 업데이트 - 
eb deploy myweb

배포 명령어 모음이다.

 

이제 vscode의 terminal에서 작업을 하면 된다.

mkdir deploy를 입력해서 폴더를 하나 만든다.

그리고 터미널 준비하기 명령어 들을 하나씩 입력해준다.

application.py 세팅하기, 패키지 설치하기, 보안 자격증명, 초기설정도 다 입력해준다. (중간에 키가 필요하다고 뜨면 복사해놓앗던 키를 붙여넣어주면 된다)

 

다시 사이트로 가서 환경이라는 것을 누르면 상태가 OK라고 뜬것을 볼 수 있다. 거기서 URL을 누르면 내가 올린 사이트를 들어갈 수 있다.

 

이 URL을 복사해서 다른곳으로 보내면 og가 잘 나오는 것도 확인할 수 있다.

 

현재 deploy 폴더 안에 있는 것들이 배포가 되어있는 상태이다.

코드를 수정할 때에는 deploy 안에 있는 index.html을 고쳐주고 cd deploy를 해주고 위의 코드 수정 & 업데이트 를 입력해주면 된다.

 

 

 

 

 


5주차 숙제. AWS 올린 내 사이트 URL  제출하기..

visa 카드가 없는 관계로 AWS 를 올리지 못했는데,, 그래서 5주차 숙제도 못하게 되었다..

그대신 팬명록 사이트를 내가 좋아하는 엔믹스 팬명록 사이트로 만든 것을 올려본다..

 

[app.py]

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

from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.q7rbruf.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)

 

[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>

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

    <meta property="og:title" content="NMIX 팬명록" />
    <meta property="og:description" content="아티스트에게 응원 한마디!" />
    <meta property="og:image" content="https://img3.yna.co.kr/photo/yna/YH/2022/08/23/PYH2022082310520001300_P4.jpg" />

    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap"
        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)),
                url("https://img3.yna.co.kr/photo/yna/YH/2022/08/23/PYH2022082310520001300_P4.jpg");
            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>NMIX 팬명록</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>

 

결과

완성!!!

 

 

 

<< 5주차 완강 후기 >>

왕!!! 드디어 완강을 했다!

사실 길지도 짧지도 않은 기간이었지만, 강사님께서 설명도 쉽게 해주시고 반복도 많이 해서 어려운 부분도 금방 익숙해 질 수 있었다. 

하지만 백엔드를 다 배웠다기엔 아직 부족한 부분도 많은 거 같아서 조금 아쉬운 점이 남는다. 그래도 짧은 시간에 비해는 몰랐던 부분을 많이 배워서 좋았다 !!

이 강의를 다른사람에게 추천하겠냐고 물으면 당연 yes일 것 같다. 

웹 개발을 공부하기 위한 기초를 다지기 좋았다. !!!

 

친절하셨던 강사님, 튜터분들 다들 감사합니당..;-;

반응형