![[왕초보] 비개발자를 위한, 웹개발 종합반 5주차](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FAz0IB%2FbtrP8Zw8hmf%2F1uv38ViKBNbFdvYlIyGqJ1%2Fimg.png)
[ 수업목표 ]
1. Flask 프레임워크를 활용해서 API를 만들 수 있다.
2. '버킷리스트'를 완성한다.
3. EC2에 내 프로젝트를 올리고, 자랑한다!
[ 설치할 프로그램들 ]
1. 파일질라 다운로드 : https://filezilla-project.org/download.php
1-1) 다운로드 클릭 후 가장 기본 버전 (스크린샷 기준 왼쪽) 다운로드
2. 가비아 가입하기 & 도메인 구입하기
2-1) 접속하기 & 가입하기 : https://www.gabia.com
가비아에서 할인이벤트(500원/1년)를 진행하는 도메인을 구매해서 진행 할 예정
기억하기 - 무통장입금(가상계좌)으로 결제하시기를 추천
2-2) 로그인 후, 메인 페이지에서 원하는 도메인을 검색
2-3) 마침 .shop 도메인이 500원/1년으로 할인중이니, 추천
2-4) 결제를 마무리
결제 기간을 1년으로 맞추기. 그래야 500원 찬스
2-5) 무통장입금을 선택(1,000원 이하는 카드 결제가 안됨)
2-6) 마이페이지에 접속하고, 10분 정도 기다리면 → 총 서비스 수가 '1'로 바뀜
[ 버킷리스트 - 프로젝트 세팅 ]
sparta → projects → bucket 폴더를 열고 시작
1. 프로젝트 설정 - flask 폴더 구조 만들기
1-1) static, templates 폴더 + app.py 만들기
2. 패키지 설치하기 ( flask, pymongo, dnspython )
[ 버킷리스트 - 뼈대 준비하기 ]
1. 버킷리스트 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)
2. 버킷리스트 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 {
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>
3. mongoDB Atlas 창 띄워두기 : https://cloud.mongodb.com/
[ 버킷리스트 - POST 연습(기록하기) ]
1. API 만들고 사용하기 - 버킷리스트 기록 API (Create→ POST)
1. 요청 정보 : URL= /bucket, 요청 방식 = POST
2. 클라(ajax) → 서버(flask) : bucket
3. 서버(flask) → 클라(ajax) : 메시지를 보냄 (기록 완료!)
단! 서버에서 한 가지 일을 더 해야합니다.
→ 번호를 만들어 함께 넣어주는 것. 그래야 업데이트가 가능하겠죠!
1-1) 클라이언트와 서버 연결 확인하기
- 서버 코드 - 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>
1-2) 서버부터 만들기
- bucket 정보를 받아서 저장
- 버킷 번호와 완료 여부를 함께 넣어주는 것
- 우리가 일전에 만들어둔 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']
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': '등록 완료!'})
1-3) 클라이언트 만들기
- 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-4) 완성 확인하기
- DB에 잘 들어갔는지 확인
[ 버킷리스트 - GET연습(보여주기) ]
1. API 만들고 사용하기 - 버킷리스트 조회 API
1. 요청 정보 : URL= /bucket, 요청 방식 = GET
2. 클라(ajax) → 서버(flask) : (없음)
3. 서버(flask) → 클라(ajax) : 전체 버킷리스트를 보여주기
1-1) 클라이언트와 서버 연결 확인하기
- 서버 코드 - 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"])
}
});
}
1-2) 서버부터 만들기
- 받을 것 없이 bucket에 주문정보를 담아서 내려주기만 하면 됨
@app.route("/bucket", methods=["GET"])
def bucket_get():
buckets_list = list(db.bucket.find({},{'_id':False}))
return jsonify({'buckets':buckets_list})
1-3) 클라이언트 만들기
- 응답을 잘 받아서 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>
<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)
}
}
});
}
1-4) 완성 확인하기
- 버킷리스트가 잘 붙었는지 확인
[ 버킷리스트 - POST 연습(완료하기) ]
1. API 만들고 사용하기 - 버킷리스트 완료 API (Update→ POST)
1. 요청 정보 : URL= /bucket/done, 요청 방식 = POST
2. 클라(ajax) → 서버(flask) : num (버킷 넘버)
3. 서버(flask) → 클라(ajax) : 메시지를 보냄 (버킷 완료!)
1-1) 클라이언트와 서버 연결 확인
- 서버 코드 - 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>
1-2) 서버부터 만들기
- 버킷번호를 받아서, 업데이트 하면 됨
- 그런데 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': '버킷 완료!'})
.
1-3) 클라이언트 만들기
- 버킷 넘버를 보여주면 됨. 버킷 넘버는 HTML이 만들어질 때 적히게 됨
function done_bucket(num){
$.ajax({
type: "POST",
url: "/bucket/done",
data: {'num_give':num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
1-4) 완성 확인
- 선이 쫙! 그어진 것 확인
[ 내 프로젝트를 서버에 올리기 ]
1. "웹서비스 런칭" 에 필요한 개념 소개
이제 내가 만든 프로젝트를 배포해봅니다. 배포는 누구나 내 서비스를 사용할 수 있게 하기 위해서
하는 작업들이에요. 웹 서비스를 런칭하는 거죠!
1-1) 웹 서비스를 런칭하기 위해 클라이언트의 요청에 항상 응답해줄 수 있는 서버에 프로젝트를 실행시킬 것임
1-2) 언제나 요청에 응답하려면,
1) 컴퓨터가 항상 켜져있고 프로그램이 실행되어 있어야하고,
2) 모두가 접근할 수 있는 공개 주소인 공개 IP 주소(Public IP Address)로 나의 웹 서비스에 접근할 수 있도록
해야해요.
1-3) 서버는 그냥 컴퓨터라는거 기억나시죠? 외부 접속이 가능하게 설정한 다음에 내 컴퓨터를 서버로
사용할 수도 있음
1-4) 우리는 AWS 라는 클라우드 서비스에서 편하게 서버를 관리하기 위해서 항상 켜 놓을 수 있는
컴퓨터인 EC2 사용권을 구입해 서버로 사용할 것임
'Coding' 카테고리의 다른 글
[왕초보] 비개발자를 위한, 웹개발 종합반 4주차 숙제 (0) | 2022.10.28 |
---|---|
[왕초보] 비개발자를 위한, 웹개발 종합반 4주차 (0) | 2022.10.27 |
[왕초보] 비개발자를 위한, 웹개발 종합반 3주차 숙제 (0) | 2022.10.27 |
[왕초보] 비개발자를 위한, 웹개발 종합반 3주차 (0) | 2022.10.25 |
[왕초보] 비개발자를 위한, 웹개발 종합반 2주차 숙제 (0) | 2022.10.24 |
github : https://github.com/dnjfht
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!