웹개발 종합반

네 번째 미니 프로젝트: 팬명록

Won's log 2023. 5. 11. 17:37

이번 프로젝트는 팬명록 만들기이다

좋아하는 연예인의 팬명록을 만드는 것인데

닉네임, 응원댓글을 기록하면

아래로 기록들이 달리는 사이트이다

 

결과 먼저 보기

대표사진 삭제
 

사진 설명을 입력하세요.

나는 좋아하는 연예인이 없어서

친한 친구가 좋아하는 연예인(비투비 이창섭씨)을

대상으로 하여 만들었다 :)

 

이번 프로젝트에도 사용한 언어는 python이며

프레임워크는 flask를 사용하였다

이전 포스트와 마찬가지로

주요 코드를 공유하는 것으로 포스트를 마치고자 한다

 

python

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

from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://sparta:test@cluster1.g5zvb7v.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
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)
 

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://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAxNzExMjdfMTQg%2FMDAxNTExNzkxODc0NzIx.jLpMdXfSmhsfwxca8wIYaYK0qobtzffrhKCOy91lD6Ig.IctGUP3cy2KyBIQHlFMJr50YH5AjKMleK0c_jdJXTW0g.JPEG.cooljazzme%2F5715.jpg&type=a340" />


  <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://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAxNzExMjdfMTQg%2FMDAxNTExNzkxODc0NzIx.jLpMdXfSmhsfwxca8wIYaYK0qobtzffrhKCOy91lD6Ig.IctGUP3cy2KyBIQHlFMJr50YH5AjKMleK0c_jdJXTW0g.JPEG.cooljazzme%2F5715.jpg&type=a340");
      background-position: center 30%;
      background-size: cover;

      color: white;

      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background-size: contain;
    }

    .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"
 
</blockquote>
      </div>
    </div>
  </div>
</body>

</html>​

결과

 

참고로 이번에는 내가 만든 팬명록을 배포하는 작업도 했다

무슨 의미냐면, 나 혼자만 보는 것이 아니라

모든 사람들이 볼 수 있도록 웹사이트 URL을 만드는 것이었다

배포를 위해서는 직접 만들 순 없고

배포 서비스를 제공하는 곳에서 사야한다고 한다

 

우리가 이번 배포할 때 사용한 서비스는 AWS였다

AWS는 아마존에서 사용하는 클라우드 서비스로

인터넷에 있는 컴퓨터를 빌려서

내 컴퓨터마냥 배포하도록 돕는 서비스라고 한다

 

URL 하나는 무료로 1년 간 제공하고 있기 때문에

해당 서비스로 웹사이트를 배포해 보았다

배포하고 친구들에게 자랑했다 ㅎ

뿌듯해따

더 열심히 해야징