-app.py
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
## HTML을 주는 부분
@app.route('/')
def home():
return render_template('index.html')
## API 역할을 하는 부분
@app.route('/review', methods=['POST'])
def write_review():
title_receive = request.form['title_give']
author_receive = request.form['author_give']
review_receive = request.form['review_give']
doc={
'title':title_receive,
'author':author_receive,
'review':review_receive
}
db.bookreview.insert_one(doc)
return jsonify({'msg': '저장 완료되었습니다.'})
@app.route('/review', methods=['GET'])
def read_reviews():
reviews=list(db.bookreview.find({},{'_id':False}))
return jsonify({'all_reviews':reviews})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
-index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<!-- Webpage Title -->
<title>책 리뷰 쓰기</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<!-- JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<!-- 구글폰트 -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nanum+Myeongjo&display=swap" rel="stylesheet">
<script type="text/javascript">
$(document).ready(function () {
showReview();
});
function makeReview() {
let title=$('#title').val()
let author=$('#author').val()
let review=$('#bookReview').val()
$.ajax({
type: "POST",
url: "/review",
data: {title_give:title,author_give:author,review_give:review},
success: function (response) {
alert(response["msg"]);
window.location.reload();
}
})
}
function showReview() {
$.ajax({
type: "GET",
url: "/review",
data: {},
success: function (response) {
let reviews=response['all_reviews']
for(let i=0;i<reviews.length;i++){
let title=reviews[i]['title']
let author=reviews[i]['author']
let review=reviews[i]['review']
let temp_html=` <tr>
<td>${title}</td>
<td>${author}</td>
<td>${review}</td>
</tr>`
$('#reviews-box').append(temp_html)
}
}
})
}
</script>
<style type="text/css">
* {
font-family: 'Nanum Myeongjo', serif;
}
h1,
h5 {
display: inline;
}
.info {
margin-top: 20px;
margin-bottom: 20px;
}
.review {
text-align: center;
}
.reviews {
margin-top: 100px;
}
</style>
</head>
<body>
<div class="container">
<img src="https://cdn.pixabay.com/photo/2020/07/24/09/49/books-5433432_960_720.jpg"
class="img-fluid" alt="Responsive image">
<div class="info">
<h1>읽은 책에 대해 말씀해주세요.</h1>
<p>다른 사람을 위해 리뷰를 남겨주세요! 다 같이 좋은 책을 읽는다면 다 함께 행복해질 수 있지 않을까요?</p>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">제목</span>
</div>
<input type="text" class="form-control" id="title">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">저자</span>
</div>
<input type="text" class="form-control" id="author">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">리뷰</span>
</div>
<textarea class="form-control" id="bookReview"
cols="30"
rows="5" placeholder="140자까지 입력할 수 있습니다."></textarea>
</div>
<div class="review">
<button onclick="makeReview()" type="button" class="btn btn-primary">리뷰 작성하기</button>
</div>
</div>
<div class="reviews">
<table class="table">
<thead>
<tr>
<th scope="col">제목</th>
<th scope="col">저자</th>
<th scope="col">리뷰</th>
</tr>
</thead>
<tbody id="reviews-box">
</tbody>
</table>
</div>
</div>
</body>
</html>
* API 만들고 사용하기- 제목, 저자, 리뷰 정보 저장하기(Create->POST)
1. 클라이언트와 서버 확인하기
2. 서버부터 만들기
3. 클라이언트 만들기
4. 완성 확인하기
'웹' 카테고리의 다른 글
20. 영화 리뷰 메모장(2) (0) | 2021.09.10 |
---|---|
19. 메모장(1) (0) | 2021.09.08 |
17. flask (0) | 2021.09.05 |
16. 웹스크래핑 연습 (0) | 2021.09.04 |
15. pymongo로 DB조작하기 (0) | 2021.09.03 |
댓글