나홀로 메모장
2022. 1. 6. 00:58ㆍ코딩공부/프로젝트 완성본
- flask framework를 사용하여 서버구동
- bs4를 사용하여 크롤링(웹스크래핑)
- ajax를 사용하여 포스팅 박스를 열고 닫을 수 있게함
- client에서 ajax로 유저가 입력한 정보를 API에 post & get
- API에서 pymong로 client로부터 받은 정보를 request해서 DB에 insert해주고 보여줄 정보를 find해서 다시 client에 전송
삭제 delete 기능 추가
에러 : 삭제 버튼을 눌렀을 때 삭제가 작동은 안하고 404에러를 띄웠다
해결 :
- 삭제 링크 onclick에 delete함수를 넣었는데 그 부분에 파라미터가 설정되지 않은걸 확인
// <p><a href="#" onclick="deleteArticle()">삭제</a></p>
<p><a href="#" onclick="deleteArticle('${comment}')">삭제</a></p>
- 이 전 프로젝트와 비교해보다가 API의 @app.route와 client파일의 ajax부분의 url을 listing, saving, delete 별로 다 나누어주니 정상작동 했다.
function postArticle() {
// post-url과 post-comment에 입력된 값 가져오기
let url = $('#post-url').val()
let comment = $('#post-comment').val()
$.ajax({
type: "POST",
url: "/memo/input",
data: {url_give: url, comment_give: comment},
success: function (response) { // 성공하면
alert(response["msg"]);
window.location.reload() // 새로고침
}
})
}
function showArticles() {
$.ajax({
type: "GET",
url: "/memo/list",
data: {},
success: function (response) {
let articles = response['all_articles']
for (let i = 0; i < articles.length; i++) {
let title = articles[i]['title']
let image = articles[i]['img']
let url = articles[i]['url']
let desc= articles[i]['desc']
let comment = articles[i]['comment']
let temp_html = `<div class="card">
<img class="card-img-top"
src="${image}"
alt="Card image cap">
<div class="card-body">
<a target="_blank" href="${url}" class="card-title">${title}</a>
<p class="card-text">${desc}</p>
<p class="card-text comment">${comment}</p>
<p><a href="#" onclick="deleteArticle('${comment}')">삭제</a></p>
</div>
</div>`
$('#cards-box').append(temp_html)
}
}
})
}
function deleteArticle(comment) {
$.ajax({
type: 'POST',
url: '/memo/delete',
data: {comment_give: comment},
success: function (response) {
alert(response['msg']);
window.location.reload()
}
});
}
@app.route('/memo/list', methods=['GET'])
def listing():
articles = list(db.articles.find({}, {'_id': False}))
return jsonify({'all_articles':articles})
## API 역할을 하는 부분
@app.route('/memo/input', methods=['POST'])
def saving():
# 클라이언트에서 url과 comment 데이터를 받아온다
url_receive = request.form['url_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) # url_receive를 넣어줌
soup = BeautifulSoup(data.text, 'html.parser')
title = soup.select_one('meta[property="og:title"]')['content']
img = soup.select_one('meta[property="og:image"]')['content']
desc = soup.select_one('meta[property="og:description"]')['content']
# db에 가져온 데이터 insert
doc = {
'title': title,
'img': img,
'desc': desc,
'url': url_receive,
'comment': comment_receive
}
db.articles.insert_one(doc)
return jsonify({'msg':'저장되었습니다!'})
@app.route('/memo/delete', methods=['POST'])
def delete_article():
comment_receive = request.form['comment_give']
db.articles.delete_one({'comment': comment_receive})
return jsonify({'msg': '삭제 완료!'})
문제
같은 url의 카드가 2개이상 작성되었을 경우에 삭제 버튼을 누르면 삭제버튼을 누른 카드가 아니라 먼저 작성된 카드부터 삭제가 된다
해결
삭제하는 함수의 파라미터를 title로 받아서 DB에서 삭제기능을 수행할 때 같은 title이면 어떤 데이터인지 구분을 못했다. 삭제 함수 파라미터를 보조키인 comment로 바꾸니 정상작동하였다.
'코딩공부 > 프로젝트 완성본' 카테고리의 다른 글
JavaScript 조건문 나혼자 해본 실습(주간야간모드) (0) | 2022.01.08 |
---|---|
마이 페이보릿 무비스타 (0) | 2022.01.07 |
원페이지 쇼핑몰 (0) | 2022.01.06 |
모두의 책리뷰 (0) | 2022.01.06 |