flask 시작 코드 (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)
어떻게 돌아가는가 :
1. flask import
2. 변수 app에 Flask를 담아 인스턴스 생성
이때 매직 메소드인 __name__ 변수는 현재 사용하는 모듈 상태 나타냄
3. @(데코레이터)로 app 인스턴스의 route 함수의 기능을 밑의 home() 함수에 붙여 꾸밈
'/'라는 매개변수를 통해 HTTP에 요청을 처리
4. app.run()을 통해 app 객체 실행
참고 : https://mld42.tistory.com/m/12
route('/') : 웹표현 메소드참고 : https://m.blog.naver.com/21ahn/221830372908
@app.route('/') : 장식자. 함수 장식자는 함수 코드 바꾸지 않고도, 장식자 안의 내용만 바꿈으로 함수 동작 조절 가능
여기서 URL '/'는 다음 행에 정의된 함수와 연결됨
route 장식자는 Flask 서버로 '/'URL 요청이 들어왔을 때 어떤 함수를 호출할 것인지 조정
장식된 함수에서 결과 반환 때까지 기다리다 결과 반환되면 대기중인 웹 브라우저로 반환
장식자를 사용하면 다음 행의 함수부터 장식자 적용됨
localhost:5000/ 주소에서 맨 뒤에 route에서 설정한 /가 붙는 걸 볼 수 있다
@app.route('/mypage')의 경우 주소는 localhost:5000/mypage
app.run('0.0.0.0',port=5000,debug=True) 에서
- '0.0.0.0'은 host='0.0.0.0' : 모든 호스트로 접속이 가능하다. host 설정 기본값은 localhost(=127.0.0.1)
- port=5000 : 5000번 포트로 실행. 기본 app.run()이 포트 5000으로 실행된다
예시 이미지
$.ajax({
type: "GET",
url: "/test?title_give=봄날은간다",
data: {},
success: function (response) {
console.log(response)
}
})
(웹사이트 크롤링에 쓰던 ajax.. 해당 url에서 데이터 갖고 온다)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
사용 예
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function hey() {
$.ajax({
type: "GET",
url: "/test?title_give=봄날은간다",
data: {},
success: function (response) {
console.log(response)
}
})
}
</script>
</head>
<body>
<h1>나의 첫 웹페이지</h1>
<button onclick="hey()">버튼을 만들자</button>
</body>
</html>
(hey() 함수에 넣어 사용)
이 /test 창구는 어떻게 만드나? -> GET 요청 API 코드 사용
@app.route('/test', methods=['GET'])
def test_get():
title_receive = request.args.get('title_give')
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 GET!'})
localhost:5000/test에 들어가보면 이렇다
전체 코드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=5000,debug=True)
모듈 설명
버튼을 누르면 콘솔에 이렇게 나온다. (좌측 상단 파이참 콘솔에 '봄날은간다' 찍힘)
<script>
function hey() {
$.ajax({
type: "POST",
url: "/test",
data: {title_give: '봄날은간다'},
success: function (response) {
console.log(response)
}
})
}
</script>
@app.route('/test', methods=['POST'])
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
과정
1. hey() 실행
2. /test 창구에 POST 요청으로 Ajax 요청 (Ajax)
3. title_give 받아서 title_receive 변수에 저장, (파이참 콘솔에)출력 (API)
4. 일 끝나서 json 형식의 데이터 반환 (API)
5. 반환받은 값이 response에 들어옴, 콘솔에 출력 (Ajax)
window.location.reload() : 창 새로고침
$(document).ready(function () {
함수();
});