Introduction to Flask - Adopt a Pet!

I am having trouble completing this challenge, I don’t know the correct syntax for the animals and pet functions. I don’t know if my animals function is correct, please help.

I stopped codding on the 12th step, here is my code:


from helper import pets

app = Flask(__name__)

@app.route('/')

def index():

  return '''

  <h1>Adopt a Pet!</h1>

  <p>Browse through the links below to find your new furry friend:</p>

  <ul>

    <li><a href= '/animals/dogs'>Dogs</a></li>

    <li><a href= '/animals/cats'>Cats</a></li>

    <li><a href= '/animals/rabbits'>Rabbits</a></li>

  </ul>

  '''

@app.route('/animals/<pet_type>')

def animals(pet_type):

  html = '<h1>List of {pet_type}</h1>'

  for pet_type in pets:

    pet = '<li>{pet_type}</li>'

  return html + pet

@app.route('/animals/<pet_type>/int:<pet_id>')

def pet(pet_id):```
3 Likes

I got stuck on step 12 and can’t go any further. Hopefully, somebody can help us both.

2 Likes

I can get all the step except the last. I can’t figure out how to access the image and paragraph with the backslashes.

from flask import Flask
from helper import pets

app = Flask(__name__)

@app.route('/')
def index():
  return '''
  <h1>Adopt a Pet!</h1>
  <p>Browse through the links below to find your new furry friend:</p>
  <ul>
  <li><a href="/animals/dogs">Dogs</a></li>
  <li><a href="/animals/cats">Cats</a></li>
  <li><a href="/animals/rabbits">Rabbits</a></li>
  </ul>
  '''

@app.route('/animals/<pet_type>')
def animals(pet_type):
  html = f"<h1>{pet_type.title()}<h1>"
  pet = pets[pet_type]
  list = ""
  for i in range(len(pet)):
    list += f"<a href='/animals/{pet_type}/{i}'><li>{pet[i]['name']}</li></a>"
  return html + '<ul>' + list + '</ul>'  

@app.route('/animals/<pet_type>/<int:pet_id>')
def pet(pet_type, pet_id):
  pet = pets[pet_type]
  heading = f'<h1>{pet[pet_id]["name"]}</h1>'
  image = f"<img src='{pet[pet_id]['url']}'>"
  paragraph = f"<p>{pet[pet_id]['description']}</p>"
  return heading + image + paragraph
2 Likes

This is how my working solution looks, hopefully that can help you;

from flask import Flask
from helper import pets

app = Flask(__name__)

@app.route('/')
def index():
  return '''
  <h1>Adopt a Pet!</h1>
  <p>Browse through the links below to find your new furry friend:</p>
  <ul>
  <li><a href='/animals/dogs'>Dogs</a></li>
  <li><a href='/animals/cats'>Cats</a></li>
  <li><a href='/animals/rabbits'>Rabbits</a></li>
  </ul>
  '''

@app.route('/animals/<pet_type>')
def animals(pet_type):
  pet_list = f'<h1>List of {pet_type}</h1>'
  pet_list += '<ul>'
  pet = pets[pet_type]
  for index, p in enumerate(pet):
    pet_list += f"<li><a href=/animals/{pet_type}/{str(index)}>{p['name']}</a></li>"
  pet_list += '</ul>'
  print(pet_list)
  return pet_list

@app.route('/animals/<pet_type>/<int:pet_id>')
def pet(pet_type, pet_id):
  pet = pets[pet_type][pet_id]
  return f"""
  <h1>{pet['name']}</h1>
  <img src={pet['url']} alt='alt text'>
  <p>{pet['description']}</p>
  <ul>
  <li>{pet['breed']}</li>
  <li>{pet['age']}</li>
  </ul>
  """
8 Likes

First, html needs, to have f in the first so

HTML = f'<h1> List of {pet_type} </h1'

Next, for pet_type in pets, we need to get keys. so
so,

pet = '<li> {pet_type} </li>

So here is fully working bit for reference. Hope it helps.

from flask import Flask
from helper import pets

app = Flask(__name__)

@app.route('/')
def index():
  return '''
  <h1> Adopt a Pet!</h1> 
  <p>Browse through the links below to find your new furry friend:</p>
  <ul>
    <li> <a href = '/animals/dogs'>Dogs</a>
    <li> <a href = '/animals/cats'>Cats
    <li> <a href = '/animals/rabbits'>Rabbits
  </ul>
  '''

@app.route('/animals/<pet_type>')
def animals(pet_type):
  html = f'<h1> List of {pet_type}: </h1>'
  html += '<ul>'
  for idx, pet in enumerate(pets[pet_type]):
    html += '<li>{link}{namey}</li>'.format(link='<a href="/animals/{pet_type}/{idx}">'.format(pet_type=pet_type, idx=idx),namey='{n}'.format(n=pet['name']))
  html += '</a>'
  html += '</ul>'  
  return html

@app.route('/animals/<pet_type>/<int:pet_id>')
def pet(pet_type, pet_id):
    pet = pets[pet_type][pet_id]
    return f"""
  <h1>{pet['name']}</h1>
  <img src={pet['url']} alt='alt text'>
  <p>{pet['description']}</p>
  <ul>
  <li>{pet['breed']}</li>
  <li>{pet['age']}</li>
  </ul>
  """




1 Like

Hi there. I noticed answers are placed over multiple years so I just take a shot in the hope it helps anyone in the future.

In my case (also at step 12) it was lack of a proper understanding of enumerate that got me stuck (as well as forgetting about function arguments → didn’t read the instruction properly :face_with_monocle: ).

To better understand enumerate I copied the code from helper.py into an Idle shell and then ran the enumerate code.

Like follows:

for petId, pet in enumerate(pets['dogs']):
	print(petId)
	print(pet.get('name'))

#which gives:
0 # petID
Spot # pet.get('name')) 
1 # petId etc.
Shadow

"""
sidenote
pet.get('name') returns the same as pet['name']
as would pets.get(pet_type)[pet_id] return the same as pets[pet_type][pet_id] 
"""

After that I was able to solve the rest pretty quick, since it’s all the same logic.

Good luck and I hoped this helped anyone :wink:

p.s. this article on Geeks for Geeks also helped me along the way: Enumerate() in Python

Hey, I also struggled with this bit and understanding the wording. I’ve added my full working code with comments for the more difficult parts to explain the functions and for loop:

from flask import Flask
from helper import pets
app = Flask(__name__)

@app.route('/')
def index():
  return """<h1>Adopt a Pet!</h1>
            <p>Browse through the links below to find your new furry friend:</p>
            <ul>
            <li><a href="/animals/dogs">Dogs</a></li>
            <li><a href="/animals/cats">Cats</a></li>
            <li><a href="/animals/rabbits">Rabbits</a></li>
            </ul>
            """

@app.route('/animals/<pet_type>')
def animals(pet_type):
  html = f"""<h1>List of {pet_type}</h1>
              """
  html += '<ul>'
  #step 12 
  #step 16:
  # for each index and pet in pets dict of pets type, give a li linking to its individual page
  #enumerate() is needed to give each one an index and str() to turn it into a string type
  for index, pet in enumerate(pets[pet_type]):
    html += f"""<li><a href="/animals/{pet_type}/{str(index)}">{pet["name"]}</a></li>"""
  return html

#step 13
@app.route('/animals/<pet_type>/<int:pet_id>')
def pet(pet_type, pet_id):
  #step 14
  #get specific pet from type and id in request parameters
  pet = pets[pet_type][pet_id]
  # step 15 - show pet name in html
  #step 17 - add img, p, ul, li
  html = f"""<h1>{pet["name"]}</h1>
              <img src="{pet["url"]}"></img>
              <p>{pet["description"]}</p>
              <ul>
              <li>Breed: {pet["breed"]}</li>
              <li>Age: {pet["age"]}</li>
              <ul>
              """
  return html

I am not sure what I am doing wrong. I keep getting the error (name ) is not defined.
Here is my code.

from flask import Flask
from helper import pets
app = Flask(name)
@app.route(‘/’)
def index():
return ‘’’

Thank you

Here is a hint, you need to use dunder methods.

i.e. __name__ :white_check_mark:
name :x:

Thank you, now I will understand how you did. Tasks 16 and 17 were a little hard for me.

A post was split to a new topic: My Adopt a Pet solution