[웹개발] 서버 만들기

Sohyun An·2021년 10월 29일
0

SpartaCodingClub

목록 보기
15/18

💡 Flask란?

-Flask 프레임워크란, 서버를 구동시켜주는 편한 코드 모음을 말합니다.
서버를 구동하려면 필요한 복잡한 일들을 쉽게 가져다 쓸 수 있습니다.
-파일 이름은 아무렇게나 해도 상관없지만,
통상적으로 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)

-@app.route('/) 부분을 수정해서 URL을 나눌 수 있습니다.
url 별로 함수명이 같거나, route('/')내의 주소가 같으면 안됩니다.

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)

💡 Flask 서버 만들기

-Flask 서버를 만들 때, 항상,

프로젝트 폴더 안에,
ㄴstatic 폴더 (이미지, css파일을 넣어둡니다)
ㄴtemplates 폴더 (html파일을 넣어둡니다)
ㄴapp.py 파일

이렇게 세 개를 만들어두고 시작하세요.
(꼭 참고!! venv는 실제로는 보이지만, 안보인다~라고 생각하세요)

templates 폴더의 역할을 알아보겠습니다.
HTML 파일을 담아두고, 불러오는 역할을 합니다.
flask 내장함수 render_template를 이용하면 html 파일을 불러올 수 있습니다.

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)

-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코드

$.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코드

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

0개의 댓글