05-03

일기장 토이프로젝트를 한번구현해보았다.
mongodDb, python을 통해서 데이터를 저장하고 가져오고

<!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>왕규의 Todo List</title>


    <style>
        .input_wrap {
            border: solid;
            border-radius: 10px;
            margin: 15px;
            padding: 20px;
        }

        .todo_lists {
            margin: 10px;
        }

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

        .save_button {
            display: block;
            margin: auto;
        }
    </style>

    <script>
        let input_status = 0

        $(document).ready(function () {
            show_todo();
            get_Date();
        });


        function input_on() {
            input_status += 1
            if (input_status % 2 == 0) {
                $('.input_wrap').show()
            } else {
                $('.input_wrap').hide()
            }
        }


        function save_todo() {
            let date = $('#today_date').val()
            let todo = $('#todo').val()

            $.ajax({
                type: "POST",
                url: "/today/save",
                data: {today_date: date, today_do: todo}, //여기부분은 post할떄 사용
                success: function (response) {
                    console.log(response)
                }
            })
            alert('저장되었습니다.')
            window.location.reload()
        }

        function show_todo() {
            $.ajax({
                type: "GET",
                url: "/today/show",
                data: {}, //여기부분은 post할떄 사용
                success: function (response) {
                    rows = response['msg']
                    for (let i = 0; i < rows.length; i++) {
                        let date = rows[i]['date']
                        let todo = rows[i]['todo']

                        let temp_html = `<div class="card">
                <div class="card-body">
                    <h5 class="card-title">${date}</h5>
                    <p class="card-text">${todo}</p>
                </div>
            </div>`
                        $('#card_list').append(temp_html)
                    }
                }
            })
        }

        function get_Date() {
            let today = new Date();

            let week = new Array('일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일')

            let year = today.getFullYear(); // 년도
            let month = today.getMonth() + 1;  // 월
            let date = today.getDate();  // 날짜
            let day = today.getDay();  // 요일

            let real_date = year+'/'+month+'/'+date+'/'+week[day]
            $('#today_date').val(real_date)
        }
    </script>
</head>

<body>
<div class="wrap">
    <div class="jumbotron">
        <h1 class="display-4">안녕하세요</h1>
        <p class="lead">Flask와 mongoDb를 사용한 To do List 입니다.</p>
        <hr class="my-4">
        <p>오늘할일을 적어주세요</p>
        <p class="lead">
            <a class="btn btn-primary btn-lg" onclick="input_on()" href="#" role="button">오늘하루추가</a>
        </p>
    </div>
    <div class="input_wrap">
        <div>
            <div class="form-group">
                <label for="today_date">오늘 날짜</label>
                <input class="form-control" id="today_date" aria-describedby="emailHelp"
                       placeholder="Enter Day">
            </div>
            <div class="form-group">
                <label for="todo">오늘할일</label>
                <input class="form-control" id="todo" placeholder="To do">
            </div>
            <button onclick="save_todo()" class="btn btn-primary save_button">저장하기</button>
        </div>
    </div>
    <div class="todo_lists">
        <div id="card_list" class="card-columns">

        </div>

    </div>
</body>

</html>
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 index_page():
    return render_template('index.html')

## POST 오늘할일 저장
@app.route('/today/save', methods=['POST'])
def save_todo():
    date = request.form['today_date']
    todo = request.form['today_do']
    doc = {'date': date, 'todo': todo}
    db.cwTodo.insert_one(doc)
    return jsonify({'msg': '이 요청은 POST!'})

## GET 오늘할일 저장한거 보여주기
@app.route('/today/show', methods=['GET'])
def show_todo():
    lists = list(db.cwTodo.find({},{'_id':False}))
    return jsonify({'msg': lists})

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


여기서 버튼에 span태그의 text값 가져오고싶은대 어떻게해야하나

this.id 로 하면 어디id가져오는지 모르겠음

좋은 웹페이지 즐겨찾기