폴더 생성 & 가상 환경 설치
|-- venv
|-- app.py (서버)
|-- templates
|---|--index.html (클라이언트 파일)
- Flask 폴더 구조 규칙 지키기
- 터미널이 bash로 생성된 것 확인하기
- 가상환경 활성화 확인 - 터미널에 (venv)
Flask 패키지 설치
- 터미널에 pip install flask 입력 후 엔터
Flask 실행
- 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)
- Flask Url 나눠보기
- 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 MyPage' if __name__ == '__main__': app.run('0.0.0.0', port = 5000, debug = True)
1) 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>Title</title>
<script>
function hi() {
alert('안녕!');
}
</script>
</head>
<body>
<button onclick = "hi()">버튼</button>
</body>
</html>
2) HTML 파일 불러오기
flask 내장함수 render_template를 이용
from flask import Flask, render_template
app = Flask(__name__)
# URL 별로 함수명이 같거나, route('/') 등의 주소가 같으면 안됨
@app.route('/')
def home():
return 'This is Home'
@app.route('/mypage')
def mypage():
return render_template('index.html')
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
- GET
- 통상적으로 데이터 조회(Read) 요청 시 사용
- 데이터 전달: URL 뒤에 물음표를 붙여 key=value로 전달
- POST
- 통상적으로 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 시 사용
- 데이터 전달: 바로 보이지 않는 HTML
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
@app.route('/test', methods=['GET'])
def test_get():
title_receive = request.args.get('title_give')
print(title_receive)
return jsonify({'result':'success', 'msg':'GET 요청'})
fetch('/test').then(res => res.json()).then(data => {
console.log(data)
});
@app.route('/test', method['POST'])
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg':'POST 요청'})
let formData = new FormData();
formData.append("title_give", "블랙펜서");
fetch('/test', {method: "POST", body: formData}).then(res => res.json()).then(data => {
console.log(data);
});