4주차 개발 일지(숙제)
☑️ 1주차에 완성한 쇼핑몰을 완성
- 주문하기(POST): 정보 입력 후 '주문하기' 버튼클릭 시 주문목록에 추가
- 주문내역보기(GET): 페이지 로딩 후 하단 주문 목록이 자동으로 보이기
-
힌트
-https://getbootstrap.com/docs/4.4/content/tables/
-[모두의 책 리뷰] 참고
- 뼈대코드
⎯ 원페이지 쇼핑몰(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('index.html')
# 주문하기(POST) API
@app.route('/order', methods=['POST'])
def save_order():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg': '이 요청은 POST!'})
# 주문 목록보기(Read) API
@app.route('/order', methods=['GET'])
def view_orders():
sample_receive = request.args.get('sample_give')
print(sample_receive)
return jsonify({'msg': '이 요청은 GET!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
⎯ 팬명록(index.html), 2주차 숙제 활용
<!doctype html>
<html lang="ko">
<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=Do+Hyeon&display=swap" rel="stylesheet">
<style>
* {
font-family: 'Do Hyeon', sans-serif;
}
.myitem {
width: 500px;
height: 300px;
background-image: url("https://t1.daumcdn.net/liveboard/nts/5bcccfbd33da4865817b9c606b6b852e.JPG");
background-position: center;
background-size: cover;
}
.price {
font-size: 16px;
}
.desc {
width: 500px;
margin-top: 20px;
margin-bottom: 20px;
}
.order-box {
width: 500px;
margin-bottom: 40px;
}
.mybtn {
width: 100px;
margin: auto;
display: block;
}
.wrap {
margin: auto;
width: 500px;
}
.rate {
color: blue;
}
</style>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "https://api.manana.kr/exchange/rate.json",
data: {},
success: function (response) {
let nowRate = response[1]['rate'];
$('#rate-box').text(nowRate);
}
})
order_listing();
});
function order_listing() {
// 주문목록 보기 API 연결
$.ajax({
type: "GET",
url: "/order?sample_give=샘플데이터",
data: {},
success: function (response) {
alert(response["msg"]);
}
})
}
function order() {
// 주문하기 API 연결
$.ajax({
type: "POST",
url: "/order",
data: {sample_give:'샘플데이터'},
success: function (response) { // 성공하면
alert(response["msg"]);
}
})
}
</script>
</head>
<body>
<div class="wrap">
<div class="myitem"></div>
<div class="desc">
<h1>양초를 팝니다 <span class="price">가격:3,000원/개</span></h1>
<p>이 양초는 특별한 힘을 가지고 있습니다. 하나 두 개 켜 놓으면 또 다른 촛불을 찾을 수 있죠!</p>
<p class="rate">달러-원 환율: <span id="rate-box">1,000</span></p>
</div>
<div class="order-box">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">주문자이름</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="inputGroupSelect01">수량</label>
</div>
<select id="order-count" class="custom-select">
<option selected>-- 수량을 선택하세요 --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">주소</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" id="inputGroup-sizing-default">전화번호</span>
</div>
<input id="order-phone" type="text" class="form-control" aria-label="Default"
aria-describedby="inputGroup-sizing-default">
</div>
<button onclick="order()" type="button" class="btn btn-primary mybtn">주문하기</button>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">이름</th>
<th scope="col">수량</th>
<th scope="col">주소</th>
<th scope="col">전화번호</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">홍길동</th>
<td>1</td>
<td>서울시 동작구</td>
<td>010-1234-5678</td>
</tr>
<tr>
<th scope="row">신사임당</th>
<td>2</td>
<td>서울시 영등포구</td>
<td>010-1234-5678</td>
</tr>
<tr>
<th scope="row">장영실</th>
<td>1</td>
<td>부산시 중구</td>
<td>010-1234-5678</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
- 완성코드
⎯ 서버코드(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('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)
<!doctype html>
<html lang="ko">
<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 rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR:wght@100;300&display=swap" rel="stylesheet">
<style>
* {
font-family: 'IBM Plex Sans KR', sans-serif;
}
.wrap {
width: 500px;
margin: auto;
}
.img-fluid {
width: 100%;
margin: auto auto 30px auto;
}
.btn {
width: 90px;
margin: 20px auto 40px auto;
display: block;
}
.explan {
margin: 10px auto 30px auto;
}
.maintxt {
font-weight: bold;
}
.price {
font-size: 18px;
}
.rate {
color: blue;
}
</style>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "https://api.manana.kr/exchange/rate.json",
data: {},
success: function (response) {
let nowRate = response[1]['rate'];
$('#rate-box').text(nowRate);
}
})
order_listing();
});
function order_listing() {
// 주문목록 보기 API 연결
$.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>`
$('#orders-box').append(temp_html)
}
}
}
})
}
function order() {
// 주문하기 API 연결
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();
}
}
})
}
</script>
</head>
<body>
<div class="wrap">
<img src="https://images.unsplash.com/photo-1535585209827-a15fcdbc4c2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"
class="img-fluid" alt="Responsive image">
<h2 class="maintxt"> 샴푸 (Mani Shampoo) <span class="price">가격:6,000/개</span></h2>
<p class="explan">우리는 황금시대를 우리 피어나는 거선의 작고 우리 무엇을 이것이다. 때에, 위하여서, 용감하고 얼음이 인간의 것이다. 싶이 청춘의 밥을 있는 그림자는 끓는 피가 두기 황금시대의
이것이다. 들어 내려온
웅대한...</p>
<p class="rate">달러-원-환율 : <span id="now_rate">1185.6</span></p>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default1">주문자 이름</span>
</div>
<input 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="inputGroupSelect01">수량</label>
</div>
<select class="custom-select" id="inputGroupSelect01">
<option selected>-- 수량을 선택하세요 --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default2">주소</span>
</div>
<input 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" id="inputGroup-sizing-default3">전화번호</span>
</div>
<input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
<a onclick="order()" class="btn btn-primary" href="#" role="button">주문하기</a>
<table class="table">
<thead>
<tr>
<th scope="col">이름</th>
<th scope="col">수량</th>
<th scope="col">주소</th>
<th scope="col">전화번호</th>
</tr>
</thead>
<tbody id="orders-box">
</tbody>
</table>
</div>
</body>
</html>
정답보고 똑같이 따라했는데 안됨 ㅋ.... 때려쳐 🤬🤬🤬🤬🤬🤬🤬🤬
POST http://localhost:5000/order 500 (INTERNAL SERVER ERROR)
이 오류는 검색해도 모르겠고
TypeError: 'ImmutableMultiDict' object is not callable
얘는 어쩌라는지도 모르겠고 구글링도 지쳐서 맥북 뿌수고싶다
- 정답 코드
⎯ 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('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
<!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: 500px;
height: 300px;
background-image: url("https://t1.daumcdn.net/liveboard/nts/5bcccfbd33da4865817b9c606b6b852e.JPG");
background-position: center;
background-size: cover;
}
.price {
font-size: 20px;
}
.item-desc {
width: 500px;
margin-top: 20px;
margin-bottom: 20px;
}
.item-order {
width: 500px;
margin-bottom: 50px;
}
.btn-order {
margin: auto;
width: 100px;
display: block;
}
.wrap {
width: 500px;
margin: auto;
}
.rate {
color: blue;
}
</style>
<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>`
$('#orders-box').append(temp_html)
}
}
}
})
}
function get_rate() {
$.ajax({
type: "GET",
url: "https://api.manana.kr/exchange/rate.json",
data: {},
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();
}
}
})
}
</script>
</head>
<body>
<div class="wrap">
<div class="item-img"></div>
<div class="item-desc">
<h1>양초를 팝니다 <span class="price">가격:3,000원/개</span></h1>
<p>이 양초는 사실 특별한 힘을 지니고 있어요!</p>
<p class="rate">달러-원 환율: <span id="now-rate">1219.15</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="inputGroupSelect01">수량</label>
</div>
<select id="order-count" class="custom-select">
<option selected>-- 수량을 선택하세요 --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</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>
</tr>
</thead>
<tbody id="orders-box">
</tbody>
</table>
</div>
</body>
</html>
아니.. 왜 정답은 작동하고 내가한거는 안되는건데 .............
바디말고 내가 바꾼게 뭐가 있다고 하 진짜 ㅁ니아러밎더랙ㅈ덜뱌ㅐ럊ㅁ
Author And Source
이 문제에 관하여(4주차 개발 일지(숙제)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@dudgus899/4주차-개발-일지숙제저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)