[10.21] 내일배움캠프 4일차(웹개발종합)

박상훈·2022년 10월 21일
0

[10.21] 내일배움캠프 4일차(웹개발종합)

👉 3일차 내용을 바탕으로 Flask를 통해 서버를 열어보자

1. Flask

  • Flask FrameWork
    👉 라이브러리와 다르게 프레임 워크는 약속된 규칙을 지켜야함
    👉 규칙 1) : templates Dir ( html , css )
    👉 규칙 2) : static Dir ( 이미지 등.. )
    👉 규칙 3) : app.py ( 동작 python )
  • app.py
@app.route('/')
def home():
   return render_template('index.html') --> index.html 파일 랜더링 -> spring의 컨트롤러 같다..

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

----- ajax , flask ---

@app.route('/test', methods=['GET'])
def test_get():
    title_receive = request.args.get('title_give')
    print(title_receive)
    return jsonify({'result':'success', 'msg': '이 요청은 GET!'})

@app.route('/test', methods=['POST'])
def test_post():
    title_receive = request.form['title_give']
    print(title_receive)
    return jsonify({'result':'success', 'msg': '요청을 잘 받았어요!'})
  • index.html( 랜더링 받는 html )
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script>
        function hey() {
            $.ajax({
                type: "POST",
                url: "/test",
                data: {title_give: '봄날은간다'},
                success: function (response) {
                    console.log(response['msg'])
                }
            })

        }

    </script>
</head>
<body>
<h1>나의 첫 웹 페이지</h1>
<button onclick="hey()">버튼을 만들자</button>
</body>
</html>

👉 /test로 Post요청을 보냈기 때문에 return으로 '요청을 잘 받았어요!'
가 콘솔창에 출력되게 된다.

2. Flask를 활용해 예제 만들기

👉 이름, 주소, 평수를 선택해 주문하여 MongoDB에 저장 해보자.

  • app.py
from flask import Flask, render_template, request, jsonify
from pymongo import MongoClient

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

app = Flask(__name__)


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

# 이름,주소,평수를 index.html의 js구문으로 받아 MongoDB에 저장하는 부분
@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': '주문 완료!'})

# 현재 저장 된 MongoDB를 읽어와서 index.html에 뿌려주는 부분
@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)
  • 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();
        });
