AWS : 인터넷에 웹사이트를 배포하기 위해 사용하는 서비스
1. 위 사진과 같이 세팅
2. flask 라이브러리를 사용하기 위해 가상환경을 설정해준다.
3. flask, pymongo, dnspython 설치
# POST 연습하기
1. 데이터 명세
2. 클라이언트와 서버 연결 확인하기
3. 서버부터 만들기
4. 클라이언트 만들기
5. 완성 확인하기
* 사용자가 입력한 데이터를 프론트엔드에서 받아서 백엔드로 넘겨주고 데이터를 db에 저장하기
<!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() {
fetch('/bucket').then(res => res.json()).then(data => {
console.log(data)
alert(data["msg"]);
})
}
function save_bucket() {
let bucket = $('#bucket').val();
let formData = new FormData();
formData.append("bucket_give", bucket);
fetch('/bucket', {method: "POST",body: formData,}).then((response) => response.json()).then((data) => {
alert(data["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 class="mybox" id="bucket-list">
<li>
<h2>✅ 호주에서 스카이다이빙 하기</h2>
</li>
</div>
</body>
</html>
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb://sparta:test@ac-6joxava-shard-00-00.oag1hfc.mongodb.net:27017,ac-6joxava-shard-00-01.oag1hfc.mongodb.net:27017,ac-6joxava-shard-00-02.oag1hfc.mongodb.net:27017/?ssl=true&replicaSet=atlas-di6vv2-shard-0&authSource=admin&retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/bucket", methods=["POST"])
def bucket_post():
bucket_receive = request.form['bucket_give']
doc = {
'bucket': bucket_receive
}
db.bucket.insert_one(doc)
return jsonify({'msg': '저장 완료!'})
@app.route("/bucket", methods=["GET"])
def bucket_get():
return jsonify({'msg': 'GET 연결 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5001, debug=True)
기록하기 버튼을 누르면 save_bucket() 함수가 실행된다
이루고 싶은 것을 입력하는 input 데이터를 jQuery를 이용해서 변수 bucket에 할당했다. formData.append("bucket_give", bucket) 를 통해 백엔드로 유저가 입력한 데이터를 보내줬다.
백엔드에서 bucket_give를 받아 bucket_receive에 할당했고 doc 에 딕셔너리 형태로 담아 insert_one을 사용해 db에 담아줬다.
그리고 다시 프론트엔드로 'msg' : '저장 완료!' 가 return 되고
alert(data["msg"]) 를 통해 저장 완료 alert가 뜨게 되고 window.location.reload()는 웹페이지를 자동으로 새로고침 해주는 코드이다
db에 입력한 데이터가 정상적으로 저장된 것도 볼 수 있다. 여기까지하면 POST 방식으로 db 저장이 완료된다.
# GET 연습하기
* db에 저장한 데이터를 몽땅 가져와서 프론트로 내려주기
db에 저장된 데이터를 모두 가져와 all_buckets에 할당 후 딕셔너리 형태로 'result' : all_buckets 를 프론트로 보내준다.
show_bucket 함수 내에서 받게 되고 data['result'] 즉, all_buckets 데이터를 row에 할당한 후 forEach 반복문을 통해 db에 저장된 데이터를 하나씩 꺼내서 console을 찍어보았다.
새로고침하고 개발자도구의 console 창을 보면 이와 같이 db에 있는 데이터가 하나씩 출력이 된다.
입력한 버킷리스트가 html로 부분 부분을 temp_html에 할당하고, 버킷리스트 html이 추가되는 부분의 id인 bucket-list을 지정하여 append 를 사용해 html로 붙여준다.
'코딩 > 웹개발 종합반' 카테고리의 다른 글
웹개발 종합반 5주차(서버 배포) (0) | 2023.03.23 |
---|---|
웹개발 종합반 5주차(팬명록) (0) | 2023.03.22 |
웹개발 종합반 4주차(스파르타 피디아) (0) | 2023.03.22 |
웹개발 종합반 4주차(화성땅 공동구매) (0) | 2023.03.21 |
웹개발 종합반 4주차 (0) | 2023.03.21 |
댓글