본문 바로가기
코딩/웹개발 종합반

웹개발 종합반 4주차(화성땅 공동구매)

by junhub 2023. 3. 21.

 02.MARS 폴더에 python3 -m venv venv를 터미널에서 실행시켜서 가상환경을 만들어준 후 이와 같이 파일을 만들어준다.

이때 폴더명 templates는 무조건 고정이다. 그 후 내가 쓸 라이브러리를 venv 폴더에 적용시켜 줄 것이다. 

 

1. pip install flask(flask는 python 서버 프레임워크 이름)

2. pip install pymongo(데이터를 쏴서 어딘가에 저장하기 위한 목적)

3. pip install dnspython(db와 연결하기 위한 라이브러리)


# POST 요청, 주문 저장하기 

 

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

from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb://sparta:test@ac-6joxava-shard-00-00.oag1hfc.mongodb.net:27017,ac-6joxava-shard-00-01.oag1hfc.mongodb.net:27017,ac-6joxava-shard-00-02.oag1hfc.mongodb.net:27017/?ssl=true&replicaSet=atlas-di6vv2-shard-0&authSource=admin&retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta


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

@app.route("/mars", methods=["POST"])
def mars_post():
    name_receive = request.form['name_give']
    address_receive = request.form['address_give']
    size_receive = request.form['size_give']

    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)

app.py(백엔드) 코드이다.

 

from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb://sparta:test@ac-6joxava-shard-00-00.oag1hfc.mongodb.net:27017,ac-6joxava-shard-00-01.oag1hfc.mongodb.net:27017,ac-6joxava-shard-00-02.oag1hfc.mongodb.net:27017/?ssl=true&replicaSet=atlas-di6vv2-shard-0&authSource=admin&retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta

mongoDB와 연결될 수 있도록 app.py에 위 코드를 사용했다. 

 

<!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>

index.html 코드이다. 

 

 

app.py 코드의 이 부분을 보면 render_template('index.html')을 통해 백엔드와 프론트엔드가 연결되어 있음을 알 수 있다. 


 

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

from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb://sparta:test@ac-6joxava-shard-00-00.oag1hfc.mongodb.net:27017,ac-6joxava-shard-00-01.oag1hfc.mongodb.net:27017,ac-6joxava-shard-00-02.oag1hfc.mongodb.net:27017/?ssl=true&replicaSet=atlas-di6vv2-shard-0&authSource=admin&retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta


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

@app.route("/mars", methods=["POST"])
def mars_post():
    name_receive = request.form['name_give']
    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():
    return jsonify({'msg':'GET 연결 완료!'})

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

위 코드에서 이 부분을 보면 db에 데이터를 넣을 때 사용하는 insert_one()을 사용했고 이름, 주소, 평수를 db에 넣기 위해 doc 에 딕셔너리를 위와 같이 딕셔너리를 만들어줬다. 

 

<!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 name = $('#name').val()
            let address = $('#address').val()
            let size = $('#size').val()

            let formData = new FormData();
            formData.append("name_give", name);
            formData.append("address_give", address);
            formData.append("size_give", size);

            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>

이름, 주소, 평수를 입력 후 주문하기 버튼을 누르면 작동하는 함수에 접근해야 되기 때문에 

이 함수를 건드릴 것이다. 각 변수명에 jquery를 이용해서 

 

각 변수명에 jquery를 이용해서 데이터가 입력되는 부분의 id를 가져와 할당을 해준다.

이때 val( )은 Form Element 의 값을 받아오는데 쓰인다. (주로 input 이나 textarea)

- 주의해야할 점은 Form Element 이외의 값은 받아오질 못한다는 점.

 

formData.append()를 이용해서 "name_give"에 name 데이터를 할당해서 백엔드로 보내주고 나머지도 같은 원리로 app.py 즉, 백엔드로 데이터가 넘어가게 된다. 

 

