항해99/웹개발종합반

4주차 강의

숲별 2022. 8. 10. 19:39
728x90

러프한 메모

 

[웹개발강의 4-1]
내 컴퓨터에서 서버 만들고 내가 테스트
=> 로컬개발환경


[웹개발강의 4-2 Flask시작하기-서버만들기]
- Flask 프레임워크: 서버를 구동시켜주는 편한 코드 모음. 서버를 구동하려면 필요한 복잡한 일들을 쉽게 가져다 쓸 수 있다.
    
    <aside>
    👉 프레임워크를 쓰지 않으면 태양초를 빻아서 고추장을 만드는 격!
    프레임워크는 3분 요리/소스 세트라고 생각하면 되겠습니다!
    
서버를 직접만드는 개발자는 이 세상에 없다고 java면 java에 있는 프레임워크, 파이썬이면 파이썬에 있는 프레임워크를 사용해 서버 만듦.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

@app.route('/mypage')
def mypage():
   return 'This is Mypage!'

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


[웹개발강의 4-3 Flask-HTML]
참고라고 밑에 달아뒀던 강의자료 자세히 안 살폈었는데(강의 중 영상에 드문드문 보여주니까) 유용한 단축키들도 있어서 나중에 한번 훑어야겠다. 2회독 때 한 번 정리해야겠어.

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

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

if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)
---------
http://localhost:5000/
서버에서 작동하는 페이즈를 보는 것이고

파이참에서 크롬버튼으로 들어가는 건 내 컴퓨터 파일을 연 것. 이제부턴 이걸로 들어갈 일이 없어.

[웹개발강의 4-4 Flask-API만들기]
은행 창구에 가는 방법 2가지

Get: 데이터 조회
Post: 데이터 생성(create), 변경(update), 삭제(delete) 

프론트엔드 -HTML
백엔드-flask 서버
-------
$.ajax({
                type: "GET",
                url: "/test?title_give=봄날은간다",
                data: {},
                success: function (response) {
                    console.log(response)
                }
            })
-------
=> /test라는 창구로 가서
title_give라는 이름으로 봄날은 간다를 가지고 갈게
잘된다면 내가 콘솔에 찍어볼게

---------------
$.ajax({
type: "POST",
url: "/test",
data: { title_give:'봄날은간다' },
success: function(response){
console.log(response)
}
})
----------------------

@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '요청을 잘 받았어요'})

파이썬은 들여쓰기가 중요하다더니..정말
코드 복사해서 넣었는데 들여쓰기 안 되어있어서 에러났었음..ㅎㅎ

파이썬 파일의 return jsonify를
html의 response로 가져옴.
--------


[웹개발강의 4-5]
파일-설정-프로젝트-python 인터프리터
flask, pymongo, dnspython
3개 설치
...프로젝트 폴더별로 패키지를 설치해야하는 건가?



[웹개발강의 4-7]
페이지 새로고침
window.location.reload()

소소한 에러는 꽤 구체적으로 파이썬이 알려준다.
이정도면 그냥 니가 알아서 고쳐줬어도 되는 거 아닌가 싶을 정도?ㅋㅋ

일단, 실행창에 문제가 있는 줄이 뜬다.
찾아가기 쉽게 몇째줄인지도 알려줌.

그 외에도 오류가 나면 그 때 그때 우측상단에 빨갛게 뜨는데 눌러보면 쉼표가 빠졌다, 중괄호가 빠졌다 등 상세하게 알려줌.

 

[웹개발강의 4-8 화성땅 공동구매]
###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+Batang:wght@400;700&display=swap" rel="stylesheet">

    <title>선착순 공동구매</title>


    <style>
        * {
            font-family: 'Gowun Batang', serif;
            color: white;
        }

        body {
            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://cdn.aitimes.com/news/photo/202010/132592_129694_3139.jpg');
            background-position: center;
            background-size: cover;
        }

        h1 {
            font-weight: bold;
        }

        .order {
            width: 500px;
            margin: 60px auto 0px auto;
            padding-bottom: 60px;
        }

        .mybtn {
            width: 100%;
        }

        .order > table {
            margin: 40px 0;
            font-size: 18px;
        }

        option {
            color: black;
        }
    </style>
    <script>
        $(document).ready(function () {
            show_order();
        });

        function show_order() {
            $.ajax({
                type: 'GET',
                url: '/mars',
                data: {},
                success: function (response) {
                    let rows = response['orders']
                    for (let i = 0; i < rows.length; i++) {
                        let name = rows[i]['name']
                        let address = rows[i]['address']
                        let size = rows[i]['size']

                        let temp_html = `<tr>
                                            <td>홍길동${name}</td>
                                            <td>${address}</td>
                                            <td>${size}</td>
                                        </tr>`
                        $('#order-box').append((temp_html))
                    }
                }
            });
        }

        function save_order() {
            let name = $('#name').val()
            let address = $('#address').val()
            let size = $('#size').val()


            $.ajax({
                type: 'POST',
                url: '/mars',
                data: {name_give: name, address_give: address, size_give: size},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            });
        }
    </script>
