티스토리 뷰

Edu_hanghae99/웹개발종합반

4주차 개발일지

soobin Choi 2022. 10. 18. 19:56

정말 외계어 같다...

 

*API는 은행 창구와 같다!
----------index.html
4-4. Flask 시작하기 - 본격 API 만들기

1. Jquery 임포트

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>



2. GET 요청 확인 Ajax 코드 

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

 

/test라는 창구에 title_give라는 이름으로 봄날은 간다라는 데이터를 가지고 간다
like 주민등록번호라는 이름으로 960922-******* 라는 숫자를 가지고 갈게
success 잘 된다면 다시 너가 주는 데이터를 내가 console에다가 찍어볼게 이런 의미

-> 그렇다면 /test 라는 창구는 어떻게 만드나?
---------------app.py
3. GET 요청 API 코드

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

 

title_give라는 이름으로 뭔가를 받아와서 title_receive 변수에다 넣었고
변수를 찍워 줬어라는 뜻, /test라는 창구에서 그것을 받고 있음

=> 서버에서 버튼 클릭 시 console에 {msg: '이 요청은 GET!', result: 'success'} 이렇게 찍힘
PROCESS?
: button 을 onclick 하면 hey() 함수 실행 - '봄날은 간다'라는 데이터를 가지고 옴
- title_receive 변수에 찍음 - print 찍힘 - 우리가 준 것 {'result':'success', 'msg': '이 요청은 GET!'}을
다시 '봄날은 간다' 데이터가 받아감 - console에 찍은 것임

4. POST 요청 확인 Ajax 코드

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

 

*사실 GET 요청에서 데이터를 가져가는 경우는 별로 없고 POST 요청에서 데이터를 많이 가져감

5. POST 요청 API 코드

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

 

2~3과 마찬가지로 console 창에 msg 와 result 가 표시됨
PROCESS? (one more time)
index.html
버튼을 누르면 hey()가 불렸고 Ajax 요청을 했음. 어디에? /test라는 창구에 POST 요청으로
app.py
'봄날은 간다'라고 쓰여있는 데이터(title_give)를 가져왔는지? 그렇다면 변수(title_receive)에 저장해서
print 찍었어! 이제 너에게 '{'result':'success', 'msg': '요청을 잘 받았어'}''라는 데이터를 줄 거야
index.html
response에 '{'result':'success', 'msg': '요청을 잘 받았어'}'' 이 값이 들어옴
console로 우리가 찍어본 것임
*여기서 'result'와 'msg'는 key이고 'success'와 '요청을 잘 받았어'는 value이다.

'Edu_hanghae99 > 웹개발종합반' 카테고리의 다른 글

5주차 개발일지  (0) 2022.10.20
3주차 개발일지  (0) 2022.10.18
2주차 개발일지  (0) 2022.10.17
1주차 개발일지  (0) 2022.10.14