Flask란?
Flask란 파이썬에서 웹 서버를 쉽게 구동시켜주는 프레임워크이다.
구조는 다음과 같다.
- static
- templates
app.py
static 폴더에는 css, js같은 파일들을 넣고, templates 폴더에는 html 파일들, 그리고 app.py에서 그것들을 연결, 설정하고 웹 서버를 구동한다.
이전에 ajax를 통해 서버에 Get이나 Post로 데이터를 요청하여 받았는데,
Flask에서 그러한 Get, Post 요청에 대한 처리를 app.py에서 설정할 수 있다.
먼저 Get에 대한 처리 예제는 다음과 같다.
@app.route("/mars", methods=["GET"])
def mars_get():
orders_list = list(db.orders.find({},{'_id':False}))
return jsonify({'orders':orders_list})
/mars 라는 url로 들어오는 Get 요청에 대하여 db에서 orders라는 것을 찾아 json형태로 반환하여 주는 구문이다.
다음은 Post에 대한 처리 예제이다.
@app.route("/mars", methods=["POST"])
def mars_post():
name_receive = request.form['name_give']
address_receive = request.form['address_give']
size_receive = request.form['size_give']
doc = {
'name': name_receive,
'address': address_receive,
'size': size_receive
}
db.orders.insert_one(doc)
return jsonify({'msg': '주문 완료!'})
/mars 라는 url로 들어오는 Post 요청에 대하여, 요청의 name_give를 name, address_give를 address, size_give를 size로 doc을 만들어 db에 저장한 후, msg를 키로 '주문완료!'라는 데이터를 담아 반환하는 구문이다.
4주차 숙제
4주차 숙제의 목표는 응원문구과 이름을 등록하면, 그 밑의 응원목록에 추가해주는 것이다.
@app.route("/homework", methods=["POST"])
def homework_post():
name = request.form['name']
comment = request.form['comment']
db.users.insert_one({
'name' : name,
'comment' : comment
})
return jsonify({'msg':'POST 연결 완료!'})
응원 남기기 버튼을 눌렀을 때, 키가 name, comment인 Json으로 요청을 보내게 되고
그러한 request에서 데이터를 뽑아서 db의 users에 위와 같은 형태로 저장하고 POST 연결 완료라는 msg를 반환한다.
@app.route("/homework", methods=["GET"])
def homework_get():
comments = list(db.users.find({}, {'_id': False}))
return jsonify({'comments': comments})
페이지를 새로 시작하게되면 /homework url로 응원목록에 대하여 Get 요청을 하는데,
그때 users에 있는 모든 데이터를 comments를 키로 하는 Json 데이터로 반환한다.
'교육 > 스파르타코딩클럽 - 내일배움단' 카테고리의 다른 글
[5주차] AWS로 웹서비스 배포하기 (0) | 2022.11.16 |
---|---|
[3주차] Python 크롤링 (0) | 2022.11.16 |
[2주차] JQuery와 Ajax (0) | 2022.11.16 |
[1주차] HTML, CSS, JS 기본 (0) | 2022.10.19 |