<スパルタ3週目>1ページのショッピングモールを完成


1週目に作成したショッピングモール(弾丸イカ)にPOST、GET機能を実装しました.
★開始前準備事項★
1.static,templatesフォルダ+app.pyを作ろう!
2.pymongo,フラスコ取付(設定→Python解釈器→+ボタン)

名前、数量、住所、電話番号を入力し、「注文」をクリックすると、次のリストにデータが表示されます。


▼ app.py

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('hw_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)

▼ index.html


(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>`
                            $('#order_box').append(temp_html);
                        }
                    }
                }
            })

        }
        function get_rate() {
            $.ajax({
                type: "GET",
                url: "https://api.manana.kr/exchange/rate.json",
                date: {},
                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();
                    }
                }
            })
        }
Today I Learned
整理
  • コード操作シーケンス
  • エラーに注意!
  • 中端コンソールによる確認と操作