SHARE
TWEET

Untitled

a guest Feb 24th, 2017 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #models.py
  2. class Question(db.Model):
  3.     text = db.Column('text', db.String)
  4.  
  5. class Choice(db.Model):
  6.     text = db.Column('text', db.String)
  7.     q_id = db.Column('q_id', db.Integer, db.ForeignKey(Question.id))
  8.     question = db.relationship('Question', foreign_keys=q_id)
  9.  
  10.  
  11. #services.py
  12. class QuestionService(object):
  13.     def __init__(self, question_repository, choice_repository):
  14.         self.question_repository = question_repository
  15.         self.choice_repository = choice_repository
  16.  
  17.     def create_question(self, payload):
  18.         try:
  19.             question = models.Question(text = payload['question'])
  20.             question = self.question_repository.create(question)
  21.             self.create_choices(payload['choices'], question.id)
  22.             db.session.commit()
  23.         except SQLALchemyError:
  24.             db.session.rollback()
  25.  
  26.     def create_choices(self, choices, question_id):
  27.         choices = [ models.Choice(text=choice_text, q_id=question_id)
  28.                     for choice_text in choices ]
  29.         self.choice_repository.create_all(choices)
  30.  
  31.     def fetch_by_text(self, text):
  32.         #called from views.py
  33.         return self.question_repository.fetch_by_text(text)
  34.  
  35.     def fetch_by_id(self, id):
  36.         #called from views.py
  37.         question = self.question_repository.fetch(id)
  38.         if not question:
  39.             raise ResourceNotFound()
  40.         return question
  41.  
  42.  
  43. #repositories.py
  44. from models import db
  45. class BaseRepository(object):
  46.     def __init__(self, db=None):
  47.         self.db = db
  48.  
  49.     def create(self, item):
  50.         self.db.session.add(item)
  51.         self.db.session.flush()
  52.         return item
  53.  
  54.     def create_all(self, item):
  55.         self.db.session.add_all(item)
  56.         self.db.session.flush()
  57.         return item
  58.  
  59. class QuestionRepository(BaseRepository):
  60.     def fetch(self, id):
  61.         return self.session.query(Question).filter(Question.id == id).first()
  62.  
  63.     def fetch_by_text(self, text):
  64.         return self.session.query(Question).filter(Question.text == text).all()
  65.  
  66. class ChoiceRepository(BaseRepository):
  67.     pass
RAW Paste Data
Top