1) API 만들고 사용하기 - 버킷리스트 기록 API (Create→ POST)
👉 1. 요청 정보 : URL= /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)
}
}
});
}
1) API 만들고 사용하기 - 버킷리스트 완료 API (Update→ POST)
👉 1. 요청 정보 : URL= /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': '버킷 완료!'})
버킷 넘버를 보여주면 됩니다! 버킷 넘버는? HTML이 만들어질 때 적히게 되죠!
바로 이렇게!
![Untitled](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/67491e49-7ea3-4dfc-bf66-e8367dccfe71/Untitled.png)
function done_bucket(num){
$.ajax({
type: "POST",
url: "/bucket/done",
data: {'num_give':num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
1) "웹서비스 런칭" 에 필요한 개념 소개
👉 이제 내가 만든 프로젝트를 배포해봅니다. 배포는 누구나 내 서비스를 사용할 수 있게 하기 위해서 작업들이에요. 웹 서비스를 런칭하는 거죠!
1) EC2 서버 구매하기
[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)
구매 화면들 따라하기
👉 Ubuntu Server 18.04 또는 20.04 버전을 구매합니다.
Name은 sparta_web
으로 해주세요.(선택)
Ubuntu로 18.04 or 20.04를 선택해주세요! (ubuntu 선택 중요!)
t2.micro가 무료 서비스
랍니다!(1년 기한)
KEY 생성하기를 클릭 후, key를 발급 받아요(서버 접속 시, 매우 중요!!!)
나머지 체크리스트들을 체크 후, Launch instance를 클릭해주세요!
2) EC2 서버 종료하는 방법 (1년 후 자동결제 방지!)
💡 중지 또는 종료하는 법. 무료 기간(1년) 후 결제가 되기 전에, 이렇게 종료하세요!
대상 인스턴스에 마우스 우클릭 > '인스턴스 상태' 를 클릭합니다. 중지 또는 종료 중 하나를 클릭하면 명령을 실행합니다.
AWSInstance_exported (1)_exported (1).mp4
3) EC2에 접속하기
다른 컴퓨터에 접속할 때 쓰는 프로그램입니다. 다른 것들 보다 보안이 상대적으로 뛰어납니다.
접속할 컴퓨터가 22번 포트가 열려있어야 접속 가능합니다. AWS EC2의 경우, 이미 22번 포트가 열려있습니다. 확인해볼까요?
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
4) 간단한 리눅스 명령어 연습하기
리눅스는 윈도우 같지 않아서, '쉘 명령어'를 통해 OS를 조작한다. (일종의 마우스 역할)
[가장 많이 쓰는 몇 가지 명령어]
팁! 리눅스 커널에서 윗화살표를 누르면 바로 전에 썼던 명령어가 나옵니다.
ls: 내 위치의 모든 파일을 보여준다.
pwd: 내 위치(폴더의 경로)를 알려준다.
mkdir: 내 위치 아래에 폴더를 하나 만든다.
cd [갈 곳]: 나를 [갈 곳] 폴더로 이동시킨다.
cd .. : 나를 상위 폴더로 이동시킨다.
cp -r [복사할 것] [붙여넣기 할 것]: 복사 붙여넣기
rm -rf [지울 것]: 지우기
sudo [실행 할 명령어]: 명령어를 관리자 권한으로 실행한다.
sudo su: 관리가 권한으로 들어간다. (나올때는 exit으로 나옴)
1) 서버 환경 통일하기
💡 우리는 지금 막! 컴퓨터를 구매한 상태예요. 여기에 이런저런 세팅들(업그레이드, DB설치, 명령어 통일 등)을 해줘야 본격적으로 이용할 때 편리하답니다!
[코드스니펫] EC2 한방에 세팅하기
# 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
⚠️ 진행 중 아래와 같은 화면이 나타나면 설정 변경 없이 를 선택 후 엔터를 쳐서 창을 닫아주시면 됩니다!
2) filezilla를 이용해서, 간단한 python 파일을 올려봅니다.
스크린샷 2022-08-29 오전 2.30.14.mp4
# 아주 간단하게, 이 정도만 적어볼까요?
# 그리고 적당한 곳에 파일을 저장해봅니다.
print('hello sparta!!')
![https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c91661f0-1274-4f35-b9c2-3a09879a0b09/Untitled.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c91661f0-1274-4f35-b9c2-3a09879a0b09/Untitled.png)
`왼쪽이 내 컴퓨터` vs `오른쪽이 내가 방금 산 컴퓨터`
![https://s3-us-west-2.amazonaws.com/secure.notion-static.com/47a40685-1be7-421f-939f-0fdad19c7d81/Untitled.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/47a40685-1be7-421f-939f-0fdad19c7d81/Untitled.png)
3) 파이썬 파일을 실행해보기
filezliaTestpy_exported (1).mp4
python [test.py](http://test1.py)
4) [한 걸음 더] 서버 환경 세팅 - 한 줄씩 설명
💡 실제 업무에서는 아래 내용을 인프라 엔지니어 또는 개발 팀장님이 해두시는 경우가 많습니다. 튜터들도 모두 외우고 있는 코드가 아니기에, 맥락만 이해해주시면 되겠습니다!
파이썬 (python3 → python)
💡 python3 명령어를 python으로 사용할 수 있게 하는 명령어
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
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포트)
💡 80포트로 들어오는 요청을 5000포트로 넘겨주는 명령어
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 5000
1) 팬명록 완성본을 filezilla로 EC2에 업로드해봅니다.
python app.py
2) pip로 패키지를 설치하기
💡 우리가 file → setting → .. 에서 +
버튼 누르고 설치했던 작업을, 명령어로 하면 이렇게 된답니다! 🤓
pip install flask
3) 하는 김에, 다른 패키지들도 설치해줄까요?
pip install pymongo dnspython
4) 다시 flask 서버를 실행해보기
python app.py
크롬 브라우저 창에 아래와 같이 입력합니다.
http://[내 EC2 IP]:5000/
👉 아직, 작동하지 않을 걸요! → AWS에서 약간의 설정이 더 필요합니다.5) AWS에서 5000포트를 열어주기
→ 그래서 AWS EC2 Security Group에서 인바운드 요청 포트를 열어줘야 합니다.
6) 어떻게 되는걸까? 포트 번호 없애기 - 기본 개념
💡 우리는 이미 포트포워딩 세팅을 해뒀기 때문에, 여기서는 개념만!
7) 다시 접속해봅니다!
# 아래의 명령어로 실행하면 된다
nohup python app.py &
ps -ef | grep 'python app.py' | awk '{print $2}' | xargs kill
http://내AWS아이피/
https://dns.gabia.com/
http://내AWS아이피/
http://내도메인/
1) og 태그 만들기
스파르타피디아에서 배웠던 og:image, og:title, og:description 태그 기억하시나요?
👉 내 프로젝트도 카톡/페이스북/슬랙에 공유했을 때 예쁘게 나오도록,
미리 꾸며봅시다!
static 폴더 아래에 이미지 파일을 넣고, 각자 프로젝트 HTML의 ~ 사이에 아래 내용을 작성하면 og 태그를 개인 프로젝트에 사용할 수 있습니다.
[코드스니펫] og태그 넣기
```jsx
<meta property="og:title" content="내 사이트의 제목" />
<meta property="og:description" content="보고 있는 페이지의 내용 요약" />
<meta property="og:image" content="이미지URL" />
```
참고! 이미지를 바꿨는데 이전 ogimage가 그대로 나와요!
👉 그것은 페이스북/카카오톡 등에서 처음 것을 한동안 저장해놓기 때문입니다.