quiz-the-word/database.py

87 lines
2.8 KiB
Python

from flask import current_app, g
import sqlalchemy
from sqlalchemy import Column, JSON, String, Integer, create_engine, ForeignKey, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import sessionmaker, relationship
from config import DB_URL
engine = create_engine(DB_URL)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class AllQuestions(Base):
__tablename__ = "all_questions"
question_id = Column(Integer, primary_key=True, nullable=False)
question = Column(String)
answer = Column(String)
addresses = Column(String)
def __repr__(self):
return f"<Question: {self.question_id}>"
class HiddenAnswer(Base):
__tablename__ = "category_hidden_answer"
question_id = Column(Integer, ForeignKey("all_questions.question_id"), primary_key=True)
difficulty = Column(Integer)
hint = Column(JSON)
all_question_relationship = relationship("AllQuestions", primaryjoin="HiddenAnswer.question_id==AllQuestions.question_id", lazy="joined", uselist=False)
question = association_proxy("all_question_relationship", "question")
answer = association_proxy("all_question_relationship", "answer")
addresses = association_proxy("all_question_relationship", "addresses")
def __repr__(self):
return f"<Question Hidden Answer: {self.question_id}>"
class MultipleChoice(Base):
__tablename__ = "category_multiple_choice"
question_id = Column(Integer, ForeignKey("all_questions.question_id"), primary_key=True)
difficulty = Column(Integer)
hint = Column(JSON)
wrong_answers = Column(String)
all_question_relationship = relationship("AllQuestions", primaryjoin="MultipleChoice.question_id==AllQuestions.question_id", lazy="joined", uselist=False)
question = association_proxy("all_question_relationship", "question")
answer = association_proxy("all_question_relationship", "answer")
addresses = association_proxy("all_question_relationship", "addresses")
def __repr__(self):
return f"<Question Multiple Choice: {self.question_id}>"
def get_all_questions():
session = Session()
return session.query(AllQuestions).all()
def get_all_hidden_answer():
session = Session()
return session.query(HiddenAnswer).all()
def get_all_multiple_choice():
session = Session()
return session.query(MultipleChoice).all()
def get_category_count(category):
session = Session()
return session.query(category).count()
def get_question(category, question_id):
session = Session()
return session.query(category).filter(category.question_id == question_id).one_or_none()
def get_random_question_of_difficulty(category, difficulty):
session = Session()
return session.query(category).filter(category.difficulty == difficulty).order_by(func.random()).first()