[스파르타코딩클럽] 웹개발 종합반 - 5주차 개발일지

이지영·2022년 8월 25일
0

웹개발종합반

목록 보기
5/6

5주차 배운것

  • Flask 프레임워크를 활용해서 API만들기
  • 미니프로젝트3(버킷리스트)
  • EC2, nohup설정, 도메인연결, og태그

미니프로젝트3(버킷리스트)


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() {
            $('#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)
                    }
                }
            });
        }

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

        function done_bucket(num) {
            $.ajax({
                type: "POST",
                url: "/bucket/done",
                data: {'num_give': num},
                success: function (response) {
                    alert(response["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>
        <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>

app.py

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)
from pymongo import MongoClient

client = MongoClient('mongodb+srv://test:sparta@cluster0.ncyx6sm.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"]

    bucket_list = list(db.bucket.find({},{'_id':False}))
    count =len(bucket_list) + 1


    doc = {
        'num':count,
        'bucket': bucket_receive,
        'done':0
    }

    db.bucket.insert_one(doc)
    return jsonify({'msg':'등록 완료!'})


@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': '버킷 완료!'})


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


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

nohup 설정하기

  • SSH 접속을 끊어도 서버가 계속 돌게 하기
    원격 접속을 종료하더라도 서버가 계속 돌아가게 하기

  • Git bash 또는 맥의 터미널

    nohup python app.py &

  • 서버 종료하기 - 강제종료

    ps -ef | grep 'python app.py' | awk '{print $2}' | xargs kill

og 태그

  • URL로 Facebook등의 SNS에 공유되는데, Facebook에 콘텐츠가 표시되는 방식을 관리하기 위해 오픈 그래프 태그로 웹 사이트를 마크업하는 것

  • static 폴더 아래에 이미지 파일을 넣고, 각자 프로젝트 HTML의 ~ 사이에 아래 내용을 작성하면 og 태그를 개인 프로젝트에 사용

    <meta property="og:title" content="내 사이트의 제목" />
    <meta property="og:description" content="보고 있는 페이지의 내용 요약" />
    <meta property="og:image" content="이미지URL" />

5주차 숙제

도메인 제출하기
http://2jiyeong0.shop/

5주차 회고


5주 차 수업이 끝났다 미니 프로젝트들도 잘 끝냈고 내 웹페이지까지 완성! 강의들이 짧고 설명을 잘해주셔서 너무 만족했던 수업이었다. 한 주차한 주차 끝낼 때마다 결과물이 있고 내가 좋아하는 것들로 꾸미니 더 재밌게 들었던 수업 이 강의를 듣고 완벽하게 웹 개발을 한다고는 못하겠지만 시작하는 입장에서 이 수업을 듣는다면 너무 좋은 수업이 될듯하다.

profile
🐶🦶📏

0개의 댓글