상세 컨텐츠

본문 제목

todo 완성 mysql 적용

pymysql

by bumychoi 2025. 5. 19. 15:06

본문

 

import pymysql
from flask import Flask,render_template,request,jsonify

app=  Flask(__name__)

conn = pymysql.connect(
    host = "127.0.0.1",
    user="root",
    passwd="비밀번호",
    # db="dolist",
    charset ="utf8",
    autocommit=True
)

cur = conn.cursor()

cur.execute(f"CREATE SCHEMA IF NOT EXISTS dolist")

conn.select_db("dolist")

@app.route("/list",methods=['GET'])
def list_todo():
    date =request.args.get('date')

    cur.execute(f"SELECT * FROM userTable WHERE date= %s",(date,))
    contents = cur.fetchall()
    result = [{"number":row[0],"content":row[1],"check":row[2],"date":row[3]} for row in contents]

    # print(result)
    return jsonify({"result":result})

@app.route("/post" ,methods=["POST"])
def post_todo():
    content = request.form['content_give']
    date = request.form['date_give']
    # print(connect)

    cur.execute("CREATE TABLE  IF NOT EXISTS userTable(\
                number INT PRIMARY KEY AUTO_INCREMENT,\
                content char(20) NOT NULL,\
                is_checked  BOOLEAN NOT NULL DEFAULT FALSE,\
                date DATE);")

    sql = ("INSERT INTO usertable (content,date) VALUES(%s,%s)")
    cur.execute(sql,(content,date,))
    conn.commit()

    return jsonify({"msg":"등록완료"})

@app.route('/modify', methods=["POST"])
def modify_todo():
    try:
        number_receive = request.form["number_give"]
        content_receive = request.form["content_give"]
        sql = "UPDATE userTable SET content=%s WHERE number=%s"
        cur.execute(sql, (content_receive, number_receive))
        return jsonify({"msg":"수정완료"})

    except Exception as e:
        return jsonify({"error": str(e)})

@app.route('/delete', methods=["POST"])
def delete_todo():
    try:
        number_receive = request.form["number_give"]
        new_content = f"{number_receive}"
        sql=("DELETE FROM userTable WHERE number=%s")
        cur.execute(sql, (number_receive))
        return jsonify({"msg":"삭제완료"})
   
    except Exception as e:
        return jsonify({"error": str(e)})

