Question

need help to complete the task: app.py is the Python server-side application. It includes a class...

need help to complete the task:

  • app.py is the Python server-side application.
    • It includes a class for representing the list of albums. You need to complete the missing parts such that it loads data from the data/albums.txt and data/tracks.txt files. You can decide what internal data structure you want to use for storing the data.
    • It is already implemented that a single instance of the Albums class is used, so that loading from the files happens only once (and not for each request).

heres the code:

from flask import Flask, request, g
app = Flask(__name__)
class Albums():
"""Class representing a collection of albums."""
def __init__(self, albums_file, tracks_file):
self.__albums = {}
self.__load_albums(albums_file)
self.__load_tracks(tracks_file)
def __load_albums(self, albums_file):
"""Loads a list of albums from a file."""
# TODO complete
pass
def __load_tracks(self, tracks_file):
"""Loads a list of tracks from a file."""
# TODO complete
pass
def get_albums(self):
"""Returns a list of all albums, with album_id, artist and title."""
# TODO complete
return None
def get_album(self, album_id):
"""Returns all details of an album."""
# TODO complete
return None
# the Albums class is instantiated and stored in a config variable
# it's not the cleanest thing ever, but makes sure that the we load the text files only once
app.config["albums"] = Albums("data/albums.txt", "data/tracks.txt")
@app.route("/albums")
def albums():
"""Returns a list of albums (with album_id, author, and title) in JSON."""
albums = app.config["albums"]
# TODO complete (return albums.get_albums() in JSON format)
return ""
@app.route("/albuminfo")
def albuminfo():
albums = app.config["albums"]
album_id = request.args.get("album_id", None)
if album_id:
# TODO complete (return albums.get_album(album_id) in JSON format)
return ""
return ""
@app.route("/sample")
def sample():
return app.send_static_file("index_static.html")
@app.route("/")
def index():
return app.send_static_file("index.html")
if __name__ == "__main__":
app.run()

i have to textfiles:

tracks.txt:

1   Politik   5:18
1   In My Place   3:48
1   God Put a Smile upon Your Face   4:57
1   The Scientist   5:09
1   Clocks   5:07
1   Daylight   5:27
1   Green Eyes   3:43
1   Warning Sign   5:31
1   A Whisper   3:58
1   A Rush of Blood to the Head   5:51
1   Amsterdam   5:19
2   Right Next Door to Hell   3:02
2   Dust N' Bones   4:58
2   Live and Let Die   3:04
2   Don't Cry   4:44
2   Perfect Crime   2:23
2   You Ain't the First   2:36
2   Bad Obsession   5:28
2   Back Off Btch   5:03
2   Double Talkin' Jive   3:23
2   November Rain   8:57
2   The Garden   5:22
2   Garden of Eden   2:41
2   Don't Dam Me   5:18
2   Bad Apples   4:28
2   Dead Horse   4:17
2   Coma   10:13

albums.txt:

1   Coldplay   A Rush of Blood to the Head   Coldplay-ARushofBlood.jpg
2   Guns N' Roses   Use Your Illusion I   GnR-UseYourIllusion1.jpg

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the Python code. I have tested it by hitting the API request through a Postman client and it is working. I have put inline comments in code for explanation. Note that I have assumed that the data in albums.txt and tracks.txt is tab delimited.

from flask import Flask, request, jsonify

app = Flask(__name__)


class Albums():
   """Class representing a collection of albums."""
   def __init__(self, albums_file, tracks_file):
       self.__albums = {}
       self.__load_albums(albums_file)
       self.__load_tracks(tracks_file)

   def __load_albums(self, albums_file):
       """Loads a list of albums from a file."""
       with open(albums_file, "r") as f:
           data = f.read()

       # Read each line by splitting data with '\n'
       for line in data.split("\n"):

           # Assuming that the file is delimited with tabs ('\t'),
           # get the album details from the line by splitting with '\t' and add it to `self.__albums`
           # We create an empty list per album under the key "tracks" that will be populated later in __load_tracks function
           album_id, artist, title, image = line.split("\t")
           self.__albums[album_id] = {
               "artist": artist,
               "title": title,
               "tracks": []
           }

   def __load_tracks(self, tracks_file):
       """Loads a list of tracks from a file."""
       with open(tracks_file, "r") as f:
           data = f.read()

       # Read each line by splitting data with '\n'
       for line in data.split("\n"):

           # Assuming that the file is delimited with tabs ('\t'),
           # get the track details from the line by splitting with '\t'
           album_id, song, duration = line.split("\t")
           track_details = {
               "song": song,
               "duration": duration
           }

           # Add the track details to self.__albums under the corresponding album_id
           self.__albums[album_id]["tracks"].append(track_details)

   def get_albums(self):
       """Returns a list of all albums, with album_id, artist and title."""
       album_details = []
       for album_id, album_info in self.__albums.items():
           album_details.append({
               "album_id": album_id,
               "artist": album_info["artist"],
               "title": album_info["title"]
           })
       return album_details

   def get_album(self, album_id):
       """Returns all details of an album."""
       return self.__albums[album_id]

