Flask 서버 만들기
1. 원하는 폴더로 이동
2. app.py를 만든다
3. 터미널을 켠다
4. 가상환경을 잡는다(python3 -m venv venv)
가상환경이란 프로젝트별로 라이브러리를 담아두는 통이다.
가상환경을 만들었으니 flask라는 라이브러리를 담는다(설치한다). 통상적으로 flask를 실행시킬 가장 기본이 되는 python 파일 이름을 app.py로 정한다.
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=5001,debug=True)
flask 라이브러리의 기본 시작 코드이다. 코드 실행 후 브라우저에서 localhost:5001 로 들어가게 되면
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=5001,debug=True)
@app.route('/') 밑에 하나 더 복사해서 위와 같이 만들고 실행한 뒤 localhost:5001/mypage 에 들어가면
이와 같이 나오게 된다.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'This is Home!'
@app.route('/mypage')
def mypage():
return '<button>버튼입니다</button>'
if __name__ == '__main__':
app.run('0.0.0.0',port=5001,debug=True)
HTML도 추가할 수 있다.
index.html 파일은 app.py 내부에 간단하게 넣으려고 한다.
app.py 파일 맨 윗줄에 , render_template 를 추가한다. Flask에 render_templates 기능을 이용하겠다는 의미이다.
/mypage에 넣고 싶으니 return render_template('해당 html 파일')을 실행시켜준다.
저장 후 실행시켜보면 /mypage 에서 html의 내용이 정상적으로 실행됨을 알 수 있다.
전체적으로 봤을 때, 만들어놓은 index.html 파일을 Flask라고 하는 파이썬 백엔드 서버가 돌면서 가져다 주는 것이다.
GET 요청
통상적으로 데이터 조회(Read)를 요청할 때 사용, 데이터를 건드리지 않을 때
예) 영화 목록 조회
→ 데이터 전달 : URL 뒤에 물음표를 붙여 key=value로 전달
POST 요청
통상적으로 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때 사용, 데이터 조작 가능
예) 회원가입, 회원탈퇴, 비밀번호 수정
→ 데이터 전달 : 바로 보이지 않는 HTML
API를 만들고 사용하는 과정에서 두가지가 필요하다.
1. Flask의 request
2. jsonify
GET 요청
@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 요청 API 코드이다.
fetch("/test").then(res => res.json()).then(data => {
console.log(data)
})
GET 요청 확인 Fetch 코드이다. /test 라고 하는 URL에서 데이터를 받아오는 것이다. HTML 파일에 추가된다.
나는 버튼! 을 누르고 크롬 console을 확인해보면
이와 같이 나오게 된다.
from flask import Flask , render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/test', methods=['GET'])
def test_get():
title_receive = request.args.get('title_give')
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 GET!'})
if __name__ == '__main__':
app.run('0.0.0.0',port=5001,debug=True)
app.py의 코드(백엔드)에서
<!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(){
fetch("/test").then(res => res.json()).then(data => {
console.log(data)
})
}
</script>
</head>
<body>
<h1>제목을 입력합니다</h1>
<button onclick="hey()">나는 버튼!</button>
</body>
</html>
index.html(프론트엔드)로 들어오게 된 것이다.
fetch에서 /test를 통해 요청이 가고 백엔드의 해당 데이터가 내려오게 된 것이다.
POST 요청
@app.route('/test', methods=['POST'])
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
POST 요청 API 코드이다.
let formData = new FormData();
formData.append("title_give", "블랙팬서");
fetch("/test", { method: "POST", body: formData }).then(res => res.json()).then(data => {
console.log(data)
})
POST 요청 확인 Fetch 코드이다.
from flask import Flask , render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/test', methods=['POST'])
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
if __name__ == '__main__':
app.run('0.0.0.0',port=5001,debug=True)
app.py(백엔드) 코드이다.
<!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() {
let formData = new FormData();
formData.append("title_give", "블랙팬서");
fetch("/test", { method: "POST", body: formData }).then(res => res.json()).then(data => {
console.log(data)
})
}
</script>
</head>
<body>
<h1>제목을 입력합니다</h1>
<button onclick="hey()">나는 버튼!</button>
</body>
</html>
index.html 코드이다.
버튼을 누르면
크롬 console에 이와 같이 찍히게 되고
터미널에도 이와 같이 찍히게 된다.
app.py(백엔드)에서 보낸 데이터가 index.html의 fetch의 결과, data에 담기는 것이다.
'코딩 > 웹개발 종합반' 카테고리의 다른 글
웹개발 종합반 4주차(스파르타 피디아) (0) | 2023.03.22 |
---|---|
웹개발 종합반 4주차(화성땅 공동구매) (0) | 2023.03.21 |
웹개발 종합반 3주차 (0) | 2023.03.21 |
웹개발 종합반 2주차 (0) | 2023.03.13 |
웹개발 종합반 1주차 (0) | 2023.03.09 |
댓글