[웹개발일지] #9. mini_project_2. 나홀로메모장
풀스택 웹개발 공부 기록하기 #9.
url을 입력하고 기사 저장을 눌렀을 때 '포스팅 성공!' alert 메시지!
😉Flask 활용, API, meta태그 스크래핑, POST, GET 😉
https://github.com/janghr1225/alonememo
💻 No.2 alone memo 💻
👉포스팅 박스를 열어
메모할 링크, 메모할 내용을 입력하고, 저장 버튼을 누르면
meta 태그가 불려오면서 입력한 내용이 저장됨!
💾 meta 태그 스크래핑
메타 태그는 <head></head> 부분에 들어가는, 눈으로 보이는 것(body)외에 사이트의 속성을 설명해주는 태그.
구글 검색시 표시 될 설명문, 사이트 제목, 카톡 공유 시 표시 될 이미지 등..
그 중 image, title, description을 크롤링 할 것.
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')
# 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.
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']
💾 POST (메모하기)
👉 만들 API- 포스팅 API (create -> POST)
클라이언트에서 받은 url, comment를 이용해서 페이지 정보 찾고 저장하기
👉 서버가 전달받아야 하는 정보
url(url_give), comment(comment_give)
👉 meta 태그 스크래핑해서 데이터 저장(create)
url, title, desc, image, comment
👉 서버 로직
1. 클라이언트로부터 데이터 받기
2. meta tag 스크래핑하기
3. mongoDB에 데이터 넣기
👉 클라이언트 로직
1. 유저가 입력한 데이터를 #post-url과 #post-comment에서 가져오기
2. /memo에 POST 방식으로 메모 생성 요청하기
3. 성공 시 페이지 새로고침하기
서버 만들기
## API 역할을 하는 부분
@app.route('/memo', methods=['POST'])
def saving():
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)
soup = BeautifulSoup(data.text, 'html.parser')
# 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.
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 = {
'title':title,
'image':image,
'desc':desc,
'url':url_receive,
'comment':comment_receive
}
db.articles.insert_one(doc)
return jsonify({'msg':'저장이 완료되었습니다!'})
클라이언트 만들기
function postArticle() {
let url = $('#post-url').val()
let comment = $('#post-comment').val()
$.ajax({
type: "POST",
url: "/memo",
data: {url_give:url, comment_give:comment},
success: function (response) { // 성공하면
alert(response["msg"]);
window.location.reload()
}
})
}
💾 GET(보여주기)
👉 만들 API- 리스팅 API (Read -> GET)
저장된 카드 보여주기
👉 서버 로직
1. mongoDB에서 _id값을 제외한 모든 데이터 조회해오기(Read)
2. article라는 키 값으로 articles 정보 보내주기
👉 클라이언트 로직
1. /memo에 GET 방식으로 메모 정보 요청하고 articles로 메모 정보 받기
2. , makeCard함수를 이용해서 카드 HTML 붙이기
서버 만들기
@app.route('/memo', methods=['GET'])
def listing():
articles = list(db.articles.find({}, {'_id': False}))
return jsonify({'all_articles':articles})
클라이언트 만들기
function showArticles() {
$.ajax({
type: "GET",
url: "/memo",
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]['image']
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>
</div>
</div>`
$('#cards-box').append(temp_html)
}
}
})
}