Files
lab_server/poem_server/app/views.py
2026-04-10 17:59:16 -04:00

89 lines
3.0 KiB
Python

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):
'Get a random line of poetry'
return {'line': Line.objects.random().text}
@route_get('lines/about/<topic>', args={'topic': str})
def get_about_topic(params):
'Get a random line of poetry about a selected topic'
topic = params['topic']
if not topic:
raise BadRequest("Please enter a topic")
return {'line': Line.objects.filter(clean_text__contains=topic).random().text}
@route_get('lines/rhyme/<word>', args={'word': str})
def get_random_rhyme(params):
'Get a random line of poetry that rhymes with a selected word'
word = params['word']
if not word:
raise BadRequest("Please enter a word to explore poetry lines that rhyme with the selected word")
rhymes = Rhyme.get_rhyme_for_word(word)
rhymed_lines = rhymes.line
return{'line': rhymed_lines.random().text}
@route_get('couplets/random', args={})
def get_random_couplet(params):
'Get a random rhyming couplet'
first_line=Line.objects.random()
first_line_last=first_line.last_word()
rhymes = Rhyme.get_rhymes_for_word(first_line_last)
rhymed_lines= rhymes.line
second_line=rhymed_lines.random()
return {'couplet line 1': first_line.text,
'couplet line 2': second_line.text
}
@route_get('couplets/about/<topic>', args= {'topic': str})
def get_random_couplets_topic(params):
'Get a random rhyming couplet about a selected topic'
topic = params['topic']
first_line=Line.objects.filter(clean_text__contains=topic).random()
first_line_last=first_line.last_word()
rhymes = Rhyme.get_rhymes_for_word(first_line_last)
rhymed_lines= rhymes.line
second_line=rhymed_lines.random()
return {'couplet line 1': first_line.text,
'couplet line 2': second_line.text
}
@route_get('couplets/rhyme/<word>', args = {'word':str})
def get_random_rhyming_couplet(params):
word = params['word']
rhymes = Rhyme.get_rhyme_for_word(word)
rhymed_lines = rhymes.line
first_line=rhymed_lines.random()
second_line=rhymed_lines.random()
return { 'couplet line 1': first_line.text,
'couplet line 2': second_line.text }
def first_word(self):
"Gets the first word from a line, lower case and without punctuation."
parts = self.clean_text.split()
if parts:
return parts[0]
@route_get('couplet/last/first', args = {})
def get_last_first_couplet(params):
'Get a random couplet whose second lines first word start with first lines last'
first_line=Line.objects.random()
first_line_last=first_line.last_word()
first_last_match = []
for line in Line.objects.all():
if line.first_word() == first_line_last:
first_last_match.append(line)
second_line= first_last_match.random()
return { 'couplet line 1': first_line.text,
'couplet line 2': second_line.text }