WEB/python

[python] GET요청과 POST요청 코드 기본/ ajax코드

자바칩 프라푸치노 2021. 6. 10. 19:57

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_give로 가져온 값을 가져와 그게 title_receive야
   title_receive = request.args.get('title_give')
   print(title_receive)
   # 이쪽을 response로 보내줄게
   return jsonify({'result':'success', 'msg': '이 요청은 GET!'})

@app.route('/test', methods=['POST'])
def test_post():
   #  title_give으로 받아온 값 가져와봐
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 POST!'})

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

우선 get요청부터 보자면

title_receive라는 변수에 title_give라고 가져온 값을 넣어서 print를 하고 있고

response응답으로 success와 메세지를 넘긴다

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

ajax코드는 이것이다.

title_give는 봄날은 간다이다.

response로 이 요청은 Post!라는 메세지를 주었으니 그것이 콘솔에 찍히겠다.

 

Post요청을 보면

똑같이 title_give로 받은 값을 title_receive에 저장한다

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

data로 title_give이름으로 봄날은 간다라는 데이터를 보낸다.

그러면 서버에서는 응답으로 msg메세지를 남기고

콘솔에 그 메세지가 찍힌다

728x90