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): #returns a random line of poetry# return {'line': Line.objects.random().text} @route_get('lines/about', args={'topic': str}) def lines_about(params): #returns a random line containing the given topic# topic = params['topic'] lines = Line.objects.filter(clean_text__contains=topic) if lines.count() == 0: raise NotFound(f"No lines found containg '{topic}'") line = lines.random() return { 'line': line.text, 'topic': topic } @route_get('lines/rhyme', args = {'word': str}) def lines_rhyme(params): #returns a random line which rhyms with the given word# word = params['word'] rhyme = Rhyme.get_rhyme_for_word(word) if not rhyme or rhyme.lines.count() == 0: raise NotFound(f"No rhymes found for '{word}'") line = rhyme.lines.random() return { 'line': line.text, 'word': word } @route_get('couplets/random', args = {}) def random_couplet(params): #returns a random rhyming couplet line1 = Line.objects.random() line2 = line1.rhyming_lines().exclude(id=line1.id).random() return{ 'lines': [line1.text, line2.text] } @route_get('couplets/about', args = {'topic': str}) def couplets_about(params): #returns a rhyming couplet where the first line contains to topic topic = params['topic'] lines = Line.objects.filter(clean_text__contains = topic) if lines.count() == 0: raise NotFound(f"No lines found containing '{topic}'") line1 = lines.random() lines2 = line1.rhyming_lines().exclude(id=line1.id).random() return{ 'lines': [line1.text, line2.text], 'topic' : topic } @route_get('couplets/rhyme', args = {'word': str}) def couplets_rhyme(params): #returns a rhyming couplet for the given word word = params['word'] rhyme = Rhyme.get_rhyme_for_word(word) if not rhyme or rhyme.lines.count() < 2: raise NotFound(f"Not enough rhymes found for '{word}' to make a couplet") line1 = rhyme.lines.random() line2 = line1.rhyming_lines().exclude(id=line1.id).random() return{ 'lines': [line1.text, line2.text], 'word': word } @route_get('lines/start', args = {'prefix': str}) def lines_starting_with(params): #returns a random line that starts with the given prefix prefix = params['prefix'] lines = Line.object.filter(clean_text__startswith=prefix) if lines.count() == 0: raise NotFound(f"No lines start with '{prefix}'") line = lines.random() return{ 'line': line.text, 'prefix': prefix }