on
4주차_Flask_get, post(2)
4주차_Flask_get, post(2)
우리가 만들 API 두 가지
1) 포스팅API - 카드 생성 (Create) : 클라이언트에서 받은 url, comment를 이용해서 정보를 찾고 저장하기 (POST)
2) 리스팅API - 저장된 카드 보여주기 (Read) (GET)
1) POST
①클라이언트와 서버 연결 확인하기
[서버 코드 - app.py]
@app.route('/memo', methods=['POST'])
def saving():
url_receive = request.form['url_give']
comment_receive = request.form['comment_give']
return jsonify({'msg':'저장완료'})
[클라이언트 코드 - index.html]
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();
}
})
}
동작 테스트
'기사저장' 버튼을 클릭했을 때, '저장완료' alert창이 뜨면 클라이언트 코드와 서버 코드가 연결 되어있는 것입니다.
②서버, 클라이언트 만들기
위에 미리 설계해 둔 API 정보를 보고 만들어보겠습니다.
메모를 작성하기 위해 서버가 전달받아야하는 정보는 다음 두 가지 입니다.
URL(url_give)
코멘트(comment_give)
그리고 URL를 meta tag를 스크래핑해서 아래 데이터를 저장(Create)합니다.
URL(url)
제목(title)
설명(desc)
이미지URL(image)
코멘트(comment)
따라서 서버 로직은 다음 단계로 구성되어야 합니다.
클라이언트로부터 데이터를 받기. meta tag를 스크래핑하기 mongoDB에 데이터를 넣기
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 (); //정보를 입력한 뒤에 새로고침 @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' )
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' : ' 저장완료 ' })
from http://ojy4535.tistory.com/38 by ccl(A) rewrite - 2021-07-24 22:26:26