스파르타코딩클럽/내일배움단
내일배움단 웹개발 4주차
YONS
2021. 11. 16. 12:56
1. flask
서버를 구동하는데 필요한 코드들을 복잡하게 직접 짤 필요 없이 쉽게 가져다 쓸 수 있다.
flask 서버를 돌리는데 필요한 파일 이름은 아무거나 상관 없지만 통상적으로 app.py
flask 서버를 만들 때 프로젝트 폴더 안엔 항상
- static 폴더 (이미지, css 파일 등)
- templates 폴더 (html 파일)
- app.py 파일
이 들어가야함
이유는 render_template < 이게 templates 폴더에서 불러오라는 함수인 것 등
flask 함수가 그렇게 정해져있기 때문
from flask import Flask, render_template
app = Flask(__name__)
## URL 별로 함수명이 같거나,
## route('/') 등의 주소가 같으면 안됩니다.
# app의 기본 주소
@app.route('/')
def home():
# render_template로 templates 폴더에서 index.html를 출력해라!
return render_template('index.html')
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
2.
# GET요청 API 코드
# 경로는 /test, 형식은 GET
@app.route('/test', methods=['GET'])
def test_get(): # test_get이라는 함수를 실행
title_receive = request.args.get('title_give') # title_give 를 request를 통해 가져옴
print(title_receive) # 방금 가져와서 title_receive에 넣은 내용 프린트
return jsonify({'result':'success', 'msg': '이 요청은 GET!'})
// GET 요청 확인 Ajax 코드
$.ajax({
type: "GET",
url: "/test?title_give=봄날은간다", // test 경로에 있는 title_give에 봄날은간다 넣어줌
data: {},
success: function(response){
console.log(response)
}
})
# POST 요청 API 코드
@app.route('/test', methods=['POST'])
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
// POST 요청 확인 Ajax 코드
$.ajax({
type: "POST",
url: "/test", // GIVE랑 다르게 url엔 경로만
data: { title_give:'봄날은간다' }, // data에서 title_give에 값 설정
success: function(response){
console.log(response)
}
})
3. 그 외의 요청타입들