Python

웹개발 4주차 (백엔드-프론트엔드, 프로젝트1 : 화성땅 공동구매)

sangwoo_rhie 2023. 5. 2. 15:49

https://teamsparta.notion.site/4-9791c957e35f444e9ba2d90bd985c153#a82de201b5df41849cb3bdb124643163

 

app.py는 백엔드,  html은 프론트엔드!

 

1. 원하는 폴더(01.prac, 02.mars 등)로 이동한다.
2. app.py 새 파일 만든다.
3. python -m venv venv 입력 

4. interpreter를 venv로 잡아줌.

6. venv폴더에 app.py파일이 있으니, 그 다음에 templates 폴더 만들고 그안에 index.html파일 만들어줌.

즉, app.py는 venv폴더에 자동저장되고, 

index.html은 templates 폴더 만들어서 저장시키기

 

7. app.py파일에

 

pip install flask 설치,

pip install pymongo 설치, (-> mongoDB저장)

pip install dnspython 설치,

(경우에 따라 pip install  bs4 설치할수도)

 

귀찮게 다 할필요없이, pip install flask pymongo dnspython requests bs4 이렇게해도 하나씩 설치됨.

 

8. 아래같이 flask 시작코드 코딩하고, localhost:5000 웹브라우저 이동.

 

1. app.py(백엔드)에서  POST 요청 (API 코드) --->  index.html (프론트엔드)에서 POST 요청 확인(Fetch 코드)
2. app.py(백엔드)에서  GET 요청 (API 코드) --->  index.html (프론트엔드)에서 GET 요청 확인(Fetch 코드)

 

 
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

@app.route('/mypage')  
def mypage():
   return '<button>버튼입니다</button>' -> 'This is mypage!' 이런식으로해도 됨.

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

 

templates 이라는 폴더를 새로 만들고, 그 안에 index.html 파일을 만든다음 예제코드 삽입

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>
        function hey(){
            alert('안녕!')
        }
    </script>
</head>
<body>
    <button onclick="hey()">나는 버튼!</button>
</body>
</html>

그러고 나서 app.py파일로 다시 와서

 

 
  from flask import Flask, render_template     -> 써주기. template 폴더를 가져온다는 뜻
  app = Flask(__name__)

  @app.route('/')
  def home():
   return 'This is Home!'

  @app.route('/mypage')
  def mypage():
   return render_template('index.html')  -> 써주기. template폴더의 index.html 파일을 가져온다는 뜻

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

 

GET요청 API 코드 -> app.py(백엔드)파일에 추가.

 

@app.route('/test', methods=['GET'])
def test_get():
   title_receive = request.args.get('title_give')
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 GET!'})

 

 
  from flask import Flask, render_template, request, jsonify      -> request와 jsonify를 추가함.
  app = Flask(__name__)

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

  @app.route('/test', methods=['GET'])     -> 웹페이지 마지막 /test 써서 GET 요청 들어준다는 뜻
  def test_get():
    title_receive = request.args.get('title_give')    -> 'title_give" 데이터를 title_receive 변수에 넣는다.
    print(title_receive)
    return jsonify({'result' : 'success''msg' : '이 요청은 GET!'})   -> print 해서 백엔드에서 프론트엔드로 데이터 내려준다

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

 

GET요청 확인 Fetch 코드  -> index.html (프론트엔드)파일에 추가.

 

fetch("/test").then(res => res.json()).then(data => {
console.log(data)
})

 

▼ index.html 파일에 Get요청 확인 Fetch 코드 넣기.

   
    <script>
        function hey() {
            fetch("/test").then(res => res.json()).then(data => {
                console.log(data)
            })
        }
    </script>
 

 

http://localhost:5000 가서 버튼클릭 -> 마우스우클릭 -> 검사 -> 콘솔 : app.py 내용물 나옴.

 

 

POST요청 API 코드 -> app.py(백엔드)파일에 추가.

 

@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 POST!'})

 

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

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

  @app.route('/test', methods=['POST'])    -> 웹페이지 마지막 /test 써서 POST 요청 들어준다는 뜻
  def test_post():
    title_receive = request.form['title_give']    -> 'title_give" 데이터를 title_receive 변수에 넣는다.
    print(title_receive)
    return jsonify({'result':'success', 'msg': '이 요청은 POST!'})   -> print 해서 백엔드에서 프론트엔드로 데이터 내려준다

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

 

POST요청 확인 Fetch 코드  -> index.html(프론트엔드) 파일에 추가.

fetch("/test").then(res => res.json()).then(data => {
console.log(data)
})

 

 
  <script>
        function hey() {              -> hey에 넣은 데이터를 밑에 fetch("/test'~)에 넣음.
            let formData = new FormData();
            formData.append("title_give", "블랙팬서");

            fetch("/test", { method: "POST", body: formData }).then(res => res.json()).then(data => {
                console.log(data)
            })
        }
    </script>
 

 

 

1. index.html(프론트엔드)에서의 title name이 '블랙팬서'이므로, app.py(백엔드)에서의 title name도 블랙펜서로 변경 ▼

2. index.html(프론트엔드)에서의 console.log(data)에 해당부분의 정보가 들어감. ({'result' : 'success', 'msg' : '이 요청은 POST!'})

 

Index.html 프론트엔드 내용

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>
        function hey() {
            fetch("/test").then(res => res.json()).then(data => {   ->GET 요청 확인 Fetch 코드
                console.log(data)
            })
        }

        function hey() {
            let formData = new FormData();
            formData.append("title_give", "블랙팬서");  ->POST 요청 확인 Fetch 코드

            fetch("/test", { method: "POST", body: formData }).then(res => res.json()).then(data => {
                console.log(data)
            })
        }

    </script>
</head>

<body>
    <h1>제목을 입력합니다</h1>
    <button onclick="hey()">나는 버튼!</button>
</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('/test', methods=['GET'])
def test_get():
   title_receive = request.args.get('title_give')
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 GET!'}  -> GET요청 API코드
 
@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 POST!'}) -> POST요청 API코드


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

 

 

프로젝트1 : 화성땅 공동구매

 

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" />
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>
    <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)),
            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) => {
                let rows = data['result']
                $('#order-box').empty()
                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)
                })
            })
        }
        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) => {
                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 pymongo import MongoClient
from flask import Flask, render_template, request, jsonify
app = Flask(_name_)
client = MongoClient(
    'mongodb+srv://sparta:test@cluster0.chqkznt.mongodb.net/?retryWrites=true&w=majority')
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():
    mars_data = list(db.mars.find({},{'_id':False}))
    return jsonify({'result':mars_data})


if _name_ == '_main_':
    app.run('0.0.0.0', port=5000, debug=True)