[스파르타] 따봉댕댕.. 서버에 올리기!

이용찬·2021년 11월 19일
0

내일배움단

목록 보기
14/14
post-thumbnail

나만의 쇼핑몰! 따봉댕댕 마무리..

01. 따봉댕댕 원목식탁

app 코드

from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

# import requests
# from bs4 import BeautifulSoup

from pymongo import MongoClient

client = MongoClient('mongodb://test:test@localhost', 27017)
# client = MongoClient('localhost', 27017)
db = client.dbsparta


## HTML 화면 보여주기
@app.route('/')
def homework():
    return render_template('index.html')


# 주문하기(POST) API
@app.route('/order', methods=['POST'])
def save_order():
    name_receive = request.form['name_give']
    quantity_receive = request.form['quantity_give']
    address_receive = request.form['address_give']
    phone_receive = request.form['phone_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 = {'name': name_receive, 'quantity': quantity_receive, 'address': address_receive, 'phone': phone_receive}
    db.order.insert_one(doc)
    return jsonify({'msg':'"댕댕이: 주문완료!"'})


# 주문 목록보기(Read) API
@app.route('/order', methods=['GET'])
def view_orders():
    orders = list(db.order.find({}, {'_id':False}))
    return jsonify({'all_order_txt':orders})

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

index 코드

<!doctype html>
<html lang="ko">

<head>
    <!-- Required meta tags -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Single+Day&display=swap" rel="stylesheet">

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>

    <title>따봉댕댕 원목식탁</title>

    <meta property="og:title" content="[따봉댕댕] 원목식탁"/>
    <meta property="og:description" content="댕댕이의, 댕댕이에 의한, 댕댕이를 위한!"/>
    <meta property="og:image" content="{{ url_for('static', filename='ogimage.jpg') }}"/>

    <style>
        * {
            font-family: 'Single Day', cursive;
        }

        .myitem {
            width: 600px;
            height: 400px;
            border-radius: 10px;

            background-image: url("https://search.pstatic.net/common/?src=http%3A%2F%2Fshop1.phinf.naver.net%2F20210809_276%2F1628518291742GIISU_JPEG%2F29654190450034502_252533649.jpg&type=sc960_832");
            background-position: center;
            background-size: cover;
        }

        .font_rate {
            font-size: 25px;
            color: blue;
        }

        .desc {
            width: 600px;
            margin-top: 20px;
            margin-bottom: 20px;
        }

        .order-box {
            width: 600px;
            margin-bottom: 40px;
        }

        .mybtn {
            width: 100px;
            margin: auto;
            display: block;
        }

        .wrap {
            margin: auto;
            width: 600px;
        }

        .rate {
            color: blue;
        }
    </style>
    <script>
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "https://api.manana.kr/exchange/rate.json",
                data: {},
                success: function (response) {
                    let nowRate = response[1]['rate'];
                    $('#rate-box').text(nowRate);
                }
            })
            order_listing();
        });

        function order_listing() {
            // 주문목록 보기 API 연결
            $.ajax({
                type: "GET",
                url: "/order",
                data: {},
                success: function (response) {
                    let order_txt=response['all_order_txt']

                    for(i=0; i<order_txt.length; i++) {
                        let name=order_txt[i]['name']
                        let quantity=order_txt[i]['quantity']
                        let address=order_txt[i]['address']
                        let phone=order_txt[i]['phone']

                        let temp_html=`
                            <tr>
                                <th scope="row">${name}</th>
                                <td>${quantity}</td>
                                <td>${address}</td>
                                <td>${phone}</td>
                            </tr>`
                        $('#order-box').append(temp_html)
                    }


                }
            })
        }

        function order() {
            let name=$('#order-name').val()
            let quantity=$('#order-count').val()
            let address=$('#order-address').val()
            let phone=$('#order-phone').val()

            // 주문하기 API 연결
            $.ajax({
                type: "POST",
                url: "/order",
                data: {name_give:name, quantity_give:quantity, address_give:address, phone_give:phone},
                success: function (response) { // 성공하면
                    alert(response["msg"]);
                    window.location.reload()
                }
            })
        }
    </script>
</head>

<body>
<div class="wrap">
    <div class="myitem"></div>
    <div class="desc">
        <p>
        <h2>따봉댕댕 원목식탁<span class="font_rate">가격: 18,000원/개</span></h2></p>
        <p>낮은 식기사용은 소화불량이 생길 수 있다는 사실!</p>
        <p>댕댕이들은 목이 뻣뻣하기 때문에 낮은 식기를 사용하면 고개를 깊숙이 숙여서 먹어야 하기 때문에<br>급하게 먹게 되면 목에 걸리기 쉽고 소화불량의 원인이 될 수 있어요.</p>
        <p class="rate">달러-원 환율: <span id="rate-box">1,000</span></p>
    </div>
    <div class="order-box">
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="inputGroup-sizing-default">주문자이름</span>
            </div>
            <input id="order-name" type="text" class="form-control" aria-label="Default"
                   aria-describedby="inputGroup-sizing-default">
        </div>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <label class="input-group-text" for="inputGroupSelect01">수량</label>
            </div>
            <select id="order-count" class="custom-select">
                <option selected>-- 수량을 선택하세요 --</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>
        </div>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="inputGroup-sizing-default">주소</span>
            </div>
            <input id="order-address" type="text" class="form-control" aria-label="Default"
                   aria-describedby="inputGroup-sizing-default">
        </div>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="inputGroup-sizing-default">전화번호</span>
            </div>
            <input id="order-phone" type="text" class="form-control" aria-label="Default"
                   aria-describedby="inputGroup-sizing-default">
        </div>
        <button onclick="order()" type="button" class="btn btn-primary mybtn">주문하기</button>
    </div>
    <table class="table">
        <thead>
        <tr>
            <th scope="col">이름</th>
            <th scope="col">수량</th>
            <th scope="col">주소</th>
            <th scope="col">전화번호</th>
        </tr>
        </thead>
        <tbody id="order-box">

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

</html>

결과물: 따봉댕댕!

02. 따봉댕댕 놀러 오세요!

http://yongchanlee.shop/

03. 느낀점

나만의 쇼핑몰 사이트를 만든 것에 대한 뿌듯함!
2주 전 나의 모습과 지금의 나의 모습

profile
안녕하세요. 클래식을 즐기는 개발자, 이용찬입니다.

0개의 댓글

관련 채용 정보