1. 5주차 오늘 배울 것 & 설치
- 버킷리스트 프로젝트
- 배포
- Filezilla 설치, 가비아 가입해 도메인 구입하기
2. [버킷리스트] - 프로젝트 세팅
- 프로젝트 설정 : flask 폴더 구조 만들기(static, templates 폴더, app.py)
- 패키지 설치 : flask, pymongo, dnspython
3. [버킷리스트] - 뼈대 준비하기
- 프로젝트 준비하기 : index.html, app.py 준비하기
#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", method=["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)
<!--index.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 {
diplay: 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: {sample_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="" type="button" class="btn btn-outline-primary>기록하기</button>
</div>
</div>
<div class="mybox" id="bucket-list">
<li>
<h2>✅ 호주에서 스카이다이빙 하기</h2>
<button onclick="save_bucket()" type="button" class="btn btn-outline-primary">완료!</button>
</li>
<li>
<h2 class="done">✅ 호주에서 스카이다이빙 하기</h2>
</li>
<li>
<h2>✅ 호주에서 스카이다이빙 하기</h2>
<button onclick="done_bucket(5)" type="button" class="btn btn-outline-primary">완료!</button>
</li>
</div>
</body>
</html>
*space-between : 아이템들의 "사이(between)"에 균일한 간격을 만든다
- mongoDB Atlas 창 띄워두기
4. [버킷리스트] - POST연습(기록하기)
- 내용
1) 요청 정보 : URL = "/bucket", 요청 방식="POST"
2) 클라이언트(ajax) -> 서버(flask) : bucket
3) 서버(flask) -> 클라이언트(ajax) : 메시지를 보냄(기록 완료!)
4) 번호를 만들어 함께 넣어서 업데이트
- 클라이언트와 서버 연결 확인
#서버코드 - 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>
- 서버부터 만들기
@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()
}
)};
}
- 완성 확인하기 : DB에 잘 들어갔는지 확인
5. [버킷리스트] - GET연습(보여주기)
- 내용
1) 요청 정보 : URL="/bucket", 요청 방식="GET"
2) 클라이언트(ajax) -> 서버(flask) : 없음
3) 서버(flask) -> 클라이언트(ajax) : 전체 버킷리스트 보여주기
- 클라이언트와 서버 연결 확인하기
#서버 코드 - 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})
- 클라이언트 만들기
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)
}
}
});
}
- 완성 확인하기 : 버킷리스트가 잘 붙어있는지 확인
6. [버킷리스트] - POST연습(완료하기)
- 내용
1) 요청 정보 : URL="/bucket/done", 요청 방식="POST"
2) 클라이언트(ajax) -> 서버(flask) : num(버킷 넘버)
3) 서버(flask) -> 클라이언트(ajax) : 메시지를 보냄(버킷 완료!)
- 클라이언트와 서버 연결 확인하기
#서버 코드 - 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()
}
});
}
- 완성하기 : 선이 그어져 있는 것을 확인
7. 내 프로젝트를 서버에 올리기
- 웹서비스 런칭을 위해 클라이언트 요청에 항상 응답할 수 있는 서버에 프로젝트를 실행
- 컴퓨터 항상 켜져있고 프로그램 실행 or 모두가 접근 가능한 공개 주소인 공개 IP주소로 나의 웹 서비스에 접근
- 내 컴퓨터를 서버로 사용 가능
- AWS라는 클라우드 서비스로 서버를 관리하기 위해 항상 켜 놓을 수 있는 컴퓨터인 EC2 사용권 구입해 서버로 사용
8. AWS 서버 구매하기
- EC2 서버 구매 : OS로 리눅스의 Ubuntu 설치
- EC2 서버 종료(1년 후 자동결제 방지) : 대상 인스턴스에 '인스턴스 상태'를 중지 또는 종료로 선택
- EC2 접속
1) SSH(Secure Shell Protocol) : 다른 컴퓨터에 접속할 때 쓰는 프로그램, 22번 포트가 열려있어야 접속 가능
2) 윈도우의 경우 ssh가 없어 git bash라는 프로그램 이용
ssh -i 받은키페어끌어다놓기 ubuntu@AWS에적힌내아이피
- 간단한 리눅스 명령어
ls : 내 위치의 모든 파일을 보여준다.
pwd : 내 위치(폴더의 경로)를 알려준다.
mkdir : 내 위치 아래에 폴더를 하나 만든다.
cd [갈 곳] : 나를 [갈 곳] 폴더로 이동시킨다.
cd .. : 나를 상위 폴더로 이동시킨다.
cp -r [복사할 것] [붙여넣기 할 것] : 복사 붙여넣기
rm -rf [지울 것] : 지우기
sudo [실행 할 명령어] : 명령어를 관리자 권한으로 실행한다.
sudo su : 관리가 권한으로 들어간다.(나올 때는 exit으로 나옴)
9. 서버 세팅하기(1)
- 업그레이드, DB 설치, 명령어 통일 등 기본 세팅
#python3 --> python
#python3 명령어를 python으로 사용할 수 있게 하는 명령어
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
#pip3 -> pip
#pip3를 설치하고, 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
#80포트로 들어오는 요청을 5000포트로 넘겨주는 명령어
#http 요청을 우리 서버의 5000포트로 전달할 수 있어 뒤에 포트번호를 붙이지 않아도 된다.
sudo iptables -t nat -A PREROUTING -i eth0 tcp --dport 80 -j REDIRECT --to-port 5000
10. 서버 세팅하기(2)
- filezilla를 이용해 간단한 python 파일 올리기
- python 파일 실행해보기
11. Flask 서버 실행해보기
- 팬명록 완성본을 filezilla로 EC2에 업로드하기 -> homework 폴더 통째로 드래그드롭해 home/ubuntu 폴더에 업로드
- app.py 파일 실행하기 -> python app.py
- pip로 패키지 설치하기 -> pip install flask
- 기타 패키지 설치하기 -> pip install pymongo dnspython
- 다시 flask 서버 실행 -> python app.py
- 서버 실행 성공시 크롬에서 접속해보기 -> http://[내 EC2 IP]:5000/ ->안 될 것... 설정 변경 더 필요
- AWS에서 5000포트 열어주기
- 다시 접속해보기 -> http://내아이피
12. nohup 설정하기
- SSH 접속을 끊어도 서버가 계속 돌게 하기
nohup python app.py &
- 서버 강제종료 후 브라우저에서 다시 접속해보기
ps -ef | grep 'python app.py' | awk '{print $2}' | xargs kill
13. 도메인 연결하기
- 가비아에 접속해 도메인 구입
- 도메인 설정에 들어가 호스트 이름에 @, IP주소에 IP주소 입력 -> 10분 정도 대기
- 내 IP주소로 flask 서버가 잘 돌고 있는 지 확인 후 내 도메인으로 접속해보기
14. og 태그
- 내 프로젝트를 공유 시 예쁘게 나오도록 꾸미기
- static 폴더 아래 이미지 파일을 넣고, 각자 프로젝트 HTML의 <hea>~~</head> 사이에 아래 내용을 작성 -> og 태그 사용 가능
//og 태그 넣기
<meta property="og:title" content="내 사이트의 제목" />
<meta property="og:description" content="보고 있는 페이지의 내용 요약" />
<meta property="og:image" content="이미지URL" />
- 페이스북 og 태그 초기화 : https://developers.facebook.com/tools/debug/
- 카카오톡 og 태그 초기화 : https://developers.kakao.com/tool/clear/og
'개발일지 > 스파르타코딩클럽_웹개발' 카테고리의 다른 글
Day06(4-1~4-14) (0) | 2022.08.09 |
---|---|
Day05(3-1~3-13) (0) | 2022.08.05 |
Day04(2-1~2-13) (0) | 2022.08.04 |
Day03(1-14~1-20) (0) | 2022.07.02 |
Day02(1-3~1-13) (0) | 2022.07.02 |