Flask

서재환·2021년 9월 15일
0

WEB

목록 보기
2/8

✍️ API란?

 🛎️ 클라이언트의 요청을 처리하기 위해 마련한 창구
    
    여러 창구중 대표적인 창구에 대해서 알아보자
    
    GET
    데이터 조회(Read) 요청할 때
    
    POST
    데이터를 생성, 변경, 삭제를 요청할 때 

✍️ Flask Server에 Ajax를 사용하여 요청해보자

상황) ¹local 개발 환경에서 flask를 이용해 서버를 구축하였고 ²자바스크립트 라이브러리
       Ajax를 사용 및 'Post method' or 'Get method' 서버와 통신을 하였다.

      ¹flask server를 구성한 python의 코드가 아래와 같고 ²브라우저에서 렌더링한 페이지
       내에서 console 창에서의 Ajax code가 아래와 같을 때 code를 이해해보자.
#python

case 1)

  @app.route('/test', methods=['GET'])
  def test_get():
      title_receive = request.args.get('title_give')  # title_give 값 가져온다.
      print(title_receive)
      return jsonify({'result': 'success', 'msg': '이 요청은 GET!'})
   도메인에서 test창구로 데이터를 조회할 대 test_get()함수를 작동시킨다.
   key 'title_give'에 할당한 값을 title_receive 변수에 담는다.
//javascript

$.ajax({
    type: "GET",
    url: "/test?title_give=봄날은간다",
    data: {},
    success: function(response){
       console.log(response)
    }
  })
   서버가 요청에 응했다면 서버는 제이슨 형식의 값을 리턴할 것이다.
   
   {msg: '이 요청은 GET!', result: 'success'}
case 2)

  @app.route('/test', methods=['POST'])
  def test_post():
      title_receive = request.form['title_give']
      print(title_receive)
      # title_give 값 가져온다.
      return jsonify({'result': 'success', 'msg': '이 요청은 POST!'})
   도메인에서 test창구로 POST 방식으로 데이터를 조회할 대 test_post()함수를 작동시킨다.
   key 'title_give'에 할당한 값을 title_receive 변수에 담는다.
//javascript
  $.ajax({
      type: "POST",
      url: "/test",
      data: { title_give:'봄날은간다' },
      success: function(response){
         console.log(response)
      }
    })
   서버가 요청에 응했다면 서버는 제이슨 형식의 값을 리턴할 것이다.
   
   {msg: '이 요청은 POST!', result: 'success'}

0개의 댓글