第4週目の「Web開発」ジョブ:Flashを使用したホームページの作成、APIおよびHTMLの使用

48367 ワード

あ、宿題が難しすぎます.
<ジョブ>
📃 1週間目に完成したショッピングモールを完成してください!
ショッピングモールは2つの機能を実行する必要があります.
1)注文(POST):情報を入力して「注文」ボタンをクリックして注文リストに追加する
2)注文履歴の表示(GET):ページのロード後に自動的に下の注文リストを表示する
以下の完成本を参考にしてください!
http://spartacodingclub.shop/homework
Pythonコード
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']
    phone_receive = request.form['phone_give']

    doc = {
        'name': name_receive,
        'count': count_receive,
        'address': address_receive,
        'phone': phone_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)
htmlコード
<!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">

    <!-- 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>

    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR&display=swap" rel="stylesheet">


    <style>
        * {
            font-family: 'IBM Plex Sans KR', sans-serif;
        }

        .wrap {
            width: 400px;
            margin: 0px auto 30px auto;
        }

        .button {
            width: fit-content;
            margin: auto;
        }

        .exchange {
            color: blue;
        }

        .table {
            margin-top: 50px;
        }
    </style>

    <script>
        $(document).ready(function () {
            get_rate();
            listing();
        });

        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 phone = orders[i]['phone'];

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

        function get_rate() {
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/rate",
                data: {},
                success: function (response) {
                    let now_rate = response[1]["rate"];
                    $('#now-rate').text(now_rate);
                }
            });
        }

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

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

<body>
    <div>
        <div class=wrap>
            <img class="rounded mx-auto d-block"
                 src="https://t1.daumcdn.net/thumb/R720x0.fjpg/?fname=http://t1.daumcdn.net/brunch/service/user/aiNp/image/tZm7Dzz3d7SLQMq6_nt1SqSxxoU.jpg"
                 alt="사진이 안나와요">
            <div>
                <h1 style="display: inline">캔들 팝니다</h1>
                <h5 style="display: inline">가격: 30,000원 / 개</h5>
                <h6>이 상품은 향이 엄청 좋아요. 저 잘 때 꼭 이거 열어놓고 잘 만큼 발향도 좋고, 그냥 디게 좋슴돠 안사면 후회할지도 몰라yo</h6>
                <p class="exchange">환율 원-환율: <span id = "now_rate">1212</span> </p>
            </div>

            <div class = "item-order">
                <div class="input-group mb-3">
                    <span class="input-group-text">주문자 이름</span>
                    <input id = "order-name" type="text" class="form-control" aria-label="Username"
                           aria-describedby="basic-addon1" >
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <label class="input-group-text" for="Select">수량</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">
                    <span class="input-group-text">주소</span>
                    <input type="text" class="form-control"
                           aria-describedby="basic-add" id = "order-address">
                </div>
                <div class="input-group mb-3">
                    <span class="input-group-text">전화번호</span>
                    <input type="text" class="form-control"
                           aria-describedby="basic-phone-num" id = "order-phone">
                </div>
            </div>
            <div class="button">
                <button type="button" onclick="order()" class="btn btn-primary btn-order">주문하기</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>
    </div>
</body>

</html>