항해 99/사전 기본 스터디

Flask 기본 시작 - 서버만들기 (feat. PyCharm)

U_D 2022. 2. 25. 14:23

1. 서버 만들기 - 기본 세팅

 

#1. 패키지 설치

이번에도 역시 프레임워크(패키지) 설치를 우선적으로 해줘야 한다.

서버를 간편하게 만드는 프레임워크인 flask를 설치했다.

 

*Flask 프레임워크

서버를 구동시켜주는 편한 코드 모음 - 서버를 구동하기위해 필요한 복잡한 일들을 쉽게 가져다 쓸 수 있다.

 

 

 

#2. flask 시작 세팅

파이썬 파일 'app.py'를 만들어 flask 시작 코드를 입력한다.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

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

 

 

 

#3. 서버 구동 확인

오른쪽 클릭 → 실행 후, 크롬에서 http://localhost:5000/ 으로 접속한다.

화면에 위에서 입력한 메시지 'This is Home!'이 뜨면 성공.

 

 

 

#4. URL 나눠보기

@app.route('/) 부분을 수정해서 아래와 같이 URL을 나눌 수 있다.

 

2개의 페이지가 만들어 졌다!

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

@app.route('/mypage')
def mypage():  
   return 'This is My Page!'

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

 

 

#5. HTML 파일 주기

flask를 사용할 땐 항상 기본 폴더구조를 세팅해야 한다.

 

프로젝트 폴더 안에 아래와 같이 생성한다.

  ㄴstatic 폴더 (이미지, css파일을 넣어두는 곳)

  ㄴtemplates 폴더 (html파일을 넣어두는 곳)

  ㄴapp.py 파일 (파이썬 작업 파일)

 

 

기본 세팅이 끝나면, 이제 flask 내장함수 render_template를 이용해서 

만들어 놓은 html 파일을 불러온다.

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

@app.route('/')
def home():
   return render_template('index.html')  #html 파일명 입력

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

 

 

#6. GET 요청 & POST 요청 타입 리마인드 연습

먼저, HTML 파일에 JQuery를 임포트 한다.

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

 

그리고 파이썬 파일에 request, jsonify를 입력해준다.

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

 

 

GET 요청 방식 먼저 연습해보기.

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라는 창구에서

 

다음으로 GET 요청 Ajax 코드 입력.

$.ajax({
    type: "GET",
    url: "/test?title_give=봄날은간다",
    data: {},
    success: function(response){
       console.log(response)
    }
  })
  
  // /test라는 창구에서 
  // title_give라는 이름으로 '봄날은 간다'라는 값을 갖고 갈게
  // 그리고 잘 된다면 reponse 값을 콘솔에 찍어볼게.

 

 

이제, POST 타입 요청을 연습해보자.

이번엔 POST 요청 Ajax 코드를 먼저 입력.

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

 

다음으로, POST 타입 요청 API 코드 입력.

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