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().text} @route_get('lines/about', args={'topic': str}) def get_lines_about(params): lines = Line.objects.filter(text__icontains=params['topic']) if not lines: raise NotFound("No lines found about that topic") return {'line': choice(lines).text, 'topic': params['topic'] } @route_get('lines/rhyme', args={'word': str}) def get_lines_rhyme(params): rhymes = Rhyme.get_rhyme_for_word(params['word']) lines = list(rhymes.lines.all()) if not rhymes: raise NotFound("No rhymes found for that word") line=choice(lines) return {'line': line.text, 'word': params['word'] } @route_get('couplets/random', args={}) def get_random_couplet(params): poem= Poem.objects.random() lines= sample(list(poem.lines.all()), 2) return {'lines': [lines[0].text, lines[1].text]} @route_get('couplets/about', args={'topic': str}) def get_couplets_about(params): lines = Line.objects.filter(text__icontains=params['topic']) if not lines: raise NotFound("No lines found about that topic") line1 = choice(lines) line2 = choice(line1.poem.lines.exclude(id=line1.id)) return {'lines': [line1.text, line2.text], 'topic': params['topic'] } @route_get('couplets/rhyme', args={'word': str}) def get_couplets_rhyme(params): rhyme = Rhyme.get_rhyme_for_word(params['word']) lines = list(rhyme.lines.all()) if not lines: raise NotFound("No rhymes found for that word") line1 = choice(lines) line2 = choice(rhyme.lines.exclude(id=line1.id)) return {'lines': [line1.text, line2.text], 'word': params['word'] } @route_get('lines/lastword', args={'word': str}) def get_lines_lastword(params): lines = Line.objects.filter(clean_text__endswith=params['word']) if not lines: raise NotFound("No lines found that end with that word") return {'line': choice(lines).text, 'word': params['word'] }