SW/Flask

Flask 기초

ahhyeon 2023. 3. 20. 23:55

1. Flask 기본 폴더구조

⭐ 항상 이렇게 세팅하고 시작!

프로젝트 폴더 안에,
ㄴstatic 디렉터리 : 스타일시트(.css), 자바스크립트(.js) 그리고 이미지 파일(.jpg, .png) 등을 저장
ㄴtemplates 디렉터리 : html파일 저장
ㄴapp.py 파일

2. Flask 기초

2-1. index.html 파일을 templates 안에 만들기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Document</title>

    <script>
        function hey(){
            alert('안녕!')
        }
    </script>
</head>
<body>
    <button onclick="hey()">나는 버튼!</button>
</body>
</html>

2-2. html 파일 불러오기

 ✔️ flask 내장함수 render_template 이용!

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

# URL 별로 함수명이 같거나,
# route('/') 등의 주소가 같으면 안됨

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

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

3. Flask  API 만들기

API란 ?
은행이 고객을 받기 위해 만든 창구처럼, 서버가 클라이언트 요청을 받기 위해 만든 창구라고 생각!
은행에서도 고객이 돈을 빌릴려면 신분증/통장 들고와야 하는 규칙이 있듯이, 
클라이언트도 서버한테 요청하기 위해서는 규칙을 만족해야 한다.

 

여러 방식(링크)이 존재하지만,

대표적인 GET, POST 방식만 다뤄보려고 함

 

3-1. GET 

➡️ 통상적으로 데이터 조회(Read)를 요청할 때

      ex) 영화 목록 조회

➡️ 데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달

➡️ 예: google.com?q=북극곰

 

3-2. POST

➡️통상적으로 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때

     ex) 회원가입, 회원탈퇴, 비밀번호 수정

➡️ 데이터 전달 : 바로 보이지 않는 HTML body에 key:value 형태로 전달

 

3-3. 클라이언트의 데이터를 받는 방법

예를 들어, 클라이언트에서 서버에 title_give란 키 값으로 데이터를 들고 옴

(주민등록번호 키값으로 990101-.. 을 가져온 것과 같은 뜻)

 

Jquery 임포트

✔️script 만들어서 Ajax 쓰면 됨!

// title 아래
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
서버에 데이터 요청할때 ➡️ Ajax 사용!
클라이언트는 Ajax를 이용해 서버에 요청
서버는 API를 이용해 클라이언트에 답변
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!'})
GET 요청 확인하는 Ajax 코드(클라이언트)를입력
url: "/test?title_give="쿠키"

/test : 웹페이지 주소
? : 해당정보

➡️ 이는 querystring으로, GET방식에서는 url을 통해 정보를 조회함
➡️ 여기서 title_give라는 이름으로 "쿠키"를 가져오라는 요청을 함!
$.ajax({
    type: "GET",
    url: "/test?title_give=쿠키",
    data: {},
    success: function(response){
       console.log(response)
    }
  })
POST 요청 API 코드
@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
POST 요청 확인하는 Ajax 코드
GET 방식과 다르게,

url : "/test"
➡️ 여기서는 url이 변경되지 않았음을 확인할 수 있음!

data : {title_give: '쿠키' }
➡️ POST방식에서는 GET 방식에서 url을 통해 전해졌던 정보가 data 키 안에 벨류로 들어감!
➡️ (GET 방식에서는 data:{}로 빈 딕셔너리가 반환했었음)
$.ajax({
    type: "POST",
    url: "/test",
    data: { title_give:'쿠키' },
    success: function(response){
       console.log(response)
    }
  })

 


4. 완성

index.html 코드
  • Ajax 코드(클라이언트) - GET 요청
  • function hey() {}
    •  'index.html' >>>  button에 onclick hey() 연결
    •  function hey() { Ajax 코드 넣음 }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function hey() {
            alert('안녕!')
         $.ajax({
                type: "GET",
                url: "/test?title_give=쿠키",
                data: {},
                success: function(response){
                    console.log(response)
                }
            })
        }
    </script>
</head>
<body>
    <button onclick="hey()">나는 버튼!</button>
</body>
</html>
app.py 코드
  • 창구 만들기
  • @app.route('/test', methods=['GET'])
    • 맨 위에 request, jsonify 추가
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

@app.route('/')
def home():
   # render_template: template 파일 중 index.html을 불러 옴
   return render_template('index.html')

# 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!'})
   
# POST 요청 API 코드
@app.route('/test', methods=['POST'])
def test_post():
   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)