'Our Playlist' 사이트 바로가기
👉 output
원래 숙제는 4주차 숙제로 한 팬명록 : 웹개발 종합반_homework_4주차를 웹배포하는 거 였지만, 팬명록을 응용해서 만든 playlist 사이트로 대체함
❗️ 작업 순서
① 클라이언트와 서버 연결 확인하기
② 서버부터 만들기
③ 클라이언트 만들기
app.py
파일에 DB 연결, 데이터 추가 코드 기입# post 요청 api 코드
@app.route("/playlist", methods=["POST"])
def playlist_post():
name_receive = request.form['name_give']
artist_receive = request.form['artist_give']
title_receive = request.form['title_give']
# DB 값 저장
if (name_receive == '' or artist_receive == '' or title_receive == '') :
return jsonify({'msg_x': 'Fill in the blanks'})
else: doc = {
'name': name_receive,
'artist': artist_receive,
'title': title_receive
}
db.playlist.insert_one(doc)
return jsonify({'msg_o': 'Thank you for your recommendation!'})
❗️ 오류코드
초반에는 일단 모든 DB 값을 저장하고, 목록의 값이 공백인 데이터를 삭제하는 방식으로 구현하려고 했으나 오류남 (방식이 아예 틀린 건 아닌 것 같은데, 어떻게 해야 정상적으로 실행되는 지는 모르겠음)
doc = { 'name' : name_receive, 'artist' : artist_receive, 'title' : title_receive } db.playlist.insert_one(doc) return jsonify({'msg':'Thank you for your recommendation!'}) # 데이터 삭제하기 db.playlist.delete_many({'artist' : ''}) db.playlist.delete_many({'song' : ''}) db.playlist.delete_many({'name' : ''})
index.html
파일에 input에 기입되는 값을 데이터로 만든 후 app.py
파일과 연결 및 새로고침 기능 추가// # 플리 저장하기
function save_playlist(){
// # input id box 입력한 데이터 가져오기
let name = $('#name').val()
let artist = $('#artist').val()
let title = $('#title').val()
$.ajax({
type: 'POST',
url: '/playlist',
// # app.py 파일에서 명칭한 대로 데이터 연결
data: { name_give : name, artist_give : artist, title_give : title },
success: function (response) {
if (name == '' || artist == '' || title == '') {
alert(response['msg_x'])
}else {
alert(response['msg_o'])
// # 새로고침 코드
window.location.reload()
}
}
})
}
❗️ 작업 순서
① 클라이언트와 서버 연결 확인하기
② 서버부터 만들기
③ 클라이언트 만들기
④ 확인하기
app.py
실행해서 index.html
와의 연결 확인app.py
파일에 데이터 가져오는 코드 기입# get 요청 api 코드
@app.route("/playlist", methods=["GET"])
def playlist_get():
# DB 모든 값 가져오기
song_list = list(db.playlist.find({}, {'_id' : False}))
return jsonify({'lists' : song_list})
index.html
파일에 로딩 시 DB의 리스트를 조건문으로 가져오고, DB 값을 태그 내 탬플릿으로 붙이기 // # 로딩 후 바로 호출
$(document).ready(function () {
show_playlist()
// # 플리 보여주기
function show_playlist(){
$.ajax({
type: "GET",
url: "/playlist",
data: {},
success: function (response) {
// # DB의 리스트 가져오기
let rows = response['lists']
for (let i = 0; i < rows.length; i++) {
let name = rows[i]['name']
let artist = rows[i]['artist']
let title = rows[i]['title']
// # DB 값 태그 내 탬플릿으로 붙이기
if (name != '' & artist != '' & title != '') {
let temp_html = `<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p><span style= "font-weight: bold;">${title}</span></p>
<footer class="blockquote-footer"><span style= "font-weight: bold;">${artist}</span> <span style= "font-size: 14px;">(written by ${name})</span></cite></footer>
</blockquote>
</div>
</div>`
$('#songs').append(temp_html)
}
}
}
});
}
Fill in the blanks
메시지 알림👉 output
🔎 추가로 서칭한 내용
- 특정 단어 크기 조절
<span style="font-size: 30px;"> 특정 단어</span>
- 특정 단어 폰트 굵기 조절
<span style="font-weight: bold"> 특정 단어</span>
리스트 저장하기와 보여주기에서 클라이언트 만들 때 일일이 목록의 값이 빈칸이 아닐 때만 DB 저장하는 조건문을 달았는데, 오류는 없지만 뭔가 간단한 정리법이 있을 것 같아서 만족스럽지는 않다. 또 뭔가 쓸데없이 코드가 길어진 느낌이다.