</head>
<body>
<div class="mask"></div>
<div class="order">
    <h1>화성에 땅 사놓기!</h1>
    <h3>가격: 평 당 500원</h3>
    <p>
        화성에 땅을 사둘 수 있다고?<br/>
        앞으로 백년 간 오지 않을 기회. 화성에서 즐기는 노후!
    </p>
    <div class="order-info">
        <div class="input-group mb-3">
            <span class="input-group-text">이름</span>
            <input id="name" type="text" class="form-control">
        </div>
        <div class="input-group mb-3">
            <span class="input-group-text">주소</span>
            <input id="address" type="text" class="form-control">
        </div>
        <div class="input-group mb-3">
            <label class="input-group-text" for="size">평수</label>
            <select class="form-select" id="size">
                <option selected>-- 주문 평수 --</option>
                <option value="10평">10평</option>
                <option value="20평">20평</option>
                <option value="30평">30평</option>
                <option value="40평">40평</option>
                <option value="50평">50평</option>
            </select>
        </div>
        <button onclick="save_order()" type="button" class="btn btn-warning mybtn">주문하기</button>
    </div>
    <table class="table">
        <thead>
        <tr>
            <th scope="col">이름</th>
            <th scope="col">주소</th>
            <th scope="col">평수</th>
        </tr>
        </thead>
        <tbody id = "order-box">

        </tbody>
    </table>
</div>
</body>
</html>

-------


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

from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.bqbsmxx.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta


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

@app.route("/mars", methods=["POST"])
def web_mars_post():
    name_receive = request.form['name_give']
    address_receive = request.form['address_give']
    size_receive = request.form['size_give']
    doc = {
        'name':name_receive,
        'address':address_receive,
        'size':size_receive
    }
    db.mars.insert_one(doc)
    return jsonify({'msg':'주문완료!'})

@app.route("/mars", methods=["GET"])
def web_mars_get():
    order_list = list(db.mars.find({}, {'_id': False}))
    return jsonify({'orders': order_list})

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

------



[웹개발강의 4-9 스파르타피디아 프로젝트 셋팅]

movie폴더 안에 static, templates폴더 만듦.
패키지설치
(flask, pymongo, dnspython)
=>플라스크와 데이터베이스 연결 

나는 인터넷 환경 때문에 certifi도 설치

(requests, bs4)
=>크롤링(조각기능..?)


[웹개발강의 4-10 조각기능]
https://movie.naver.com/movie/bi/mi/basic.naver?code=191597
에서 가져올건데 네이버가 사람이 접근하는 랑 코드가 접근하는 거에 다르게 반응해서 저번이랑 조금 다르게 가져올 거임.


API: Application Program Interface, 라이브러리에 접근하기 위한 규칙들을 정의한 것

[웹개발강의 4-13]
####app.py
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient
import certifi

ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.bqbsmxx.mongodb.net/Cluster0?retryWrites=true&w=majority',
                     tlsCAFile=ca)
db = client.dbsparta

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


@app.route("/movie", methods=["POST"])
def movie_post():
    url_receive = request.form['url_give']
    star_receive = request.form['star_give']
    comment_receive = request.form['comment_give']

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get(url_receive, headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')

    title = soup.select_one('meta[property="og:title"]')['content']
    image = soup.select_one('meta[property="og:image"]')['content']
    desc = soup.select_one('meta[property="og:description"]')['content']

    doc = {
        'title':title,
        'image':image,
        'desc':desc,
        'star':star_receive,
        'comment':comment_receive

   }
    db.movies.insert_one(doc)
    return jsonify({'msg':'저장 완료!'})



@app.route("/movie", methods=["GET"])
def movie_get():
    movie_list = list(db.movies.find({}, {'_id': False}))
    return jsonify({'movies': movie_list})


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 name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


    <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=Gowun+Dodum&display=swap" rel="stylesheet">

    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }

        .mytitle {
            width: 100%;
            height: 250px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg');
            background-position: center;
            background-size: cover;

            color: white;

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

        .mytitle > button {
            width: 200px;
            height: 50px;

            background-color: transparent;
            color: white;

            border-radius: 50px;
            border: 1px solid white;

            margin-top: 10px;
        }

        .mytitle > button:hover {
            border: 2px solid white;
        }

        .mycomment {
            color: gray;
        }

        .mycards {
            margin: 20px auto 0px auto;
            width: 95%;
            max-width: 1200px;
        }

        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 0px auto;
            padding: 20px;
            box-shadow: 0px 0px 3px 0px gray;

            display: none;
        }

        .mybtns {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;

            margin-top: 20px;
        }

        .mybtns > button {
            margin-right: 10px;
        }
    </style>
    <script>
        $(document).ready(function () {
            listing();
        });

        function listing() {
            $.ajax({
                type: 'GET',
                url: '/movie',
                data: {},
                success: function (response) {
                    let rows = response['movies']
                    for(let i=0; i<rows.length;i++){
                        let comment = rows[i]['comment']
                        let title = rows[i]['title']
                        let desc = rows[i]['desc']
                        let image = rows[i]['image']
                        let star = rows[i]['star']

                        let star_image = '⭐'.repeat(star)

                        let temp_html=`<div class="col">
                                            <div class="card h-100">
                                                <img src="${image}"
                                                     class="card-img-top">
                                                <div class="card-body">
                                                    <h5 class="card-title">${title}</h5>
                                                    <p class="card-text">${desc}</p>
                                                    <p>${star_image}</p>
                                                    <p class="mycomment">${comment}</p>
                                                </div>
                                            </div>
                                        </div>`
                        $('#cards-box').append(temp_html)

                    }


                }
            })
        }

        function posting() {
            let url = $('#url').val()
            let star = $('#star').val()
            let comment = $('#comment').val()

            $.ajax({
                type: 'POST',
                url: '/movie',
                data: {url_give: url, star_give: star, comment_give: comment},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            });
        }

        function open_box() {
            $('#post-box').show()
        }

        function close_box() {
            $('#post-box').hide()
        }
    </script>