// MongoDB의 저장된 데이터를 app.py로 받아 html에 찍어주는 부분
        function show_order() {

            $.ajax({
                type: 'GET',
                url: '/mars',
                data: {},
                success: function (response) {
			//app.py에서 json타입으로 DB data를 'orders'로 보냄
                    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 html = `<tr>
                                        <td>${name}</td>
                                        <td>${address}</td>
                                        <td>${size}</td>
                                    </tr>`
						//html에 찍어주는 부분
                         $('#order-box').append(html)


                    }
                }
            });
        }

        function save_order() {
	 	  //입력한 정보를 긁어오는 부분
            let name = $('#name').val()
            let address = $('#address').val()
            let size = $('#size').val()
		  //긁은 정보를 app.py로 보내는 부분
            $.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>
  • MongoDB ( Mars )

2-1. Flask를 사용해 예제 만들기 2

👉 네이버 영화 url를 입력해서 별점, 코멘트와 함께 저장하고 불러오기
👉 여기서는 metaData로 접근한다.

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

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient

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

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

# 입력창에서 url, 별점, 코멘트를 받아온 부분
@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'}
        #받아온 url로 data를 완성 시켜준다.
    data = requests.get(url_receive, headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')
    #기존에는  테그 > 테그 식으로 접근 했지만 여기서는 header부분 meta에 접근
    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에 저장
    db.movies.insert_one(doc)

	##저장완료 response
    return jsonify({'msg':'저장 완료!'})


@app.route("/movie", methods=["GET"])
def movie_get():
	#DB정보 전부 긁어오기
    movie_list = list(db.movies.find({}, {'_id': False}))
    #'movies' json 형태로 response
    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();
        });

      //모든 DB가져와서 html 뿌려주는 곳
        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']
                        //별점 반복을 위해 쓰는 Method
                        let start_img = '⭐'.repeat(star)

                        let 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>${start_img}</p>
                                                <p class="mycomment">${comment}</p>
                                            </div>
                                        </div>
                                    </div>`
                        $('#cards-box').append(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'])
                    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>
  • MongoDB( movies )

2-2.Flask를 사용해 예제 만들기 3[HomeWork]

👉 전에 작성했던 팬명록에서 닉네임, 댓글을 받아 MongoDB에 저장하고 저장된 팬명록을 불러오자

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

from pymongo import MongoClient

client = MongoClient('mongodb+srv://test:sparta@cluster0.cygiufq.mongodb.net/Cluster0?retryWrites=true&w=majority')
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']
    comment_receive = request.form['comment']
    doc = {
        'name':name_receive,
        'comment':comment_receive
    }

    db.fan.insert_one(doc)


    return jsonify({'msg':'저장 완료!'})

# 저장된 DB를 전부 가져와 반환 해주는 부분
@app.route("/homework", methods=["GET"])
def homework_get():

    fan_list = list(db.fan.find({}, {'_id': False}))

    return jsonify({'fan_list':fan_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 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: 400px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://t1.daumcdn.net/cfile/tistory/99BA7A495CA352A814');
            background-position: center ;
            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': name,
                       'comment':comment},
                success: function (response) {
                    alert(response['msg'])
                    window.location.reload()
                }
            })
        }

      //저장된 DB를 전부 보내준 것을 html에 찍어주는 부분
        function show_comment() {
            $.ajax({
                type: "GET",
                url: "/homework",
                data: {},

                success: function (response) {
                   let rows = response['fan_list']
                    for(let i=0;i < rows.length;i++){
                        let name = rows[i]['name']
                        let comment = rows[i]['comment']

                         let html = ` <div class="card">
                                        <div class="card-body">
                                            <blockquote class="blockquote mb-0">
                                                <p>${name}</p>
                                                <footer class="blockquote-footer">${comment}</footer>
                                            </blockquote>
                                        </div>`

                        $('#comment-list').append(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>
  • MongoDB( fan )

2-3. Flask를 사용해 예제 만들기 4[Remake]

👉 기존에 혼자 만들었 던 관광지 추천 웹 페이지에서 url을 입력 받아 MongoDB에 저장하고 뿌려주자.

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

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient

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

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

# 입력 받은 url로 요청,별점을 저장하는 부분
@app.route("/trip", methods=["POST"])
def movie_post():
    url_receive = request.form['url']
    score_receive = request.form['score']

    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'].split('-')[0]
    image = soup.select_one('meta[property="og:image"]')['content']
    desc = soup.select_one('meta[property="og:description"]')['content']

    print(title,image,desc)

    doc = {'title':title,
           'image':image,
           'desc':desc,
           'star':score_receive
           }

    db.trips.insert_one(doc)


    return jsonify({'msg':'저장 완료!'})

# DB에 저장되어 있는 정보를 전부 가져와 Response해주는 부분
@app.route("/trip", methods=["GET"])
def movie_get():
    trip_list = list(db.trips.find({}, {'_id': False}))
    return jsonify({'trips': trip_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 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>
    <link href="https://fonts.googleapis.com/css2?family=Black+Han+Sans&family=Nanum+Gothic&display=swap"
          rel="stylesheet">
    <title>다시 연습해보기</title>
    <style>
        * {
            font-family: 'Hi Melody', cursive;
        }

        .mytitle {
            background-color: green;
            height: 300px;
            width: 100%;
            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://post-phinf.pstatic.net/MjAxODAzMTdfNzYg/MDAxNTIxMjIxNjQxNDQ3.Z4UwpknVj4agsPoHEg4Mk8HLscjzd_dMO5l7Z20MS3Ag.32_e21NxEl-bxbQjWcEXIXxVPRL3nFwmeoLZKhPUw-Mg.JPEG/1.jpg?type=w1200");
            background-position: center;
            background-size: cover;


            color: white;

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

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

            background-color: transparent;
            color: white;
            border-radius: 50px;
            border: 1px solid white;
            margin-top: 10px;

        }

        .writeContent {

            max-width: 500px;
            width: 95%;
            margin: 20px auto 0 auto;

            box-shadow: 0px 0px 3px 0px gray;
            padding: 20px;

            display: none;


        }

        .score {
            margin: 10px auto auto auto;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
        }

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

        .ad_btn {
            margin: 10px auto auto auto;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            background-color: skyblue;
            color: white;
            border-radius: 5px;
            border: 1px solid white;
        }
    </style>

    <script>

        $(document).ready(function () {
            listing();
        });

      // DB에서 가져온 정보 뿌려주는 부분
        function listing() {
            $.ajax({
                type: 'GET',
                url: '/trip',
                data: {},
                success: function (response) {

                    let rows = response['trips']

                    for(let i =0;i < rows.length;i++){
                        let image = rows[i]['image']
                        let title = rows[i]['title']
                        let desc = rows[i]['desc']
                        let star = rows[i]['star']
                        let star_count = '⭐'.repeat(star)

                        let html = `<div class="card">
                                        <img src="${image}"
                                             class="card-img-top" alt="...">
                                        <div class="card-body">
                                            <h5 class="card-title">${title}</h5>
                                            <p class="card-text">${desc}</p>
                                            <p class="card-text">${star_count}</p>
                                        </div>
                                    </div>`

                          $('#card-group').append(html)


                    }

                }
            })

        }
      //url과 평점 넘겨주는 부분
        function posting() {

            let url = $('#formGroupExampleInput').val()
            let score = document.querySelector('input[name="inlineRadioOptions"]:checked').value;


            if (url == "") {
                alert("명소 url을 입력하세요!!")
                return
            }

            // alert(url + "을(를)" + score + "점으로 추천하셨군요!!")

            $.ajax({
                type: 'POST',
                url: '/trip',
                data: {
                    'url': url,
                    'score': score
                },
                success: function (response) {

                        alert(response['msg'])
                        location.reload()

                }

            })

        }


        function rec() {

            $('#writeContent').show()

        }
    </script>
</head>
<body>
<div class="mytitle">
    <h1>관광지 추천</h1>
    <button onclick="rec()">추천 해보기</button>
</div>

<div class="writeContent" id="writeContent">
    <div class="mb-3">
        <label for="formGroupExampleInput" class="form-label">명소 url</label>
        <input type="text" class="form-control" id="formGroupExampleInput" placeholder="">
    </div>


    <div class="score">

        ❤️
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="1" checked>
            <label class="form-check-label" for="inlineRadio1">1</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="2">
            <label class="form-check-label" for="inlineRadio2">2</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="3">
            <label class="form-check-label" for="inlineRadio3">3 </label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio4" value="4">
            <label class="form-check-label" for="inlineRadio4">4 </label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio5" value="5">
            <label class="form-check-label" for="inlineRadio5">5 </label>
        </div>

    </div>
    <button type="button" class="ad_btn" onclick="posting()">추천하기</button>

</div>

<div class="card-group" id ="card-group">

</div>


</body>
</html>

3. 느낀점⭐

  1. flask로 로컬 서버를 여는 것이 spring에서 내장 톰켓 썼던 것과 유사하다.
  2. 크롤링 할 때 테그가 이상하다면 header > meta로 가보는 것도 좋다.
profile
기록하는 습관

0개의 댓글