본문 바로가기
들은 강의

[웹개발 입문 강의] [프로젝트 실습] 화성땅 공동구매 페이지

by hotdog7778 2023. 6. 9.

스파르타 코딩클럽 웹개발 종합반 인강 - 공부 기록

 

수강 시작 ~ 

2023. 06. 06 ~ 

 

https://github.com/hotdog7778/sparta

 


화성땅 공동구매 페이지를 만드는 간단한 프로젝트

 

 

프로젝트 디렉토리 구성하기

  • 02.mars 디렉토리 에서 진행
  • app.py 생성
  • venv 세팅
  • flask를 위해 templates 폴더 생성, 그안에 index.html 생성

 

라이브러리 설치

  • pip install flask
  • pip install pymongo
  • pip install dnspython

 

뼈대 준비

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Batang:wght@400;700&display=swap" rel="stylesheet" />

    <title>선착순 공동구매</title>

    <style>
        * {
            font-family: "Gowun Batang", serif;
            color: white;
        }

        body {
            background-image: linear-gradient(0deg,
                    rgba(0, 0, 0, 0.5),
                    rgba(0, 0, 0, 0.5)),
                url("https://cdn.aitimes.com/news/photo/202010/132592_129694_3139.jpg");
            background-position: center;
            background-size: cover;
        }

        h1 {
            font-weight: bold;
        }

        .order {
            width: 500px;
            margin: 60px auto 0px auto;
            padding-bottom: 60px;
        }

        .mybtn {
            width: 100%;
        }

        .order>table {
            margin: 40px 0;
            font-size: 18px;
        }

        option {
            color: black;
        }
    </style>
    <script>
        $(document).ready(function () {
            show_order();
        });
        function show_order() {
            fetch('/mars').then((res) => res.json()).then((data) => {
                console.log(data)
                alert(data['msg'])
            })
        }
        function save_order() {
            let formData = new FormData();
            formData.append("sample_give", "샘플데이터");

            fetch('/mars', { method: "POST", body: formData }).then((res) => res.json()).then((data) => {
                console.log(data);
                alert(data["msg"]);
            });
        }
    </script>
</head>

<body>
    <div class="mask"></div>
    <div class="order">
        <h1>화성에 땅 사놓기!</h1>
        <h3>가격: 평 당 500원</h3>
        <p>
            화성에 땅을 사둘 수 있다고?<br />
            앞으로 백년 간 오지 않을 기회. 화성에서 즐기는 노후!
        </p>
        <div class="order-info">
            <div class="input-group mb-3">
                <span class="input-group-text">이름</span>
                <input id="name" type="text" class="form-control" />
            </div>
            <div class="input-group mb-3">
                <span class="input-group-text">주소</span>
                <input id="address" type="text" class="form-control" />
            </div>
            <div class="input-group mb-3">
                <label class="input-group-text" for="size">평수</label>
                <select class="form-select" id="size">
                    <option selected>-- 주문 평수 --</option>
                    <option value="10평">10평</option>
                    <option value="20평">20평</option>
                    <option value="30평">30평</option>
                    <option value="40평">40평</option>
                    <option value="50평">50평</option>
                </select>
            </div>
            <button onclick="save_order()" type="button" class="btn btn-warning mybtn">
                주문하기
            </button>
        </div>
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">이름</th>
                    <th scope="col">주소</th>
                    <th scope="col">평수</th>
                </tr>
            </thead>
            <tbody id="order-box">
                <tr>
                    <td>홍길동</td>
                    <td>서울시 용산구</td>
                    <td>20평</td>
                </tr>
                <tr>
                    <td>임꺽정</td>
                    <td>부산시 동구</td>
                    <td>10평</td>
                </tr>
                <tr>
                    <td>세종대왕</td>
                    <td>세종시 대왕구</td>
                    <td>30평</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

</html>

app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

@app.route("/mars", methods=["POST"])
def mars_post():
    sample_receive = request.form['sample_give']
    print(sample_receive)
    return jsonify({'msg':'POST 연결 완료!'})

@app.route("/mars", methods=["GET"])
def mars_get():
    return jsonify({'msg':'GET 연결 완료!'})

if __name__ == '__main__':
    app.run('0.0.0.0', port=5001, debug=True)