그럼 app.py의 위 코드에서 name_give, address_give, size_give를 받아 각 _receive 변수에 할당하여 doc = { } 를 통해 db에 딕셔너리 형태로 데이터를 넣어주게 된다. 그 후 'msg' : '저장완료!' 를 리턴하게 되는데 이 msg는 다시 index.html(프론트엔드)로 가서 

 

alert 창으로 뜨게 된다. 이때 window.location.reload()는 주문하기를 눌렀을 때 데이터가 저장되고 새로고침을 자동으로 해주는 코드이다


localhost:5001 에 들어갔을 때 모습 

 

input 값 입력 후 주문하기를 누르면 저장완료 alert가 뜬다. 

 

그 후 mongoDB를 보면 데이터가 정상적으로 db에 저장됐음을 알 수 있다.


# GET 요청, 주문 보여주기 

 

$(document).ready(function () { show_order () } 를 보고 페이지가 새로고침되면 자동으로 show_order 라는 이름의 함수가 실행됨을 알 수 있다. 

 

show_order 함수를 보면 따로 보내는 데이터 없이 /mars에 날린다는 의미이다. 

 

app.py(백엔드) 코드를 보면 index.html(프론트)와 연결되어 GET 연결 완료! 라는 메세지를 리턴하고 있다. 

즉, 프론트에서 받는 data가 {'msg' : 'GET 연결 완료!'} 인 것이다. 


위 코드를 사용해서 db에 있는 데이터를 가져올 수 있다. 

@app.route("/mars", methods=["GET"])
def mars_get():
    mars_data = list(db.mars.find({},{'_id':False}))
    return jsonify({'result': mars_data})

여기서 mars_data를 리턴하게 되면 db에 있는 데이터가 모두 리턴되게 된다. 

 

function show_order() {
            fetch('/mars').then((res) => res.json()).then((data) => {
                console.log(data)
            })
        }

이때 index.html에서 return 된 data를 console.log에 찍으라고 했기 때문에 웹에서 새로고침 한 후 개발자 도구를 열어 console을 보면 

 

이와 같이 db에 있는 모든 데이터가 index.html 즉, 프론트엔드로 넘어오게 된다. 

 

function show_order() {
            fetch('/mars').then((res) => res.json()).then((data) => {
                
                let rows = data['result']
                rows.forEach((a) => {
                    console.log(a)
                })
            })
        }

받은 데이터를 변수 rows에 할당해 forEach 반복문을 돌려 console.log를 찍어보면 

 

이와 같이 딕셔너리 형태로 하나씩 찍히게 된다. 여기서 원하는 값만 반복문으로 출력되게 하려면 

 

각 데이터를 변수에 할당해주고 원하는 데이터를 html로 보여줘야 하기때문에 temp_html이라는 변수에 넣고싶은 부분을 가져와서 할당해준다. 

이렇게 넣으면 반복문이 돌면서 db에 있는 데이터가 html로 나오게 된다. 

 

   function show_order() {
            fetch('/mars').then((res) => res.json()).then((data) => {

                let rows = data['result']
                rows.forEach((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)              
                })
            })
        }

마지막으로 $('#order-box').append(temp_html)을 사용하면 temp_html 이 html로 웹페이지에 붙게 된다. 

 

db에 있는 홍길동, 아무개 데이터가 html로 표시되고 있음을 알 수 있다. 

 

기존에 표시되고 있던 홍길동, 임꺽정, 세종대왕 데이터를 지우고 db에 있는 데이터만 가져와서 표시하려면 위의 코드와 같이 반복문이 돌기전에 empty() 함수를 사용해 지워주면 된다. order-box 는 이름 주소 평수가 표시되고 있는 부분의 id명 이다.

 

정보를 입력하고 주문하기를 누르면 저장완료! 라는 alert창이 뜨고 자동으로 새로고침이 된 후 데이터가 바로 html로 붙는 것을 볼 수 있다.

댓글