본문 바로가기

20. 영화 리뷰 메모장(2)

by Rudy 2021. 9. 10.

<POST>

 

만들어야 하는 API

1. 포스팅 API-카드생성(Create): 클라이언트에서 받은 url, comment를 이용해서 페이지 정보를 찾고 저장한다.

2. 리스팅 API-저장된 카드를 보여준다.(Read)

 

1) 클라이언트와 서버 연결을 확인한다.

2) 서버를 만든다.

-> 메모를 작성하기 위해 서버가 전달받아야하는 정보는 URL과 코멘트이다. 그리고 URL을 meta tag를 스크래핑해서 URL, title, desc, image, comment 를 저장(Create) 한다.

 

서버 로직은 다음과 같다.

1. 클라이언트로부터 데이터를 받는다.

2. meta tag를 스크래핑한다.

3. mongoDB에 데이터를 넣는다.

 

3) 클라이언트 만들기

메모를 작성하기 위해 서버에게 주어야 하는 정보는 URL: meta tag를 가져올 url(url_give), comment: 유저가 입력한 코멘트이다. 그러므로 클라이언트 로직은 다음과 같다.

 

1. 유저가 입력한 데이터를 #post-url과 #post-comment에서 가져온다.

2. /memo에 POST 방식으로 메모 생성을 요청한다.

3. 성공하면 페이지를 새로고침한다.

 

-app.py


## 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']
    description = soup.select_one('meta[property="og:description"]')['content']

    doc={
        'title':title,
        'image':image,
        'desc':description,
        'url':url_receive,
        'comment':comment_receive
    }
    db.articles.insert_one(doc)
    return jsonify({'msg':'저장이 완료되었습니다.'})

    return jsonify({'msg':'POST 연결되었습니다!'})

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

<GET>

 

만들어야 하는 API

1. 포스팅 API- 카드생성(Create): 클라이언트에서 받은 url, comment를 이용해서 페이지 정보를 찾고 저장한다.

2. 리스팅 API- 저장된 카드를 보여준다.(Read)

 

1) 클라이언트와 서버 연결을 확인한다.

2) 서버부터 만든다.

-> 메모를 보여주기 위해 서버가 추가로 전달받아야 하는 정보는 없다. 그러므로 서버 로직은 다음과 같다.

 

1. mongoDB에서 _id 값을 제외한 모든 데이터를 조회해온다.(Read)

2. articels 라는 키 값으로 articles 정보를 보내준다.

 

3) 클라이언트 로직은 다음과 같다.

 

1. /memo 에 GET 방식으로 메모 정보를 요청하고 articles로 메모 정보를 받는다.

2. makeCard 함수를 이용해서 카드 HTML을 붙인다.

3. 동작 테스트 한다.

 

* 카드가 정렬되는 순서는 위에서 아래로 채워지고, 왼쪽부터 오른쪽으로 순서대로 채워진다. 이는 부트스트랩 컴퍼넌트 페이지에 적혀 있다. 

 

-app.py

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():
    article=list(db.articles.find({},{'_id':False}))
    return jsonify({'all_articles':article}) #article은 잠깐 데이터를 받기 위해 만든 변수

## 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']
    description = soup.select_one('meta[property="og:description"]')['content']

    doc={
        'title':title,
        'image':image,
        'desc':description,
        'url':url_receive,
        'comment':comment_receive
    }
    db.articles.insert_one(doc)
    return jsonify({'msg':'저장이 완료되었습니다.'})

    return jsonify({'msg':'POST 연결되었습니다!'})

if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)

-index.html

 

<!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: "Stylish", 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?sample_give=샘플데이터",
                    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) 2022.01.31
21. 간이 쇼핑몰 페이지 만들기  (0) 2021.09.11
19. 메모장(1)  (0) 2021.09.08
18. 모두의 북리뷰 페이지 만들기  (0) 2021.09.06
17. flask  (0) 2021.09.05

댓글