7주차 진행사항

app.py

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

from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:[email protected]/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

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

# 마이페이지
@app.route('/mypage')
def mypage():
   return render_template('mypage.html')

# 기록하기
@app.route('/record')
def record():
    return render_template('record.html')

# 수정하기
@app.route('/modify')
def modify():
    return render_template('modify.html')

# 기록 페이지에서 기록한 거 POST
@app.route("/record", methods=["POST"])
def record_post():
    Id_receive = request.form['Id_give']
    Name_receive = request.form['Name_give']
    Introduce_receive = request.form['Introduce_give']
    Goal_receive = request.form['Goal_give']
    Favorite_thing_receive = request.form['Favorite_thing_give']
    Good_thing_receive = request.form['Good_thing_give']
    First_values_receive = request.form['First_values_give']
    World_needs_receive = request.form['World_needs_give']

    doc = {
        'Id': Id_receive,
        'Name': Name_receive,
        'Introduce': Introduce_receive,
        'Goal': Goal_receive,
        'Favorite_thing': Favorite_thing_receive,
        'Good_thing': Good_thing_receive,
        'First_values': First_values_receive,
        'World_needs': World_needs_receive,
    }
    db.record.insert_one(doc)

    return jsonify({'msg': '기록 완료!'})

# 수정 페이지에서 수정한 거 POST
@app.route("/modify", methods=["POST"])
def modify_post():
    Id_receive = request.form['Id_give']
    Name_receive = request.form['Name_give']
    Introduce_receive = request.form['Introduce_give']
    Goal_receive = request.form['Goal_give']
    Favorite_thing_receive = request.form['Favorite_thing_give']
    Good_thing_receive = request.form['Good_thing_give']
    First_values_receive = request.form['First_values_give']
    World_needs_receive = request.form['World_needs_give']

    db.record.update_one({'Id': Id_receive}, {'$set': {'Name': Name_receive}})
    db.record.update_one({'Id': Id_receive}, {'$set': {'Introduce': Introduce_receive}})
    db.record.update_one({'Id': Id_receive}, {'$set': {'Goal': Goal_receive}})
    db.record.update_one({'Id': Id_receive}, {'$set': {'Favorite_thing': Favorite_thing_receive}})
    db.record.update_one({'Id': Id_receive}, {'$set': {'Good_thing': Good_thing_receive}})
    db.record.update_one({'Id': Id_receive}, {'$set': {'First_values': First_values_receive}})
    db.record.update_one({'Id': Id_receive}, {'$set': {'World_needs':World_needs_receive}})

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

# 기록된 데이터 마이페이지에 불러오기
@app.route("/mypages", methods=["GET"])
def record_get():
    record_list = list(db.record.find({}, {'_id': False}))
    return jsonify({'records': record_list})

# 아이디 중복 확인
@app.route("/logins", methods=["GET"])
def login_get():
    id_list = list(db.record.find({}, {'_id': False}))
    return jsonify({'ids': id_list})

# 기록된 데이터 불러오기
@app.route("/edit", methods=["GET"])
def edit_get():
    edit_list = list(db.record.find({}, {'_id': False}))
    return jsonify({'edit': edit_list})

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>홈페이지</title>
    <script>
        $(document).ready(function () {
            mypages();
        });

        function mypages() {
            $.ajax({
                type: 'GET',
                url: '/mypages',
                data: {},
                success: function (response) {
                    let rows = response['records']
                    for (let i = 0; i < rows.length; i++) {
                        let Name = rows[i]['Name']
                        let Introduce = rows[i]['Introduce']
                        let Id = rows[i]['Id']
                        let temp_html = `<div class="card" id="Card" type="button" onclick="location.href= '/mypage?userid='+ '${Id}'">
                                            <p class="title" id="Title">${Introduce}</p>
                                            <p class="name" id="Name">${Name}</p>
                                        </div>`
                        $('#box').append(temp_html)
                    }
                }
            });
        }
    </script>
</head>
<body>
    <p type="button" onclick="location.href='/record'">기록하기</p>
    <div class="box" id="box">
    </div>
</body>
</html>

