드디어 길고 길었던 4주차...사실 밀려서 지금 엄청나게 급하게 하는중...
이번주에는 총 3가지 웹페이지를 만들었다
서버 하나에 html 3개 번갈아가며 넣은거니까 3개로 칠 수 있는지는 모르겠지만...ㅎㅎㅎ
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('mongodb+srv://real:비밀번호는 가리는게 정석이쥬@cluster0.cni45.mongodb.net/dbsparta?retryWrites=true&w=majority')
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/mars", methods=["POST"])
def web_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 web_mars_get():
order_list = list(db.mars.find({},{'_id':False}))
return jsonify({'orders': order_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
<!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() {
$.ajax({
type: "GET",
url: "/mars",
data: {},
success: function (response) {
let rows = response["orders"];
for (let i = 0; i < rows.length; i++) {
let name = rows[i]["name"];
let address = rows[i]["address"];
let size = rows[i]["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();
$.ajax({
type: "POST",
url: "/mars",
data: { name_give: name, address_give: address, size_give: size },
success: function (response) {
alert(response["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">
>
</tbody>
</table>
</div>
</body>
</html>
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('mongodb+srv://real:비밀번호는 가려줘야 제맛@cluster0.cni45.mongodb.net/Cluster0?retryWrites=true&w=majority')
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']
star_receive = request.form['star_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')
og_image = soup.select_one('meta[property="og:image"]')
og_title = soup.select_one('meta[property="og:title"]')
og_description = soup.select_one('meta[property="og:description"]')
image = og_image['content']
title = og_title['content']
description = og_description['content']
doc = {
'image':image,
'title':title,
'desc':description,
'star':star_receive,
'comment':comment_receive
}
db.movies.insert_one(doc)
return jsonify({'msg':'기록 완료!'})
@app.route("/movie", methods=["GET"])
def movie_get():
movies_list = list(db.movies.find({},{'_id':False}))
return jsonify({'movies':movies_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, 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() {
$.ajax({
type: "GET",
url: "/movie",
data: {},
success: function (response) {
let rows = response["movies"];
for (let i = 0; i < rows.length; i++) {
let comment = rows[i]["comment"];
let title = rows[i]["title"];
let desc = rows[i]["desc"];
let image = rows[i]["image"];
let star = rows[i]["star"];
let star_image = "⭐".repeat(star);
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_image}</p>
<p class="mycomment">${comment}</p>
</div>
</div>
</div>`;
$("#cards-box").append(temp_html);
}
},
});
}
function posting() {
let url = $("#url").val();
let star = $("#star").val();
let comment = $("#comment").val();
$.ajax({
type: "POST",
url: "/movie",
data: { url_give: url, star_give: star, comment_give: comment },
success: function (response) {
alert(response["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>
</div>
</body>
</html>
하도 몰라서 결국 튜터님께 질문했다.
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('mongodb+srv://real:비밀번호 안알랴줌@cluster0.cni45.mongodb.net/dbsparta?retryWrites=true&w=majority')
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/homework", methods=["POST"])
def homework_post():
nickname_receive = request.form['nickname_give']
comment_receive = request.form['comment_give']
doc = {
'nickname':nickname_receive,
'comment':comment_receive
}
db.homework.insert_one(doc)
return jsonify({'msg':'응원 완료!'})
@app.route("/homework", methods=["GET"])
def homework_get():
comment_list = list(db.homework.find({},{'_id':False}))
return jsonify({'comments':comment_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
<!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>
<title>허광한 팬명록</title>
<link
href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap"
rel="stylesheet"
/>
<style>
* {
font-family: "Noto Serif KR", serif;
}
.mypic {
width: 100%;
height: 300px;
background-image: linear-gradient(
0deg,
rgba(0, 0, 0, 0.5),
rgba(0, 0, 0, 0.5)
),
url("https://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAyMDAyMTZfMTI1%2FMDAxNTgxODYyMDY0Mzcz.eT3jfREbrjg_iEyXfM1SrlgfE-FphDhB83G0Ij4zOd0g.aWcpioWF6sPhXul9Pigifu3iiulUmibRIKYi_zXgBcog.JPEG.debedebedep%2FIMG_1319.JPG&type=sc960_832");
background-position: center 30%;
background-size: cover;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.mypost {
width: 95%;
max-width: 500px;
margin: 20px auto 20px auto;
box-shadow: 0px 0px 3px 0px black;
padding: 20px;
}
.mypost > button {
margin-top: 15px;
}
.mycards {
width: 95%;
max-width: 500px;
margin: auto;
}
.mycards > .card {
margin-top: 10px;
margin-bottom: 10px;
}
</style>
<script>
$(document).ready(function () {
set_temp();
show_comment();
});
function set_temp() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function (response) {
$("#temp").text(response["temp"]);
},
});
}
function show_comment() {
$("#comment-list").empty();
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response["comments"];
for (let i = 0; i < rows.length; i++) {
let nickname = rows[i]["nickname"];
let comment = rows[i]["comment"];
let temp_html = `<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment}</p>
<footer class="blockquote-footer">${nickname}</footer>
</blockquote>
</div>
</div>`;
$("#comment-list").append(temp_html);
}
},
});
}
function save_comment() {
let nickname = $("#nickname").val();
let comment = $("#comment").val();
$.ajax({
type: "POST",
url: "/homework",
data: { nickname_give: nickname, comment_give: comment },
success: function (response) {
alert(response["msg"]);
window.location.reload();
},
});
}
</script>
</head>
<body>
<div class="mypic">
<h1>허광한 팬명록</h1>
<p>현재기온: <span id="temp">36</span>도</p>
</div>
<div class="mypost">
<div class="form-floating mb-3">
<input
type="text"
class="form-control"
id="nickname"
placeholder="url"
/>
<label for="floatingInput">닉네임</label>
</div>
<div class="form-floating">
<textarea
class="form-control"
placeholder="Leave a comment here"
id="comment"
style="height: 100px"
></textarea>
<label for="floatingTextarea2">응원댓글</label>
</div>
<button onclick="save_comment()" type="button" class="btn btn-dark">
응원 남기기
</button>
</div>
<div class="mycards" id="comment-list"></div>
</body>
</html>
미쳐미쳐...... }뒤에 세미콜론 하나 붙였다가 진짜 onclick이랑 success인식 안되서 코드 다시 복붙하고 지우고 쓰기를 한 100번은 한 듯
function show_comment() {
$('#comment_list').empty()
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response["comments"]
for (let i = 0; i < rows.length; i++) {
let nickname = rows[i]["nickname"];
let comment = rows[i]["comment"];
console.log(name, comment)
}
}
});
};
function save_comment() {
let nickname = $("#nickname").val();
let comment = $("#comment").val();
$.ajax({
type: "POST",
url: "/homework",
data: {'nickname_give': nickname, 'comment_give': comment},
success: function (response) {
alert(response["msg"]);
window.location.reload();
}
});
};
혼돈의 4주차였다...진짜 5주차까지 끝나면 html과 css 공부를 추가적으로 많이해야할 것 같다. 요즘 너무 훑고 슝 넘어가는 느낌이 많이 들어서 머리가 아프다ㅠㅠ