본문 바로가기
Knowledge/sparta web develope

project. 화성땅 공동구매

by w.developer 2023. 5. 12.

1. 프로젝트 세팅

 

1-1. 이전에 사용했던 서버 종료를 해준다. 터미널 창에서 ctrl + c

 

1-2. 파일을 만들어 환경을 세팅해준다. 

  • app.py에 venv 만들기  < python -m venv venv >
  • 패키지 설치하기  < pip install flask pymongo dnspython >

 

2. 뼈대 준비하기

 

2-1. app.py와 index.html 구성하기

 

2-2. mongodb 세팅해두기

 

3-3. ※ localhost:5000으로 접속하기!  html에서 접속하는거 아님!

 

3. POST 연습 (주문을 몽고DB에 넣고 저장하는 부분)

 

※ 참고 

이름 부분 id : name

주소 부분 id : address

평수 부분 id : size

<app.py>

 
@app.route("/mars", methods=["POST"])               # /mars에서 보낸 데이터를 받는다
def mars_post():
    name_receive = request.form['name_give']   
    address_receive = request.form['address_give'
    size_receive = request.form['size_give']     # html에서 size_give를 받아서 size_receive 로 표시한다.           

    doc = {
        'name' : name_receive,          
        'address' : address_receive,         #몽고db에 넣는 양식
        'size' : size_receive   # 몽고db사이트에 size 라는 이름으로 위에서 받아온 size_receive 값을 넣는다
    }
    db.mars.insert_one(doc)             #몽고db mars라는 폴더에

    return jsonify({'msg':'저장완료!'})  #저장완료라는 메세지 띄우기

 

<index.html>

 
 
function save_order() {
            let name = $('#name').val()                  
            let address = $('#address').val()
            let size = $('#size').val()      // 아래 html id에서 size 값을 가져와서 size라는 변수를 설정한다


            let formData = new FormData();
            formData.append("name_give", name);     
            formData.append("address_give", address);
            formData.append("size_give", size);  // 위의 save_order() 에서  size 을 받아와서 백엔드                                                                   app.py에 size_give로 보낸다.
 
            fetch('/mars', { method: "POST", body: formData }).then((res) => res.json()).then((data) => {
             alert(data["msg"]);
             window.location.reload()               이름,주소,평수 부분 초기화 "오타주의"
            });
        }

 

4. GET 연습 ( 저장되어있는 데이터를 가져와서 html로 붙치는 작업)

 

<index.html>

 

 
$(document).ready(function () {                  페이지가 로딩이 되면
            show_order();                                 show_order()가 불린다
        });
        function show_order() {                                
            fetch('/mars').then((res) => res.json()).then((data) => {        mars에서 데이터를 받는다
 
               let rows = data['result']                 app.py에서 {'result':mars_data} 가 date로 들어온다
               $('#order-box').empty()          order-box 기본값 초기화
               rows.forEach((a) => {            들어온 데이터를 foreach로 돌려준다
                    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)     데이터 가져와서 html로 붙치는과정   
                })                        
            })
        }

 

 

<app.py>

 
 
@app.route("/mars", methods=["GET"])           #html에서 mars로 날아옴    
def mars_get():
    mars_data = list(db.mars.find({},{'_id':False}))
    return jsonify({'result':mars_data})    #'result':mars_data 로 다시 html로 내린다