[내일배움캠프 사전공부 웹개발 5주차]

안떽왕·2023년 3월 14일
0

버킷리스트 프로젝트

<app.py>

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

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

플라스크 프레임워크 사용을 위한 코드와 데이터베이스 접근을 위한 코드 작성

앱이 실행되었을때 index.html을 불러와 보여주는 home 함수

프론트로부터 정보가 도착했을때 doc형태로 저장하고 데이터베이스에 저장하는 역할인 bucket_post

데이터베이스에 id값을 제외한 모든 데이터를 불러오고 result를 키로 갖는 딕셔너리 형태를 리턴

<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 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 class="done">✅ 호주에서 스카이다이빙 하기</h2>
        </li>
    </div>
</body>

</html>

실행되었을때 show_bucket을 사용

show_bucket함수

bucket 데이터베이스로부터 데이터를 가져오고 rows변수에 result를 키로 갖는 값을 받아옴

반복문이 돌기전 기존에 있던 데이터를 비우기위해 empty 사용

rows를 반복문으로 돌려 a변수에 값을 하나씩 저장하고 bucket변수에 a의 bucket값을 저장

temp_html이라는 임시 저장소를 만들고 html부분의 양식과 동일하게 작성후 bucket의 값을 저장

bucket_list에 temp_html의 값을 추가

save_bucket 함수

입력받은 정보를 bucket에 저장

formdata에 bucket_give를 키로 갖고 bucket을 값으로 갖는 딕셔너리를 추가 이로서 백엔드에서 bucket_give를 가지고 데이터를 검색할 수 있다.

post 요청이 완료되면 백앤드에서 보낸 메시지를 alert로 띄우고 페이지를 새로고침한다.

팬명록 프로젝트

<app.py>

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

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

@app.route(’/’) → 플라스크의 기본 포트는 http://localhost:5000이다. 여기에 /가 들어갔으니 http://localhost:5000/ 가 된다.

http://localhost:5000/ 가 실행 되었을때 home이라는 함수를 실행시키는데 home함수는 index.html을 불러온다.

@app.route("/guestbook", methods=["POST"]) → http://localhost:5000/guestbook 을 주소로 받고 post방식일때

guestbook_post함수를 실행 → 프론트로 부터 name과 comment를 받고 이 정보를 각각 name_receive와 comment_receive에 저장한뒤

doc라는 변수에 딕셔너리 형태로 보관 후 db에 저장시키고 json형식으로 저장완료라는 메시지를 프론트로 보낸다.

@app.route("/guestbook", methods=["GET"]) → http://localhost:5000/guestbook 을 주소로 받고 get방식일때

guestbook_get함수를 실행 → all_comments 라는 변수 안에 db중 fan에 있는 모든 데이터를 아이디를 제외하고 가져온다.

그후 json형식으로 all_comments를 값으로 result를 키로 리턴시킨다.

<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="뉴진스 팬명록" />
    <meta property="og:description" content="아티스트에게 응원 한마디!" />
    <meta property="og:image" content="https://live.staticflickr.com/65535/52347841663_e5c966eb19_o.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://live.staticflickr.com/65535/52347841663_e5c966eb19_o.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>내가 만든 뉴진스 팬명록</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>

스크립트 설명

페이지가 열릴때 set_temp함수와 show_comment함수가 실행된다.

set_temp함수는 서울시 기온 api를 가져와 temp임시저장소에 저장하고 text만을 추출해 데이터를 페이지에 띄워준다.

profile
이제 막 개발 배우는 코린이

0개의 댓글