🦄 팬명록 프로젝트(서버, DB)
사용자가 닉네임과 응원댓글을 입력하고 '응원 남기기' 버튼 클릭시, DB에 해당 정보들을 저장한다.
Window가 reload되면, DB에 있는 댓글 리스트들을 가져와서 화면에 보여준다.
배너에는 간단한 날씨API를 받아와서 현재기온도 추가 해 주도록 한다.
01 팬명록 - 프로젝트 셋팅
- 서버, DB만 사용 => flask, pymongo, dnspython => 날씨 API는 프론트에서 Fetch로 바로 진행할 것
$ pip install flask pymongo dnspython
02 팬명록 - 뼈대 준비하기
- app.py
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('mongodb+srv://junvely:test@cluster0.38f4se1.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/guestbook", methods=["POST"])
def guestbook_post():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg': 'POST 연결 완료!'})
@app.route("/guestbook", methods=["GET"])
def guestbook_get():
return jsonify({'msg': 'GET 연결 완료!'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
03 서울 날씨 Open API로 정보 가져오기
"http://spartacodingclub.shop/sparta_api/weather/seoul"
function set_temp() {
fetch("http://spartacodingclub.shop/sparta_api/weather/seoul")
.then((res) => res.json())
.then((data) => {
let weather = data["temp"];
$("#temp").text(weather);
});
}
04 팬명록 프로젝트 - POST API
1. 백엔드 POST API
def guestbook_post():
name_receive = request.form['name_give']
comment_receive = request.form['comment_give']
doc = {
'name' : name_receive,
'comment' : comment_receive,
}
db.comments.insert_one(doc)
print(doc)
return jsonify({'msg': '응원 완료!'})
2. 프론트 POST 요청
function save_comment() {
let name = $("#name").val();
let comment = $("#comment").val();
let formData = new FormData();
formData.append("name_give", name);
formData.append("comment_give", comment);
fetch("/guestbook", { method: "POST", body: formData })
.then((res) => res.json())
.then((data) => {
alert(data["msg"]);
window.location.reload();
});
}
05 팬명록 프로젝트 - GET API
1. 백엔드 GET API
@app.route("/guestbook", methods=["GET"])
def guestbook_get():
comments = list(db.comments.find({},{'_id':False}))
print(comments)
return jsonify({'comments':comments})
2. 프론트 GET 요청
function show_comment() {
fetch("/guestbook")
.then((res) => res.json())
.then((data) => {
$("#comment-list").empty();
let comments = data["comments"];
comments.forEach((comment) => {
let name = comment["name"];
let text = comment["comment"];
let temp_html = `
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${text}</p>
<footer class="blockquote-footer">${name}</footer>
</blockquote>
</div>
</div>
`;
$("#comment-list").append(temp_html);
});
});
}
06 og태그 넣기
- 내 홈페이지를 카톡 등 다른 곳에서 공유했을 때, og이미지와 타이틀 등으로 예쁜 참고설명이 뜨도록 만들기
1. <head>안에 <title>아래에 og태그 넣기
<meta property="og:title" content="내 사이트의 제목" />
<meta property="og:description" content="보고 있는 페이지의 내용 요약" />
<meta property="og:image" content="이미지URL" />
- 마음에 드는 사진과 설명을 content에 넣기
<meta property="og:title" content="김석진 팬명록" />
<meta property="og:description" content="김석진을 응원하는 팬명록입니다." />
<meta
property="og:image"
content="https://thumb.mtstarnews.com/06/2021/07/2021071608021016763_1.jpg/dims/optimize"
/>
- 완성!!🙌
728x90
반응형
'항해99 > 프로젝트' 카테고리의 다른 글
[TIL-024] 토이 프로젝트 협업 셋팅 (0) | 2023.05.06 |
---|---|
[AWS] 클라우드 서버에 배포하기 (0) | 2023.02.15 |
[Flask] 버킷리스트 프로젝트(서버, DB) (0) | 2023.02.15 |
[Flask] 스파르타피디아 프로젝트(서버, 크롤링, DB) (0) | 2023.02.15 |
[Flask] 화성땅 공동구매 프로젝트(서버, DB) (0) | 2023.02.14 |