파이썬(Python)/블로그 만들기(python,flask,mongo)

블로그만들기(3) - (파이썬, summernote)웹에디터 게시판 글쓰기에 추가하기

끄적끄적아무거나 2021. 2. 4. 17:07
반응형

블로그 만들기(2)에서 만들었던 내용에서 웹에디터를 추가해보겠다. 웹에디터란 흔히 티스토리나 네이버 블로그에서 글을 작성할때 색깔이나 편집을 편하게 하도록 만들어진 UI이다. 직접 만드는 것은 javascript 나 css에 굉장한 노력이 들어간다. 하지만 이를 간단히 해결하는 방법은 summernote라는 오픈 소스를 사용하는 것이다. 오픈 소스를 통해 아래와 같은 웹에디터를 가질 수 있다.

 

 

 

아래는 summernote 웹페이지 주소이다. 해당 링크로 들어가면 어떻게 사용하는지 자세히 설명 되어 있다.

summernote.org/

 

Summernote - Super Simple WYSIWYG editor

Super Simple WYSIWYG Editor on Bootstrap Summernote is a JavaScript library that helps you create WYSIWYG editors online.

summernote.org

위지위그(WYSIWYG: What You See Is What You Get, "보는 대로 얻는다") 로 간단하게 웹에디터를 말한다고 생각하면 된다. 

 


 

 

순차적으로 어떻게 작성했는지 설명하겠다. 

 

1. Summernote 웹에디터는 bootstrap을 사용하는 해당 bootstrap은 HTML5 양식을 따르므로 HTML파일을 아래처럼 구성해야한다. 혹시 안되어 있다면 아래처럼 HTML에 추가하길 바란다. 

<!DOCTYPE html>

 

2. Summernote 웹에디터를 구동하기 위해 아래와 같이 <head>에 bootstrap 주소와 jquery 를 넣어서 summernote 오픈소스가 동작 가능하게 해줘야 한다. 그리고 해당 오픈소스 주소도 아래처럼 같이 넣어주어야한다. 해당 주소는 업데이트 될 수 있으니 위에 summernote 주소에서 최신으로 업데이트를 해줄 수 있다면 변경하길 바란다.

<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- include libraries(jQuery, bootstrap) -->
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

        <!-- include summernote css/js -->
        <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet">
        <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script>

 

3. 다음으로 HTML 문서가 준비되면 summernote 가 동작할 수 있도록 jquery 로 해당 함수를 선언해 준다.

        <script>

            $(document).ready(function() {
            $('#summernote').summernote();
            });

        </script>    

 

4. summernote 함수가 적용될 부분에 id를 summernote로 지정하면 적용은 완성이다.

                    <tr>
                        <td>Title</td>
                        <td><input type="text" name="title"></td>
                    </tr>
                    <tr>
                        <td>Content</td>
                        <td><textarea id="summernote" name="contents"></textarea></td>
                    </tr>
                    <tr>
                        <td><input type="submit"></td>
                    </tr>

 

5. 마지막으로 적용해서 글을 작성해서 db로 보내고 db로 보낸것을 그냥 읽으면 태그가 적용된 내용을 확인하게 된다 이를 방지하기 위해 아래와 같이 태그가 적용될 수 있도록 해야 된다. 

<body>
    {{db_data.title}}
    <br>
    {{db_data.pubdate}}
    <br>
    {% autoescape false %}{{db_data.contents}}{% endautoescape %}
    <br>
</body>

 


 

 

다음은 전체 코드를 정리해서 아래에 남기겠다. 그리고 코드를 적용했을 때 나오는 결과 화면을 같이 공유하겠다.

 

코드 - bulletin_wr.html>>

<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- include libraries(jQuery, bootstrap) -->
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

        <!-- include summernote css/js -->
        <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet">
        <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script>


        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>bulletin_write</title>

        <script>

            $(document).ready(function() {
            $('#summernote').summernote();
            });

        </script>       


    </head>
    <body>
        <table>
            <form name="form" method="POST" action="/bulletin_wr">
                <tbody>
                    <tr>
                        <td>Title</td>
                        <td><input type="text" name="title"></td>
                    </tr>
                    <tr>
                        <td>Content</td>
                        <td><textarea id="summernote" name="contents"></textarea></td>
                    </tr>
                    <tr>
                        <td><input type="submit"></td>
                    </tr>
                </tbody>
            </form>
        </table>
    </body>
</html>

 

코드 - bulletin_rd.html>>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bulletin_read</title>
</head>
<body>
    {{db_data.title}}
    <br>
    {{db_data.pubdate}}
    <br>
    {% autoescape false %}{{db_data.contents}}{% endautoescape %}
    <br>
</body>
</html>

 

코드 - board.py>>

from flask import *
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
import time

#########################################################
# Flask 선언, mongodb와 연결
web_bulletin = Flask(__name__, template_folder="templates")
web_bulletin.config["MONGO_URI"] = "mongodb://localhost:27017/bulletin" 
web_bulletin.config['SECRET_KEY'] = 'psswrd'

mongo = PyMongo(web_bulletin)
#########################################################

@web_bulletin.route("/bulletin_wr", methods=["GET", "POST"])
def bulletin_write():
    if request.method == "POST":
        cur_time = time.strftime("%y%m%d_%H%M%S")
        title = request.form.get("title")
        contents = request.form.get("contents")

        bulletin = mongo.db.bulletin

        to_db = {
            "title": title,
            "contents": contents,
            "view_cnt": 0,
            "pubdate": cur_time,
        }
        to_db_post = bulletin.insert_one(to_db)
        print("to_db_post :",to_db_post)

        return redirect(url_for("bulletin_rd", idx = to_db_post.inserted_id))
    else:
        return render_template("bulletin_wr.html")

@web_bulletin.route("/bulletin_rd")
def bulletin_rd():
    if request.args.get("idx") :
        idx = request.args.get("idx")
        bulletin = mongo.db.bulletin
        if bulletin.find_one({"_id": ObjectId(idx)}):
            bulletin_data = bulletin.find_one({"_id": ObjectId(idx)})
            #db에서 찾을때 _id 값은 string이 아닌 ObjectId로 바꿔야함
            if bulletin_data != "":
                db_data = {
                    "id": bulletin_data.get("_id"),
                    "title": bulletin_data.get("title"),
                    "contents": bulletin_data.get("contents"),
                    "pubdate": bulletin_data.get("pubdate")
                }

                return render_template("bulletin_rd.html", db_data = db_data)
        return abort(404)
    return abort(404)


if __name__ == "__main__":
    web_bulletin.run(host='0.0.0.0', debug=True, port=9999)


 

결과>>

 

 

 

 

 

 

 

 

반응형