기본 페이지

 

 

데이터 저장 구현

주문하기를 누르면 이름, 주소, 평수 데이터를 db로 보내서 저장 하도록 만들어보자.

먼저, pymongo를 사용해서 DB에 연결하기 위해 연결정보를 app.py에 기입해준다

브라우저에서 데이터 기입 → 버튼을 누른다 → 백엔드에 데이터 적재 → DB로 데이터 인설트

버튼을 눌렀을 때 API(POST)를 호출하도록 만들자.

POST를 호출했으니까 백엔드까지 데이터를 가지고 도착

파이썬에서는 받은 데이터를 잘 포장해서 DB로 insert 하면 끝.

근데 세가지 데이터를 한번에 받으니까 그것만 잘 고려하면 된다.

 

 

index.html

// 필요부분만
...
<script>
  ...
	...

	function save_order() {
	    let name = $('#name').val() // 사용자가 이름을 입력하는 input 태그의 id가 name 이다.
	    let address = $('#address').val() // 사용자가 주소을 입력하는 input 태그의 id가 address 이다.
	    let size = $('#size').val() // 사용자가 평수를 선택 하는 select 태그의 id가 size 이다.
	
	    let formData = new FormData();
	    // "name_give" 의 값은 name 이라는 식으로 저장한다고 보면됨
	    // { name_give : input받은 이름1 }
	    // { address_give : input받은 주소1 }
	    // { size_give : input받은 평수1 }
	    formData.append("name_give", name);
	    formData.append("address_give", address);
	    formData.append("size_give", size);
	
	    // formdata에 저장한 input 값을을 백엔드로 POST 해준다.
	    fetch('/mars', { method: "POST", body: formData }).then((res) => res.json()).then((data) => {
	        // console.log(data);
	        alert(data["msg"]);
	        window.location.reload
	    });
	}

	...
	...
</script>

app.py

@app.route('/')
def home():
    return render_template('index.html')

@app.route("/mars", methods=["POST"])
def mars_post():
    # sample_receive = request.form['sample_give']
    # print(sample_receive)
    
    name_receive = request.form['name_give'] # fetch로 부터 이름 데이터를 받자
    address_receive = request.form['address_give'] # 주소 데이터를 받자
    size_receive = request.form['size_give'] # 평수 데이터를 받자
    
		# 프론트에서 받은 데이터 파이썬이 따로 저장. db로 보내기전에 포장
    doc = {
        'name':name_receive,
        'address':address_receive,
        'size':size_receive
    }
    
		# DB로 데이터를 전달하는 내용
		db.mars.insert_one(doc)

		# 프론트엔드로 메세지를 리턴. 프론트는 이거 받아서 알람에 띄우면 클라이언트가 저장이 잘됐구나 확인 가능
    return jsonify({'msg':'저장완료!'})

주문하기 누른 다음에 브라우저가 새로고침 되도록 하는 방법

  • fetch 안에 window.location.reload 작성 해준다.

 

 

데이터를 읽어서 주문하기 아래에 보여주기

페이지가 로딩이 되면 DB에서 이름 주소 평수를 불러와서 주문하기 아래에 보여주는것

 

 

