SW/Flask
[Flask, MongoDB] 버킷리스트 프로젝트
ahhyeon
2023. 4. 3. 23:58
⭐ 문제분석
"완성작" 부터 보고 나만의 코드 작성하기
1. 기본 세팅
[서버 코드 - app.py]
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
# @app.route("/bucket", methods=["POST"])
# @app.route("/bucket/done", methods=["POST"])
# @app.route("/bucket", methods=["GET"])
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
[클라이언트 코드 - index.html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">
<title>인생 버킷리스트</title>
<style>
* {
font-family: 'Gowun Dodum', sans-serif;
}
.mypic {
width: 100%;
height: 200px;
background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://images.unsplash.com/photo-1601024445121-e5b82f020549?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1189&q=80');
background-position: center;
background-size: cover;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.mypic > h1 {
font-size: 30px;
}
.mybox {
width: 95%;
max-width: 700px;
padding: 20px;
box-shadow: 0px 0px 10px 0px lightblue;
margin: 20px auto;
}
.mybucket {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.mybucket > input {
width: 70%;
}
.mybox > li {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-bottom: 10px;
min-height: 48px;
}
.mybox > li > h2 {
max-width: 75%;
font-size: 20px;
font-weight: 500;
margin-right: auto;
margin-bottom: 0px;
}
.mybox > li > h2.done {
text-decoration:line-through
}
</style>
</head>
<body>
<div class="mypic">
<h1>나의 버킷리스트</h1>
</div>
<div class="mybox">
<div class="mybucket">
<input id="bucket" class="form-control" type="text" placeholder="이루고 싶은 것을 입력하세요">
<button onclick="save_bucket()" type="button" class="btn btn-outline-primary">기록하기</button>
</div>
</div>
</div>
<div class="mybox" id="bucketlist">
<li>
<h2>✅ 스위스 일주일 여행가기</h2>
<butto type="button" class="btn btn-outline-primary">완료!</button>
</li>
<li>
<h2>✅ 스위스 이글루 호텔에서 1박 보내기</h2>
<button type="button" class="btn btn-outline-primary">완료!</button>
</li>
<li>
<h2>✅ 스위스 인터라켄 패러글라이딩 하기</h2>
<button type="button" class="btn btn-outline-primary">완료!</button>
</li>
</div>
</body>
</html>
2. POST(기록)
➡️ API 만들고 사용 - 버킷리스트 기록 API
1) 요청 정보 : URL = /bucket, 요청방식 = POST
2) 클라이언트(ajax) → 서버(flask) : bucket
3) 서버(flask) → 클라이언트(ajax) : 메시지를 보냄(기록 완료!)
단, 서버에서 한가지 일을 추가적으로 더 해야 함
→ 번호를 만들어 함께 넣어주기. 그래야 업데이트가 가능하다.
2-1 서버 만들기
- bucket 정보를 받아서 저장
- 단, 버킷번호와 완료여부를 함께 넣어줄것!
# MongoDB 데이터베이스에서 문서의 수를 게산, 추가될 문서의 '_id' 값을 생성하는데 사용
db.bucket.fine({}, {'_id' : False})
num = len(count) + 1
# MongoDB의 find 함수를 사용하여 bucket 컬렉션에서 모든 문서를 가져옴
# 이 때, 첫번째 인자 {}는 검색쿼리를 지정하지 않고 모든 문서를 반환하도록 함
# 두번째 인자 {'_id' : False}는 '_id' 필드를 제외한 모든 필드를 반환하도록 지정
[ POST 1️⃣ ]
2-1-1. 변수 설정
@app.route("/bucket", methods=["POST"])
def bucket_post():
bucket_receive = request.form['bucket_give']
2-1-2. Mongo 코드 붙여 넣어주기
from pymongo import MongoClient
client = MongoClient('mongodb://test:ahhyeon@ac-n9ccs4r-shard-00-00.arcitzi.mongodb.net:27017,ac-n9ccs4r-shard-00-01.arcitzi.mongodb.net:27017,ac-n9ccs4r-shard-00-02.arcitzi.mongodb.net:27017/?ssl=true&replicaSet=atlas-8qe01r-shard-0&authSource=admin&retryWrites=true&w=majority')
db = client.dbtest
2-1-3. DB에 데이터 저장
doc = {
'num' : count, # 버킷리스트 번호
'bucket' : bucket_receive,
'done':0 # 완료(1), 미완료(0)
}
2-1-4. 버킷리스트 전체 불러와서 count에 번호 저장
count = len(list(db.bucket.find({},{'_id':False})))
[서버 코드 - app.py]
@app.route("/bucket", methods=["POST"])
def bucket_post():
bucket_receive = request.form["bucket_give"] # 뼈대에서 수정 >>> 1. 변수설정
# 추가
# [POST] 4. 버킷리스트 전체 불러와서 count에 번호 저장!
count = len(list(db.bucket.find({},{'_id':False})))
# [POST] 2. Mongo 코드 붙여넣어주기
# [POST] 3. DB에 데이터 저장
doc = {
'num':count,
'bucket': bucket_receive,
'done':0
}
db.bucket.insert_one(doc) # 추가
return jsonify({'msg':'등록 완료!'})
2-2. 클라이언트 만들기
- bucket 정보만 보내주기
2-2-1. 입력받은 데이터를 변수에 저장
function save_bucket(){
let bucket = $('#bucket').val()
2-2-2. 서버로 보내주기
$.ajax({
data: {bucket_give:bucket},
});
2-2-3. 새로고침 코드 추가
$.ajax({
window.location.reload()
});
[클라이언트코드 - index.html]
function save_bucket(){
let bucket = $('#bucket').val() # 추가
$.ajax({
type: "POST",
url: "/bucket",
data: {bucket_give:bucket}, # 수정
success: function (response) {
alert(response["msg"])
window.location.reload() # 추가
}
});
}
2-3. MongoDB Atlas 실행
3. GET (보여주기)
➡️ API 만들고 사용 - 버킷리스트 조회 API
1) 요청 정보 : URL = /bucket, 요청 방식 = GET
2) 클라이언트(ajax) → 서버(flask) : 없음
3) 서버(flask) → 클라이언트(ajax) : 전체 버킷리스트를 보여주기
[ GET ]
3-1 서버 만들기
- 받을 것 없이 buckets에 주문정보 담기
3-1-1. 서버에서 모든 데이터 가져오기
@app.route("/bucket", methods=["GET"])
def bucket_get():
ucket_list = list(db.bucket.find({}, {'_id':False}))
3-1-2. buckets_list에 담아서 클라이언트로 보내주기
return jsonify({'buckets':bucket_list})
[서버코드 - app.py]
@app.route("/bucket", methods=["GET"])
def bucket_get():
buckets_list = list(db.bucket.find({}, {'_id':False})) # 추가
return jsonify({'msg' : 'GET 연결 완료!'})
3-2 클라이언트 만들기
- 응답을 잘 받아서 for 문으로 붙여주기
3-2-1. 사전형 데이터를 변수 각각에 할당
function show_bucket() {
$('#bucket-list').empty()
$.ajax({
type: "GET",
url: "/bucket",
data: {},
success: function(response) {
// [GET] 사전형 데이터를 변수 각각에 할당
// for문 추가
let rows = response['buckets']
for (let i = 0; i < rows.length; i++) {
let bucket = rows[i]['bucket']
let num = rows[i]['num']
let done = rows[i]['done']
3-2-2. done에 따라서 li의 형태 바꿔주기
let temp_html = ``
if(done == 0) {
temp_html = `<li>
<h2>✅ ${bucket}</h2>
<button onclick="done_bucket(${num})" type="button" class="btn btn-outline-primary">완료!</button>
</li>`
} else {
temp_html = `<li>
<h2 class="done">✅ ${bucket}</h2>
</li>`
}
3-2-3. 기존의 데이터에 붙여주기
$('#bucketlist').append(temp_html)
[클라이언트코드 - index.html]
$(document).ready(function () {
show_bucket();
});
function show_bucket() {
$('#bucket-list').empty()
$.ajax({
type: "GET",
url: "/bucket",
data: {},
success: function(response) {
// for문 추가
let rows = response['buckets']
for (let i = 0; i < rows.length; i++) {
let bucket = rows[i]['bucket']
let num = rows[i]['num']
let done = rows[i]['done']
let temp_html = ``
if(done == 0) {
temp_html = `<li>
<h2>✅ ${bucket}</h2>
<button onclick="done_bucket(${num})" type="button" class="btn btn-outline-primary">완료!</button>
</li>`
} else {
temp_html = `<li>
<h2 class="done">✅ ${bucket}</h2>
</li>`
}
$('#bucketlist').append(temp_html)
}
}
});
}
3-3. 실행
4. POST(완료하기)
➡️ API 만들고 사용 - 버킷리스트 완료 API
1) 요청 정보 : URL = /bucket/done, 요청 방식 = POST
2) 클라이언트(ajax) → 서버(flask) : num(버킷 넘버)
3) 서버(flask) → 클라이언트(ajax) : 메세지를 보냄(버킷 완료!)
[ POST 2️⃣]
4-1 서버 만들기
- 버킷번호(변수)를 받아서, 업데이트하기
- 단, num_receive는 문자열로 들어오기 때문, 숫자로 바꿔줄것!
@app.route("/bucket/done", methods=["POST"])
def bucket_done():
num_receive = request.form['num_give']
# 클라이언트에서 서버로 숫자를 넘겨줘도, 서버는 문자로 받음 >>> 따로 변환필요!
db.bucket.update_one({'num': int(num_receive)}, {'$set': {'done': 1}})
return jsonify({'msg': '버킷 완료!'})
4-2 클라이언트 만들기
- 버킷넘버 보여주기
- 버킷넘버는? HTML이 만들어질 때 적힘!
- 새로고침 코드추가
// 버킷 넘버
function done_bucket(num) { // 새로운 줄이 생성될 때, 줄의 번호와 같이 생성됨!
$.ajax({
type: "POST",
url: "/bucket/done",
// num을 바로 넘겨주기
data: {'num_give' : num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
4-3. 실행
✔️ DB에 데이터 저장 후 확인!
- done : 0 ➡️ 미완료
- done : 1 ➡️ 완료
5. 최종코드
[서버 코드 - app.py]
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
import certifi
ca = certifi.where();
from pymongo import MongoClient
client = MongoClient('mongodb://test:ahhyeon@ac-n9ccs4r-shard-00-00.arcitzi.mongodb.net:27017,ac-n9ccs4r-shard-00-01.arcitzi.mongodb.net:27017,ac-n9ccs4r-shard-00-02.arcitzi.mongodb.net:27017/?ssl=true&replicaSet=atlas-8qe01r-shard-0&authSource=admin&retryWrites=true&w=majority')
db = client.dbtest
@app.route('/')
def home():
return render_template('index.html')
@app.route("/bucket", methods=["POST"])
def bucket_post():
bucket_receive = request.form['bucket_give']
count = len(list(db.bucket.find({},{'_id':False})))
doc = {
'num' : count,
'bucket' : bucket_receive,
'done':0
}
db.bucket.insert_one(doc)
return jsonify({'msg': '등록 완료!'})
@app.route("/bucket/done", methods=["POST"])
def bucket_done():
num_receive = request.form['num_give']
db.bucket.update_one({'num': int(num_receive)}, {'$set': {'done': 1}})
return jsonify({'msg': '버킷 완료!'})
@app.route("/bucket", methods=["GET"])
def bucket_get():
buckets_list = list(db.bucket.find({}, {'_id':False}))
return jsonify({'buckets':buckets_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
[클라이언트코드 - index.html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">
<title>인생 버킷리스트</title>
<style>
* {
font-family: 'Gowun Dodum', sans-serif;
}
.mypic {
width: 100%;
height: 200px;
background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://images.unsplash.com/photo-1601024445121-e5b82f020549?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1189&q=80');
background-position: center;
background-size: cover;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.mypic > h1 {
font-size: 30px;
}
.mybox {
width: 95%;
max-width: 700px;
padding: 20px;
box-shadow: 0px 0px 10px 0px lightblue;
margin: 20px auto;
}
.mybucket {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.mybucket > input {
width: 70%;
}
.mybox > li {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-bottom: 10px;
min-height: 48px;
}
.mybox > li > h2 {
max-width: 75%;
font-size: 20px;
font-weight: 500;
margin-right: auto;
margin-bottom: 0px;
}
.mybox > li > h2.done {
text-decoration:line-through
}
</style>
<script>
$(document).ready(function () {
show_bucket();
});
function show_bucket() {
$('#bucket-list').empty()
$.ajax({
type: "GET",
url: "/bucket",
data: {},
success: function(response) {
// for문 추가
let rows = response['buckets']
for (let i = 0; i < rows.length; i++) {
let bucket = rows[i]['bucket']
let num = rows[i]['num']
let done = rows[i]['done']
// done에 따라서 li의 형태 바꿔주기
let temp_html = ``
if(done == 0) {
temp_html = `<li>
<h2>✅ ${bucket}</h2>
<button onclick="done_bucket(${num})" type="button" class="btn btn-outline-primary">완료!</button>
</li>`
} else {
temp_html = `<li>
<h2 class="done">✅ ${bucket}</h2>
</li>`
}
// 기존의 데이터에 붙여주기
$('#bucketlist').append(temp_html)
}
}
});
}
function save_bucket(){
// [POST] 5. 입력받은 데이터를 변수에 저장
let bucket = $('#bucket').val()
$.ajax({
type: "POST",
url: "/bucket",
data: {bucket_give:bucket}, // [POST] 6. 서버로 보내줌
success: function (response) {
alert(response["msg"])
window.location.reload() // [POST] 7. 새로고침
}
});
}
function done_bucket(num){
$.ajax({
type: "POST",
url: "/bucket/done",
data: {'num_give':num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
</script>
</head>
<body>
<div class="mypic">
<h1>나의 버킷리스트</h1>
</div>
<div class="mybox">
<div class="mybucket">
<input id="bucket" class="form-control" type="text" placeholder="이루고 싶은 것을 입력하세요">
<button onclick="save_bucket()" type="button" class="btn btn-outline-primary">기록하기</button>
</div>
</div>
</div>
<div class="mybox" id="bucketlist">
<li>
<h2>✅ 스위스 일주일 여행가기</h2>
<button onclick="done_bucket(5)" type="button" class="btn btn-outline-primary">완료!</button>
</li>
<li>
<h2 class="done">✅ 스위스 이글루 호텔에서 1박 보내기</h2>
</li>
<li>
<h2>✅ 스위스 인터라켄 패러글라이딩 하기</h2>
<button type="button" class="btn btn-outline-primary">완료!</button>
</li>
</div>
</body>
</html>