서버와 데이터관리 담당.
유저에게 보이지 않는 서버와 인프라를 구축하는 것. 어떤 형태의 서버를 이용할지, 서버 구조, 데이터 구조 등 다양한 측면을 포괄적으로 다룸.
사용자에게 웹을 제공하기 위한 서버. 웹에서 사용자가 서비스를 요청하는 경우 네트워크를 통해 HTML로 구성된 웹 페이지를 제공함.
서버를 구축할 때 프레임워크(라이브러리)가 필요함.
기본 세팅:
1. app.py 생성
2. 가상환경 설정 (python3 -m venv venv) (프로젝트 별로 라이브러리를 담아두는 통)
3. 라이브러리 다운로드 (pip install flask)
4. 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) # 맥에서는 port=5001
위 코드에서 return 값으로 HTML 코드를 넘겨줄 수 있지만 너무 길어지고 복잡해짐.
사용법:
1. app.py가 존재하는 디렉토리에 templates라는 폴더 생성.
2. templates 안에 index.html 생성. (예시)
<!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>
GET과 POST는 둘 다 브라우저가 서버에 요청을 하는 것.
# backend (서버)
@app.route('/test', methods=['GET']) # /test라는 경로에 GET 요청이 들어옴
def test_get():
title_receive = request.args.get('title_give') # 상단에 import request. title_give라는 데이터가 있으면 그 데이터를 title_receive에 할당.
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 GET!'}) # import jsonify. 반환 값.
# frontend (클라이언트)
function hey() {
fetch("/test").then(res => res.json()).then(data => { # /test에 요청 보냄
console.log(data)
})
}
보통 GET은 데이터 조회에, POST는 데이터 생성/변경/삭제에 사용됨.
# backend
@app.route('/test', methods=['POST']) # /test라는 경로에 POST 요청이 들어옴
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
# frontend
function hey() {
let formData = new FormData();
formData.append("title_give", "블랙팬서");
fetch("/test", { method: "POST", body: formData }).then(res => res.json()).then(data => { # POST에 body는 필수
console.log(data)
})
}