#프론트엔드 #FrontEnd #웹개발 #HTML #CSS #Javascript #ajax #Python #MongoDB #Flask #Server
#EC2
웹 개발 5주차를 끝으로 마무리를 하였다.5주차는 생각보다 쉽게 진행되었다.기존에 만들어두었던 웹 페이지를 EC2로 연결하여 모든 사람들이 볼 수 있도록 배포하는 것이 주된 수업이었다.
근데 항상 어렵게 느끼는 부분은 새로운 툴을 받아서 환경 구축하는 부분이다.분명 난 똑같이 따라하고 있는 건데 왜 자꾸 새로운 오류가 뜨는 걸까.그래도 끝까지 결과물을 만들어내었고 별 다른 이상 없이 수업을 마쳤다.
오늘 한 수업은1. 서버 연결, DB, 클라이언트를 모두 연결하여 웹 페이지를 만드는 데, 새로운 기능을 몇가지 넣어서
버킷리스트 페이지를 만드는 수업
2. 4주차때 만들어두었던 웹 페이지를 AWS EC2를 사용하여 배포하는 것
이 2가지였다.
일단 1번의 코드들을 작성해본다.
이 버킷리스트엔 버킷리스트 작성, 완료하는 것까지만 배우는데, 나는 추가적으로 완료한 것을 제거하는 기능까지 넣었다.
(실수 없이 추가 기능 진행한 거 칭찬해~)
## 버킷리스트 클라이언트 스크립트 코드
## 제거용 코드 추가한 것 빼곤 기존의 수업과 같다.
<script>
$(document).ready(function () {
show_bucket();
});
function show_bucket() {
$.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>
<button onclick="delete_bucket(${num})" type="button" class="btn btn-outline-primary">제거</button>
<!--제거용 버튼 하나 더 만들어줬음-->
</li>`
}
$('#bucket-list').append(temp_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()
}
});
}
function done_bucket(num) {
$.ajax({
type: "POST",
url: "/bucket/done",
data: {num_give : num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
function delete_bucket(num) { // 삭제도 똑같이 done하고 같게 만들어준다.
$.ajax({
type: "POST",
url: "/bucket/delete",
data: {num_give : num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
</script>
## 서버 연결용 파이썬 코드
## 이것도 제거용 코드 하나 더 넣은 것 말곤 똑같다.
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('mongodb+srv://znuki:znuki@cluster0.mo5ena6.mongodb.net/?retryWrites=true&w=majority')
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']
bucket_list = list(db.bucket.find({}, {'_id': False}))
count = len(bucket_list) + 1
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/delete", methods=["POST"])
def bucket_delete():
num_receive = request.form['num_give']
db.bucket.delete_one({'num': int(num_receive)}) ## done이랑 똑같이 진행을 하지만 delete 경로를 추가해주었다.
return jsonify({'msg': '삭제 완료 !'})
@app.route("/bucket", methods=["GET"])
def bucket_get():
bucket_list = list(db.bucket.find({}, {'_id': False}))
return jsonify({'buckets': bucket_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)

이 후 만든 페이지를 가지고 EC2에 옮겨 모든 사람들에게 배포를 하는 일만 남았다.
순서는 다음과 같다.
Git bash 설치 (내가 산 ec2를 작동시킬 터미널) -> Filezilla 설치 (내가 만든 파일을 원격 컴퓨터로 옮기기위함)
-> ec2로 서버 만들기 -> git bash로 원격 우분투 내 폴더 만들기 -> Filezilla로 원격 컴퓨터로 실행할 파일 옮기기
-> git bash로 실행
밑에 코드는 터미널을 켰을 때, 개발 환경에 대한 설정을 위한 코드이다. 참고할 것!
# 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
# 강제종료하기
ps -ef | grep 'python app.py' | awk '{print $2}' | xargs kill
# 원격접속 종료해도 서버 계속 돌아가게 하는 것
nohup python app.py &
# 아마존 ec2 우분투 접속하기
ssh -i <비밀번호pem키 파일 경로> ubuntu@서버퍼블릭주소

5주동안 고생 많았다. 이제부터 진짜 개발 시작이다!
'Loopy's 개발일지' 카테고리의 다른 글
[SQL] 데이터 분석 연습 2주차 (0) | 2023.03.03 |
---|---|
[SQL] 데이터 분석 연습 1주차 (0) | 2023.02.23 |
웹 개발 4주차 (0) | 2023.01.11 |
웹 개발 3주차 (0) | 2023.01.10 |
웹 개발 2주차 (0) | 2023.01.08 |