
app.py 부분
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.9sxfkbl.mongodb.net/Cluster0?retryWrites=true&w=majority',tlsCAFile=ca)
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route('/bucket_list')
def bucket():
return render_template('bucket.html')
@app.route('/mars_list')
def mars():
return render_template('mars.html')
@app.route('/movie_list')
def movie():
return render_template('movie.html')
@app.route("/homework", methods=["POST"])
def homework_post():
name_receive = request.form['name_give']
comment_receive = request.form['comment_give']
doc = {
'name':name_receive,
'comment':comment_receive
}
db.homeworks.insert_one(doc)
print(name_receive)
return jsonify({'msg': '응원 완료!'})
@app.route("/homework", methods=["GET"])
def homework_get():
comment_list = list(db.homeworks.find({}, {'_id': False}))
return jsonify({'comments':comment_list})
# bucket 작성하기 app.py
@app.route("/bucket", methods=["POST"])
def bucket_post():
bucket_receive = request.form['bucket_give']
bucket_list = list(db.buckets.find({}, {'_id': False}))
count = len(bucket_list) + 1
doc = {
'bucket':bucket_receive,
'num': count,
'done': 0
}
db.buckets.insert_one(doc)
return jsonify({'msg': '버킷 저장 완료!'})
@app.route("/bucket/done", methods=["POST"])
def bucket_done():
num_receive = request.form['num_give']
db.buckets.update_one({'num': int(num_receive)}, {'$set': {'done': 1}})
return jsonify({'msg': '버킷 완료!'})
@app.route("/bucket", methods=["GET"])
def bucket_get():
bucket_list = list(db.buckets.find({}, {'_id': False}))
return jsonify({'buckets': bucket_list})
# mars 땅 사기-----------------------------------------------------------
@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})
#movie 영화 기록하기-------------------------------------------------
@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')
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 = {
'star':star_receive,
'comment':comment_receive,
'title':title,
'desc':desc,
'image':image
}
db.movies.insert_one(doc)
return jsonify({'msg':'영화 기록 완료!'})
@app.route("/movie", methods=["GET"])
def movie_get():
movie_list = list(db.movies.find({}, {'_id': False}))
return jsonify({'movies':movie_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
index 부분
<!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">
<meta property="og:title" content="developer 김재우" />
<meta property="og:description" content="김재우의 웹페이지" />
<meta property="og:image" content="https://images.unsplash.com/photo-1597665951742-f4c50175d04a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fCVFQSVCNSVBQyVFQiVBNiU4NHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60" />
<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://images.unsplash.com/photo-1597665951742-f4c50175d04a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1031&q=80');
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 save_comment() {
let name = $('#name').val()
let comment = $('#comment').val()
$.ajax({
type: 'POST',
url: '/homework',
data: {name_give:name, comment_give:comment},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
function show_comment() {
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response['comments']
for (let i =0; i < rows.length; i++) {
let name = rows[i]['name']
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">${name}</footer>
</blockquote>
</div>
</div>`
$('#comment-list').append(temp_html)
}
}
});
}
</script>
</head>
<body>
<div class="mypic">
<h1>developer 김재우</h1>
<p>현재기온: <span id="temp">36</span>도</p>
</div>
<div>
<nav class="navbar navbar-dark bg-dark">
<nav class="navbar navbar-expand-lg navbar-light bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="http://localhost:5000">home</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active" aria-current="page" href="http://localhost:5000/mars_list">mars</a>
<a class="nav-link" href="http://localhost:5000/bucket_list">버킷리스트 작성하기</a>
<a class="nav-link" href="http://localhost:5000/movie_list">영화 기록하기</a>
<a class="nav-link disabled" href="http://localhost:5000" tabindex="-1" aria-disabled="true">나의 작업물</a>
</div>
</div>
</div>
</nav>
<!-- Navbar content -->
</nav>
</div>
<div class="mypost">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="name" 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>
app.py 를 실행하였을땐 네비바의 버킷리스트, 영화기록하기,mars 땅 사기 등등 정상 동작을 하는데 git-bash 로 app.py를 실행하였을땐
localhost 오류가 납니다. AWS랑 pymongo, 가비아 등등 다 살펴보았는데 해결 방법을 모르겠어서 질문 드립니다. 어떻게 해야 localhost:5000/bucket_list 웹페이지도 핸드폰에서 정상적으로 열려서 동작할 수 있을지 궁금합니다. ㅠㅠ
