[스파르타] 4주차 쇼핑몰 완성하기

0

1,2,3주차도 써야했는데 매우 귀찮았음으로 4주차부터 쓰게되었다...

4주차에서 배운것은 Flask, MongoDB로 나만의 API를 만들고 DB에 저장하며 웹페이지와 연결하는 것. 최종 숙제로 완성된 웹페이지를 만들게 되었다

어쩌면 당연한거지만 강의를 볼땐 애매하게 몰랐던 사실이 숙제를 함에 있어서 이것저것 해보니까 더 내것이 되는 기분.. 이래서 스스로 해봐야 한다

app.py파일에서 맨처음 import해야하는 라이브러리들.

from flask import Flask, render_template, jsonify, request
from pymongo import MongoClient

DB에서 필요한 정보를 불러오기

@app.route('/order', methods=['GET'])
def listing():
    order = list(db.shop.find({}, {'_id': False}))
    return jsonify({'all_orders': order})

주문에 필요한 API: 이름, 수량, 주소, 전화번호를 웹페이지로부터 받아와서 DB에 저장하게 되며 주문이 완료되었다는 메시지를 띄우게된다.

@app.route('/order', methods=['POST'])
def 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']
    doc = {
        'name' : name_receive,
        'quantity' : quantity_receive,
        'address': address_receive,
        'phone' : phone_receive
    }
    db.shop.insert_one(doc)
    return jsonify({'msg':'주문이 완료되었습니다!'})

실제 웹페이지에서 동작하는 자바스크립트 부분

function order() {
            let name = $('#name').val()
            let quantity = $('#quantity').val()
            let address = $('#address').val()
            let phone = $('#phone').val()
            $.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()
                }
            })
            console.log(name, quantity, address, phone)
        }

DB 에서 받아온 정보로 테이블을 만드는 함수 :

주문을 하게되면 temp_html 부분이 테이블 밑에 붙어 하나의 행을 만들게된다. (별거아니지만 개인적으로 넘 신기했음)
function showOrders() {
            $.ajax({
                type: "GET",
                url: "/order",
                data: {},
                success: function (response) {
                    let orders = response['all_orders']
                    for (let i = 0; i < orders.length; i++) {
                        let name = orders[i]['name']
                        let quantity = orders[i]['quantity']
                        let address = orders[i]['address']
                        let phone = orders[i]['phone']
                        temp_html = `<tr>
                                        <th scope="row">${i + 1}</th>
                                        <td>${name}</td>
                                        <td>${quantity}</td>
                                        <td>${address}</td>
                                        <td>${phone}</td>
                                    </tr>`
                        $('#order_table').append(temp_html)
                    }
                }
            })
        }

완성된 사이트

0개의 댓글