상세 컨텐츠

본문 제목

flask 서버 환경에서 API 만들기

CS전공 지식/웹서비스 이해하기

by 본투비곰손 2022. 12. 5. 23:07

본문

728x90

Jquery를 사용하여 Ajax 함수를 만든다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function hey(){
               $.ajax({
                    type: "POST",
                    url: "/test",
                    data: { title_give:'봄날은간다' }, 
                    //title_give:'봄날은간다' 값이 '봄날은간다.'인 title_give를 /test로 보낸다.
                    success: function(response){
                    console.log(response) // 성공하면 콘솔창에 response를 출력한다.
                    }
                    })
                }
    </script>
</head>
<body>
<h1>나의 첫 웹 페이지</h1>
<button onclick="hey()">버튼 만들기</button> // 클릭을하면 함수 hye()가 실행된다.
</body>
</html>

post 방식의 API를 만들어 준다.

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

@app.route('/')
def home():
   return render_template('index.html')

@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give'] #클릭하여 받아온 title_give의 값인 '봄날은간다' 를
   print(title_receive) #변수 title_receive에 넣고 출력한다.
   return jsonify({'result':'success', 'msg': '이 요청은 POST!'}) 
	#리턴되는 값 'result':'success', 'msg': '이 요청은 POST!' 은 script의 response로 가서 출력된다.
if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)
728x90

'CS전공 지식 > 웹서비스 이해하기' 카테고리의 다른 글

API GET방식 POST방식 연습 2  (0) 2022.12.15
API GET방식, POST방식 연습 1  (0) 2022.12.07
서버 만들기  (0) 2022.12.05
지니뮤직 크롤링하기  (0) 2022.12.05
mongoDB에 가입하고 사용해보기  (0) 2022.12.02

관련글 더보기