개발 공부 일지/웹

화성땅 공동구매 프로젝트

월수 2022. 9. 19. 22:39
반응형

프로젝트 세팅

sparta → projects → mars 폴더에서 시작!

mars 폴더에서 프로젝트 시작
mars 폴더 밑에 venv 폴더 확인
생성 완료

폴더 구조 만들기

static 만들기

mars 폴더 마우스 우클릭하여 Directory(경로) 클릭하여 static라는 새 Directory를 만들어주고,

templates Directory

같은 방법으로 templates Directory도 만들어 준다.

mars 폴더 마우스 우클릭하여 python 파일 만들기를 선택 후 app.py도 만들어준다.

app.py

패키지 설치

flask 설치

좌측 상단 파일을 누르고 설정 python 인터프리터 선택 후 + 클릭 패키지를 검색해서 설치하면 된다.

pymongo 설치
dnspython 설치

뼈대 준비하기

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 web_mars_post():
    sample_receive = request.form['sample_give']
    print(sample_receive)
    return jsonify({'msg': 'POST 연결 완료!'})

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

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

브라우저에서 localhost:5000

app.py에서 마우스 우클릭 후 실행을 하고 브라우저에서 localhost:5000 입력 후 엔터!

 

index.html 파일 만들고 코드 입력

templates 폴더에 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() {
            $.ajax({
                type: 'GET',
                url: '/mars',
                data: {},
                success: function (response) {
                    alert(response['msg'])
                }
            });
        }
        function save_order() {
            $.ajax({
                type: 'POST',
                url: '/mars',
                data: { sample_give:'데이터전송' },
                success: function (response) {
                    alert(response['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>
              <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>

mongoDB Atlas 창 띄워두기

링크: https://cloud.mongodb.com/

 

MongoDB Cloud

MongoDB Cloud is a unified data platform for modern applications and includes a global cloud database, search, data lake, mobile, and application services.

www.mongodb.com

접속한 모습
Browse Collections 클릭한 모습

POST 연습(주문 저장)

API 만들고 사용하기 - 이름, 주소, 평수 저장하기(Create → POST)

  1. 요청 정보 :  URL= /mars, 요청 방식 = POST
  2. 클라(ajax) → 서버(flask) : nameaddresssize
  3. 서버(flask) → 클라(ajax) : 메시지를 보냄 (주문 완료!)

클라이언트와 서버 연결 확인하기

서버 코드 - app.py

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

sparta 폴더 → pythonprac 폴더 → dbprac 파일을 파이 참으로 끌어당겨서 이동!

파이참에서 dbprac 파일이 열린 모습

위 내용 중 저장 예시를 참조하면서 app.py 파일에서 코드를 아래와 같이 수정 입력하면 서버 쪽에서 할 일은 끝난 것!

클라이언트 코드 - index.html

@app.route("/mars", methods=["POST"])
def web_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.orders.insert_one(doc)

    return jsonify({'msg': '주문 완료!'})
function save_order() {
    $.ajax({
        type: 'POST',
        url: '/mars',
        data: { sample_give:'데이터전송' },
        success: function (response) {
            alert(response['msg'])
        }
    });
}

인덱스 바디에 input 코드 확인

이제 가져가야 할 name, addrress, size를 body 부분에서 확인해 보면 input으로 된 코드를 찾아보면 된다.

window.location.reload() 다 되면 새로고침 한번 해달라는 코드

mongodb에서 데이더가 저장된 것을 확인하면 완료!

GET 연습(주문 보여주기)

API 만들고 사용하기 - 저장된 주문을 화면에 보여주기(Read → GET)

  1. 요청 정보 :  URL= /mars, 요청 방식 = GET
  2. 클라(ajax) → 서버(flask) : (없음)
  3. 서버(flask) → 클라(ajax) : 전체 주문을 보내주기

클라이언트와 서버 확인하기

서버 코드 - app.py

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

 

클라이언트 코드 - index.html

$(document).ready(function () {
    show_order();
});
function show_order() {
    $.ajax({
        type: 'GET',
        url: '/mars',
        data: {},
        success: function (response) {
            alert(response['msg'])
        }
    });
}

 

서버부터 만들기

받을 것 없이 orders 에 주문정보를 담아서 내려주기만 하면 된다!

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

 

클라이언트 만들기

응답을 잘 받아서 for 문으로 붙여주면 끝!

function show_order() {
    $('#order-box').empty()
    $.ajax({
        type: 'GET',
        url: '/mars',
        data: {},
        success: function (response) {
            let rows = response['orders']
            for (let i = 0; i < rows.length; i++) {
                let name = rows[i]['name']
                let address = rows[i]['address']
                let size = rows[i]['size']

                let temp_html = `<tr>
                                    <td>${name}</td>
                                    <td>${address}</td>
                                    <td>${size}</td>
                                  </tr>`
                $('#order-box').append(temp_html)
            }

        }
    });
}

 

완성 확인하기

동작 테스트: 화면을 새로고침 했을 때, DB에 저장된 리뷰가 화면에 올바르게 나타나는지 확인한다.

반응형