<스파르타3주차>원페이지쇼핑몰 완성하기

김경수·2022년 4월 19일
0

1주차에 만든 원페이지쇼핑몰(총알오징어)에 POST, GET 기능 구현해보았습니다.

★시작 전 준비사항★
1. static, templates 폴더 + app.py 만들기!
2. pymongo, flask 설치하기(setting → python interpreter → +버튼)

이름, 수량, 주소, 전화번호를 입력하고 주문하기를 클릭하면 아래 list에 데이터가 나타나도록 해줄꺼에요.

▼ 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

  1. 코드 작업 순서 정리하기
  2. 오타 주의!
  3. 중간 중간 console을 통해 확인하며 작업하기
profile
개발은 1도 모르는 직장인의 개발자로 거듭나기

0개의 댓글