# the Albums class is instantiated and stored in a config variable
# it's not the cleanest thing ever, but makes sure that the we load the text files only once
app.config["albums"] = Albums("data/albums.txt", "data/tracks.txt")

@app.route("/albums")
def albums():
   """Returns a list of albums (with album_id, author, and title) in JSON."""
   albums = app.config["albums"]
   return jsonify({"albums": albums.get_albums()})

@app.route("/albuminfo")
def albuminfo():
   albums = app.config["albums"]
   album_id = request.args.get("album_id", None)
   if album_id:
       return jsonify(albums.get_album(album_id))
   return jsonify({})

@app.route("/sample")
def sample():
   return app.send_static_file("index_static.html")

@app.route("/")
def index():
   return app.send_static_file("index.html")

if __name__ == "__main__":
   app.run()

Add a comment
Know the answer?
Add Answer to:
need help to complete the task: app.py is the Python server-side application. It includes a class...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have a java class that i need to rewrite in python. this is what i...

    I have a java class that i need to rewrite in python. this is what i have so far: class Publisher: __publisherName='' __publisherAddress=''    def __init__(self,publisherName,publisherAddress): self.__publisherName=publisherName self.__publisherAddress=publisherAddress    def getName(self): return self.__publisherName    def setName(self,publisherName): self.__publisherName=publisherName    def getAddress(self): return self.__publisherAddress    def setAddress(self,publisherAddress): self.__publisherAddress=publisherAddress    def toString(self): and here is the Java class that i need in python: public class Publisher { //Todo: Publisher has a name and an address. private String name; private String address; public Publisher(String...

  • from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked...

    from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked list. Note that this is considered a "private class", one which is only meant to be used in this module by the LinkedList class, but not by client code. === Attributes === item: The data stored in this node. next: The next node in the list, or None if there are no more nodes. """ item: Any next: Optional[_Node] def __init__(self, item: Any) ->...

  • Task 2: SecretWord class: Download and save a copy of LinkedLists.py (found at the bottom of...

    Task 2: SecretWord class: Download and save a copy of LinkedLists.py (found at the bottom of this assignment page on eClass). In this file, you have been given the complete code for a LinkedList class. Familiarize yourself with this class, noticing that it uses the Node class from Task 1 and is almost identical to the SLinkedList class given in the lectures. However, it also has a complete insert(pos, item) method (which should be similar to the insert method you...

  • Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Ini...

    Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Initialize the object properties def __init__(self, id, name, mark): # TODO # Print the object as an string def __str__(self): return ' - {}, {}, {}'.format(self.id, self.name, self.mark) # Check if the mark of the input student is greater than the student object # The output is either True or False def is_greater_than(self, another_student): # TODO # Sort the student_list # The output is the sorted...

  • PYTHON 3 PLEASE FOLLOW INSTRUCTIONS COMPLETE CODE Problem : Complete the function predecessor() to take in...

    PYTHON 3 PLEASE FOLLOW INSTRUCTIONS COMPLETE CODE Problem : Complete the function predecessor() to take in an arbitrary node of a BST, and return the value of the predecessor of the given node. Code : class Node: def __init__(self, value): self.value = value self.left = None self.right = None    def predecessor(node): # TODO

  • ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value):...

    ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value): self.value = value self.next = None def __repr__(self): return "{}".format(self.value) def __init__(self): self.top = None def shuffle(self): card_list = 4 * [x for x in range(2, 12)] + 12 * [10] random.shuffle(card_list) self.top = None for card in card_list: new_card = self.Card(card) new_card.next = self.top self.top = new_card def __repr__(self): curr = self.top out = "" card_list = [] while curr is not None:...

  • Finish each function python 3 LList.py class node(object): """ A version of the Node class with...

    Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class.    Since there are no setters and getters, we use the attributes directly.    This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...

  • In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains,...

    In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains, insert, and normal_list methods. You may use default arguments and/or helper functions. The file must be named: LinkedList.py Here is what I have for my code so far. The methods I need the recursive implementations for will be bolded: class Node: """ Represents a node in a linked list (parent class) """ def __init__(self, data): self.data = data self.next = None class LinkedList: """...

  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

  • Python 3: Write a LinkedList method named contains, that takes a value as a parameter and...

    Python 3: Write a LinkedList method named contains, that takes a value as a parameter and returns True if that value is in the linked list, but returns False otherwise. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT