왕초보 웹개발 종합반 4주차

장정인·2021년 7월 19일
0

4주차 소감

  • 이젠 3주차 내용이랑 다 섞여서 헷갈린다.
  • 그래도 db를 이용해서 서버를 제작해보니까 대강 웹페이지들이 어떻게 만들어지는지 알 것 같다. 5주차에서 더 명확하게 알 수 있으리라 생각한다.
  • 새 프로젝트 시작할 때마다 Flask, pymongo, requests, bs4를 깔고 파이썬 서두에 입력해야 하는데 자주 잊어버린다.

서버 구현하는 법

  1. file만들기
    이 파일을 선택해 프로젝트를 열고 venv가 끝에 있는지 확인, 3.8인지 확인
    그 후 templates, ststic, app.py 만들고 templates안에 index.html만들기.(venv는 건드는거 아님.)

  2. settings> python interpreter을 통해 확장팩깔기. 서버 만들기 위해 flask, pymongo 깔기, 크롤링을 하려면 requests, bs4를 깔아야 함.

  3. flask 시작코드

    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def home():
       return 'This is Home!'
    
    if __name__ == '__main__':  
       app.run('0.0.0.0',port=5000,debug=True)

    이후 ctrl shift F10으로 run함.
    그럼 이제 localhost:5000 으로 들어가야 함.

  4. index.html파일 연결하기

    from flask import Flask, render_template
    app = Flask(__name__)
    
    @app.route('/')
    def home():
       return render_template('index.html')
    
    if __name__ == '__main__':  
       app.run('0.0.0.0',port=5000,debug=True)

    localhost:5000을 입력하면 @app/route('/')로 들어옴

    그래서 그 안에있는 html함수로 들어오는 것.

  1. GET: 데이터 조회- 원하는 정보 서버에서 가져오기

    서버코드- 요청 API코드 (.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!'})

    클라이언트 코드- 요청확인 Ajax 코드 (.html에서 사용)

    $.ajax({
        type: "GET",
        url: "/test?title_give=봄날은간다",
        data: {},
        success: function(response){
           console.log(response)
        }
      })
  1. POST: 데이터 생성, 변경,삭제

    서버코드- 요청 API코드 (.py에서 사용)

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

    클라이언트 코드- 요청확인 Ajax 코드 (.html에서 사용)

    $.ajax({
        type: "POST",
        url: "/test",
        data: { title_give:'봄날은간다' },
        success: function(response){
           console.log(response)
        }
      })

실수한 것

  1. 파이썬 시작 전에 jsonify, request등을 서두에 입력해야지 get, post가 가능하다.
from flask import Flask, render_template,jsonify,request
app = Flask(__name__)
  1. 왜 get이 안되는거지? 이러고 있었는데 새로고침하자마자 작동이되게 안해놔서 그런 거였다.

이렇게 하면 안된다

function showOrder() {
            $.ajax({
                type: "GET",
                url: "/order",
                data: {},
                success: function (response) {
                    let orders = response['all_orders']
                    for (let i = 0; i < orders.length; i++) {
                        let name = orders[i]['name']
                        let count = orders[i]['count']
                        let address = orders[i]['address']
                        let phone = orders[i]['phone']

                        let temp_html = `<tr>
                                        <th scope="row">${name}</th>
                                        <td>${count}</td>
                                        <td>${address}</td>
                                        <td>${phone}</td>

                                    </tr>`

                        $('#orderTable').append(temp_html)
                    }
                }
            })
        }

모범답안

$(document).ready(function () {
            get_rate()
            listing()
        });

        function listing(){$.ajax({
                type: "GET",
                url: "/order",
                data: {},
                success: function (response) {
                    let orders = response['all_orders']
                    for (let i = 0; i < orders.length; i++) {
                        let name = orders[i]['name']
                        let count = orders[i]['count']
                        let address = orders[i]['address']
                        let phone = orders[i]['phone']

                        let temp_html = `<tr>
                                        <th scope="row">${name}</th>
                                        <td>${count}</td>
                                        <td>${address}</td>
                                        <td>${phone}</td>

                                    </tr>`

                        $('#orderTable').append(temp_html)
                    }
                }
            })

        }

로딩 후 실행 함수-이거 자주 까먹는다.

$(document).ready(function () {
            get_rate()
            alert('다 로딩됐다!')
        });

0개의 댓글