- FILEZILLA 설치 및 가비아 가입하기
- [버킷리스트] - 프로젝트 세팅
- [버킷리스트] - 뼈대 준비하기
- [버킷리스트] - POST연습(기록하기)
- [버킷리스트] - GET연습(보여주기)
- [버킷리스트] - POST연습(완료하기)
- 내 프로젝트를 서버에 올리기
- AWS 서버 구매하기
- 서버 세팅하기
- FLASK 서버를 실행해보기
- nohup 설정하기
- 도메인 연결하기
- og 태그
- 5주차 끝 & 숙제
👉 오늘은 아직 익숙해지지 않았을 당신을 위해! 같은 난이도의 유사한 프로젝트를 진행하며 머릿속의 퍼즐을 맞출 예정입니다.
그리고 드디어! 친구들도 볼수록 배포하는 일까지, 한번 쭉-해보겠습니다!
[https://filezilla-project.org/download.php](https://filezilla-project.org/download.php)
[https://www.gabia.com](https://www.gabia.com/)
🚨 기억하기 - 무통장입금(가상계좌)으로 결제하시기를 추천드립니다!
💡 원하는 도메인을 구매하세요!
bumkyulee.shop
은 제가 구매했으니, 당연히 여러분은 안 되겠죠? 🤣
👉 결제 기간을 1년으로 맞춰주세요! 그래야 500원 찬스!
👉 1,000원 이하는 카드 결제가 안된대요~!
🔥 sparta → projects → bucket 폴더를 열고 시작!
bucket
: "버킷리스트" 관련 코드를 작성합니다.index.html
, 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"])
def bucket_post():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg': 'POST(기록) 연결 완료!'})
@app.route("/bucket/done", methods=["POST"])
def bucket_done():
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)
<!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(){
$.ajax({
type: "GET",
url: "/bucket",
data: {},
success: function (response) {
alert(response["msg"])
}
});
}
function save_bucket(){
$.ajax({
type: "POST",
url: "/bucket",
data: {sameple_give:'데이터전송'},
success: function (response) {
alert(response["msg"])
}
});
}
function done_bucket(num){
$.ajax({
type: "POST",
url: "/bucket/done",
data: {sameple_give:'데이터전송'},
success: function (response) {
alert(response["msg"])
}
});
}
</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>
https://cloud.mongodb.com/
/bucket
, 요청 방식 = POST
클라(ajax) → 서버(flask) : bucket
서버(flask) → 클라(ajax) : 메시지를 보냄 (기록 완료!)
단! 서버에서 한 가지 일을 더 해야합니다.
→ 번호를 만들어 함께 넣어주는 것. 그래야 업데이트가 가능하겠죠!
app.py
]@app.route("/bucket", methods=["POST"])
def bucket_post():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg': 'POST(기록) 연결 완료!'})
[클라이언트 코드 - index.html
]function save_bucket(){
$.ajax({
type: "POST",
url: "/bucket",
data: {sample_give:'데이터전송'},
success: function (response) {
alert(response["msg"])
}
});
}
<button onclick="save_bucket()" type="button" class="btn btn-outline-primary">기록하기</button>
bucket
정보를 받아서, 저장하면 되겠죠?
단, 한 가지 일이 더 있답니다. → 네, 버킷 번호 와 완료여부 를 함께 넣어주는 것!
우리가 일전에 만들어둔 [dbtest.py](http://dbtest.py)
파일도 불러와봅시다!
재밌는 사실! 아래 코드도 살펴봅시다.
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':'등록 완료!'})
쉬워요! bucket
정보만 보내주면 되겠죠?
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()
}
});
}
1) API 만들고 사용하기 - 버킷리스트 조회 API (Read→ GET)
👉 1. 요청 정보 : URL= /bucket
, 요청 방식 = GET
app.py
]@app.route("/bucket", methods=["GET"])
def bucket_get():
return jsonify({'msg': 'GET 연결 완료!'})
[클라이언트 코드 - index.html
]$(document).ready(function () {
show_bucket();
});
function show_bucket(){
$.ajax({
type: "GET",
url: "/bucket",
data: {},
success: function (response) {
alert(response["msg"])
}
});
}
받을 것 없이 buckets
에 주문정보를 담아서 내려주기만 하면 됩니다!
@app.route("/bucket", methods=["GET"])
def bucket_get():
buckets_list = list(db.bucket.find({},{'_id':False}))
return jsonify({'buckets':buckets_list})
응답을 잘 받아서 for 문으로! 붙여주면 끝이겠죠!
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>
<buttontoken interpolation">${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)
}
}
});
}
/bucket/done
, 요청 방식 = POST
num
(버킷 넘버)app.py
]@app.route("/bucket/done", methods=["POST"])
def bucket_done():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg': 'POST(완료) 연결 완료!'})
[클라이언트 코드 - index.html
]function done_bucket(num){
$.ajax({
type: "POST",
url: "/bucket/done",
data: {sameple_give:'데이터전송'},
success: function (response) {
alert(response["msg"])
}
});
}
<button onclick="done_bucket(5)" type="button" class="btn btn-outline-primary">완료!</button>
버킷 번호
를 받아서, 업데이트 하면 됩니다!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': '버킷 완료!'})
function done_bucket(num){
$.ajax({
type: "POST",
url: "/bucket/done",
data: {'num_give':num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
👉 이제 내가 만든 프로젝트를 배포해봅니다. 배포는 누구나 내 서비스를 사용할 수 있게 하기 위해서 작업들이에요. 웹 서비스를 런칭하는 거죠!
[https://ap-northeast-2.console.aws.amazon.com/ec2/v2/home?region=ap-northeast-2](https://ap-northeast-2.console.aws.amazon.com/ec2/v2/home?region=ap-northeast-2#Instances:sort=instanceId)
sudo chmod 400 받은키페어를끌어다놓기
ssh -i 받은키페어를끌어다놓기 ubuntu@AWS에적힌내아이피
예) 아래와 비슷한 생김새!
ssh -i /path/my-key-pair.pem ubuntu@13.125.250.20
ssh -i 받은키페어를끌어다놓기 ubuntu@AWS에적힌내아이피
예) 아래와 비슷한 생김새!
ssh -i /path/my-key-pair.pem ubuntu@13.125.250.20
리눅스는 윈도우 같지 않아서, '쉘 명령어'를 통해 OS를 조작한다. (일종의 마우스 역할)
[가장 많이 쓰는 몇 가지 명령어]
팁! 리눅스 커널에서 윗화살표를 누르면 바로 전에 썼던 명령어가 나옵니다.
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
# 아주 간단하게, 이 정도만 적어볼까요?
# 그리고 적당한 곳에 파일을 저장해봅니다.
print('hello sparta!!')
왼쪽이 내 컴퓨터
vs 오른쪽이 내가 방금 산 컴퓨터
python [test.py](http://test1.py)
파이썬 (python3 → python)
💡 python3 명령어를 python으로 사용할 수 있게 하는 명령어
pip (pip3 → pip)
💡 1) pip3 설치
2) pip3 명령어를 pip으로 사용할 수 있게 하는 명령어
# pip3 설치
sudo apt-get update
sudo apt-get install -y python3-pip
# pip3 대신 pip 라고 입력하기 위한 명령어
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1
💡 80포트로 들어오는 요청을 5000포트로 넘겨주는 명령어
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 5000
python app.py
+
버튼 누르고 설치했던 작업을, 명령어로 하면 이렇게 된답니다! 🤓 pip install flask
3) 하는 김에, 다른 패키지들도 설치해줄까요?
pip install pymongo dnspython
4) 다시 flask 서버를 실행해보기
아래 명령어로 flask 서버를 실행합니다.
python app.py
서버 실행이 되면, 크롬에서 접속을 해봅니다.
크롬 브라우저 창에 아래와 같이 입력합니다.
http://[내 EC2 IP]:5000/
👉 아직, 작동하지 않을 걸요! → AWS에서 약간의 설정이 더 필요합니다.
5) AWS에서 5000포트를 열어주기
→ 그래서 AWS EC2 Security Group에서 인바운드 요청 포트를 열어줘야 합니다.
→ 80포트: HTTP 접속을 위한 기본포트
→ 5000포트: flask 기본포트
# 아래의 명령어로 실행하면 된다
nohup python app.py &
ps -ef | grep 'python app.py' | awk '{print $2}' | xargs kill
http://내AWS아이피/
https://dns.gabia.com/
(DNS 설정 클릭)
(호스트 이름에 @, IP주소에 IP주소를 입력합니다)
(이렇게!)
http://내AWS아이피/
http://내도메인/
<meta property="og:title" content="내 사이트의 제목" />
<meta property="og:description" content="보고 있는 페이지의 내용 요약" />
<meta property="og:image" content="이미지URL" />
👉 그것은 페이스북/카카오톡 등에서 처음 것을 한동안 저장해놓기 때문입니다.
후기?
대략 3일 동안 5주 치를 들어서 사실 지금 정신이 없다. 근데 우연하게 5주차를 한번 더 들을 기회가 생겼는데, 다시 한번 >> 강의를 들었을 때, 해당 강의의 효과를 느꼈다. 2번째 강의를 듣다보니 이해의 깊이가 달랐고, 해당 코드와 사이트 들의 필요성을 체감하게 되었다. 그래서 기회가 된다면, 최대한 많은 강의를 들어야 겠다라는 생각을 하게 되었다. 역시 코딩은 많이 해야하고, 지식은 많이 보아야 한다는 걸 체감했다. 그럼 복습하러 이만~~! ( 스터디 구해야 겠지? 헤헤 )