1. 프로젝트 세팅
환경을 세팅해준다.
- app.py에 venv 만들기 < python -m venv venv >
- 패키지 설치하기 < pip install flask pymongo dnspython >
2. 뼈대 준비하기
2-1. app.py와 index.html 구성하기
2-2. mongodb 세팅해두기
3-3. ※ localhost:5000으로 접속하기! html에서 접속하는거 아님!
<app.py>
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
3. POST 연습 (데이터 보냄)
※ 참고
댓글창 코멘트 id = comment
<index.html>
function save_insult() {
let comment = $('#comment').val() => html의 comment라는 id값을 받아와서 comment 변수로 설정
let formData = new FormData();
formData.append("comment_give", comment); =>comment 변수를 comment_give 로 app.py에 보냄
fetch('/users', { method: "POST", body: formData }).then((res) => res.json()).then((data) => {
alert(data["msg"]); => petch로 데이터 보내는 부분
window.location.reload()
})
}
<app.py>
@app.route('/users', methods=['POST'])
def test_post():
comment_receive = request.form['comment_give'] =>html에서 comment_give 받아옴
doc = {
'comment' : comment_receive => 몽고 db에 들어갈 데이터 설정
}
db.users.insert_one(doc) =>몽고 db에 데이터 insert 해줌
return jsonify({'msg':'저장완료!'})
4. GET 연습 (데이터 받아옴)
<index.html>
$(document).ready(function () {
show_comment();
});
function show_comment() {
fetch('/users').then((res) => res.json()).then((data) => {
let rows = data['result']
rows.forEach((a) => {
let comment = a['comment']
let temp_html = `<div class="order-box"> =>
<p class="commentcomment">${comment}</p>
<button onclick="comment_delete('${comment}')" class="deleteform">삭제</button>
<h2></h2>
</div>`
$('#order-box').append(temp_html) =>몽고 db에서 데이터를 받아와서 html에 붙치는 부분
})
});
}
<app.py>
@app.route("/users", methods=["GET"]) #get의 fetch에서 users로 데이터가 날아옴
def users_get():
users_data = list(db.users.find({},{'_id':False}))
return jsonify({'result':users_data}) #'result':mars_data 로 다시 html로 내린다
5. DELETE 연습 (데이터 삭제)
<index.html>
function comment_delete(comment) { => GET에서 삭제버튼에 comment_delete 함수를 걸어뒀는데, 삭제버튼 클릭시 행동 설정
let delcomment = comment
let formData = new FormData();
formData.append("comment_del",delcomment); => 변수 설정후 delcomment를 comment_del로 보냄
fetch('/users', { method: "DELETE", body: formData }).then((res) => res.json()).then((data) => {
alert(data["msg"]);
window.location.reload()
})
}
<app.py>
@app.route('/users', methods=['DELETE'])
def users_del():
comment_receive = request.form['comment_del']
=>comment_del을 html에서 받아와서 comment_receive 로 함수설정
db.users.delete_one({'comment': comment_receive})
=>몽고 db에서 데이터 삭제
return jsonify({'msg': '삭제 완료!'})
'Knowledge > sparta web develope' 카테고리의 다른 글
[back end] 기술 면접 (0) | 2023.08.17 |
---|---|
project. 화성땅 공동구매 (1) | 2023.05.12 |
CSS, 깃허브 (0) | 2023.05.11 |
mongo DB , FLASK (0) | 2023.05.09 |
파이썬 기본 , 웹스크래핑(크롤링) (0) | 2023.05.09 |