Flask 패키지 설치!
파일 > 설정 > 인터프리터
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'This is Home!'
@app.route('/mypage')
def mypage():
return 'mypage'
if __name__ == '__main__':
app.run('0.0.0.0',port=5000,debug=True)
Flask 서버를 만들 때, 항상,
프로젝트 폴더 안에,
ㄴstatic 폴더 (이미지, css파일을 넣어둡니다)
ㄴtemplates 폴더 (html파일을 넣어둡니다)
ㄴapp.py 파일
이렇게 세 개를 만들어두고 시작해야한다. 이제 각 폴더의 역할이 있다.
templates 폴더의 역할은
HTML 파일을 담아두고, 불러오는 역할을 한다.
templates 안의 index.html 와 연결하기 위해서는 위와 같이 render+template을 import 하여 return render_template('index.html')로 사용한다.
function hey() {
$.ajax({
type: "GET",
url: "/test?title_give=봄날은간다",
data: {},
success: function (response) {
console.log(response)
}
})
}
function hey() 를 넣어 onclick 이벤트로 연결하고, Ajax코드를 작성했다.@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코드를 만들어 통신할 수 있도록 한다. 이때, request 와 jsonify를 import 해준다. POST도 GET과 같은 방식이다.$.ajax({
type: "POST",
url: "/test",
data: { title_give:'봄날은간다' },
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!'})
위에서 title부터 아랫줄들이 줄정렬이 안되면 에러가 발생하는데,GET POST 요청과 API 통신을 통해 프론트와 백엔드의 통신 구조를 이해하고,TIL