4주차 코딩 개발 일지(4-10~4-15)

영현·2022년 3월 21일
0

☑️ [나홀로메모장] 프로젝트

  • API 설계하기
    ✔︎ 포스팅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': 아티클 정보

✔︎ 스크랩핑이 필요한 부분 → '기사 제목', '썸네일 이미지', '내용'

  • meta 태그 알아보기
- 메타 태그는, <head></head> 부분에 들어가는,
  눈으로 보이는 것 (body) 외에 사이트의 속성을 설명해주는 태그들
    
    예) 구글 검색 시 표시 될 설명문, 사이트 제목, 카톡 공유 시 표시 될 이미지 등
    
- 그 중 og:image / og:title / og:description 을 크롤링 할 예정
  • meta 태그 스크랩핑 하기
    -크롤링 기본코드
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')

# 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.
  • select_one을 이용해 meta tag를 가져오고
    가져온 meta tag의 content 가져오기
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')

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']

print(title,image,desc)

☑️ [나홀로메모장] - POST 연습(메모하기)

  • 포스팅API → 카드 생성 (Create) : 클라이언트에서 받은 url, comment를 이용해서 페이지 정보를 찾고 저장하기
  • 리스팅API → 저장된 카드 보여주기 (Read)
  1. 클라이언트와 서버 연결 확인하기

⎯ 서버코드 (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>

✔︎ '기사저장' 버튼을 클릭했을 때, 'POST 연결되었습니다!' alert창이 뜨면 클라이언트 코드와 서버 코드가 연결 되어있는 것.

  1. 서버 만들기

✔︎ 서버가 전달받아야하는 정보

  • URL(url_give)
  • 코멘트(comment_give)

✔︎ URL를 meta tag를 스크래핑 후 아래 데이터를 저장(Create)

  • URL(url)
  • 제목(title)
  • 설명(desc)
  • 이미지URL(image)
  • 코멘트(comment)

✔︎ 서버 로직 구성 단계

1️⃣ 클라이언트로부터 데이터를 받기.
2️⃣ meta tag를 스크래핑하기
3️⃣ mongoDB에 데이터를 넣기

@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':'저장이 완료되었습니다!'})
  1. 클라이언트 만들기

✔︎ 서버에게 주어야하는 정보

  • URL (url_give) : meta tag를 가져올 url
  • comment (comment_give) : 유저가 입력한 코멘트

✔︎ 클라이언트 로직 구성 단계

1️⃣ 유저가 입력한 데이터를 #post-url과 #post-comment에서 가져오기
2️⃣ /memo에 POST 방식으로 메모 생성 요청하기
3️⃣ 성공 시 페이지 새로고침하기

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() → 새로고침 하기
          }
      })
  }

✔︎ https://movie.naver.com/movie/bi/mi/basic.nhn?code=171539 ← 이 URL을 입력하고 기사저장을 눌렀을 때, '포스팅 성공!' alert창이 뜨는지 확인.

☑️ [나홀로메모장] - GET 연습(보여주기)

  • 포스팅API → 카드 생성 (Create) : 클라이언트에서 받은 url, comment를 이용해서 페이지 정보를 찾고 저장하기
  • 리스팅API → 저장된 카드 보여주기 (Read)

1.클라이언트와 서버 연결 확인하기

⎯ 서버코드 (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"]);
      }
    }
  })
}

✔︎ 새로고침했을 때, 'GET 연결되었습니다!' alert창이 뜨면 클라이언트 코드와 서버 코드가 연결 되어있는 것.

  1. 서버 만들기

✔︎ 조건없이 모든 메모를 보여주기 때문에 서버가 전달받아야하는 정보는 없다.

✔︎ 서버 로직 구성 단계

1️⃣ mongoDB에서 _id 값을 제외한 모든 데이터 조회해오기 (Read)
2️⃣ articles라는 키 값으로 articles 정보 보내주기

@app.route('/memo', methods=['GET'])
def listing():
    articles = list(db.articles.find({}, {'_id': False}))
    return jsonify({'all_articles':articles})
  1. 클라이언트 만들기

✔︎ 클라이언트 로직 구성 단계

1️⃣ /memo에 GET 방식으로 메모 정보 요청하고 articles로 메모 정보 받기
2️⃣ , 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)
            }
        }
    })
}

✔︎ 새로고침했을 때, 앞 포스팅 API를 만들고 테스트했던 메모가 보이면 성공

☑️ [나홀로메모장] 전체 완성 코드

  • 서버 코드
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)

import requests
from bs4 import BeautifulSoup

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta

## HTML을 주는 부분
@app.route('/')
def home():
   return render_template('index.html')

@app.route('/memo', methods=['GET'])
def listing():
    articles = list(db.articles.find({}, {'_id': False}))
    return jsonify({'all_articles':articles})


## 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')

    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':'저장 완료!'})

if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)
  • 클라이언트 코드
<!Doctype html>
<html lang="ko">

    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
              integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
              crossorigin="anonymous">

        <!-- JS -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
                integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
                crossorigin="anonymous"></script>

        <!-- 구글폰트 -->
        <link href="https://fonts.googleapis.com/css?family=Stylish&display=swap" rel="stylesheet">


        <title>스파르타코딩클럽 | 나홀로 메모장</title>

        <!-- style -->
        <style type="text/css">
            * {
                font-family: 'IBM Plex Sans KR', sans-serif;
            }

            .wrap {
                width: 900px;
                margin: auto;
            }

            .comment {
                color: blue;
                font-weight: bold;
            }

            #post-box {
                width: 500px;
                margin: 20px auto;
                padding: 50px;
                border: black solid;
                border-radius: 5px;
            }
        </style>
        <script>
            $(document).ready(function () {
                showArticles();
            });

            function openClose() {
                if ($("#post-box").css("display") == "block") {
                    $("#post-box").hide();
                    $("#btn-post-box").text("포스팅 박스 열기");
                } else {
                    $("#post-box").show();
                    $("#btn-post-box").text("포스팅 박스 닫기");
                }
            }

            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()
                    }
                })
            }

            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)

                        }
                    }
                })
            }
        </script>

    </head>

    <body>
        <div class="wrap">
            <div class="jumbotron">
                <h1 class="display-4">나홀로 링크 메모장!</h1>
                <p class="lead">중요한 링크를 저장해두고, 나중에 볼 수 있는 공간입니다</p>
                <hr class="my-4">
                <p class="lead">
                    <button onclick="openClose()" id="btn-post-box" type="button" class="btn btn-primary">포스팅 박스 열기
                    </button>
                </p>
            </div>
            <div id="post-box" class="form-post" style="display:none">
                <div>
                    <div class="form-group">
                        <label for="post-url">아티클 URL</label>
                        <input id="post-url" class="form-control" placeholder="">
                    </div>
                    <div class="form-group">
                        <label for="post-comment">간단 코멘트</label>
                        <textarea id="post-comment" class="form-control" rows="2"></textarea>
                    </div>
                    <button type="button" class="btn btn-primary" onclick="postArticle()">기사저장</button>
                </div>
            </div>
            <div id="cards-box" class="card-columns">

            </div>
        </div>
    </body>

</html>

0개의 댓글