Fork me on GitHub

基于python与flask实现一个读书笔记程序

app.py:

# -*- coding: utf-8 -*-
"""阅读笔记工具 - Flask + SQLite
功能:按书名模糊搜索书籍,查看历史笔记,追加笔记
db 文件不存在时自动新建
"""
import os
import sqlite3
from datetime import datetime
from flask import Flask, request, jsonify, render_template

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.path.join(BASE_DIR, "notes.db")

app = Flask(__name__)


def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn


def init_db():
    """数据库不存在或缺表时自动创建,可反复调用"""
    conn = get_db()
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS book (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS note (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            book_id INTEGER NOT NULL,
            content TEXT NOT NULL,
            created_at TEXT NOT NULL,
            FOREIGN KEY (book_id) REFERENCES book(id)
        );
        CREATE INDEX IF NOT EXISTS idx_note_book ON note(book_id);
        """
    )
    conn.commit()
    conn.close()


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


@app.route("/api/books", methods=["GET"])
def search_books():
    """模糊搜索书籍,返回笔记数和最近一条笔记"""
    q = request.args.get("q", "").strip()
    conn = get_db()
    if q:
        rows = conn.execute(
            """SELECT b.id, b.title, b.created_at,
                      (SELECT COUNT(*) FROM note n WHERE n.book_id = b.id) AS note_count,
                      (SELECT content FROM note n WHERE n.book_id = b.id
                       ORDER BY n.id DESC LIMIT 1) AS last_note
               FROM book b
               WHERE b.title LIKE ?
               ORDER BY note_count DESC, b.id DESC""",
            ("%" + q + "%",),
        ).fetchall()
    else:
        # 无关键字时返回笔记最多的书
        rows = conn.execute(
            """SELECT b.id, b.title, b.created_at,
                      (SELECT COUNT(*) FROM note n WHERE n.book_id = b.id) AS note_count,
                      (SELECT content FROM note n WHERE n.book_id = b.id
                       ORDER BY n.id DESC LIMIT 1) AS last_note
               FROM book b
               ORDER BY note_count DESC, b.id DESC
               LIMIT 50""",
        ).fetchall()
    conn.close()
    return jsonify([dict(r) for r in rows])


@app.route("/api/books/<int:book_id>/notes", methods=["GET"])
def get_notes(book_id):
    """获取某书的全部笔记,按时间倒序"""
    conn = get_db()
    rows = conn.execute(
        "SELECT id, content, created_at FROM note WHERE book_id = ? ORDER BY id DESC",
        (book_id,),
    ).fetchall()
    book = conn.execute(
        "SELECT id, title FROM book WHERE id = ?", (book_id,)
    ).fetchone()
    conn.close()
    if not book:
        return jsonify({"error": "书籍不存在"}), 404
    return jsonify({"book": dict(book), "notes": [dict(r) for r in rows]})


@app.route("/api/books/<int:book_id>/notes", methods=["POST"])
def add_note(book_id):
    """为书籍追加一条笔记"""
    data = request.get_json(silent=True) or {}
    content = (data.get("content") or "").strip()
    if not content:
        return jsonify({"error": "笔记内容不能为空"}), 400
    conn = get_db()
    book = conn.execute(
        "SELECT id FROM book WHERE id = ?", (book_id,)
    ).fetchone()
    if not book:
        conn.close()
        return jsonify({"error": "书籍不存在"}), 404
    conn.execute(
        "INSERT INTO note (book_id, content, created_at) VALUES (?, ?, ?)",
        (book_id, content, datetime.now().strftime("%Y-%m-%d %H:%M")),
    )
    conn.commit()
    conn.close()
    return jsonify({"ok": True})


@app.route("/api/notes/<int:note_id>", methods=["PUT"])
def update_note(note_id):
    """编辑笔记内容"""
    data = request.get_json(silent=True) or {}
    content = (data.get("content") or "").strip()
    if not content:
        return jsonify({"error": "笔记内容不能为空"}), 400
    conn = get_db()
    cur = conn.execute(
        "UPDATE note SET content = ? WHERE id = ?", (content, note_id)
    )
    conn.commit()
    conn.close()
    if cur.rowcount == 0:
        return jsonify({"error": "笔记不存在"}), 404
    return jsonify({"ok": True})


@app.route("/api/notes/<int:note_id>", methods=["DELETE"])
def delete_note(note_id):
    """删除笔记"""
    conn = get_db()
    cur = conn.execute("DELETE FROM note WHERE id = ?", (note_id,))
    conn.commit()
    conn.close()
    if cur.rowcount == 0:
        return jsonify({"error": "笔记不存在"}), 404
    return jsonify({"ok": True})


@app.route("/api/books", methods=["POST"])
def create_book():
    """新建书籍(可同时带第一条笔记)"""
    data = request.get_json(silent=True) or {}
    title = (data.get("title") or "").strip()
    content = (data.get("content") or "").strip()
    if not title:
        return jsonify({"error": "书名不能为空"}), 400
    conn = get_db()
    existing = conn.execute(
        "SELECT id FROM book WHERE title = ?", (title,)
    ).fetchone()
    if existing:
        conn.close()
        return jsonify({"error": "书名已存在", "id": existing["id"]}), 409
    now = datetime.now().strftime("%Y-%m-%d %H:%M")
    cur = conn.execute(
        "INSERT INTO book (title, created_at) VALUES (?, ?)", (title, now)
    )
    book_id = cur.lastrowid
    if content:
        conn.execute(
            "INSERT INTO note (book_id, content, created_at) VALUES (?, ?, ?)",
            (book_id, content, now),
        )
    conn.commit()
    conn.close()
    return jsonify({"ok": True, "id": book_id})


if __name__ == "__main__":
    init_db()
    print("访问 http://127.0.0.1:5000 使用")
    # host=0.0.0.0 允许局域网内手机/平板访问
    app.run(host="0.0.0.0", port=5000, debug=False)

 

index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>读书笔记</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: "Microsoft YaHei", sans-serif;
    background: #f5f0e6; /* 米色纸感 */
    color: #333;
    min-height: 100vh;
    padding: 20px;
}
.container { max-width: 900px; margin: 0 auto; }
h1 { font-size: 22px; margin-bottom: 16px; color: #8b4513; }

.search-bar { display: flex; gap: 8px; margin-bottom: 16px; }
.search-bar input {
    flex: 1; padding: 10px 14px; font-size: 16px;
    border: 1px solid #ccc; border-radius: 6px; outline: none;
}
.search-bar input:focus { border-color: #8b4513; }
.search-bar button {
    padding: 10px 18px; font-size: 15px; border: none;
    border-radius: 6px; background: #8b4513; color: #fff;
    cursor: pointer; font-weight: bold;
}
.search-bar button:hover { background: #a0522d; }

.book-list {
    background: #fff; border-radius: 8px; overflow: hidden;
    margin-bottom: 20px; box-shadow: 0 2px 6px rgba(0,0,0,0.08);
}
.book-item {
    padding: 12px 16px; border-bottom: 1px solid #eee;
    cursor: pointer; display: flex; justify-content: space-between;
    align-items: center;
}
.book-item:hover { background: #faf6ef; }
.book-item .name { font-weight: bold; font-size: 16px; }
.book-item .count {
    background: #8b4513; color: #fff; border-radius: 10px;
    padding: 2px 10px; font-size: 13px; font-weight: bold; white-space: nowrap;
}
.book-item .last-note {
    color: #888; font-size: 13px; margin-top: 4px;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 500px;
}

.detail-panel {
    background: #fff; border-radius: 8px; padding: 20px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.08);
}
.detail-panel h2 { color: #8b4513; margin-bottom: 12px; }
.note {
    background: #faf6ef; border-left: 3px solid #8b4513;
    padding: 10px 14px; margin-bottom: 10px; border-radius: 0 6px 6px 0;
}
.note .time { color: #999; font-size: 12px; margin-top: 4px; }
.note .content { font-size: 15px; line-height: 1.6; white-space: pre-wrap; }
.note .ops { margin-top: 6px; }
.note .ops button {
    border: none; background: none; color: #8b4513; cursor: pointer;
    font-size: 13px; padding: 2px 8px; border-radius: 4px;
}
.note .ops button:hover { background: #f0e6d8; }
.note .ops button.del { color: #c00; }
.note .ops button.del:hover { background: #fde8e8; }
.note-edit textarea {
    width: 100%; height: 70px; padding: 8px; font-size: 15px;
    border: 1px solid #8b4513; border-radius: 6px; resize: vertical;
    outline: none; font-family: inherit;
}

.add-note { margin-top: 16px; }
.add-note textarea {
    width: 100%; height: 70px; padding: 10px; font-size: 15px;
    border: 1px solid #ccc; border-radius: 6px; resize: vertical; outline: none;
    font-family: inherit;
}
.add-note textarea:focus { border-color: #8b4513; }
.add-note button {
    margin-top: 8px; padding: 8px 20px; border: none; border-radius: 6px;
    background: #8b4513; color: #fff; font-weight: bold; cursor: pointer; font-size: 15px;
}
.add-note button:hover { background: #a0522d; }

.hidden { display: none; }
.empty-tip { color: #aaa; padding: 20px; text-align: center; }
.error { color: #c00; font-size: 14px; margin-top: 8px; }
</style>
</head>
<body>
<div class="container">
    <h1>📖 读书笔记</h1>

    <div class="search-bar">
        <input id="searchInput" placeholder="输入书名搜索,回车如果不存在则新建…" autofocus>
        <button onclick="searchBooks()">搜索</button>
    </div>

    <div class="book-list" id="bookList"></div>

    <div class="detail-panel hidden" id="detailPanel">
        <h2 id="bookTitle"></h2>
        <div id="noteList"></div>
        <div class="add-note">
            <textarea id="noteInput" placeholder="添加笔记…"></textarea>
            <button onclick="addNote()">添加笔记</button>
            <span class="error hidden" id="noteError">笔记内容不能为空</span>
        </div>
    </div>
</div>

<script>
let currentBookId = null;

const searchInput = document.getElementById('searchInput');
const bookList = document.getElementById('bookList');
const detailPanel = document.getElementById('detailPanel');
const noteError = document.getElementById('noteError');

searchInput.addEventListener('keydown', e => {
    if (e.key === 'Enter') {
        const q = searchInput.value.trim();
        if (q) searchOrCreate(q);
    }
});
// 实时搜索
let searchTimer = null;
searchInput.addEventListener('input', () => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => searchBooks(), 300);
});

async function searchBooks() {
    const q = searchInput.value.trim();
    const resp = await fetch('/api/books?q=' + encodeURIComponent(q));
    const books = await resp.json();
    bookList.innerHTML = '';
    if (books.length === 0) {
        bookList.innerHTML = '<div class="empty-tip">没有找到书籍,回车可新建</div>';
        return;
    }
    books.forEach(b => {
        const div = document.createElement('div');
        div.className = 'book-item';
        const lastNote = b.last_note ? `<div class="last-note">最近: ${esc(b.last_note)}</div>` : '';
        div.innerHTML = `
            <div>
                <div class="name">${esc(b.title)}</div>
                ${lastNote}
            </div>
            <div class="count">${b.note_count} 条</div>`;
        div.onclick = () => showDetail(b.id, b.title);
        bookList.appendChild(div);
    });
}

// 回车:有精确匹配的书则选中,否则新建
async function searchOrCreate(q) {
    const resp = await fetch('/api/books?q=' + encodeURIComponent(q));
    const books = await resp.json();
    const exact = books.find(b => b.title.toLowerCase() === q.toLowerCase());
    if (exact) {
        showDetail(exact.id, exact.title);
    } else {
        if (confirm('书籍 "' + q + '" 不存在,是否新建?')) {
            const r = await fetch('/api/books', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({title: q})
            });
            const data = await r.json();
            if (r.ok) {
                searchBooks();
                showDetail(data.id, q);
            }
        }
    }
}

async function showDetail(bookId, title) {
    currentBookId = bookId;
    document.getElementById('bookTitle').textContent = '《' + title + '》';
    detailPanel.classList.remove('hidden');
    const resp = await fetch('/api/books/' + bookId + '/notes');
    const data = await resp.json();
    const noteList = document.getElementById('noteList');
    noteList.innerHTML = '';
    if (data.notes.length === 0) {
        noteList.innerHTML = '<div class="empty-tip">暂无笔记,在下方添加第一条</div>';
    }
    data.notes.forEach(n => {
        const div = document.createElement('div');
        div.className = 'note';
        div.innerHTML = `<div class="content" id="note-content-${n.id}">${esc(n.content)}</div>
            <div class="ops">
                <button onclick="editNote(${n.id})">编辑</button>
                <button class="del" onclick="deleteNote(${n.id})">删除</button>
                <span class="time" style="margin-left:8px">${n.created_at}</span>
            </div>`;
        noteList.appendChild(div);
    });
    document.getElementById('noteInput').focus();
}

// 编辑笔记:把该条笔记的原内容放进输入框,保存时替换原内容
async function editNote(noteId) {
    const contentDiv = document.getElementById('note-content-' + noteId);
    const oldContent = contentDiv.textContent;
    const newContent = prompt('修改笔记内容:', oldContent);
    if (newContent === null) return;  // 点了取消
    const trimmed = newContent.trim();
    if (!trimmed) { alert('笔记内容不能为空'); return; }
    const resp = await fetch('/api/notes/' + noteId, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({content: trimmed})
    });
    if (resp.ok) {
        // 刷新当前书详情
        const title = document.getElementById('bookTitle').textContent.replace(/[《》]/g, '');
        showDetail(currentBookId, title);
        searchBooks();
    }
}

async function deleteNote(noteId) {
    if (!confirm('确定删除这条笔记?')) return;
    const resp = await fetch('/api/notes/' + noteId, {method: 'DELETE'});
    if (resp.ok) {
        const title = document.getElementById('bookTitle').textContent.replace(/[《》]/g, '');
        showDetail(currentBookId, title);
        searchBooks();
    }
}

async function addNote() {
    const input = document.getElementById('noteInput');
    const content = input.value.trim();
    if (!content) {
        noteError.classList.remove('hidden');
        return;
    }
    noteError.classList.add('hidden');
    const resp = await fetch('/api/books/' + currentBookId + '/notes', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({content: content})
    });
    if (resp.ok) {
        input.value = '';
        showDetail(currentBookId, document.getElementById('bookTitle').textContent.replace(/[《》]/g, ''));
        searchBooks();
    }
}

// 防止 XSS
function esc(s) {
    const d = document.createElement('div');
    d.textContent = s || '';
    return d.innerHTML;
}

searchBooks();
</script>
</body>
</html>

任意目录\

├── app.py

└── templates\

        └── index.html

 

pip install flask →python app.py

 

posted @ 2026-11-23 20:08  烟波--钓徒  阅读(5)  评论(0)    收藏  举报