새소식

개발 공부 일지/웹

4주 차 숙제

  • -
반응형

1주 차에 완성한 팬명록을 완성하기!

두 가지 기능을 수행해야 한다.

  1. 응원 남기기(POST): 정보 입력 후 '응원 남기기' 버튼 클릭 시 주문 목록에 추가
  2. 응원 보기(GET): 페이지 로딩 후 하단 응원 목록이 자동으로 보이기

완성본 예제 링크: http://spartacodingclub.shop/web/homework

 

초미니홈피 - 팬명록

 

spartacodingclub.shop

파이참 기본 세팅 하기

새 프로젝트 homework 생성
디렉토리와 파일 만들기

homewirk에서 디렉터리 static, templates 만들고, app.py 파일을 만들고, templatesindex.html 파일 만들기!

패키지 설치하기

파이참에서 파일 → 설정 → 프로젝트:homework → python 인터프리터 → 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("/homework", methods=["POST"])
def homework_post():
    sample_receive = request.form['sample_give']
    print(sample_receive)
    return jsonify({'msg':'POST 연결 완료!'})

@app.route("/homework", methods=["GET"])
def homework_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>

    <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('아티스트 사진URL');
            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(){
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                data: {},
                success: function (response) {
                    $('#temp').text(response['temp'])
                }
            })
        }
        function save_comment(){
            $.ajax({
                type: 'POST',
                url: '/homework',
                data: {sample_give:'데이터전송'},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            })
        }
        function show_comment(){
            $.ajax({
                type: "GET",
                url: "/homework",
                data: {},
                success: function (response) {
                    alert(response["msg"])
                }
            });
        }
    </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>

inndex.html에서 1주 차에 만들었던 아이유 팬명록을 이용할 것이기에 이미지 주소 값과 타이틀을 바꿔주고 app.py에서 실행을 해준다.

브라우저 localhost:5000

이제 코드 수정하면서 시작!

app.py 코드 수정

from pymongo import MongoClient
client = MongoClient('피몽고 값')
db = client.dbsparta

위 코드를 상단에 입력!

 

post 내용을 아래처럼 수정

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

    doc = {
        'name':name_receive,
        'comment':comment_receive
    }

    db.homework.insert_one(doc)

    return jsonify({'msg':'응원 완료!'})

index.html 코드 수정

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

    $.ajax({
        type: "POST",
        url: "/homework",
        data: {'name_give':name, 'comment_give':comment},
        success: function (response) {
            alert(response["msg"])
            window.location.reload()
        }
    });
}
function show_comment() {
    $('#comment-list').empty()
    $.ajax({
        type: "GET",
        url: "/homework",
        data: {},
        success: function (response) {
            let rows = response['comments']
            for (let i = 0; i < rows.length; i++) {
                let name = rows[i]['name']
                let comment = rows[i]['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)
            }
        }
    });
}

브라우저에서 확인한 모습
dbsparta.homework

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.