feat: 阶段2 Python后端、用户管理、统计、单词收藏与响应式适配
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from .auth import login_required
|
||||
from .db import get_db, now_iso
|
||||
|
||||
vocab_bp = Blueprint("vocabulary", __name__)
|
||||
|
||||
|
||||
def row_to_dict(row):
|
||||
return dict(row)
|
||||
|
||||
|
||||
@vocab_bp.get("/api/vocabulary")
|
||||
@login_required
|
||||
def list_vocabulary(user):
|
||||
conn = get_db()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, word, english, chinese, category, created_at
|
||||
FROM vocabulary
|
||||
WHERE user_id = ?
|
||||
ORDER BY created_at DESC
|
||||
""",
|
||||
(user["id"],),
|
||||
).fetchall()
|
||||
return jsonify([row_to_dict(r) for r in rows])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@vocab_bp.post("/api/vocabulary")
|
||||
@login_required
|
||||
def add_vocabulary(user):
|
||||
data = request.get_json(silent=True) or {}
|
||||
word = (data.get("word") or "").strip()
|
||||
if not word:
|
||||
return jsonify({"error": "单词不能为空"}), 400
|
||||
conn = get_db()
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT id FROM vocabulary WHERE user_id = ? AND word = ?",
|
||||
(user["id"], word),
|
||||
).fetchone()
|
||||
if existing:
|
||||
row = conn.execute(
|
||||
"SELECT id, word, english, chinese, category, created_at FROM vocabulary WHERE id = ?",
|
||||
(existing["id"],),
|
||||
).fetchone()
|
||||
return jsonify(row_to_dict(row))
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO vocabulary (user_id, word, english, chinese, category, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
user["id"],
|
||||
word,
|
||||
(data.get("english") or "").strip(),
|
||||
(data.get("chinese") or "").strip(),
|
||||
(data.get("category") or "").strip(),
|
||||
now_iso(),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute(
|
||||
"SELECT id, word, english, chinese, category, created_at FROM vocabulary WHERE id = ?",
|
||||
(cur.lastrowid,),
|
||||
).fetchone()
|
||||
return jsonify(row_to_dict(row)), 201
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@vocab_bp.delete("/api/vocabulary/<int:item_id>")
|
||||
@login_required
|
||||
def delete_vocabulary(user, item_id):
|
||||
conn = get_db()
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM vocabulary WHERE id = ? AND user_id = ?",
|
||||
(item_id, user["id"]),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return jsonify({"error": "收藏不存在或无权访问"}), 404
|
||||
conn.execute("DELETE FROM vocabulary WHERE id = ?", (item_id,))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
Reference in New Issue
Block a user