2023. 4. 8. 17:16ㆍ항해99
스파르타 코딩클럽 웹개발 종합반 수업내용을 정리한 것입니다.
api 개발 순서
1) 데이터 명세
2) 클라이언트와 서버 확인하기
3) 서버부터 만들기
4) 클라이언트 만들기
5) 완성 확인하기
- 잘 모르는 기능 먼저 만들기
Flask
https://flask.palletsprojects.com/en/2.2.x/quickstart/
- 파일을 만들고 가상환경을 만들어야 한다.
# 터미널
python3 -m venv venv
pip install flask
1) 시작코드
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'This is Home!'
if __name__ == '__main__':
app.run('0.0.0.0',port=5001,debug=True)
- 맥은 포트 5000 이 안된다.
- localhost:5001 도메인으로 접속하면 사이트를 확인할 수 있다.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'This is Home!'
@app.route('/mypage')
def mypage():
return '<button>버튼입니다</button>'
if __name__ == '__main__':
app.run('0.0.0.0',port=5001,debug=True)
2) HTML 파일 연동
파일 생성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Document</title>
<script>
function hey() {
alert("안녕!");
}
</script>
</head>
<body>
<button onclick="hey()">나는 버튼!</button>
</body>
</html>
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return 'This is Home!'
@app.route('/mypage')
def mypage():
return render_template('index.html')
if __name__ == '__main__':
app.run('0.0.0.0',port=5001,debug=True)
3) API 만들기
- GET 요청
- 통상적으로 데이터 조회(Read) 를 요청할 때 사용한다.
- ex) 영화 목록 조회 : 데이터 전달 > URL 뒤에 물음표를 붙여 key=value 로 전달
# app.py
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/test', methods=['GET']) # GET 요청으로 test 창구로 들어온다
def test_get():
title_receive = request.args.get('title_give') # title_give 데이터가 있으면 title_receive 변수에 저장
print(title_receive) # 볼 수 있게 출력
return jsonify({'result':'success', 'msg': '이 요청은 GET!'}) # result는 success, msg 는 '이 요청은 GET!' 이렇게 내려준다
if __name__ == '__main__':
app.run('0.0.0.0',port=5001,debug=True)
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Document</title>
<script>
function hey() {
fetch("/test")
.then((res) => res.json())
.then((data) => {
console.log(data);
});
}
</script>
</head>
<body>
<h1>제목을 입력합니다</h1>
<button onclick="hey()">나는 버튼!</button>
</body>
</html>
- POST 요청
- 컴퓨터끼리 알아들을수 있는 방법으로 데이터를 왔다 갔다 함
- 우리 눈에 보이지 않는다.
- 통상적으로 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청할 때 사용
- ex) 회원가입, 회원탈퇴, 비밀번호 수정 : 데이터 전달 > 바로 보이지 않는 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('/test', methods=['POST'])
def test_post():
title_receive = request.form['title_give']
print(title_receive)
return jsonify({'result':'success', 'msg': '이 요청은 POST!'})
if __name__ == '__main__':
app.run('0.0.0.0',port=5001,debug=True)
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Document</title>
<script>
function hey() {
let formData = new FormData();
formData.append("title_give", "블랙팬서");
fetch("/test", { method: "POST", body: formData })
.then((res) => res.json())
.then((data) => {
console.log(data);
});
}
</script>
</head>
<body>
<h1>제목을 입력합니다</h1>
<button onclick="hey()">나는 버튼!</button>
</body>
</html>
- post 는 formData 로 실어나른다.
화성땅 공동구매
- 가상환경 세팅후 flask, pymongo, dnspython 패키지 설치
1) 기본 코드
<!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+Batang:wght@400;700&display=swap" rel="stylesheet" />
<title>선착순 공동구매</title>
<style>
* {
font-family: "Gowun Batang", serif;
color: white;
}
body {
background-image: linear-gradient(0deg,
rgba(0, 0, 0, 0.5),
rgba(0, 0, 0, 0.5)),
url("https://cdn.aitimes.com/news/photo/202010/132592_129694_3139.jpg");
background-position: center;
background-size: cover;
}
h1 {
font-weight: bold;
}
.order {
width: 500px;
margin: 60px auto 0px auto;
padding-bottom: 60px;
}
.mybtn {
width: 100%;
}
.order>table {
margin: 40px 0;
font-size: 18px;
}
option {
color: black;
}
</style>
<script>
$(document).ready(function () {
show_order();
});
function show_order() {
fetch('/mars').then((res) => res.json()).then((data) => {
console.log(data)
alert(data['msg'])
})
}
function save_order() {
let formData = new FormData();
formData.append("sample_give", "샘플데이터");
fetch('/mars', { method: "POST", body: formData }).then((res) => res.json()).then((data) => {
console.log(data);
alert(data["msg"]);
});
}
</script>
</head>
<body>
<div class="mask"></div>
<div class="order">
<h1>화성에 땅 사놓기!</h1>
<h3>가격: 평 당 500원</h3>
<p>
화성에 땅을 사둘 수 있다고?<br />
앞으로 백년 간 오지 않을 기회. 화성에서 즐기는 노후!
</p>
<div class="order-info">
<div class="input-group mb-3">
<span class="input-group-text">이름</span>
<input id="name" type="text" class="form-control" />
</div>
<div class="input-group mb-3">
<span class="input-group-text">주소</span>
<input id="address" type="text" class="form-control" />
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="size">평수</label>
<select class="form-select" id="size">
<option selected>-- 주문 평수 --</option>
<option value="10평">10평</option>
<option value="20평">20평</option>
<option value="30평">30평</option>
<option value="40평">40평</option>
<option value="50평">50평</option>
</select>
</div>
<button onclick="save_order()" type="button" class="btn btn-warning mybtn">
주문하기
</button>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">이름</th>
<th scope="col">주소</th>
<th scope="col">평수</th>
</tr>
</thead>
<tbody id="order-box">
<tr>
<td>홍길동</td>
<td>서울시 용산구</td>
<td>20평</td>
</tr>
<tr>
<td>임꺽정</td>
<td>부산시 동구</td>
<td>10평</td>
</tr>
<tr>
<td>세종대왕</td>
<td>세종시 대왕구</td>
<td>30평</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route("/mars", methods=["POST"])
def mars_post():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg':'POST 연결 완료!'})
@app.route("/mars", methods=["GET"])
def mars_get():
return jsonify({'msg':'GET 연결 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5001, debug=True)
- mongodb atlas 접속 후 Browser Collection 클릭 후 데이터 콜렉션을 지워준다.
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+Batang:wght@400;700&display=swap"
rel="stylesheet"
/>
<title>선착순 공동구매</title>
<style>
* {
font-family: "Gowun Batang", serif;
color: white;
}
body {
background-image: linear-gradient(
0deg,
rgba(0, 0, 0, 0.5),
rgba(0, 0, 0, 0.5)
),
url("https://cdn.aitimes.com/news/photo/202010/132592_129694_3139.jpg");
background-position: center;
background-size: cover;
}
h1 {
font-weight: bold;
}
.order {
width: 500px;
margin: 60px auto 0px auto;
padding-bottom: 60px;
}
.mybtn {
width: 100%;
}
.order > table {
margin: 40px 0;
font-size: 18px;
}
option {
color: black;
}
</style>
<script>
$(document).ready(function () {
show_order();
});
function show_order() {
fetch("/mars")
.then((res) => res.json())
.then((data) => {
console.log(data);
alert(data["msg"]);
});
}
function save_order() {
let name = $("#name").val();
let address = $("#address").val();
let size = $("#size").val();
let formData = new FormData();
formData.append("name_give", name);
formData.append("address_give", address);
formData.append("size_give", size);
fetch("/mars", { method: "POST", body: formData })
.then((res) => res.json())
.then((data) => {
alert(data["msg"]);
window.location.reload(); // 페이지 새로고침
});
}
</script>
</head>
<body>
<div class="mask"></div>
<div class="order">
<h1>화성에 땅 사놓기!</h1>
<h3>가격: 평 당 500원</h3>
<p>
화성에 땅을 사둘 수 있다고?<br />
앞으로 백년 간 오지 않을 기회. 화성에서 즐기는 노후!
</p>
<div class="order-info">
<div class="input-group mb-3">
<span class="input-group-text">이름</span>
<input id="name" type="text" class="form-control" />
</div>
<div class="input-group mb-3">
<span class="input-group-text">주소</span>
<input id="address" type="text" class="form-control" />
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="size">평수</label>
<select class="form-select" id="size">
<option selected>-- 주문 평수 --</option>
<option value="10평">10평</option>
<option value="20평">20평</option>
<option value="30평">30평</option>
<option value="40평">40평</option>
<option value="50평">50평</option>
</select>
</div>
<button
onclick="save_order()"
type="button"
class="btn btn-warning mybtn"
>
주문하기
</button>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">이름</th>
<th scope="col">주소</th>
<th scope="col">평수</th>
</tr>
</thead>
<tbody id="order-box">
<tr>
<td>홍길동</td>
<td>서울시 용산구</td>
<td>20평</td>
</tr>
<tr>
<td>임꺽정</td>
<td>부산시 동구</td>
<td>10평</td>
</tr>
<tr>
<td>세종대왕</td>
<td>세종시 대왕구</td>
<td>30평</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
# app.py
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://이름:비밀번호@cluster0.2xxwxhc.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/mars", methods=["POST"])
def mars_post():
name_receive = request.form['name_give']
address_receive = request.form['address_give']
size_receive = request.form['size_give']
doc = {
'name': name_receive,
'address' : address_receive,
'size' : size_receive
}
db.mars.insert_one(doc)
return jsonify({'msg':'저장 완료!'})
@app.route("/mars", methods=["GET"])
def mars_get():
return jsonify({'msg':'GET 연결 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5001, debug=True)
3) GET ( 주문 보여주기 )
<!-- 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+Batang:wght@400;700&display=swap"
rel="stylesheet"
/>
<title>선착순 공동구매</title>
<style>
* {
font-family: "Gowun Batang", serif;
color: white;
}
body {
background-image: linear-gradient(
0deg,
rgba(0, 0, 0, 0.5),
rgba(0, 0, 0, 0.5)
),
url("https://cdn.aitimes.com/news/photo/202010/132592_129694_3139.jpg");
background-position: center;
background-size: cover;
}
h1 {
font-weight: bold;
}
.order {
width: 500px;
margin: 60px auto 0px auto;
padding-bottom: 60px;
}
.mybtn {
width: 100%;
}
.order > table {
margin: 40px 0;
font-size: 18px;
}
option {
color: black;
}
</style>
<script>
$(document).ready(function () {
show_order();
});
function show_order() {
fetch("/mars")
.then((res) => res.json())
.then((data) => {
let rows = data["result"];
$("#order-box").empty();
rows.forEach((a) => {
let name = a["name"];
let address = a["address"];
let size = a["size"];
let temp_html = ` <tr>
<td>${name}</td>
<td>${address}</td>
<td>${size}</td>
</tr>`;
$("#order-box").append(temp_html);
});
});
}
function save_order() {
let name = $("#name").val();
let address = $("#address").val();
let size = $("#size").val();
let formData = new FormData();
formData.append("name_give", name);
formData.append("address_give", address);
formData.append("size_give", size);
fetch("/mars", { method: "POST", body: formData })
.then((res) => res.json())
.then((data) => {
alert(data["msg"]);
window.location.reload(); // 페이지 새로고침
});
}
</script>
</head>
<body>
<div class="mask"></div>
<div class="order">
<h1>화성에 땅 사놓기!</h1>
<h3>가격: 평 당 500원</h3>
<p>
화성에 땅을 사둘 수 있다고?<br />
앞으로 백년 간 오지 않을 기회. 화성에서 즐기는 노후!
</p>
<div class="order-info">
<div class="input-group mb-3">
<span class="input-group-text">이름</span>
<input id="name" type="text" class="form-control" />
</div>
<div class="input-group mb-3">
<span class="input-group-text">주소</span>
<input id="address" type="text" class="form-control" />
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="size">평수</label>
<select class="form-select" id="size">
<option selected>-- 주문 평수 --</option>
<option value="10평">10평</option>
<option value="20평">20평</option>
<option value="30평">30평</option>
<option value="40평">40평</option>
<option value="50평">50평</option>
</select>
</div>
<button
onclick="save_order()"
type="button"
class="btn btn-warning mybtn"
>
주문하기
</button>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">이름</th>
<th scope="col">주소</th>
<th scope="col">평수</th>
</tr>
</thead>
<tbody id="order-box">
<tr>
<td>홍길동</td>
<td>서울시 용산구</td>
<td>20평</td>
</tr>
<tr>
<td>임꺽정</td>
<td>부산시 동구</td>
<td>10평</td>
</tr>
<tr>
<td>세종대왕</td>
<td>세종시 대왕구</td>
<td>30평</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
# app.py
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://이름:비밀번호@cluster0.2xxwxhc.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/mars", methods=["POST"])
def mars_post():
name_receive = request.form['name_give']
address_receive = request.form['address_give']
size_receive = request.form['size_give']
doc = {
'name': name_receive,
'address' : address_receive,
'size' : size_receive
}
db.mars.insert_one(doc)
return jsonify({'msg':'저장 완료!'})
@app.route("/mars", methods=["GET"])
def mars_get():
mars_data = list(db.mars.find({}, {'_id': False}))
return jsonify({'result':mars_data})
if __name__ == '__main__':
app.run('0.0.0.0', port=5001, debug=True)
스파르타피디아
- 가상환경 구성, 패키지 설치
pip install flask pymongo dnspython requests bs4
1) 조각 기능 구현
- URL 을 전송했는데 이미지와 제목 설명이 나오는 것 ( ex : 카톡 링크 공유 )
- 썸네일 사진 - og:image
- 썸네일 제목 - og:title
- 썸네일 설명 - og:description
# meta_prac.py
import requests
from bs4 import BeautifulSoup
URL = 'https://movie.daum.net/moviedb/main?movieId=161806'
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(URL,headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
# 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.
ogtitle = soup.select_one('meta[property="og:title"]')['content'] # 메타 테그인데 og:title 인 것을 가져와라
ogdesc = soup.select_one('meta[property="og:description"]')['content']
ogimage = soup.select_one('meta[property="og:image"]')['content']
print(ogtitle, ogdesc, ogimage)
- 브라우저 > 검사 > head 부분 > 필요한 부분을 찾는다.
2) 뼈대
# app.py
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route("/movie", methods=["POST"])
def movie_post():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg':'POST 연결 완료!'})
@app.route("/movie", methods=["GET"])
def movie_get():
return jsonify({'msg':'GET 연결 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5001, debug=True)
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<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>
<title>스파르타 피디아</title>
<link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">
<style>
* {
font-family: 'Gowun Dodum', sans-serif;
}
.mytitle {
width: 100%;
height: 250px;
background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg');
background-position: center;
background-size: cover;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.mytitle > button {
width: 200px;
height: 50px;
background-color: transparent;
color: white;
border-radius: 50px;
border: 1px solid white;
margin-top: 10px;
}
.mytitle > button:hover {
border: 2px solid white;
}
.mycomment {
color: gray;
}
.mycards {
margin: 20px auto 0px auto;
width: 95%;
max-width: 1200px;
}
.mypost {
width: 95%;
max-width: 500px;
margin: 20px auto 0px auto;
padding: 20px;
box-shadow: 0px 0px 3px 0px gray;
display: none;
}
.mybtns {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-top: 20px;
}
.mybtns > button {
margin-right: 10px;
}
</style>
<script>
$(document).ready(function(){
listing();
});
function listing() {
fetch('/movie').then((res) => res.json()).then((data) => {
console.log(data)
alert(data['msg'])
})
}
function posting() {
let formData = new FormData();
formData.append("sample_give", "샘플데이터");
fetch('/movie', {method : "POST",body : formData}).then((res) => res.json()).then((data) => {
console.log(data)
alert(data['msg'])
})
}
function open_box(){
$('#post-box').show()
}
function close_box(){
$('#post-box').hide()
}
</script>
</head>
<body>
<div class="mytitle">
<h1>내 생애 최고의 영화들</h1>
<button onclick="open_box()">영화 기록하기</button>
</div>
<div class="mypost" id="post-box">
<div class="form-floating mb-3">
<input id="url" type="email" class="form-control" placeholder="name@example.com">
<label>영화URL</label>
</div>
<div class="form-floating">
<textarea id="comment" class="form-control" placeholder="Leave a comment here"></textarea>
<label for="floatingTextarea2">코멘트</label>
</div>
<div class="mybtns">
<button onclick="posting()" type="button" class="btn btn-dark">기록하기</button>
<button onclick="close_box()" type="button" class="btn btn-outline-dark">닫기</button>
</div>
</div>
<div class="mycards">
<div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">
<div class="col">
<div class="card h-100">
<img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top">
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top">
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top">
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top">
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
3) POST
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://이름:비밀번호@cluster0.2xxwxhc.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
import requests
from bs4 import BeautifulSoup
@app.route('/')
def home():
return render_template('index.html')
@app.route("/movie", methods=["POST"])
def movie_post():
url_receive = request.form['url_give']
comment_receive = request.form['comment_give']
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(url_receive,headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
# 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.
ogtitle = soup.select_one('meta[property="og:title"]')['content'] # 메타 테그인데 og:title 인 것을 가져와라
ogdesc = soup.select_one('meta[property="og:description"]')['content']
ogimage = soup.select_one('meta[property="og:image"]')['content']
doc = {
'title': ogtitle,
'desc': ogdesc,
'image': ogimage,
'comment':comment_receive
}
db.movies.insert_one(doc)
return jsonify({'msg':'저장 완료!'})
@app.route("/movie", methods=["GET"])
def movie_get():
return jsonify({'msg':'GET 연결 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5001, debug=True)
<script>
$(document).ready(function () {
listing();
});
function listing() {
fetch("/movie")
.then((res) => res.json())
.then((data) => {
console.log(data);
alert(data["msg"]);
});
}
function posting() {
let url = $("#url").val();
let comment = $("#comment").val();
let formData = new FormData();
formData.append("url_give", url);
formData.append("comment_give", comment);
fetch("/movie", { method: "POST", body: formData })
.then((res) => res.json())
.then((data) => {
alert(data["msg"]);
window.location.reload();
});
}
function open_box() {
$("#post-box").show();
}
function close_box() {
$("#post-box").hide();
}
</script>
4) GET
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://이름:비밀번호@cluster0.2xxwxhc.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
import requests
from bs4 import BeautifulSoup
@app.route('/')
def home():
return render_template('index.html')
@app.route("/movie", methods=["POST"])
def movie_post():
url_receive = request.form['url_give']
comment_receive = request.form['comment_give']
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(url_receive,headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
# 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.
ogtitle = soup.select_one('meta[property="og:title"]')['content'] # 메타 테그인데 og:title 인 것을 가져와라
ogdesc = soup.select_one('meta[property="og:description"]')['content']
ogimage = soup.select_one('meta[property="og:image"]')['content']
doc = {
'title': ogtitle,
'desc': ogdesc,
'image': ogimage,
'comment':comment_receive
}
db.movies.insert_one(doc)
return jsonify({'msg':'저장 완료!'})
@app.route("/movie", methods=["GET"])
def movie_get():
all_movies = list(db.movies.find({}, {'_id':False}))
return jsonify({'result':all_movies})
if __name__ == '__main__':
app.run('0.0.0.0', port=5001, debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<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>
<title>스파르타 피디아</title>
<link
href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap"
rel="stylesheet"
/>
<style>
* {
font-family: "Gowun Dodum", sans-serif;
}
.mytitle {
width: 100%;
height: 250px;
background-image: linear-gradient(
0deg,
rgba(0, 0, 0, 0.5),
rgba(0, 0, 0, 0.5)
),
url("https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg");
background-position: center;
background-size: cover;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.mytitle > button {
width: 200px;
height: 50px;
background-color: transparent;
color: white;
border-radius: 50px;
border: 1px solid white;
margin-top: 10px;
}
.mytitle > button:hover {
border: 2px solid white;
}
.mycomment {
color: gray;
}
.mycards {
margin: 20px auto 0px auto;
width: 95%;
max-width: 1200px;
}
.mypost {
width: 95%;
max-width: 500px;
margin: 20px auto 0px auto;
padding: 20px;
box-shadow: 0px 0px 3px 0px gray;
display: none;
}
.mybtns {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-top: 20px;
}
.mybtns > button {
margin-right: 10px;
}
</style>
<script>
$(document).ready(function () {
listing();
});
function listing() {
fetch("/movie")
.then((res) => res.json())
.then((data) => {
let rows = data["result"];
$("#cards-box").empty();
rows.forEach((a) => {
let comment = a["comment"];
let title = a["title"];
let desc = a["desc"];
let image = a["image"];
console.log(comment, title, desc, image);
let temp_html = `<div class="col">
<div class="card h-100">
<img
src="${image}"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">${title}</h5>
<p class="card-text">${desc}</p>
<p>⭐⭐⭐</p>
<p class="mycomment">${comment}</p>
</div>
</div>
</div>`;
$("#cards-box").append(temp_html);
});
});
}
function posting() {
let url = $("#url").val();
let comment = $("#comment").val();
let formData = new FormData();
formData.append("url_give", url);
formData.append("comment_give", comment);
fetch("/movie", { method: "POST", body: formData })
.then((res) => res.json())
.then((data) => {
alert(data["msg"]);
window.location.reload();
});
}
function open_box() {
$("#post-box").show();
}
function close_box() {
$("#post-box").hide();
}
</script>
</head>
<body>
<div class="mytitle">
<h1>내 생애 최고의 영화들</h1>
<button onclick="open_box()">영화 기록하기</button>
</div>
<div class="mypost" id="post-box">
<div class="form-floating mb-3">
<input
id="url"
type="email"
class="form-control"
placeholder="name@example.com"
/>
<label>영화URL</label>
</div>
<div class="form-floating">
<textarea
id="comment"
class="form-control"
placeholder="Leave a comment here"
></textarea>
<label for="floatingTextarea2">코멘트</label>
</div>
<div class="mybtns">
<button onclick="posting()" type="button" class="btn btn-dark">
기록하기
</button>
<button
onclick="close_box()"
type="button"
class="btn btn-outline-dark"
>
닫기
</button>
</div>
</div>
<div class="mycards">
<div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">
<div class="col">
<div class="card h-100">
<img
src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img
src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img
src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img
src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
스파르타피디아 별점 추가하기
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://이름:비밀번호@cluster0.2xxwxhc.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
import requests
from bs4 import BeautifulSoup
@app.route('/')
def home():
return render_template('index.html')
@app.route("/movie", methods=["POST"])
def movie_post():
url_receive = request.form['url_give']
comment_receive = request.form['comment_give']
star_receive = request.form['star_give']
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(url_receive,headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
# 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.
ogtitle = soup.select_one('meta[property="og:title"]')['content'] # 메타 테그인데 og:title 인 것을 가져와라
ogdesc = soup.select_one('meta[property="og:description"]')['content']
ogimage = soup.select_one('meta[property="og:image"]')['content']
doc = {
'title': ogtitle,
'desc': ogdesc,
'image': ogimage,
'comment':comment_receive,
'star':star_receive
}
db.movies.insert_one(doc)
return jsonify({'msg':'저장 완료!'})
@app.route("/movie", methods=["GET"])
def movie_get():
all_movies = list(db.movies.find({}, {'_id':False}))
return jsonify({'result':all_movies})
if __name__ == '__main__':
app.run('0.0.0.0', port=5001, debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<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>
<title>스파르타 피디아</title>
<link
href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap"
rel="stylesheet"
/>
<style>
* {
font-family: "Gowun Dodum", sans-serif;
}
.mytitle {
width: 100%;
height: 250px;
background-image: linear-gradient(
0deg,
rgba(0, 0, 0, 0.5),
rgba(0, 0, 0, 0.5)
),
url("https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg");
background-position: center;
background-size: cover;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.mytitle > button {
width: 200px;
height: 50px;
background-color: transparent;
color: white;
border-radius: 50px;
border: 1px solid white;
margin-top: 10px;
}
.mytitle > button:hover {
border: 2px solid white;
}
.mycomment {
color: gray;
}
.mycards {
margin: 20px auto 0px auto;
width: 95%;
max-width: 1200px;
}
.mypost {
width: 95%;
max-width: 500px;
margin: 20px auto 0px auto;
padding: 20px;
box-shadow: 0px 0px 3px 0px gray;
display: none;
}
.mybtns {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-top: 20px;
}
.mybtns > button {
margin-right: 10px;
}
</style>
<script>
$(document).ready(function () {
listing();
});
function listing() {
fetch("/movie")
.then((res) => res.json())
.then((data) => {
let rows = data["result"];
$("#cards-box").empty();
rows.forEach((a) => {
let comment = a["comment"];
let title = a["title"];
let desc = a["desc"];
let image = a["image"];
let star = a["star"];
let star_repeat = "⭐".repeat(star);
console.log(comment, title, desc, image);
let temp_html = `<div class="col">
<div class="card h-100">
<img
src="${image}"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">${title}</h5>
<p class="card-text">${desc}</p>
<p>${star_repeat}</p>
<p class="mycomment">${comment}</p>
</div>
</div>
</div>`;
$("#cards-box").append(temp_html);
});
});
}
function posting() {
let url = $("#url").val();
let comment = $("#comment").val();
let star = $("#star").val();
let formData = new FormData();
formData.append("url_give", url);
formData.append("comment_give", comment);
formData.append("star_give", star);
fetch("/movie", { method: "POST", body: formData })
.then((res) => res.json())
.then((data) => {
alert(data["msg"]);
window.location.reload();
});
}
function open_box() {
$("#post-box").show();
}
function close_box() {
$("#post-box").hide();
}
</script>
</head>
<body>
<div class="mytitle">
<h1>내 생애 최고의 영화들</h1>
<button onclick="open_box()">영화 기록하기</button>
</div>
<div class="mypost" id="post-box">
<div class="form-floating mb-3">
<input
id="url"
type="email"
class="form-control"
placeholder="name@example.com"
/>
<label>영화URL</label>
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">별점</label>
<select class="form-select" id="star">
<option selected>-- 선택하기 --</option>
<option value="1">⭐</option>
<option value="2">⭐⭐</option>
<option value="3">⭐⭐⭐</option>
<option value="4">⭐⭐⭐⭐</option>
<option value="5">⭐⭐⭐⭐⭐</option>
</select>
</div>
<div class="form-floating">
<textarea
id="comment"
class="form-control"
placeholder="Leave a comment here"
></textarea>
<label for="floatingTextarea2">코멘트</label>
</div>
<div class="mybtns">
<button onclick="posting()" type="button" class="btn btn-dark">
기록하기
</button>
<button
onclick="close_box()"
type="button"
class="btn btn-outline-dark"
>
닫기
</button>
</div>
</div>
<div class="mycards">
<div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">
<div class="col">
<div class="card h-100">
<img
src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img
src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img
src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img
src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
class="card-img-top"
/>
<div class="card-body">
<h5 class="card-title">영화 제목이 들어갑니다</h5>
<p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
<p>⭐⭐⭐</p>
<p class="mycomment">나의 한줄 평을 씁니다</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
4주차 소감
여태 배운것들이 손에 익지는 않았는데 같은부분, 비슷한부분을 반복하며 학습할 수 있게 해준 주차 였고 Flask 를 통해 더욱 쉽게 백엔드를 접해볼수 있었던거 같다.
이전에는 주먹구구식으로 api를 만들었지만 api 개발 순서를 보며 변화하며 순서에 맞게 api 를 만들다보니 흥미가 더욱 늘었던 주차였습니다.
'항해99' 카테고리의 다른 글
엑셀보다 쉬운 SQL 1주차 (0) | 2023.06.01 |
---|---|
웹개발 종합반 5주차 (0) | 2023.04.09 |
웹개발 종합반 3주차 (0) | 2023.04.08 |
웹개발 종합반 2주차 (0) | 2023.04.08 |
웹개발 종합반 1주차 (0) | 2023.04.08 |