🔥 /projects/alonememo 폴더에서 시작!
✅ 포스팅API - 카드 생성 (Create)
A. 요청 정보
- 요청 URL=
/memo
, 요청 방식 =POST
- 요청 데이터 : URL(url_give), 코멘트(comment_give)
B. 서버가 제공할 기능
- URL의 meta태그 정보를 바탕으로 제목, 설명, 이미지URL 스크래핑
- (제목, 설명, URL, 이미지URL, 코멘트) 정보를 모두 DB에 저장
C. 응답 데이터
- API가 정상적으로 작동하는지 클라이언트에게 알려주기 위해서 성공 메시지 보내기
- (JSON 형식) 'result' = 'success'
✅ 리스팅API - 저장된 카드 보여주기 (Read)
A. 요청 정보
- 요청 URL=
/memo
, 요청 방식 =GET
- 요청 데이터 : 없음
B. 서버가 제공할 기능
- DB에 저장되어있는 모든 (제목, 설명, URL, 이미지URL, 코멘트) 정보를 가져오기
C. 응답 데이터
- 아티클(기사)들의 정보(제목, 설명, URL, 이미지URL, 코멘트) → 카드 만들어서 붙이기
- (JSON 형식) 'articles': 아티클 정보
💡 Tip
API에서 수행해야하는 작업 중 익숙하지 않은 것들은, 따로 python 파일 만들어 실행해보고, 잘 되면 코드 붙여넣는 방식으로 하는게 편함
<head></head>
부분에 들어가는, 눈에 보이는 속성(body) 외 사이트의 속성을 설명해주는 태그.og:image
/ og:title
/ og:description
을 크롤링 할 예정크롤링 기본 코드
import requests
from bs4 import BeautifulSoup
url = 'https://movie.naver.com/movie/bi/mi/basic.nhn?code=171539'
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,headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
select_one을 이용해 meta tag 가져오기
og_title = soup.select_one('meta[property="og:title"]')
og_image = soup.select_one('meta[property="og:image"]')
og_description = soup.select_one('meta[property="og:description"]')
print(og_image)
print(og_title)
print(og_description)
'meta[property="og:~~~"]'.['content']
로 가져옴가져온 meta tag의 content 가져오기
url_title = og_title['content']
url_image = og_image['content']
url_description = og_description['content']
print(url_title)
print(url_image)
print(url_description)
출력 결과
app.py
index.html
✅ 만들 API 두 가지
👉 1) 포스팅API - 카드 생성 (Create)
: 클라이언트에서 받은 url, comment를 이용해서 페이지 정보를 찾고 저장하기2) 리스팅API - 저장된 카드 보여주기 (Read)
서버 코드 - app.py
@app.route('/memo', methods=['POST'])
def post_articles():
sample_receive = request.form['sample_give']
print(sample_receive)
return jsonify({'msg': 'POST 연결되었습니다!'})
클라이언트 코드 - index.html
function postArticle() {
$.ajax({
type: "POST",
url: "/memo",
data: {sample_give:'샘플데이터'},
success: function (response) { // 성공하면
alert(response['msg']);
}
})
}
<button type="button" class="btn btn-primary" onclick="postArticle()">기사저장</button>
동작 테스트
메모를 작성하기 위해 서버가 전달 받아야 하는 정보
- URL (url_give)
- 코멘트 (comment_give)
URL에서 meta tag 스크래핑해 아래 데이터를 저장(Create)함
- URL(url)
- 제목(title)
- 설명(desc)
- 이미지URL(image)
- 코멘트(comment)
서버로직
- 클라이언트로부터 데이터 받기.
- meta tag를 스크래핑하기
- mongoDB에 데이터 넣기
@app.route('/memo', methods=['POST'])
def saving():
# 1. 클라이언트에게 데이터 받기
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)
# 2. 메타태그 스크래핑
soup = BeautifulSoup(data.text, 'html.parser')
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']
# 3. mongoDB에 데이터 넣기
doc = {
'title':title,
'image':image,
'desc':desc,
'url':url_receive,
'comment':comment_receive
}
db.articles.insert_one(doc)
return jsonify({'msg':'저장이 완료되었습니다!'})
메모 작성을 위해 서버에게 주어야하는 정보
- URL (url_give) : meta tag를 가져올 url
- comment (comment_give) : 유저가 입력한 코멘트
클라이언트 로직 구성
- 유저가 입력한 데이터를 #post-url 과 #post-comment에서 가져오기
- /memo에 POST 방식으로 메모 생성 요청
- 요청 성공시 페이지 새로고침
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()
}
})
}
동작 테스트
✅ 만들 API 두 가지
1) 포스팅API - 카드 생성 (Create)
: 클라이언트에서 받은 url, comment를 이용해서 페이지 정보를 찾고 저장하기👉 2) 리스팅API - 저장된 카드 보여주기 (Read)
서버 코드 - app.py
@app.route('/memo', methods=['GET'])
def read_articles():
# 1. 모든 document 찾기 & _id 값은 출력에서 제외하기
# 2. articles라는 키 값으로 영화정보 내려주기
return jsonify({'result':'success', 'msg':'GET 연결되었습니다!'})
클라이언트 코드 - index.html
function showArticles() {
$.ajax({
type: "GET",
url: "/memo",
data: {},
success: function (response) {
if (response["result"] == "success") {
alert(response["msg"]);
}
}
})
}
동작 테스트
메모를 보여주기 위해 서버가 추가로 전달받아야 하는 정보는 없음.(조건 없이 모든 메모를 보여줄것이기 때문에!)
서버 로직
- mongoDB에서 _id 값 제외한 모든 데이터 조회해오기 (Read)
- articles 라는 키 값으로 articles 정보 보내주기
@app.route('/memo', methods=['GET'])
def listing():
articles = list(db.articles.find({}, {'_id': False}))
return jsonify({'all_articles':articles})
클라이언트 로직
- /memo에 GET 방식으로 메모 정보 요청하고, articles로 메모 정보 받기
- makeCard 함수를 이용해 카드 HTML 붙이기
(→ 2주차 Ajax 연습과 같음)
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)
}
}
})
}
동작 테스트
참고!
card 정렬 순서는 위 -> 아래 / 왼쪽 -> 오른쪽.
(부트스트랩 컴포넌트 페이지에 적혀있음)
📃 1주차에 완성한 쇼핑몰 완성하기
쇼핑몰의 두가지 기능
1) 주문하기(POST): 정보 입력 후 '주문하기' 버튼클릭 시 주문목록에 추가
2) 주문내역보기(GET): 페이지 로딩 후 하단 주문 목록이 자동으로 보이기
아래 완성본 참고
- http://spartacodingclub.shop/homework
- 아래 주문정보를 붙일 때에는, 부트스트랩 Table(링크) 이용하기
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
## HTML 화면 보여주기
@app.route('/')
def homework():
return render_template('index.html')
## 주문 목록 가져오기(Read) API
@app.route('/order', methods=['GET'])
def listing():
orders = list(db.orders.find({}, {'_id': False}))
return jsonify({'result': 'success', 'orders': orders})
## 주문을 목록에 추가하기(POST) API
@app.route('/order', methods=['POST'])
def saving():
# 1. 클라이언트에게 데이터 받기
name_receive = request.form['name_give']
count_receive = request.form['count_give']
address_receive = request.form['address_give']
phone_receive = request.form['phone_give']
# 2. mongoDB에 데이터 넣기
doc = {
'name': name_receive,
'count' : count_receive,
'address': address_receive,
'phone': phone_receive
}
db.orders.insert_one(doc)
return jsonify({'result': 'success', 'msg':'주문이 완료되었습니다!'})
if __name__ == '__main__':
app.run('0.0.0.0',port=5000,debug=True)
$(document).ready(function(){
get_rate();
listing();
})
// 목록 가져오기
function listing(){
$.ajax({
type: "GET",
url: "/order",
data: {},
success: function (response) {
if(response["result"]==="success"){
let orders = response['orders'];
//console.log(orders);
for(let i=0; i<orders.length; i++){
let name = orders[i]['name'];
let count = orders[i]['count'];
let address = orders[i]['address'];
let phone = orders[i]['phone'];
let temp_html = `<tr>
<th scope="row">${name}</th>
<td>${count}</td>
<td>${address}</td>
<td>${phone}</td>
</tr>`
$('#orders-box').append(temp_html);
}
}
}
})
}
// 현재 환율 가져오기
function get_rate() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rate",
data: {},
success: function (response) {
let now_rate = response['rate'];
$('#now-rate').text(now_rate);
}
})
}
function order() {
let name = $('#order-name').val();
let count = $('#order-count').val();
let address = $('#order-address').val();
let phone = $('#order-phone').val();
$.ajax({
type: "POST",
url: "/order",
data: {name_give: name, count_give: count, address_give: address, phone_give: phone},
success: function (response) {
if(response['result']==='success'){
alert(response['msg']);
window.location.reload();
}
}
})
}
안녕하세요. 개발과정 공부중입니다!
혹시 클라이언트 서버 연결확인하기 과정에서 'POST 연결되었습니다'라는 alert창이 안뜨면 무엇이 문제인지 알 수 있을까요 ? 제 추측으론 클라이언트와 서버가 연결이 안된거 같은데 ... 과정 그대로 따라했는데 뭐가 문제 인지 찾기 어렵습니다...