상세 컨텐츠

본문 제목

fatch 다시공부

카테고리 없음

by bumychoi 2024. 4. 11. 17:13

본문

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,
        body,
        h1,
        h2,
        h3,
        div,
        span,
        a,
        button,
        input {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background-color: burlywood;
        }

        .wrap {
            background-color: aqua;
            width: 350px;
            height: 750px;
            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: 24px;
            margin: 16px;
        }

        .todo {
            padding: 16px;
            background-color: antiquewhite;
            border-radius: 8px;
            width: 300px;
            height: 50px;
            margin-bottom: 8px;
        }

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

        }

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

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

        .add-form {
            padding: 16px;
            background-color: antiquewhite;
            border-radius: 8px;
            width: 300px;
            height: 50px;
            border: 1px solid red;
            display: none;
        }

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

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

        }

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

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

        .add-btn {
            padding: 16px;
            background-color: transparent;
            border-radius: 8px;
            width: 300px;
            height: 50px;
            border: 1px dashed rgb(44, 72, 3);
            cursor: pointer;
        }

        .add-btn>button {
            margin-right: auto;
            background-color: transparent;
            cursor: pointer;
            border: none;
            font-size: 12px;
            font-weight: 600;
        }

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

        .todo-content-modify>input {
            border: none;
            margin-left: 8px;
            margin-right: auto;
            font-size: 16px;
            color: blueviolet;
            width: 160px;
            background-color: transparent;
        }

        .todo-content-modify>input:focus-visible {
            outline: none;
        }

        .todo-content-modify>button {
            background-color: transparent;
            margin: 0px 8px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            font-size: 11px;
        }
    </style>
    <script>
        $(document).ready(() => {
            listContent()
        })
        function showAddform() {
            $("#add-form").css("display", "flex");
            $('#add-btn').hide();
        }
        function hideAddform() {
            if (confirm("취소하시겠습니까?.")) {
                $("#add-form").hide();
                $("#add-btn").css("display", "flex");
            } else {
                showAddform()
            }
        }
        function addContent() {
            let content = $("#content").val();

            let formData = new FormData()
            formData.append("content_give", content)

            fetch('/post', { method: "POST", body: formData }).then(res => res.json()).then(data => {
                alert(data["msg"])
                window.location.reload()
            })
        }
        function listContent() {
            fetch("/list").then(res => res.json()).then(data => {
                let rows = data['result']
                rows.forEach((row) => {
                    let content = row['content']
                    let _id = row['_id']
                    let temp_html = `<div id=${_id} class="todo flex-row">
                                        <input  type="checkbox">
                                        <span onclick="showUpdateForm('${_id}')" class="todo-content">${content}</span>
                                        <div style="display: none;" class="todo-content-modify flex-row">
                                            <input value="${content}" type="text">
                                            <button onclick="modifyContent('${_id}')">수정</button>
                                            <button onclick="hideUpdateForm('${_id}')">취소</button>
                                        </div>
                                    </div>`
                    $("#todos").append(temp_html)
                });
            })
        }
        function test() {
            if (confirm("확인 또는 취소를 선택해주세요.")) {
                alert("확인을 누르셨습니다.");
            } else {
                alert("취소를 누르셨습니다.");
            }
        }
        function showUpdateForm(_id) {
            $(`#${_id} > span`).hide();
            $(`#${_id} > div`).css("display", "flex");
        }
        function hideUpdateForm(_id) {
            $(`#${_id} > span`).show();
            $(`#${_id} > div`).css("display", "none");
        }
        function modifyContent(_id) {
            let new_content = $(`#${_id} > div > input`).val();
            let formData = new FormData()
            formData.append("id_give", _id)
            formData.append("content_give", new_content)

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

<body>
    <div class="wrap ">
        <div class="wrap-todo flex-col">
            <h1>오늘의 할일</h1>
            <div id="todos" class="todos flex-col">
                <!-- <div id="_id" class="todo flex-row">
                    <input type="checkbox">
                    <span onclick="showUpdateForm('_id')" class="todo-content">tkddd</span>
                    <div style="display: none;" class="todo-content-modify flex-row">
                        <input value="ffff" type="text">
                        <button>수정</button>
                        <button onclick="hideUpdateForm('_id')">취소</button>
                    </div> -->
                </div>
            </div>
            <div id="add-btn" onclick="showAddform()" class="add-btn flex-row">
                <span>+</span>
                <button>추가하기</button>
            </div>
        </div>
    </div>
</body>

</html>

 

from flask import Flask, render_template, request, jsonify
from pymongo import MongoClient
from bson.objectid import ObjectId
client = MongoClient("mongodb+srv://sparta:")
db = client.pirates_lv2

app = Flask(__name__)

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

@app.route("/list", methods=["GET"])
def list_todo():
    contents = list(db.todos.find({}))
    for content in contents:
        content["_id"] = str(content['_id'])

    return jsonify({"result":contents})

@app.route('/post', methods=["POST"])
def post_todo():
    content_receive = request.form["content_give"]
    doc={
        "content":content_receive
    }
    db.todos.insert_one(doc)

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

@app.route('/modify', methods=["POST"])
def modify_todo():
    id_receive = request.form["id_give"]
    id_receive = ObjectId(id_receive)
   
    content_receive = request.form["content_give"]
    db.todos.update_one({'_id':id_receive},{'$set':{'content':content_receive}})

    return jsonify({"msg": "수정 완료!"})

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