[스파르타 웹개발 종합반] 4주차 정리

흐아악 무슨 일이 있었는지 모르겠지만 스파르타공룡한테 한 번 잡혔다... 어떻게 이런 일이.

4주차에는 프로젝트 형식으로 진행하는 수업들이었는데, 사실 숙제 부분만 올려도 대부분은 커버가 되는 것 같아서 숙제를 그대로 올리려고 합니다.

중요한 건

이런 형식의 프로젝트라는 점

DB랑 GET POST을 응용한 개발이었습니다.

주문 내역을 작성하면 하단의 테이블에 db의 내용을 읽어와서 적어주는 형식

from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.dbhomework


## 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']
    count_receive = request.form['count_give']
    address_receive = request.form['address_give']
    tel_receive = request.form['tel_give']

    doc = {
        'name': name_receive,
        'count': count_receive,
        'address': address_receive,
        'tel': tel_receive
    }
    db.orders.insert_one(doc)

    return jsonify({'result': 'success', 'msg': '주문 완료!'})


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


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

이건 app.py

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

<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 href="https://fonts.googleapis.com/css2?family=Gaegu:wght@300;400&family=Jua&family=Yeon+Sung&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>

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

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

        .img_area {
            width: 500px;
            margin: auto;
        }

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

        .goods_info {
            width: 500px;
            /*    padding: 50px;*/
            margin: 20px auto;
        }

        .realTime {
            color: blue;
        }
    </style>
    <script>

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

        function exchange_rate() {
            $('#names-q1').empty();
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/rate",
                data: {},
                success: function (response) {
                    let rate = response['rate'];
                    let temp_html = `<span class="realTime"> ${rate}</span>`;
                    $('#realTime_exchangeRate').append(temp_html);

                }
            })
        }
        function listing() {
            $.ajax({
                type: "GET",
                url: "/order",
                data: {},
                success: function (response) {
                    if (response["result"] == "success") {
                        let orders = response['orders'];
                        for (let i = 0; i < orders.length; i++) {
                            let name = orders[i]['name'];
                            let count = orders[i]['count'];
                            let address = orders[i]['address'];
                            let tel = orders[i]['tel'];

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

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

            $.ajax({
                type: "POST",
                url: "/order",
                data: {name_give: name, count_give: count, address_give: address, tel_give: tel},
                success: function (response) {
                    if (response["result"] == "success") {
                        alert(response["msg"]);
                        window.location.reload();
                    }
                }
            })
        }




    </script>

    <title>스파르타코딩클럽 | 01주차 숙제</title>
</head>

<body>
<div class="wrap">
    <div class="img_area">
        <img src="https://image.aladin.co.kr/product/9573/37/cover500/8988060393_1.jpg">
    </div>
    <div class="goods_info">
        <h1>크툴루의 부름 수호자 룰북</h1>
        <h5>판매가 : 34,200원</h5>
        <span>H.P. 러브크래프트의 세계를 다루는 테이블 롤플레잉 게임(TRPG)이다.
                      여러분은 용감한 탐사자가 되어 기이하고 위험한 곳들을 가고, 흉악한 음모를 밝혀내고, 크툴루 신화의 공포들에 맞서게 됩니다.</span>
    </div>
    <div class="goods_info">
        <span class="realTime" id="realTime_exchangeRate">달러-원 환율:</span>
    </div>
    <div class="goods_info">
        <h1>주문하기</h1>
        <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="order-count">수량</label>
            </div>
            <select class="custom-select" id="order-count">
            <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-tel" type="text" class="form-control" aria-label="Default"
                   aria-describedby="inputGroup-sizing-default">
        </div>
        <button type="button" onclick="order()" class="btn btn-secondary button_position">주문하기</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="orders-box">
        </tbody>
    </table>


</div>
</body>

</html>

이건 index.html

좋은 웹페이지 즐겨찾기