4주차는 Flask, 기존 3주차에 배웠던 내용을통해
Flask 서버를 만들 때는 프로젝트 폴더 안에
ㄴstatic 폴더 (이미지, css파일 저장)
ㄴtemplates 폴더 (html저장)
ㄴapp.py 파일
구조로 구현한다는것을 잊지맙시다
GET → 통상적으로! 데이터 조회(Read)를 요청할 때
예) 영화 목록 조회
→ 데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달
→ 예: google.com?q=북극곰
POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때
예) 회원가입, 회원탈퇴, 비밀번호 수정
→ 데이터 전달 : 바로 보이지 않는 HTML body에 key:value 형태로 전달
## HTML 화면 보여주기
@app.route('/')
def homework():
return render_template('shopping.html')
# 주문하기(POST) API
@app.route('/order', methods=['POST'])
def save_order():
name_receive = request.form['name_give']
color_receive = request.form['color_give']
count_receive = request.form['count_give']
address_receive = request.form['address_give']
phone_receive = request.form['phone_give']
doc = {
'name':name_receive,
'color':color_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)
<!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=Jua&display=swap" rel="stylesheet">
<style>
* {
font-family: 'Jua', sans-serif;
}
.item-img {
width: 400px;
height: 300px;
background-image: url(https://search.pstatic.net/common/?src=http%3A%2F%2Fshop1.phinf.naver.net%2F20211207_56%2F1638863743526xaKHE_JPEG%2F39999632233099618_517928618.jpg&type=sc960_832);
background-position: center;
background-size: cover;
}
.price {
font-size: 20px;
}
.item-desc {
width: 400px;
margin-top: 20px;
margin-bottom: 20px;
}
.item-order {
width: 400px;
}
.btn-order {
margin: auto;
width: 100px;
display: block;
}
.wrap {
width: 400px;
margin: auto;
}
.rate {
color: green;
}
</style>
<script>
$(document).ready(function () {
Exchange_Rate();
order_save();
});
function Exchange_Rate() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rate",
data: {},
success: function (response) {
let nowrate = response['rate'];
$('#now-rate').text(nowrate);
}
})
}
function order_save() {
$.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 color = orders[i]['color']
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>${color}</td>
<td>${count}</td>
<td>${address}</td>
<td>${phone}</td>
</tr>`
$('#order-box').append(temp_html)
}
}
}
})
}
function order() {
let name = $('#order-name').val()
let color = $('#color-select').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, color_give: color, 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 class="wrap">
<div class="item-img"></div>
<div class="item-desc">
<h1>휴대폰 케이스 <span class="price">가격:15,000원/개</span></h1>
<p>당신의 휴대폰을 지켜줄 든든한 보호막!</p>
<p class="rate">Dollar-Won 환율: <span id="nowrate">1186.1</span></p>
</div>
<div class="item-order">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">주문자 성함</span>
</div>
<input id='order-name' type="text" class="form-control" aria-label="Default"
aria-describedby="inputGroup-sizing-default">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="color-select">색상</label>
</div>
<select class="custom-select" id="color-select">
<option selected>-- 색상 선택하세요 --</option>
<option value="Red">Red</option>
<option value="Black">Black</option>
<option value="Mint">Mint</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="order-count">수량</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>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">주소</span>
</div>
<input id='order-address' type="text" class="form-control" aria-label="Default"
aria-describedby="inputGroup-sizing-default">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">전화번호</span>
</div>
<input id='order-phone' type="text" class="form-control" aria-label="Default"
aria-describedby="inputGroup-sizing-default">
</div>
<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>
<th scope="col">전화번호</th>
</tr>
</thead>
<tbody id="order-box">
</tbody>
</table>
</div>
</body>
</html>