서버를 만든다!
-> 굉장히 어렵다.
서버 만들 수 있는 큰 라이브러리 : 이런 것을 프레임워크라고 부른다!
-> Flask 프레임워크: 서버를 구동시켜주는 편한 코드 모음
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)
--> 내 컴퓨터에서 만들어서 내 컴퓨터에서 돌리고 있어서 "Local 개발환경"이라고 한다.
Flask라는 프레임워크의 룰을 따라가야 한다.
1)static 폴더 (이미지, css파일 넣기)
2)templates 폴더 (html 파일 ) : 주로 templates만 쓰게 된다.
3)app.py파일
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run('0.0.0.0',port=5000,debug=True)
--> render_template('index_html') : 이걸 통해서 HTML문서를 로컬호스트로 불러옴.
로컬호스트 5000 --> 서버에서 나한테 준 HTML을 보는 것.
바로 HTML에서 열면 --> 내 컴퓨터 파일을 여는 것. ;; 앞으로 이렇게 열진 않을 거다!!!
두 개가 다르다는 것을 인식해야된다.
기존 HTML만 잘 만들어두면 이제 배포할 준비가 된 것이다!!
============================================================
**API 만들기
GET / POST 방식
Jquery 임포트 -> script 만들어서 Ajax 쓰면 된다.
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
</script>
-> Ajax 코드 ; GET 요청 /
1) function hey(){} --> Button에 onclick hey() 연결 --> 이후에 Ajax 코드를 function hey(){}에 Ajax 코드 넣는다.
function hey() {
$.ajax({
type: "GET",
url: "/test?title_give=봄날은간다",
data: {},
success: function (response) {
console.log(response)
}
})
}
--> /test(동사무소)라는 창구에 가는데, title_give(주민등록번호)라는 이름으로 '봄날은 간다(나)'라는 데이터를 갖고 갈게. --> 이게 success: function (response)(정확한 데이터라면), {console.log(response)} : 너가 주는 데이터를 내가 콘솔에 돌려줄게.
--> 창구 만들기 :
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)
1) @app.route('/test', methods=['GET'])
--> 맨 위에 request, jsonify 추가해야된다.
title_give라는 이름으로 뭔가를 받아와서, 변수에다 넣고 --> 걔를 찍어줬어 (print)
<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>
--> 버튼 클릭하면 --> hey를 script(ajax)에서 기능 --> "봄날은간다"라는 변수를 요청했어.
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)
--> 그래서 title_give에 "봄날은간다"를 title_receive = request.args.get ('title_give') 에 넣겠지.
--> 이렇게 된 것을 title_recieve로 가져오면 --> print(title_receive)를 찍으니까 : python에 입력이 되겠지.
--> 그리고 나서 jsonify를 통해서 'result':'success', 'msg': '이 요청은 GET!'을 돌려준다.
<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>
그러면 다시 success로 이 내용이 들어가서 response에 msg로 '이 요청은 GET!'이 입력이 되고
--> 이 response를 console.log(response)로 넣으니까 console 창에 '이 요청은 GET!'이 입력이 된다!!
댓글