단! 서버에서 한 가지 일을 더 해야한다.
→ 번호를 만들어 함께 넣어주는 것. 그래야 업데이트가 가능함
count = list(db.bucket.find({},{'_id':False}))
num = len(count) + 1
vs
count = db.bucket.find({},{'_id':False}).count()
num = count + 1
@app.route("/bucket", methods=["POST"])
def bucket_post():
bucket_receive = request.form["bucket_give"]
count = db.bucket.find({},{'_id':False}).count()
num = count + 1
doc = {
'num':num,
'bucket': bucket_receive,
'done':0
}
db.bucket.insert_one(doc)
return jsonify({'msg':'등록 완료!'})
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()
}
});
}
@app.route("/bucket", methods=["GET"])
def bucket_get():
buckets_list = list(db.bucket.find({},{'_id':False}))
return jsonify({'buckets':buckets_list})
function show_bucket(){
$('#bucket-list').empty()
$.ajax({
type: "GET",
url: "/bucket",
data: {},
success: function (response) {
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>`
}
$('#bucket-list').append(temp_html)
}
}
});
}
@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': '버킷 완료!'})

function done_bucket(num){
$.ajax({
type: "POST",
url: "/bucket/done",
data: {'num_give':num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}

(팁: 리눅스 커널에서 윗화살표를 누르면 바로 전에 썼던 명령어가 나온다)
ls: 내 위치의 모든 파일을 보여준다.
pwd: 내 위치(폴더의 경로)를 알려준다.
mkdir: 내 위치 아래에 폴더를 하나 만든다.
cd [갈 곳]: 나를 [갈 곳] 폴더로 이동시킨다.
cd .. : 나를 상위 폴더로 이동시킨다.
cp -r [복사할 것] [붙여넣기 할 것]: 복사 붙여넣기
rm -rf [지울 것]: 지우기
sudo [실행 할 명령어]: 명령어를 관리자 권한으로 실행한다.
sudo su: 관리가 권한으로 들어간다. (나올때는 exit으로 나옴)
# python3 -> python
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
# pip3 -> pip
sudo apt-get update
sudo apt-get install -y python3-pip
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1
# port forwarding
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 5000

# 아래의 명령어로 실행하면 된다
nohup python app.py &ps -ef | grep 'python app.py' | awk '{print $2}' | xargs kill
<meta property="og:title" content="New Jeans 팬명록" />
<meta property="og:description" content="응원 한마디 남기고 가세요!" />
<meta property="og:image" content="https://img.wowtv.co.kr/wowtv_news/dnrs/20220725/2022072516132608449d3244b4fed182172185139.jpg" />
과제 전체 코드
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.xsj14ws.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/homework", methods=["POST"])
def homework_post():
name_receive = request.form['name_give']
comment_receive = request.form['comment_give']
doc = {
'name': name_receive,
'comment': comment_receive
}
db.homework.insert_one(doc)
return jsonify({'msg':'응원 완료!'})
@app.route("/homework", methods=["GET"])
def homework_get():
comment_list = list(db.homework.find({}, {'_id': False}))
return jsonify({'comments':comment_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
<!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="New Jeans 팬명록" />
<meta property="og:description" content="응원 한마디 남기고 가세요!" />
<meta property="og:image" content="https://img.wowtv.co.kr/wowtv_news/dnrs/20220725/2022072516132608449d3244b4fed182172185139.jpg" />
<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>New Jeans - 팬명록</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;
}
.mypic {
width: 100%;
height: 300px;
background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://img.wowtv.co.kr/wowtv_news/dnrs/20220725/2022072516132608449d3244b4fed182172185139.jpg');
background-position: top;
background-size: revert;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.mypost {
width: 95%;
max-width: 500px;
margin: 20px auto 20px auto;
box-shadow: 0 0 3px 0 black;
padding: 20px;
}
.mypost > button {
margin-top: 10px;
}
.mycards {
width: 95%;
max-width: 500px;
margin: 20px auto 0 auto;
}
.mycards > card {
margin-top: 10px;
margin-bottom: 10px;
}
</style>
<script>
$('#comment-list').empty()
$(document).ready(function(){
set_temp()
show_comment()
});
function set_temp(){
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function (response) {
$('#temp').text(response['temp'])
}
})
}
function save_comment(){
let name = $('#name').val()
let comment = $('#comment').val()
$.ajax({
type: 'POST',
url: '/homework',
data: {'name_give':name, 'comment_give':comment},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
function show_comment(){
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response['comments']
for (let i = 0; i < rows.length; i++) {
let name = rows[i]['name']
let comment = rows[i]['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)
}
}
});
}
</script>
</head>
<body>
<div class="mypic">
<h1>New Jeans 팬명록</h1>
<p>현재기온: <span id="temp">36</span>도</p>
</div>
<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>
</body>
</html>
: 1주차~5주차까지 두번을 완강을 했지만 아직까지도 많이 부족한 부분들이 많고 이해가 어려운 부분들이 있어서 앞으로 다른 프로젝트를 개인적으로 만들게 되든 팀으로 프로젝트를 만들게 되든 최대한 많은 횟수로 포트폴리오를 만들어보는 것이 정말 중요할 것 같다. 지금 당장은 어려운 부분들이 많지만 당연한 것이라 생각하고 너무 조급하게 생각하지 않고 내가 할 수 있는 만큼 꾸준히 공부하고 기술을 알아나간다면 분명히 빠른 시간 내에 많은 걸 이해할 수 있는 개발자가 될 수 있다고 믿는다. 화이팅!!!!!!!!