728x90
320x100
1. 배운 것
저번 주차에 이어서 두 가지 미니프로젝트로 flask, 백엔드 연습하기! 그리고 배포까지 해 보는 마지막 주차~~
AWS부터 가입하고 시작하는 5주차이다. 뭐 이건 모르는 사람은 없을 거다.. 엄청 유명하니까!
2. 버킷리스트 만들기
이제 슬슬 눈 감고도 하겠는걸.. 갈수록 간단해지는 포스팅과 함께 ^-^
준비하기
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>
</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>
<button onclick="done_bucket(5)" type="button" class="btn btn-outline-primary">완료!</button>
</li>
<li>
<h2 class="done">✅ 호주에서 스카이다이빙 하기</h2>
</li>
<li>
<h2>✅ 호주에서 스카이다이빙 하기</h2>
<button type="button" class="btn btn-outline-primary">완료!</button>
</li>
</div>
</body>
</html>
서버 GET, POST 뼈대 (Python - flask)
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"])
def bucket_post():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg': 'POST 연결 완료!'})
@app.route("/bucket", methods=["GET"])
def bucket_get():
return jsonify({'msg': 'GET 연결 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
클라이언트 GET, POST 뼈대 (JavaScript)
$(document).ready(function () {
show_bucket();
});
//get
function show_bucket() { // 로딩이 완료되면 show_bucket()을 부른다
fetch('/bucket') // api에 요청 전달
.then(res => res.json())
.then(data => { // 받아온 걸 data에 저장
console.log(data)
alert(data["msg"]);
})
}
// post
function save_bucket() {
let formData = new FormData();
formData.append("bucket_give", bucket); //데이터 담아서
fetch('/bucket', { // /bucket에 post로 보내기
method: "POST",
body: formData,
})
.then((response) => response.json()) //받아오기
.then((data) => {
alert(data["msg"]);
window.location.reload();
});
}
POST - Creat
서버 - Python
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
# DB연결
from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.q4j284y.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta
@app.route("/bucket", methods=["POST"])
def bucket_post():
bucket_receive = request.form['bucket_give']
# DB에 저장
doc = {
'bucket' : bucket_receive
}
db.myBucket.insert_one(doc)
return jsonify({'msg': '저장 완료!'})
클라이언트 - JavaScript
// post
function save_bucket() {
// 사용자 입력값 읽기
let bucket = $('#bucket').val() // input id="bucket" type="text"
let formData = new FormData();
formData.append("bucket_give", "bucket"); //데이터 담아서
fetch('/bucket', { // /bucket에 post로 보내기
method: "POST",
body: formData,
})
.then((response) => response.json()) //받아오기
.then((data) => {
alert(data["msg"]);
window.location.reload(); // refreash
});
}
GET - Read
서버
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
@app.route("/bucket", methods=["GET"])
def bucket_get():
all_myBucket = list(db.myBucket.find({},{'_id': False})) # 데이터 DB에서 꺼내오기
return jsonify({'result':all_myBucket}) #데이터 클라이언트로 보내기
클라이언트
$(document).ready(function () {
show_bucket();
});
//get
function show_bucket() { // 로딩이 완료되면 show_bucket()을 부른다
fetch('/bucket') // api에 요청 전달
.then(res => res.json())
.then(data => { // 받아온 걸 data에 저장
let rows = data['result']
$('#bucket-list').empty()
rows.forEach((a) => {
let bucket = a['bucket']
let temp_html = `
<li>
<h2>✅ ${bucket}</h2>
<button type="button" class="btn btn-outline-primary">완료!</button>
</li>
`
$('#bucket-list').append(temp_html)
});
})
}
3. 팬명록 만들기
날씨 API 가져오기
$(document).ready(function () {
set_temp();
show_comment();
});
function set_temp() { // 기온
fetch("http://spartacodingclub.shop/sparta_api/weather/seoul") //강의에서 제공해준 날씨 API
.then((res) => res.json())
.then((data) => {
let temp = data['temp'] //온도
$('#temp').text(temp) // <span id="temp">
});
}
응원 등록하기 (POST)
사용자 입력 데이터 : 닉네임(name) , 응원댓글(comment)
서버
@app.route("/guestbook", methods=["POST"])
def guestbook_post():
name_receive = request.form['name_give']
comment_receive = request.form['comment_give']
#DB저장
doc = {
'name' : name_receive,
'comment' : comment_receive
}
db.fan.insert_one(doc)
comment_receive = request.form['comment_give']
return jsonify({'msg': '등록되었습니다.'})
클라이언트
// post
function save_comment() {
let name = $('#name').val()
let comment = $('#comment').val()
let formData = new FormData();
formData.append("name_give", name); //<input type="text" class="form-control" id="name"
formData.append("comment_give", comment); //<textarea class="form-control" placeholder="Leave a comment here" id="comment"
fetch('/guestbook', {
method: "POST",
body: formData,
})
.then((res) => res.json())
.then((data) => {
alert(data["msg"]);
window.location.reload(); // refreash
});
}
응원 보여주기 - GET
가져올 데이터 : 닉네임(name) , 응원댓글(comment)
서버
@app.route("/guestbook", methods=["GET"])
def guestbook_get():
all_comments = list(db.fan.find({},{'_id':False}))
return jsonify({
'result' : all_comments
})
클라이언트
// get
function show_comment() {
fetch('/guestbook')
.then((res) => res.json())
.then((data) => {
let rows = data['result']
$('#comment-list').empty()
rows.forEach((a) => {
let name = a['name'];
let comment = a['comment'];
let temp_html = `
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment}</p>
<footer class="blockquote-footer">${name}</footer>
</blockquote>
</div>
</div>
`
$('#comment-list').append(temp_html)
});
})
}
og 태그 넣기
<meta property="og:title" content="내 사이트의 제목" />
<meta property="og:description" content="보고 있는 페이지의 내용 요약" />
<meta property="og:image" content="이미지URL" />
전체 코드
<!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" />
<meta property="og:title" content="팬명록" />
<meta property="og:description" content="응원을 남겨주세요❤️" />
<meta property="og:image" content="https://pbs.twimg.com/media/FogwklPaUAEPu-q?format=jpg&name=4096x4096" />
<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>
<title>IU 팬명록</title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap"
rel="stylesheet" />
<style>
* {
font-family: "Noto Serif KR", serif;
}
body {
background: linear-gradient(rgba(255, 255, 255, 0), rgba(255, 255, 255, 0)), url("https://pbs.twimg.com/media/FogwklPaUAEPu-q?format=jpg&name=4096x4096");
background-repeat: no-repeat;
background-attachment: fixed !important;
background-size: 100vmax !important;
background-position: center 40% !important;
color: #fff;
}
.myTitle {
width: 100%;
height: 600px;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.content_wrapper {
width: 100vw;
position: relative;
padding: 50px;
background-color: #fff;
opacity: 0;
}
.mypost {
width: 95%;
max-width: 500px;
margin: 20px auto 20px auto;
color: #000000;
box-shadow: 0px 0px 3px 0px black;
padding: 20px;
}
.mypost>button {
margin-top: 15px;
}
.mycards {
width: 95%;
max-width: 500px;
margin: auto;
color: #000000;
}
.mycards>.card {
margin-top: 10px;
margin-bottom: 10px;
}
</style>
<script>
$(document).ready(function () {
set_temp();
show_comment();
});
function set_temp() { // 기온
fetch("http://spartacodingclub.shop/sparta_api/weather/seoul")
.then((res) => res.json())
.then((data) => {
let temp = data['temp'] //온도
$('#temp').text(temp) // <span id="temp">
});
}
// post
function save_comment() {
let name = $('#name').val()
let comment = $('#comment').val()
let formData = new FormData();
formData.append("name_give", name);
formData.append("comment_give", comment);
fetch('/guestbook', {
method: "POST",
body: formData,
})
.then((res) => res.json())
.then((data) => {
alert(data["msg"]);
window.location.reload(); // refreash
});
}
// get
function show_comment() {
fetch('/guestbook')
.then((res) => res.json())
.then((data) => {
let rows = data['result']
$('#comment-list').empty()
rows.forEach((a) => {
let name = a['name'];
let comment = a['comment'];
let temp_html = `
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment}</p>
<footer class="blockquote-footer">${name}</footer>
</blockquote>
</div>
</div>
`
$('#comment-list').append(temp_html)
});
})
}
$(document).ready(function () {
/* 1 */
$(window).scroll(function () {
/* 2 */
$('.content_wrapper').each(function (i) {
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* 3 */
if (bottom_of_window > bottom_of_object / 2) {
$(this).animate({ 'opacity': '1' }, 1500);
}
});
});
});
</script>
</head>
<body>
<div class="myTitle">
<h1>IU(아이유) 팬명록</h1>
<p>현재온도: <span id="temp">36</span>도</p>
</div>
<div class="content_wrapper">
<div class="mypost">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="name" placeholder="url" />
<label for="floatingInput">닉네임</label>
</div>
<div class="form-floating">
<textarea class="form-control" placeholder="Leave a comment here" id="comment"
style="height: 100px"></textarea>
<label for="floatingTextarea2">응원댓글</label>
</div>
<button onclick="save_comment()" type="button" class="btn btn-dark">
댓글 남기기
</button>
</div>
<div class="mycards" id="comment-list">
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p></p>
<footer class="blockquote-footer"></footer>
</blockquote>
</div>
</div>
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p></p>
<footer class="blockquote-footer"></footer>
</blockquote>
</div>
</div>
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p></p>
<footer class="blockquote-footer"></footer>
</blockquote>
</div>
</div>
</div>
</div>
</body>
</html>
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
# DB연결
from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.q4j284y.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/guestbook", methods=["POST"])
def guestbook_post():
name_receive = request.form['name_give']
comment_receive = request.form['comment_give']
#DB저장
doc = {
'name' : name_receive,
'comment' : comment_receive
}
db.fan.insert_one(doc)
comment_receive = request.form['comment_give']
return jsonify({'msg': '등록되었습니다.'})
@app.route("/guestbook", methods=["GET"])
def guestbook_get():
all_comments = list(db.fan.find({},{'_id':False}))
return jsonify({
'result' : all_comments
})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
배포하기
AWS Elastic Beanstalk으로 배포하기.
# - 터미널 준비하기 -
mkdir deploy
cp app.py deploy/application.py
cp -r templates deploy/templates
pip freeze > deploy/requirements.txt
cd deploy
# - application.py 세팅하기 -
application = app = Flask(__name__)
app.run()
# - 패키지 설치하기 -
pip install awsebcli
# - 보안 자격증명 -
eb init
# - 초기 설정 -
eb create myweb
# - 코드 수정 & 업데이트 -
eb deploy myweb
결과물
http://myweb.eba-2mjynp79.ap-northeast-2.elasticbeanstalk.com/
300x250
반응형
GitHub 댓글