index.html


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Batang:wght@400;700&display=swap" rel="stylesheet" />

    <title>선착순 공동구매</title>

    <style>
        * {
            font-family: "Gowun Batang", serif;
            color: white;
        }

        body {
            background-image: linear-gradient(0deg,
                    rgba(0, 0, 0, 0.5),
                    rgba(0, 0, 0, 0.5)),
                url("https://cdn.aitimes.com/news/photo/202010/132592_129694_3139.jpg");
            background-position: center;
            background-size: cover;
        }

        h1 {
            font-weight: bold;
        }

        .order {
            width: 500px;
            margin: 60px auto 0px auto;
            padding-bottom: 60px;
        }

        .mybtn {
            width: 100%;
        }

        .order>table {
            margin: 40px 0;
            font-size: 18px;
        }

        option {
            color: black;
        }
    </style>
    <script>
        $(document).ready(function () {
            show_order();
        });
        function show_order() {
            fetch('/mars').then((res) => res.json()).then((data) => {
                // console.log(data)
                // alert(data['msg'])
                let rows = data['result']
                
                $('#order-box').empty()
                
                rows.forEach((a) => {
                    // console.log(a)
                    let name = a['name']
                    let address = a['address']
                    let size = a['size']

                    let temp_html = `<tr>
                                        <td>${name}</td>
                                        <td>${address}</td>
                                        <td>${size}</td>
                                    </tr>`
                    $('#order-box').append(temp_html)
                    
                    
                });
            })
        }
        function save_order() {
            let name = $('#name').val() // 사용자가 이름을 입력하는 input 태그의 id가 name 이다.
            let address = $('#address').val() // 사용자가 주소을 입력하는 input 태그의 id가 address 이다.
            let size = $('#size').val() // 사용자가 평수를 선택 하는 select 태그의 id가 size 이다.

            let formData = new FormData();
            // "name_give" 의 값은 name 이라는 식으로 저장한다고 보면됨
            // { name_give : input받은 이름1 }
            // { address_give : input받은 주소1 }
            // { size_give : input받은 평수1 }
            formData.append("name_give", name);
            formData.append("address_give", address);
            formData.append("size_give", size);

            // formdata에 저장한 input 값을을 백엔드로 POST 해준다.
            fetch('/mars', { method: "POST", body: formData }).then((res) => res.json()).then((data) => {
                // console.log(data);
                alert(data["msg"]);
                window.location.reload
            });
        }
    </script>
</head>

<body>
    <div class="mask"></div>
    <div class="order">
        <h1>화성에 땅 사놓기!</h1>
        <h3>가격: 평 당 500원</h3>
        <p>
            화성에 땅을 사둘 수 있다고?<br />
            앞으로 백년 간 오지 않을 기회. 화성에서 즐기는 노후!
        </p>
        <div class="order-info">
            <div class="input-group mb-3">
                <span class="input-group-text">이름</span>
                <input id="name" type="text" class="form-control" />
            </div>
            <div class="input-group mb-3">
                <span class="input-group-text">주소</span>
                <input id="address" type="text" class="form-control" />
            </div>
            <div class="input-group mb-3">
                <label class="input-group-text" for="size">평수</label>
                <select class="form-select" id="size">
                    <option selected>-- 주문 평수 --</option>
                    <option value="10평">10평</option>
                    <option value="20평">20평</option>
                    <option value="30평">30평</option>
                    <option value="40평">40평</option>
                    <option value="50평">50평</option>
                </select>
            </div>
            <button onclick="save_order()" type="button" class="btn btn-warning mybtn">
                주문하기
            </button>
        </div>
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">이름</th>
                    <th scope="col">주소</th>
                    <th scope="col">평수</th>
                </tr>
            </thead>
            <tbody id="order-box">
                <tr>
                    <td>홍길동</td>
                    <td>서울시 용산구</td>
                    <td>20평</td>
                </tr>
                <tr>
                    <td>임꺽정</td>
                    <td>부산시 동구</td>
                    <td>10평</td>
                </tr>
                <tr>
                    <td>세종대왕</td>
                    <td>세종시 대왕구</td>
                    <td>30평</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

</html>

app.py

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

from pymongo import MongoClient
db = client.dbsparta

@app.route('/')
def home():
    return render_template('index.html')

@app.route("/mars", methods=["POST"])
def mars_post():
    # sample_receive = request.form['sample_give']
    # print(sample_receive)
    
    name_receive = request.form['name_give'] # fetch로 부터 이름 데이터를 받자
    address_receive = request.form['address_give'] # 주소 데이터를 받자
    size_receive = request.form['size_give'] # 평수 데이터를 받자
    
    doc = {
        'name':name_receive,
        'address':address_receive,
        'size':size_receive
    }
    db.mars.insert_one(doc)

    return jsonify({'msg':'저장완료!'})

@app.route("/mars", methods=["GET"])
def mars_get():
    
    # 데이터를 전부 가져오자
    mars_data = list(db.mars.find({},{'_id':False}))
    return jsonify({'result':mars_data}) # 이제 이걸 프론트엔드로(index.html) 전달하자

if __name__ == '__main__':
    app.run('0.0.0.0', port=5001, debug=True)