1,2,3주차도 써야했는데 매우 귀찮았음으로 4주차부터 쓰게되었다...
4주차에서 배운것은 Flask, MongoDB로 나만의 API를 만들고 DB에 저장하며 웹페이지와 연결하는 것. 최종 숙제로 완성된 웹페이지를 만들게 되었다
어쩌면 당연한거지만 강의를 볼땐 애매하게 몰랐던 사실이 숙제를 함에 있어서 이것저것 해보니까 더 내것이 되는 기분.. 이래서 스스로 해봐야 한다
from flask import Flask, render_template, jsonify, request
from pymongo import MongoClient
@app.route('/order', methods=['GET'])
def listing():
order = list(db.shop.find({}, {'_id': False}))
return jsonify({'all_orders': order})
@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)
}
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)
}
}
})
}