데이터 분석가

ToDoList 웹 페이지 구축 (Udemy Project 7) 본문

유데미 부트캠프 프로젝트(Final)

ToDoList 웹 페이지 구축 (Udemy Project 7)

PlintAn 2023. 6. 28. 10:00

안녕하세요 !

 

 

이번 시간에는 ToDoList를 만드는 웹 페이지를 간단하게 구축해보겠습니다!

 

1. index.html

웹 사이트 구축

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo List</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        .card-header {
            background-color: #f8f9fa;
            font-weight: bold;
        }

        .card-body {
            padding: 0;
        }

        .task-title {
            margin: 0;
            padding: 1rem;
            cursor: pointer;
        }

        .completed-task {
            text-decoration: line-through;
            opacity: 0.5;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Todo List</h5>
                    </div>
                    <div class="card-body">
                        <form action="/add_task" method="POST" class="mb-3">
                            <div class="input-group">
                                <input type="text" class="form-control" name="title" placeholder="Add a task" required>
                                <div class="input-group-append">
                                    <button type="submit" class="btn btn-primary">Add</button>
                                </div>
                            </div>
                        </form>

                        <div class="dropdown mb-3">
                            <button class="btn btn-secondary dropdown-toggle" type="button" id="sortDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                Sort By: {{ sort_by | title }}
                            </button>
                            <div class="dropdown-menu" aria-labelledby="sortDropdown">
                                <a class="dropdown-item" href="{{ url_for('index', sort_by='title', sort_order=sort_order) }}">Title</a>
                                <a class="dropdown-item" href="{{ url_for('index', sort_by='completed', sort_order=sort_order) }}">Completed</a>
                                <a class="dropdown-item" href="{{ url_for('index', sort_by='created_at', sort_order=sort_order) }}">Created At</a>
                            </div>
                            <button class="btn btn-secondary ml-2" onclick="window.location.href='{{ url_for('index', sort_by=sort_by, sort_order=toggle_sort_order(sort_order)) }}'">Toggle Order</button>
                        </div>

                        <ul class="list-group">
                            {% for task in tasks %}
                                <li class="list-group-item">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 task-title {% if task['completed'] %}completed-task{% endif %}" onclick="document.getElementById('complete-task-{{ task['id'] }}').submit();">
                                            {{ task['title'] }}
                                        </div>
                                        <div>
                                            <form id="complete-task-{{ task['id'] }}" action="/complete_task/{{ task['id'] }}" method="POST" style="display: none;"></form>
                                            <form action="/delete_task/{{ task['id'] }}" method="POST" style="display: inline;">
                                                <button type="submit" class="btn btn-danger btn-sm ml-2">Delete</button>
                                            </form>
                                            <form action="/incomplete_task/{{ task['id'] }}" method="POST" style="display: {% if task['completed'] %}inline{% else %}none{% endif %};">
                                                <button type="submit" class="btn btn-secondary btn-sm ml-2">Incomplete</button>
                                            </form>
                                        </div>
                                    </div>
                                </li>
                            {% endfor %}
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@1.16.0/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script>
        function toggle_sort_order(sort_order) {
            return (sort_order === 'asc') ? 'desc' : 'asc';
        }
    </script>
</body>
</html>

2. ToDolist.py

웹 API 구축

import os
from flask import Flask, render_template, request, redirect
import sqlite3

app = Flask(__name__)
DATABASE = 'todo.db'

# 데이터베이스 연결 함수
def get_db_connection():
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn

# 테이블 생성 함수
def create_table():
    conn = get_db_connection()
    conn.execute('''
        CREATE TABLE IF NOT EXISTS tasks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            completed INTEGER NOT NULL DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    ''')
    conn.commit()
    conn.close()

# 할 일 목록 가져오기 함수
def get_tasks(sort_by, sort_order):
    conn = get_db_connection()
    query = f"SELECT * FROM tasks ORDER BY {sort_by} {sort_order}"
    tasks = conn.execute(query).fetchall()
    conn.close()
    return tasks

@app.route('/')
def index():
    sort_by = request.args.get('sort_by', 'created_at')  # 정렬 기준 가져오기
    sort_order = request.args.get('sort_order', 'desc')  # 정렬 순서 가져오기
    tasks = get_tasks(sort_by, sort_order)  # 정렬된 할 일 목록 가져오기
    return render_template('index.html', tasks=tasks, sort_by=sort_by, sort_order=sort_order)

@app.route('/add_task', methods=['POST'])
def add_task():
    title = request.form['title']
    conn = get_db_connection()
    conn.execute('INSERT INTO tasks (title) VALUES (?)', (title,))
    conn.commit()
    conn.close()
    return redirect('/')

@app.route('/complete_task/<int:task_id>', methods=['POST'])
def complete_task(task_id):
    conn = get_db_connection()
    conn.execute('UPDATE tasks SET completed = 1 WHERE id = ?', (task_id,))
    conn.commit()
    conn.close()
    return redirect('/')

@app.route('/delete_task/<int:task_id>', methods=['POST'])
def delete_task(task_id):
    conn = get_db_connection()
    conn.execute('DELETE FROM tasks WHERE id = ?', (task_id,))
    conn.commit()
    conn.close()
    return redirect('/')

# 정렬 순서 토글 함수
@app.context_processor
def utility_processor():
    def toggle_sort_order(sort_order):
        return 'desc' if sort_order == 'asc' else 'asc'
    
    return dict(toggle_sort_order=toggle_sort_order)

if __name__ == '__main__':
    if not os.path.exists(DATABASE):
        create_table()
    app.run(debug=True)

이 코드는 Flask를 사용하여 할 일 목록을 관리하는 간단한 웹 애플리케이션입니다. 

기능으로는 할 일 목록의 추가, 완료 표시, 삭제, 정렬이 가능합니다. !

 

해당 결과로는 다음과 같습니다

 

ToDoList

Comments