mypage.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>마이 페이지</title>

    <style>
        @font-face {
            font-family: 'ChosunGu';
            src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/[email protected]/ChosunGu.woff') format('woff');
            font-weight: normal;
            font-style: normal;
        }

        @font-face {
            font-family: 'S-CoreDream-3Light';
            src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/[email protected]/S-CoreDream-3Light.woff') format('woff');
            font-weight: normal;
            font-style: normal;
        }

        @font-face {
            font-family: 'GangwonEdu_OTFLightA';
            src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/[email protected]/GangwonEdu_OTFLightA.woff') format('woff');
            font-weight: normal;
            font-style: normal;
        }

        @font-face {
            font-family: 'S-CoreDream-5Medium';
            src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/[email protected]/S-CoreDream-5Medium.woff') format('woff');
            font-weight: normal;
            font-style: normal;
        }

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

            padding: 20px;

            font-family: 'S-CoreDream-3Light';
        }

        .profile {
            margin: 10px 50px auto auto;

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

        th, td {
            border-bottom: 1px solid #b7b7b7;
            padding: 10px;
        }

        .personal {
            font-family: 'ChosunGu';
            margin: 10px auto auto 50px;
        }

        .personal > h1 {
            font-family: 'GangwonEdu_OTFLightA';
            text-align: center; /*문단 가운데 정렬*/
        }

        .goal {
            display: flex;
            flex-direction: row;
            margin: 10px auto 10px auto;
        }

        .goal > .card {
            width: 800px;
            margin: 10px auto 10px auto;
        }

        .name {
            font-family: 'S-CoreDream-5Medium';
            margin: 10px;
            padding: 3px;
            width: 200px;
            background-color: gray;
            color: white;
            text-align: center;
        }

        h5 {
            color: #b7b7b7;
            font-size: 15px;
        }
    </style>

    <script>
        $(document).ready(function () {
            mypages();
        });

        // userid 값 가져오기
        let queryString = location.search;
        const urlParams = new URLSearchParams(queryString);
        let userId = urlParams.get("userid")

        function modify() {
            location.href = "/modify?userid=" + userId;
        }

        function mypages() {
            $.ajax({
                type: 'GET',
                url: '/mypages',
                data: {},
                success: function (response) {
                    let rows = response['records']

                    for (let i = 0; i < rows.length; i++) {
                        // 가져온 userid 값과 같으면 데이터 불러와서 붙이기
                        if (rows[i]['Id'] == userId) {
                            let Name = rows[i]['Name']
                            let Introduce = rows[i]['Introduce']
                            let Goal = rows[i]['Goal']
                            let Favorite_thing = rows[i]['Favorite_thing']
                            let Good_thing = rows[i]['Good_thing']
                            let First_values = rows[i]['First_values']
                            let World_needs = rows[i]['World_needs']

                            let element_Name = document.getElementById("Name")
                            element_Name.innerText = `${Name}`
                            let element_Title = document.getElementById("Title")
                            element_Title.innerText = `${Introduce}`
                            let element_Goal = document.getElementById("Goal")
                            element_Goal.innerText = `${Goal}`
                            let element_Favorite_thing = document.getElementById("Favorite-thing")
                            element_Favorite_thing.innerText = `${Favorite_thing}`
                            let element_Good_thing = document.getElementById("Good-thing")
                            element_Good_thing.innerText = `${Good_thing}`
                            let element_First_values = document.getElementById("First-values")
                            element_First_values.innerText = `${First_values}`
                            let element_World_needs = document.getElementById("World-needs")
                            element_World_needs.innerText = `${World_needs}`
                        }
                    }
                }
            });
        }
    </script>

</head>
<body>
<div class="box">
    <div class="profile">
        <p class="name" id="Name">이름</p>

        <!--기록 페이지로 이동-->
        <p type="button" onclick="modify()">수정하기</p>

    </div>
    <div class="personal">
        <h1 class="title" id="Title">"나를 표현하는 한 문장"</h1>
        <div class="goal">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">목표</h5>
                    <p class="goal-text" id="Goal">내용</p>
                </div>
            </div>
        </div>
        <!--Components > Card > Grid cards-->
        <div class="row row-cols-1 row-cols-md-2 g-4">
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">좋아하는 것</h5>
                        <p class="favorite-thing-text" id="Favorite-thing">내용</p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">잘 하는 것</h5>
                        <p class="good-thing-text" id="Good-thing">내용</p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">우선 가치관</h5>
                        <p class="first-values-text" id="First-values">내용</p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">세상이 필요로 하는 것</h5>
                        <p class="world-needs-text" id="World-needs">내용</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
</body>
</html>

modify.html

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

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!--부트스트랩-->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

<title>수정하기</title>

<style>
    th, td {
        border-bottom: 1px solid #b7b7b7;
        padding: 10px;
    }
</style>

<script>
    $(document).ready(function () {
        edit();
    });

    let queryString = location.search;
    const urlParams = new URLSearchParams(queryString);
    let userId = urlParams.get("userid")

    // 기록된 정보 가져오기
    function edit() {
        $.ajax({
            type: 'GET',
            url: '/edit',
            data: {},
            success: function (response) {
                let rows = response['edit']

                for (let i = 0; i < rows.length; i++) {
                    if (rows[i]['Id'] == userId) {
                        let Id = rows[i]['Id']
                        let Name = rows[i]['Name']
                        let Introduce = rows[i]['Introduce']
                        let Goal = rows[i]['Goal']
                        let Favorite_thing = rows[i]['Favorite_thing']
                        let Good_thing = rows[i]['Good_thing']
                        let First_values = rows[i]['First_values']
                        let World_needs = rows[i]['World_needs']

                        let temp_html = `<table>
                                            <tbody>
                                            <tr class="id">
                                                <td>
                                                    <label for="Id">아이디</label>
                                                </td>
                                                <td>
                                                    <p id="userId">${Id}</p>
                                                </td>
                                            </tr>
                                            <tr class="tr1">
                                                <td>
                                                    <label for="Name">이름</label>
                                                </td>
                                                <td>
                                                    <p><input type="text" id="Name" class="input-name" value="${Name}"/></p>
                                                </td>
                                            </tr>
                                            <tr class="tr1">
                                                <td>
                                                    <label for="Introduce">나를 표현하는 한 문장</label>
                                                </td>
                                                <td>
                                                    <p><textarea id="Introduce" class="input-introduce">${Introduce}</textarea></p>
                                                </td>
                                            </tr>
                                            <tr class="tr1">
                                                <td>
                                                    <label for="Goal">목표</label>
                                                </td>
                                                <td>
                                                    <p><textarea id="Goal" class="input-goal">${Goal}</textarea></p>
                                                </td>
                                            </tr>
                                            <tr class="tr1">
                                                <td>
                                                    <label for="Favorite_thing">좋아하는 것</label>
                                                </td>
                                                <td>
                                                    <p><textarea id="Favorite_thing" class="input-favorite-thing">${Favorite_thing}</textarea></p>
                                                </td>
                                            </tr>
                                            <tr class="tr1">
                                                <td>
                                                    <label for="Good_thing">잘 하는 것</label>
                                                </td>
                                                <td>
                                                    <p><textarea id="Good_thing" class="input-good-thing">${Good_thing}</textarea></p>
                                                </td>
                                            </tr>
                                            <tr class="tr1">
                                                <td>
                                                    <label for="First_values">우선 가치관</label>
                                                </td>
                                                <td>
                                                    <p><textarea id="First_values" class="input-first-values">${First_values}</textarea></p>
                                                </td>
                                            </tr>
                                            <tr class="tr1">
                                                <td>
                                                    <label for="World_needs">세상이 필요로 하는 것</label>
                                                </td>
                                                <td>
                                                    <p><textarea id="World_needs" class="input-world-needs">${World_needs}</textarea></p>
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>
                                        `
                        $('#table-box').append(temp_html)
                    }
                }
            }
        })
    }

    // 기록 데이터 수정하기
    function modify() {
        let Id = userId
        let Name = $('#Name').val()
        let Introduce = $('#Introduce').val()
        let Goal = $('#Goal').val()
        let Favorite_thing = $('#Favorite_thing').val()
        let Good_thing = $('#Good_thing').val()
        let First_values = $('#First_values').val()
        let World_needs = $('#World_needs').val()
        window.location.href = "/mypage?userid=" + Id;

        $.ajax({
            type: 'POST',
            url: '/modify',
            data: {
                Id_give: Id,
                Name_give: Name,
                Introduce_give: Introduce,
                Goal_give: Goal,
                Favorite_thing_give: Favorite_thing,
                Good_thing_give: Good_thing,
                First_values_give: First_values,
                World_needs_give: World_needs
            },
            success: function (response) {
                alert(response['msg'])
                // 새로고침
                window.location.reload()
            }
        });
    }
</script>
</head>
<body>
<box id="recording-box" class="recording-box">
    <div id="table-box"></div>
    <button onclick="modify()" type="button">수정하기</button>
</box>
</body>
</html>

record.html

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

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!--부트스트랩-->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>기록하기</title>

    <style>
        th, td {
            border-bottom: 1px solid #b7b7b7;
            padding: 10px;
        }
    </style>

    <script>
        function login() {
            $.ajax({
                type: 'GET',
                url: '/logins',
                data: {},
                success: function (response) {
                    let rows = response['ids']
                    let Id_list = []
                    for (let i = 0; i < rows.length; i++) {
                        Id_list[i] = rows[i]['Id']
                    }
                    console.log(Id_list)
                    let test_id = $('#Id').val()
                    if (test_id == "") {
                        alert("아이디를 입력하세요.")
                    } else {
                        if (Id_list.includes(test_id) === true) {
                            alert("중복된 아이디입니다.")
                        } else {
                            alert("사용가능한 아이디입니다.")
                        }
                    }
                }
            });
        }

        function recording() {
            if ($('#Id').val() == "") {
                alert("아이디를 입력하세요.")
            } else if ($('#Name').val() == "") {
                alert("이름을 입력하세요.")
            } else {
                let Id = $('#Id').val()
                let Name = $('#Name').val()
                let Introduce = $('#Introduce').val()
                let Goal = $('#Goal').val()
                let Favorite_thing = $('#Favorite_thing').val()
                let Good_thing = $('#Good_thing').val()
                let First_values = $('#First_values').val()
                let World_needs = $('#World_needs').val()
                window.location.href = "/mypage?userid=" + Id;

                $.ajax({
                    type: 'POST',
                    url: '/record',
                    data: {
                        Id_give: Id,
                        Name_give: Name,
                        Introduce_give: Introduce,
                        Goal_give: Goal,
                        Favorite_thing_give: Favorite_thing,
                        Good_thing_give: Good_thing,
                        First_values_give: First_values,
                        World_needs_give: World_needs
                    },
                    success: function (response) {
                        alert(response['msg'])
                        // 새로고침
                        window.location.reload()
                    }
                });
            }
        }

    </script>
</head>
<body>
    <!--마이페이지로 이동하기-->
    <box id="recording-box" class="recording-box">
        <table>
            <tbody>
            <tr class="id">
                <td>
                    <label for="Id">아이디</label>
                </td>
                <td>
                    <p><input type="text" id="Id" class="input-id" value=""/></p>
                    <p type="button" onclick="login()">아이디 중복확인</p>
                </td>
            </tr>
            <tr class="tr1">
                <td>
                    <label for="Name">이름</label>
                </td>
                <td>
                    <p><input type="text" id="Name" class="input-name" value=""/></p>
                </td>
            </tr>
            <tr class="tr1">
                <td>
                    <label for="Introduce">나를 표현하는 한 문장</label>
                </td>
                <td>
                    <p><textarea id="Introduce" class="input-introduce" value=""></textarea></p>
                </td>
            </tr>
            <tr class="tr1">
                <td>
                    <label for="Goal">목표</label>
                </td>
                <td>
                    <p><textarea id="Goal" class="input-goal" value=""></textarea></p>
                </td>
            </tr>
            <tr class="tr1">
                <td>
                    <label for="Favorite_thing">좋아하는 것</label>
                </td>
                <td>
                    <p><textarea id="Favorite_thing" class="input-favorite-thing" value=""></textarea></p>
                </td>
            </tr>
            <tr class="tr1">
                <td>
                    <label for="Good_thing">잘 하는 것</label>
                </td>
                <td>
                    <p><textarea id="Good_thing" class="input-good-thing" value=""></textarea></p>
                </td>
            </tr>
            <tr class="tr1">
                <td>
                    <label for="First_values">우선 가치관</label>
                </td>
                <td>
                    <p><textarea id="First_values" class="input-first-values" value=""></textarea></p>
                </td>
            </tr>
            <tr class="tr1">
                <td>
                    <label for="World_needs">세상이 필요로 하는 것</label>
                </td>
                <td>
                    <p><textarea id="World_needs" class="input-world-needs" value=""></textarea></p>
                </td>
            </tr>
            </tbody>
        </table>
        <button onclick="recording();" type="button">기록하기</button>
    </box>
</body>
</html>

좋은 웹페이지 즐겨찾기