ネットワーク4週目
77710 ワード
bs 4を使用してmetaタグを記述する場合は、既存のスクリプトフォーマットとは異なる必要があります(alonememo app.pyを参照).
-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
<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']//all_reviews 자체가 respons가 아님 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: "Do Hyeon", sans-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://previews.123rf.com/images/maxxyustas/maxxyustas1511/maxxyustas151100002/47858355-education-concept-books-and-textbooks-on-the-bookshelf-3d.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>
2. alonememo-app.py
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
## HTML을 주는 부분
@app.route('/')
def home():
return render_template('index.html')
@app.route('/memo', methods=['GET'])
def listing():
articles = list(db.articles.find({}, {'_id': False}))
return jsonify({'all_articles':articles})
## API 역할을 하는 부분
@app.route('/memo', methods=['POST'])
def saving():
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')
title = soup.select_one('meta[property="og:title"]')['content']
image = soup.select_one('meta[property="og:image"]')['content']
desc = soup.select_one('meta[property="og:description"]')['content']
doc={
'title':title,
'image':image,
'desc':desc,
'url':url_receive,
'comment':comment_receive
}
db.articles.insert_one(doc)
return jsonify({'msg':'저장이 완료되었습다!'})
if __name__ == '__main__':
app.run('0.0.0.0',port=5000,debug=True)
-index.html <script>
$(document).ready(function () {
showArticles();
});
function openClose() {
if ($("#post-box").css("display") == "block") {
$("#post-box").hide();
$("#btn-post-box").text("포스팅 박스 열기");
} else {
$("#post-box").show();
$("#btn-post-box").text("포스팅 박스 닫기");
}
}
function postArticle() {
let url = $('#post-url').val();
let comment = $('#post-comment').val();
$.ajax({
type: "POST",
url: "/memo",
data: {url_give: url, comment_give: comment},
success: function (response) { // 성공하면
alert(response["msg"]);
window.location.reload();
}
})
}
function showArticles() {
$.ajax({
type: "GET",
url: "/memo",
data: {},
success: function (response) {
let articles = response['all_articles']
for (let i = 0; i < articles.length; i++) {
let title = articles[i]['title'];
let comment = articles[i]['comment'];
let url = articles[i]['url'];
let image = articles[i]['image'];
let desc = articles[i]['desc'];
let temp_html =
`<div class="card">
<img class="card-img-top"
src="${image}"
alt="Card image cap">
<div class="card-body">
<a target="_blank" href="${url}" class="card-title">${title}</a>
<p class="card-text">${desc}</p>
<p class="card-text comment">${comment}</p>
</div>
</div>`
$('#cards-box').append(temp_html);
}
}
})
}
</script>
</head>
<body>
<div class="wrap">
<div class="jumbotron">
<h1 class="display-4">나홀로 링크 메모장!</h1>
<p class="lead">중요한 링크를 저장해두고, 나중에 볼 수 있는 공간입니다</p>
<hr class="my-4">
<p class="lead">
<button onclick="openClose()" id="btn-post-box" type="button" class="btn btn-primary">포스팅 박스 열기
</button>
</p>
</div>
<div id="post-box" class="form-post" style="display:none">
<div>
<div class="form-group">
<label for="post-url">아티클 URL</label>
<input id="post-url" class="form-control" placeholder="">
</div>
<div class="form-group">l
<label for="post-comment">간단 코멘트</label>
<textarea id="post-comment" class="form-control" rows="2"></textarea>
</div>
<button type="button" class="btn btn-primary" onclick="postArticle()">기사저장</button>
</div>
</div>
<div id="cards-box" class="card-columns">
</div>
</div>
</body>
</html>
3.販売(作業)-app.py
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbhomework
## HTML 화면 보여주기
@app.route('/')
def homework():
return render_template('index.html')
# 주문하기(POST) API
@app.route('/order', methods=['POST'])
def save_order():
name_receive = request.form['name_give']
num_receive = request.form['num_give']
address_receive = request.form['address_give']
number_receive = request.form['number_give']
doc ={
'name':name_receive,
'num':num_receive,
'address':address_receive,
'number':number_receive
}
db.sales.insert_one(doc)
return jsonify({'msg': '저장 완료'})
# 주문 목록보기(Read) API
@app.route('/order', methods=['GET'])
def view_orders():
orders = list(db.sales.find({}, {'_id': False}))
return jsonify({'result':'success','all-orders':orders})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
-index.html(略記)<script>
$(document).ready(function () {
get_rate();
show();
});
function get_rate() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rate",
data: {},
success: function (response) {
let exchangeR = response['rate'];
$('#exchangeR').text(exchangeR);
}
})
}
function order() {
let name = $('#getName').val();
let num = $('#num').val();
let address = $('#getAddress').val();
let number = $('#getNumber').val();
$.ajax({
type: "POST",
url: "/order",
data: {name_give: name, num_give: num, address_give: address, number_give: number},
success: function (response) {
console.log(response)
window.location.reload();
}
})
}
function show() {
$.ajax({
type: "GET",
url: "/order",
data: {},
success: function (response) {
let orders = response['all-orders'];
for (let i = 0; i < orders.length; i++) {
let name = orders[i]['name'];
let num = orders[i]['num'];
let address = orders[i]['address'];
let number = orders[i]['number'];
temp_html = `<tr>
<th scope="row">${name}</th>
<th>${num}</th>
<th>${address}</th>
<th>${number}</th>
</tr>`
$('#form').append(temp_html);
}
}
})
}
</script>
<body>
<div class="list">
<table class="table">
<thead>
<tr>
<th scope="col">이름</th>
<th scope="col">수량</th>
<th scope="col">주소</th>
<th scope="col">전화번호</th>
</tr>
</thead>
<tbody id="form">
</tbody>
</table>
</div>
</body>
Reference
この問題について(ネットワーク4週目), 我々は、より多くの情報をここで見つけました https://velog.io/@gkscodus2/웹-4주차-숙제-추가-업로드-필요テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol