first commit
This commit is contained in:
68
backend/routers/exports.py
Normal file
68
backend/routers/exports.py
Normal file
@@ -0,0 +1,68 @@
|
||||
import csv
|
||||
import json
|
||||
from io import StringIO
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from backend.auth import get_current_user
|
||||
from backend.database import get_db
|
||||
from backend.models import Question
|
||||
from backend.services.excel_service import export_excel_bytes
|
||||
|
||||
router = APIRouter(dependencies=[Depends(get_current_user)])
|
||||
|
||||
|
||||
def _filter_questions(
|
||||
db: Session, chapter: str = "", question_type: str = "", difficulty: str = ""
|
||||
) -> list[Question]:
|
||||
query = db.query(Question)
|
||||
if chapter:
|
||||
query = query.filter(Question.chapter == chapter)
|
||||
if question_type:
|
||||
query = query.filter(Question.question_type == question_type)
|
||||
if difficulty:
|
||||
query = query.filter(Question.difficulty == difficulty)
|
||||
return query.order_by(Question.id.desc()).all()
|
||||
|
||||
|
||||
@router.get("")
|
||||
def export_questions(
|
||||
format: str = Query(default="json", pattern="^(json|csv|xlsx)$"),
|
||||
chapter: str = "",
|
||||
question_type: str = "",
|
||||
difficulty: str = "",
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
items = _filter_questions(db, chapter, question_type, difficulty)
|
||||
rows = [
|
||||
{
|
||||
"id": i.id,
|
||||
"chapter": i.chapter,
|
||||
"primary_knowledge": i.primary_knowledge,
|
||||
"secondary_knowledge": i.secondary_knowledge,
|
||||
"question_type": i.question_type,
|
||||
"difficulty": i.difficulty,
|
||||
"stem": i.stem,
|
||||
"option_a": i.option_a,
|
||||
"option_b": i.option_b,
|
||||
"option_c": i.option_c,
|
||||
"option_d": i.option_d,
|
||||
"answer": i.answer,
|
||||
"explanation": i.explanation,
|
||||
"notes": i.notes,
|
||||
"source_file": i.source_file,
|
||||
}
|
||||
for i in items
|
||||
]
|
||||
if format == "json":
|
||||
return {"format": "json", "content": json.dumps(rows, ensure_ascii=False)}
|
||||
if format == "csv":
|
||||
out = StringIO()
|
||||
writer = csv.DictWriter(out, fieldnames=rows[0].keys() if rows else ["id"])
|
||||
writer.writeheader()
|
||||
for row in rows:
|
||||
writer.writerow(row)
|
||||
return {"format": "csv", "content": out.getvalue()}
|
||||
xlsx_bytes = export_excel_bytes(rows)
|
||||
return {"format": "xlsx", "content_base64": xlsx_bytes.hex()}
|
||||
Reference in New Issue
Block a user