from banjo.urls import route_get, route_post from banjo.http import BadRequest, NotFound from app.models import Line, Poem, Rhyme from random import choice, sample @route_get('lines/random', args={}) def get_random_line(params): return {'line': Line.objects.random()} @route_get('lines/about', args={'topic': str}) def get_line_about_topic(params): try: line = Line.objects.filter(clean_text__contains=params['topic']).random() return {'lines' : line, 'topic': params['topic']} except Line.DoesNotExist: raise NotFound("No lines with that topic") @route_get('lines/rhyme', args={'rhyme': str}) def get_line_with_rhyme(params): try: line = Rhyme.get_rhyme_for_word(params['rhyme']).lines.exclude(clean_text__endswith=params['rhyme']).random() return {'lines' : line, 'rhyme': params['rhyme']} except Line.DoesNotExist: raise NotFound("No lines that rhyme") @route_get('/couplets/random', args={}) def get_random_couplet(params): flag = True while flag: line = Line.objects.random() if line.rhyming_lines().count() > 0: flag = False rhyming_line = line.rhyming_lines().random() return {'couplet' : [line, rhyming_line]} @route_get('/couplets/about', args={'topic' : str}) def get_couplet_about_topic(params): flag = True while flag: try: line = Line.objects.filter(clean_text__contains=params['topic']).random() except Line.DoesNotExist: raise NotFound("No lines with that topic") if line.rhyming_lines().count() > 0: flag = False rhyming_line = line.rhyming_lines().random() return {'couplet' : [line, rhyming_line], 'topic': params['topic']} @route_get('/couplets/rhyme', args={'rhyme' : str}) def get_couplet_with_rhyme(params): flag = True while flag: try: line = Rhyme.get_rhyme_for_word(params['rhyme']).lines.exclude(clean_text__endswith=params['rhyme']).random() except Line.DoesNotExist: raise NotFound("No lines with that rhyme") if line.rhyming_lines().count() > 0: flag = False rhyming_line = line.rhyming_lines().random() return {'couplet' : [line, rhyming_line], 'rhyme' : params['rhyme']} @route_get('poems/random', args={}) def get_random_line(params): return {'poem': Poem.objects.random()}