@app.route('/check', methods=["POST"])
def check_todo():
    try:
        number_receive = request.form["number_give"]
        check_receive = request.form["check_give"].lower() =='true'
        sql = "UPDATE userTable SET is_checked=%s WHERE number=%s"
        cur.execute(sql, (check_receive, number_receive))
        return jsonify({"msg":"체크 완료"})
   
    except Exception as e:
        return jsonify({"error": str(e)})

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

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

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <title>todo</title>
    <style>
        html,
        body,
        h1,
        h2,
        h3,
        div,
        span,
        a,
        button,
        input {
            margin: 0;
            padding: 0;
            box-sizing: border-box;

        }

        body {
            background-color: rgb(219, 235, 230);
        }

        .wrap {
            background-color: beige;
            width: 350px;
            height: 700px;
            margin: auto;
        }

        .flex-row {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;

        }

        .flex-col {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .wrap-todo {
            padding: 16px;
        }

        h1 {
            font-size: 18px;
            margin: 16px auto 20px 0px;
        }
   
        .red{
            color: red;
        }
        .blue{
            color: rgb(49, 100, 120);
        }
        .todo {
            padding: 16px;
            background-color: rgb(227, 216, 200);
            border-radius: 8px;
            width: 300px;

            margin-bottom: 8px;
        }

        .todo-content {
            margin-left: 8px;
            margin-right: auto;
        }

        .todo>input {
            zoom: 1.5;
            background-color: transparent;
        }

        .add-form {
            padding: 16px;
            background-color: rgb(242, 229, 207);
            border-radius: 8px;
            width: 300px;
            border: 1px solid red;
            display: none;
        }

        .add-form-btns {
            margin-left: auto;

        }

        .add-form-btns>button {
            background-color: transparent;
            margin: 0px 4px;
            border: none;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
        }

        .add-form>input {
            background-color: transparent;
            border: none;
            font-size: 16px;
            width: 200px;

        }

        .todo>button {
            background-color: transparent;
            border: none;
            font-weight: 600;
            cursor: pointer;
            font-size: 11px;
            color: red;

        }

        .add-form>input:focus-visible {
            outline: none;

        }

        .add-btn {
            padding: 16px;
            background-color: transparent;
            border-radius: 8px;
            width: 300px;
            border: 1px dashed rgb(190, 190, 233);
            cursor: pointer;

        }

        .add-btn>span {
            margin-bottom: 2px;
        }

        .add-btn>button {
            margin-left: 8px;
            margin-right: auto;
            background-color: transparent;
            border: none;
            cursor: pointer;
        }
        .todo-content-modify>input{
            border: none;
            margin-left: 8px;
            margin-right: auto;
            background-color: transparent;
            font-size: 16px;
            color: brown;
            width: 160px;

        }
        .todo-content-modify>input:focus-visible{
            outline: none;
        }
        .todo-content-modify>button{
            margin: 0px 8px;
            font-weight: 600;
            cursor: pointer;
            background-color: transparent;
            border: none;
            font-size: 11px;

        }
        .calender{
            background-color: rgb(226, 204, 4);
        }
        .calender>h2{
            margin: 16px 0px;
            text-align: center;
            cursor: pointer;
        }
        .days{
            display: grid;
            grid-template-columns: repeat(7,1fr);
            grid-gap: 18px;
            margin-bottom: 20px;
           
        }
        .days>div{
            width: 30px;
            height: 30px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .date{
            display: grid;
            grid-template-columns: repeat(7,1fr);
            grid-gap: 18px;
            margin-bottom: 20px;
        }
        .date>div{
            width: 30px;
            height: 30px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            cursor: pointer;
        }
        .date>div.clicked{
            background-color: black;
            border-radius: 50%;
            color: aliceblue;
        }
    </style>
    <script>
        let date_clicked;

        $(document).ready(() => {
            loadCalender()
            todayClicked()
        })
        function loadCalender(){
            let today = new Date();
            let year = today.getFullYear();
            let month = today.getMonth()+1;
            let day = today.getDay();
            let date= today.getDate();
            $("#this-month").text(`${year}${month}월`);

            let first_day = new Date(year, month-1,1).getDay()
            let last_day = new Date(year,month,0).getDate()

            for(let i = 0; i < first_day; i++){
                let temp_html=`<div></div>`
                $(`#dates`).append(temp_html)

            }
            for (let i =0; i < last_day; i++){
                let id=`${year}-${month}-${i+1}`

                let target_day = new Date(year, month-1,i+1).getDay()
                let color =''
                if (target_day ==0){
                    color= 'red'
                }
                else if (target_day==6){
                    color="blue"
                }

                let temp_html = `<div class='${color}' onclick="addClicked('${id}')" id='${id}'>${i+1}</div>`
                $(`#dates`).append(temp_html)
            }
        }

        function addClicked(id){
            $(`#dates > div`).removeClass('clicked');
            $(`#${id}`).addClass('clicked');

            $(`#today-todo`).text(`${id} =>> 오늘의 할 일`)
            date_clicked = id;

            listContent();

        }
        function todayClicked(){
            let today = new Date();
            let year = today.getFullYear();
            let month = today.getMonth()+1;
            let date= today.getDate();
            // console.log(year,month,date)
            let id = `${year}-${month}-${date}`
            $(`#${id}`).trigger("click");
        }

        function showAddForm() {
            $("#add-form").css('display', 'flex');
            $("#add-btn").hide();
        }
        function hideAddForm() {
            if (confirm("정말취소합니까?")) {
                $("#add-form").hide();
                $("#add-btn").css('display', 'flex');
            }

        }
        function addContent() {
            let content = $("#content").val();
           
            let formData = new FormData()
            formData.append("content_give", content)
            formData.append("date_give", date_clicked)

            fetch('/post', { method: "POST", body: formData }).then(res => res.json()).then(data => {
                alert(data["msg"])
                window.location.reload()
            })
        }
        function listContent() {
            let date =date_clicked;
            // console.log(date);
            let url =`/list?date=${date}`

            fetch(url).then(res => res.json()).then(data => {
                $("#todos").empty();
                let rows = data['result'];
                rows.forEach((row) => {
                    // console.log(row)
                    let number = row['number']
                    let content = row['content']
                    let check = row['check']

                    let txt_checked = ''
                    let txt_style = ''
                    if(check =='1'){
                        txt_checked = 'checked'
                        txt_style = 'style="text-decoration:line-through"'
                    }
                    let temp_html = `<div id="${number}" class="todo flex-row">
                                        <input ${txt_checked} type="checkbox" onchange=" checkContent('${number}')">
                                        <span ${txt_style} onclick="showUpdateForm('${number}')" class="todo-content">${content}</span>
                                        <button onclick=" test_1('${number}')">삭제</button>  
                                        <div style="display: none;" class="todo-content-modify flex-row">
                                            <input value="${content}" type="text">
                                            <button onclick="modifyContent('${number}')">수정</button>
                                            <button onclick="hideUpdateForm('${number}')">취소</button>
                                        </div>
                                    </div>`
                    $("#todos").append(temp_html);
                })
            })
        }
        function test() {
            if (confirm("정말취소합니까?")) {
                listContent();
            }
        }
        function showUpdateForm(number){
            $(`#${number}>span`).hide();
            $(`#${number}>button`).hide();
            $(`#${number}>input`).hide();
            $(`#${number}>.todo-content-modify`).css('display','flex');
        }

        function hideUpdateForm(number){
            $(`#${number}>span`).show();
             $(`#${number}>button`).show();
            $(`#${number}>input`).show();
            $(`#${number}>.todo-content-modify`).css('display','none');
            window.location.reload()
        }
        function modifyContent(number){
            let new_content = $(`#${number}>div > input`).val()

            let formData = new FormData()
            formData.append("number_give", number)
            formData.append("content_give", new_content)

            fetch('/modify', { method: "POST", body: formData }).then(res => res.json()).then(data => {
                alert(data["msg"])
                window.location.reload()
            })
        }

        function deleteContent(number){

            let formData = new FormData()
            formData.append("number_give", number)

            fetch('/delete', { method: "POST", body: formData }).then(res => res.json()).then(data => {
                alert(data["msg"])
                window.location.reload()
            })
        }
        function test_1(number) {
            if (confirm("정말삭제합니까?")) {
                 deleteContent(number);
            }
        }
         function checkContent(number){
            let is_checked = $(`#${number}>input`).is(':checked');
            // console.log(is_checked)
            let formData = new FormData()
            formData.append("number_give", number)
            formData.append("check_give", is_checked)

            fetch('/check', { method: "POST", body: formData }).then(res => res.json()).then(data => {
                alert(data["msg"])
                window.location.reload()
            })
         }
    </script>
</head>

<body>
    <div class="wrap">
        <div class="calender">
            <h2 onclick="todayClicked()" id="this-month">2025.5월</h2>
            <div class="days flex-col">
                <div class="red"></div>
                <div></div>
                <div></div>
                <div></div>
                <div></div>
                <div></div>
                <div class="blue"></div>
            </div>
            <div id=dates class="date flex-col">
               
            </div>
        </div>
        <div class="wrap-todo flex-col">
            <h1 id="today-todo">오늘의 할일</h1>
            <div id="todos" class="todos flex-col">
                <!-- <div id="number" class="todo flex-row">
                    <input type="checkbox">
                    <span onclick="shwoUpateFrom('number')" class="todo-content">수정작업</span>  
                    <div style="display: none;" class="todo-content-modify flex-row">
                        <input value="수정하기" type="text">
                        <button>수정</button>
                        <button onclick="hideUpateFrom('number')">취소</button>
                    </div>
                </div> -->
            </div>
            <div id="add-form" class="add-form flex-row">
                <input id="content" type="text">
                <div class="add-form-btns flex-row">
                    <button onclick="addContent()">추가</button>
                    <button onclick="hideAddForm()">취소</button>
                </div>
            </div>
            <div id="add-btn" onclick="showAddForm()" class="add-btn flex-row">
                <span>+</span>
                <button>추가하기</button>
            </div>
        </div>
    </div>
</body>

</html>


'pymysql' 카테고리의 다른 글

mysql + num박사  (0) 2025.06.11
to-list 체크 추가  (0) 2025.05.18
파이썬, 플라스크, mysql, jqury crud  (0) 2025.05.14
PYMYSQL 연습 +JQUERY  (0) 2025.05.10
페이지네이션 추가  (0) 2025.05.08

관련글 더보기