</head>

<body>
<div class="mytitle">
    <h1>내 생애 최고의 영화들</h1>
    <button onclick="open_box()">영화 기록하기</button>
</div>
<div class="mypost" id="post-box">
    <div class="form-floating mb-3">
        <input id="url" type="email" class="form-control" placeholder="name@example.com">
        <label>영화URL</label>
    </div>
    <div class="input-group mb-3">
        <label class="input-group-text" for="inputGroupSelect01">별점</label>
        <select class="form-select" id="star">
            <option selected>-- 선택하기 --</option>
            <option value="1">⭐</option>
            <option value="2">⭐⭐</option>
            <option value="3">⭐⭐⭐</option>
            <option value="4">⭐⭐⭐⭐</option>
            <option value="5">⭐⭐⭐⭐⭐</option>
        </select>
    </div>
    <div class="form-floating">
        <textarea id="comment" class="form-control" placeholder="Leave a comment here"></textarea>
        <label for="floatingTextarea2">코멘트</label>
    </div>
    <div class="mybtns">
        <button onclick="posting()" type="button" class="btn btn-dark">기록하기</button>
        <button onclick="close_box()" type="button" class="btn btn-outline-dark">닫기</button>
    </div>
</div>
<div class="mycards">
    <div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">

    </div>
</div>
</body>

</html>


[웹개발강의 4-14 숙제]
homework폴더 안에 static, templates폴더를 만들어준다.
homework폴더에 app파이썬 파일 만들고
templates폴더 안에 index.html 파일도 만든다.

패키지 설치
flask
pymongo
dnspython

사진 둘 중 고민..

https://cdn.onews.tv/news/photo/202111/96891_105931_025.jpg


리팩사진
https://assets.repress.co.kr/photos/5b1ff804e123fcb48d1ef1fcf17ac9fc/original.jpg

아래에서 에러가 어디에서 난 건지 모르겠어서 
해설영상보고 다시 만듦
-------
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

from pymongo import MongoClient
import certifi

ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.bqbsmxx.mongodb.net/Cluster0?retryWrites=true&w=majority',
                     tlsCAFile=ca)
db = client.dbsparta


@app.route('/')
def home():



    return render_template('index.html')


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


@app.route("/homework", methods=["GET"])
def homework_get():
    comment_list = list(db.homework.find({}, {'_id:False'}))

    return jsonify({'comments': comment_list})

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>

    <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: 600px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://cdn.onews.tv/news/photo/202111/96891_105931_025.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 () {
            show_comment();
        });


        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)
                    }
                }
            });
        }
    </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>닉네임</label>
    </div>
    <div class="form-floating">
<textarea class="form-control" placeholder="Leave a comment here" id="comment"
          style="height: 100px"></textarea>
        <label>응원댓글</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>



-------해설영상 보고 다시
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

from pymongo import MongoClient

import certifi

ca = certifi.where()

client = MongoClient('mongodb+srv://test:sparta@cluster0.bqbsmxx.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta

@app.route('/')
def home():


    return render_template('index.html')


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


@app.route("/homework", methods=["GET"])
def homework_get():

    comment_list = list(db.homework.find({}, {'_id': False}))
    return jsonify({'comments': comment_list})

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>

    <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: 600px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://assets.repress.co.kr/photos/5b1ff804e123fcb48d1ef1fcf17ac9fc/original.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() {
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                data: {},
                success: function (response) {
                    $('#temp').text(response['temp'])
                }
            })
        }

        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)
                    }
                }
            });
        }
    </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>
</body>
</html>

-------



참고 : https://teamsparta.notion.site/4-0056714b522240a68f7c778237525282



 

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

매 주차 강의자료 시작에 PDF파일을 올려두었어요!

teamsparta.notion.site

 

'항해99 > 웹개발종합반' 카테고리의 다른 글

사이트 정리  (0) 2022.09.10
5주차 강의  (0) 2022.08.11
3주차 강의  (0) 2022.08.07
2주차 강의  (0) 2022.08.04
1주차 강의  (0) 2022.08.01