Python flask /api query String

Wintering·2022년 4월 21일

👉Server와 Client의 관계

  • API : 서버가 클라이언트의 요청을 받기 위해 만든 창구

👉GET 요청에서 클라이언트의 데이터를 받는 방법

  • app.py에서 쓰는 코드 (server)
    @app.route('/test', methods=['GET'])
    def test_get():
       title_receive = request.args.get('title_give')
       print(title_receive)
       return jsonify({'result':'success', 'msg': '이 요청은 GET!'})
  1. url /test를 주고 GET방식 선언
  2. method 시작
  3. request.arg.get('title_give')로 받아 온 title_give 값을 title_recieve에 저장
  4. 결과를 찍어보고, client로 response 값을 내려줌
  • client에서 쓰는 코드
    $.ajax({
        type: "GET",
        url: "/test?title_give=봄날은간다",
        data: {},
        success: function(response){
           console.log(response)
        }
      })
  1. 클라이언트에서 Ajax 콜
  2. 서버에 GET 방식으로 요청
  3. url은 /test를 사용
  4. ?로 get 요청임을 알리고, title_give의 값을 서버로 전달
  5. response에 API(서버)에 내려준 값을 받음

👉POST 요청에서 클라이언트의 데이터를 받는 방법

  • 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!'})
    1. url /test를 주고, POST 방식 선언
    2. request.form['title_give']로, 가져온 title_give 값을 받음
    3. title_give값을 title_recieve에 저장
    4. 값을 찍고, 클라이언트의 response에 값을 내려준다.
  • client에서 쓰는 코드
    $.ajax({
        type: "POST",
        url: "/test",
        data: { title_give:'봄날은간다' },
        success: function(response){
           console.log(response)
        }
      })
    1. 클라이언트에서 Ajax 콜

    2. 서버에 POST 방식으로 요청

    3. url은 /test를 사용

    4. data는 title_give라는 이름으로, title_give의 값을 서버로 전달

    5. response에 API(서버)에 내려준 값을 받음

      참고할 글

      https://aimb.tistory.com/171

0개의 댓글