이번엔 드디어 서버를 만든다~
projects 폴더를 만들고 하위에 폴더 5개를 만든다.
01.prac
02.mars
03.pedia
04.bucket
05.fan
먼저 원하는 폴더로 이동한다
app.py를 만든다
터미널을 켠다.
가상환경을 잡는다.
python -m venv venv
(프로젝트 별로 라이브러리를 담아두는 통)
파이썬 버전이 나온곳을 선택하고
상단의
venv가 설정된 인터프리터를 선택한 후, 터미널을 종료하고 다시 킨다.
이렇게 터미널에 venv가 생성되면 성공~
pip install 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.py냐면. 통상적으로 flask 프레임워크를 쓸 때, 가장 기본이되는 python 파일을 app.py라고 한다.
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)
해당 코드를 입력한 후에 주소창에
localhost:5000 을 입력하면,
다음과 같은 웹 페이지가 나타난다.
코드에서 두 번째 app.route('/mypage') ~~ 가 입력되어 있다.
주소창에
localhost:5000/mypage 를 입력하면
다음과 같은 웹페이지가 열린다
여기서 알 수 있는 것은
내 컴퓨터의 주소가 localhost:5000이고
뒤의 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=5000,debug=True)
app.route의 두번째 부분의 리턴을 버튼입니다로 고쳐보았다
저장하고 다시 웹 페이지로 돌아가 새로고침을 하면 결과는
이렇게 버튼이 생겼다.
먼저 01.PRAC 안에 templates 폴더를 만든다
templates 폴더 안에 index.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.5.1/jquery.min.js"></script>
<title>Document</title>
<script>
function hey(){
alert('안녕!')
}
</script>
</head>
<body>
<h1>제목을 입력합니다</h1>
<button onclick="hey()">나는 버튼!</button>
</body>
</html>
다음 app.py로 돌아가서
from flask import Flask, render_template
app = Flask(__name__)
@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)
위의 코드와 같이 맨 윗줄에 , render.template 과
아래 return 자리에 render_template('index.html')을 추가한다.
다시 웹 페이지로 가서 확인해보면 정상작동 함을 알 수 있다.
!! 만약 웹 페이지 연결 불가가 나온다면
파이썬으로 실행하기를 한번 눌러주면 다시 정상작동 한다!
우리가 기억해야 할 것은
app.py는 백엔드.
index.html은 프론트엔드이다.
먼저 app.py의 코드는
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=5000,debug=True)
이고,
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() {
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>
이다.
해당 페이지에서 버튼을 누르고, 검사 - console 에 들어가면 명령어가 입력된 것을 볼 수 있다.
여기서 두 코드를 보며 어디에서 어디로 넘어가는지 잘 관찰하여 익힐 필요가 있다.