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 a_random_line(params): return {'line': Line.objects.random().text} @route_post('lines/about', args={'topic': str}) def a_random_line_containing_topic(params): try: return {"line":Line.objects.filter(clean_text__contains=params['topic']).random().text,"topic":params['topic']} except Line.DoesNotExist: raise NotFound("String not found") @route_post('lines/rhyme', args={'word': str}) def a_random_line_which_rhymes_with_word(params): try: return {"line":Rhyme.get_rhyme_for_word(params['word']).lines.exclude(clean_text__endswith=" "+params['word']).first().text,"word":params['word']} except Rhyme.DoesNotExist: raise NotFound("No rhyming line found") @route_get('couplets/random', args={}) def a_random_rhyming_couplet(params): while True: line = Line.objects.random() if line.rhyming_lines(): return {'lines':[line.text,list(line.rhyming_lines().sample(1))[0].text]} @route_post('couplets/about', args={'topic': str}) def a_random_rhyming_couplet_where_the_first_line_contains_topic(params): lines=Line.objects.filter(clean_text__contains=params['topic']) if lines: for line in lines: if line.rhyming_lines(): return {'lines':[line.text,line.rhyming_lines().random().text], 'topic':params['topic']} raise NotFound("No couplet found") @route_post('couplets/rhyme', args={'word': str}) def a_random_rhyming_couplet_where_both_lines_rhyme_with_word(params): try: r1=Rhyme.get_rhyme_for_word(params['word']).lines.exclude(clean_text__endswith=" "+params['word'])[0].text r2=Rhyme.get_rhyme_for_word(params['word']).lines.exclude(clean_text__endswith=" "+params['word'])[1].text return {'lines':[r1,r2], 'word':params['word']} except Rhyme.DoesNotExist: raise NotFound("No couplet found") @route_get('couplets/badpoem', args={}) def a_random_not_rhyming_couplet(params): while True: line1 = Line.objects.random() line2 = Line.objects.random() if line2 not in line1.rhyming_lines() and line1.text!=line2.text: return {'lines':[line1.text,line2.text]}