스파르타 코딩클럽 웹개발 종합반 4주차 개발일지!
4주차는 Flask, 기존 3주차에 배웠던 내용을통해
나홀로메모장, 모두의책리뷰 구현하기
Flask 서버를 만들 때는 프로젝트 폴더 안에
ㄴstatic 폴더 (이미지, css파일 저장)
ㄴtemplates 폴더 (html저장)
ㄴapp.py 파일
구조로 구현한다는것을 잊지맙시다
ET, POST 방식
-
GET → 통상적으로! 데이터 조회(Read)를 요청할 때
예) 영화 목록 조회
→ 데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달
→ 예: google.com?q=북극곰 -
POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때
예) 회원가입, 회원탈퇴, 비밀번호 수정
→ 데이터 전달 : 바로 보이지 않는 HTML body에 key:value 형태로 전달
나홀로메모장, 모두의책리뷰 구현
1주차숙제를 바탕으로 주문하기와 주문내역보기적용해보기
app.py
## 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)
shopping.html
<!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>
Author And Source
이 문제에 관하여(스파르타 코딩클럽 웹개발 종합반 4주차 개발일지!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kimuser/스파르타-코딩클럽-웹개발-종합반-4주차-개발일지저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)