API 순서
클라이언트와 서버 확인하기
서버부터 만들기
💡 서버 쪽 할 일
- 1) 클라이언트가 준 image, title, content 가져오기
- 2) DB에 정보 삽입하기
- 3) 성공 메시지 반환하기
# 일기 저장
@app.route('/diary', methods=['POST'])
def saving():
image = request.files['image_give']
title_receive = request.form['title_give']
content_receive = request.form['content_give']
# 파일 확장자 분리
extension = image.filename.split('.')[-1]
# 시간과 확장자 붙여주고 static 폴더에 저장
today = datetime.now()
date_time = today.strftime('%Y-%m-%d-%H-%M-%S')
image_name = f'image-{date_time}'
save_to = f'static/{image_name}.{extension}'
image.save(save_to)
#diary 컬렉션에 저장
doc = {
'image': f'{image_name}.{extension}',
'title': title_receive,
'content': content_receive
}
db.diary.insert_one(doc)
return jsonify({'msg': '저장이 완료되었습니다!'})
✅ Check Point
form data form에서 file 가져오는 형태 주의!
마지막 배열 값 -1로 가져오기
f-string 앞에 f를 붙여주면 변수값을 {}로 가져올 수 있음
Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
datetime 참고
import 해주기! from datetime import datetime
클라이언트 만들기
💡 클라이언트 쪽 할 일
- 1) image, title, content를 서버에 넘기기
- 2) 받은 msg를 alert로 띄우고 → 새로고침 하기
function save() {
let image = $('#file')[0].files[0]
let title = $('#card-title').val()
let content = $('#card-text').val()
// 파일은 form으로 받음
let form_data = new FormData()
form_data.append("image_give", image)
form_data.append("title_give", title)
form_data.append("content_give", content)
// 데이터 전달하고 컬렉션에 저장되면 확인
$.ajax({
type: "POST",
url: "/diary",
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function (response) {
alert(response["msg"])
window.location.reload()
}
})
}
✅ Check Point
file data 변수에 파일 넣는 형태 주의!
form data form에 데이터 어떻게 넣는지 확인
완성 확인하기
클라이언트와 서버 확인하기
→ 이건 이미 위에서 완료!
서버부터 만들기
💡 서버 쪽 할 일
- 1) 클라이언트에서 받을 것 없음!
- 2) DB에서 title, content를 리스트로 가져오기
- 3) 가져온 리스트를 클라이언트에 보내주기
# diary 컬렉션 데이터 보내주기
@app.route('/diary', methods=['GET'])
def listing():
diaries = list(db.diary.find({}, {'_id': False}))
return jsonify({'all_diary': diaries})
클라이언트 만들기
💡 클라이언트 쪽 할 일
- 1) 서버에 요청 (데이터 줄 것 없음!)
- 2) 받은 데이터로 카드를 만들어 붙여주기
// 받은 데이터 불러와서 카드에 하나씩 넣고 붙이기
function listing() {
$.ajax({
type: "GET",
url: "/diary",
data: {},
success: function (response) {
let diaries = response['all_diary']
for (let i = 0; i < diaries.length; i++) {
let image = diaries[i]['image']
let title = diaries[i]['title']
let content = diaries[i]['content']
let temp_html = `
<div class="card">
<img class="card-img-top" src="../static/${image}" alt="이미지">
<h5 class="card-title">${title}</h5>
<p class="card-text">${content}</p>
<p class="card-time"><small class="text-muted">${image.split('-').slice(1,4).join("-")}</small></p>
</div>
`
$('#cards-box').append(temp_html)
}
}
})
}
완성 확인하기
SAVE 💾
강의를 쭉 보고 그냥 맨 땅에서 쌓았다. 헷갈렸던 건 폼에 file 넣는 것과
file명에 어차피 시간이 들어가는데 또 넣는 건 별로인 것 같아서 따로 함수를 지정해줬다.
${image.split('-').slice(1,4).join("-")}
split은 구분자에 따라 나눈 뒤, slice로 배열 새로 넣고 join으로 붙이는데 사이에 구분자 넣기.
티스토리가 불편해서 벨로그로 넘어왔는데... 놀랍게도 더 어려움😭
css도 잘 안먹히고 들여쓰기도... 더보기도 안되고 서식도 없는 것 같고 흑흑..