4주차 개발일지💖

4주차 배운내용

  • Flask, 모두의책리뷰, 나홀로메모장

Flask 시작코드

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

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

Flask 기본 폴더구죠

Flask 서버를 만들 때, 항상,

프로젝트 폴더 안에,
ㄴstatic 폴더 (이미지, css파일을 넣어둡니다)
ㄴtemplates 폴더 (html파일을 넣어둡니다)
ㄴapp.py 파일

이렇게 세 개를 만들어두고 시작

(꼭 참고!! venv는 실제로는 보이지만, 안보인다~라고 생각하세요! 기억하시죠?)

html 파일 불러오기

from flask import Flask, render_template
app = Flask(__name__)

## URL 별로 함수명이 같거나,
## route('/') 등의 주소가 같으면 안됩니다.

@app.route('/')
def home():
   return render_template('index.html')

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

모두의 책리뷰

  • app.py
        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 home():
            return render_template('index.html')

        ## API 역할을 하는 부분
        @app.route('/review', methods=['POST'])
        def write_review():
            title_receive = request.form['title_give']
            author_receive = request.form['author_give']
            review_receive = request.form['review_give']

            doc = {
                'title':title_receive,
                'author':author_receive,
                'review':review_receive
            }

            db.bookreview.insert_one(doc)

            return jsonify({'msg': '저장 완료!'})

        @app.route('/review', methods=['GET'])
        def read_reviews():
            reviews = list(db.bookreview.find({}, {'_id': False}))
            return jsonify({'all_reviews': reviews})

        if __name__ == '__main__':
            app.run('0.0.0.0', port=5000, debug=True)
  • index.html
        <!DOCTYPE html>
        <html lang="ko">

            <head>
                <!-- Webpage Title -->
                <title>모두의 책리뷰 | 스파르타코딩클럽</title>

                <!-- 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=Do+Hyeon&display=swap" rel="stylesheet">

                <script type="text/javascript">

                    $(document).ready(function () {
                        showReview();
                    });

                    function makeReview() {
                        let title = $('#title').val()
                        let author = $('#author').val()
                        let review = $('#bookReview').val()

                        $.ajax({
                            type: "POST",
                            url: "/review",
                            data: {title_give:title,author_give:author,review_give:review},
                            success: function (response) {
                                alert(response["msg"]);
                                window.location.reload();
                            }
                        })
                    }

                    function showReview() {
                        $.ajax({
                            type: "GET",
                            url: "/review",
                            data: {},
                            success: function (response) {
                                let reviews = response['all_reviews']
                                for (let i = 0; i < reviews.length; i++) {
                                    let title = reviews[i]['title']
                                    let author = reviews[i]['author']
                                    let review = reviews[i]['review']

                                    let temp_html = `<tr>
                                                        <td>${title}</td>
                                                        <td>${author}</td>
                                                        <td>${review}</td>
                                                    </tr>`
                                    $('#reviews-box').append(temp_html)
                                }
                            }
                        })
                    }

                </script>

                <style type="text/css">
                    * {
                        font-family: "Do Hyeon", sans-serif;
                    }

                    h1,
                    h5 {
                        display: inline;
                    }

                    .info {
                        margin-top: 20px;
                        margin-bottom: 20px;
                    }

                    .review {
                        text-align: center;
                    }

                    .reviews {
                        margin-top: 100px;
                    }
                </style>
            </head>

            <body>
                <div class="container" style="max-width: 600px;">
                    <img src="https://image.freepik.com/free-vector/large-bookcase-with-books-library-book-shelf-interior_92863-357.jpg"
                         class="img-fluid" alt="Responsive image">
                    <div class="info">
                        <h1>읽은 책에 대해 말씀해주세요.</h1>
                        <p>다른 사람을 위해 리뷰를 남겨주세요! 다 같이 좋은 책을 읽는다면 다 함께 행복해질 수 있지 않을까요?</p>
                        <div class="input-group mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text">제목</span>
                            </div>
                            <input type="text" class="form-control" id="title">
                        </div>
                        <div class="input-group mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text">저자</span>
                            </div>
                            <input type="text" class="form-control" id="author">
                        </div>
                        <div class="input-group mb-3">
                            <div class="input-group-prepend">
                                <span class="input-group-text">리뷰</span>
                            </div>
                            <textarea class="form-control" id="bookReview"
                                      cols="30"
                                      rows="5" placeholder="140자까지 입력할 수 있습니다."></textarea>
                        </div>
                        <div class="review">
                            <button onclick="makeReview()" type="button" class="btn btn-primary">리뷰 작성하기</button>
                        </div>
                    </div>
                    <div class="reviews">
                        <table class="table">
                            <thead>
                            <tr>
                                <th scope="col">제목</th>
                                <th scope="col">저자</th>
                                <th scope="col">리뷰</th>
                            </tr>
                            </thead>
                            <tbody id="reviews-box">
                            </tbody>
                        </table>
                    </div>
                </div>
            </body>

        </html>

나홀로 메모장

  • 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",
                            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>
  • 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():
            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)

4주차 숙제 : 원페이지 쇼핑몰 완성하기

from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.dbhomework


## HTML 화면 보여주기
@app.route('/')
def homework():
    return render_template('index.html')


# 주문하기(POST) API
@app.route('/order', methods=['POST'])
def save_order():
    name_receive = request.form['name_give']
    count_receive = request.form['count_give']
    address_receive = request.form['address_give']
    phone_receive = request.form['phone_give']

    doc = {
        'name': name_receive,
        'count': count_receive,
        'address': address_receive,
        'phone': phone_receive
    }
    db.orders.insert_one(doc)

    return jsonify({'result': 'success', 'msg': '주문 완료!'})


# 주문 목록보기(Read) API
@app.route('/order', methods=['GET'])
def view_orders():
    orders = list(db.orders.find({}, {'_id': False}))
    return jsonify({'result': 'success', 'orders': orders})


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

좋은 웹페이지 즐겨찾기