✅ 윈도우
좌상단File → setting → Python interpreter → Python interpreter 화면에서 + 버튼 누르기 →
Flask
검색 → Install package 클릭
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 서버를 만들 때는 항!상!
프로젝트 폴더 안에, 아래 세 개를 만들고 시작하기!!!
① static 폴더 : 이미지, css파일을 넣어둔다.
② templates 폴더 : html파일을 넣어둔다.
③ app.py 파일
venv은 실제로 보이지만, 안 보인다고 생각하기
templates 폴더는 HTML 파일을 담아두고, 불러오는 역할을 한다!
✅ 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.4.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h1>서버를 만들었다!</h1>
</body>
</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)
- 데이터 조회(Read)를 요청할 때
EX) 영화 목록 조회- 데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달
EX) 예: google.com?q=북극곰
- 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청할 때
EX) 회원가입, 회원탈퇴, 비밀번호 수정- 데이터 전달 : 바로 보이지 않는 HTML body에 key:value 형태로 전달
@app.route('/test', methods=['GET'])
def test_get():
title_receive = request.args.get('title_give')
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 GET!'})
$.ajax({
type: "GET",
url: "/test?title_give=봄날은간다",
data: {},
success: function(response){
console.log(response)
}
})
@app.route('/test', methods=['POST'])
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
$.ajax({
type: "POST",
url: "/test",
data: { title_give:'봄날은간다' },
success: function(response){
console.log(response)
}
})