[Python] How to Save and Display Custom Fields in SQLite Database for a Quiz Application?

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a quiz application where I need to save and display custom fields (model and threshold) in the SQLite database. However, when I view the quiz history, these fields show up as unknown default values instead of the expected values from the configuration.

    Here is a simplified version of my code:

    config.py:

    # Configuration settings
    use_concision_metric = False
    completeness_threshold = 0.6
    evaluation_model = "gpt-4o-mini"


    database.py:

    import sqlite3
    from typing import List, Dict

    class QuizDatabase:
    def __init__(self, db_path: str = "quiz.db"):
    self.db_path = db_path
    self.init_database()

    def init_database(self):
    with sqlite3.connect(self.db_path) as conn:
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS quiz_history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    total_score FLOAT NOT NULL,
    total_questions INTEGER NOT NULL,
    model TEXT NOT NULL,
    threshold FLOAT NOT NULL
    )
    """)
    conn.commit()

    def save_quiz_results(self, scores: list, model: str, threshold: float):
    with sqlite3.connect(self.db_path) as conn:
    cursor = conn.cursor()
    total_score = sum(scores)
    total_questions = len(scores)
    cursor.execute(
    "INSERT INTO quiz_history (total_score, total_questions, model, threshold) VALUES (?, ?, ?, ?)",
    (total_score, total_questions, model, threshold)
    )
    conn.commit()

    def get_quiz_history(self) -> List[Dict]:
    with sqlite3.connect(self.db_path) as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM quiz_history")
    return cursor.fetchall()


    gui.py:

    from config import evaluation_model, completeness_threshold
    from database import QuizDatabase

    db = QuizDatabase()

    def submit_quiz():
    scores = [0.5, 0.7, 0.8] # Example scores
    db.save_quiz_results(scores, evaluation_model, completeness_threshold)

    def view_history():
    history = db.get_quiz_history()
    for record in history:
    print(record)

    submit_quiz()
    view_history()


    When I run the code, the model and threshold fields in the quiz_history table show up as default values instead of the expected values from config.py.

    Continue reading...

Compartilhe esta Página