User Listening History
Introduction: Why User Listening History Matters
Welcome back! In the previous lessons, you learned how to set up a backend for a music player app, serve track data, and log when a user listens to a track. Now, let’s take the next step: accessing and displaying a user’s listening history.
Showing users their listening history is a key feature in most music apps. It helps users remember what they have listened to, discover patterns in their listening habits, and even get personalized recommendations. In this lesson, you will learn how to retrieve and display this history using the data we have been collecting.
Quick Recap: App and Data Structure
Before we dive in, let’s quickly remind ourselves of the app’s structure and the data files involved. You have already set up:
- A
tracks.jsonfile that stores information about all available tracks. - A
sessions.csvfile that logs each time a user listens to a track.
Here’s a quick look at how these are loaded and used in the app:
This code shows how we use Pandas to read both the track and session data. We will use these dataframes to find and display a user’s listening history.
How We Store and Find Listening Sessions
Whenever a user listens to a track, we log that session in the sessions.csv file. Each row in this file represents one listening event and contains the following columns:
| user_id | track_id | timestamp |
|---|---|---|
| 1 | 101 | 2024-06-01T10:00:00 |
| 2 | 102 | 2024-06-01T10:05:00 |
| 1 | 103 | 2024-06-01T10:10:00 |
To get a specific user’s listening history, we need to filter this file for their user_id. Here’s how this is done in the code:
Explanation:
- The function checks if the
sessionsfile exists. - It loads the sessions into a DataFrame.
- It filters the DataFrame to include only rows where
user_idmatches the given user. - If anything goes wrong, it returns an empty DataFrame.
Example Output:
If you call get_user_listening_history("1"), you might get:
| user_id | track_id | timestamp |
|---|---|---|
| 1 | 101 | 2024-06-01T10:00:00 |
| 1 | 103 | 2024-06-01T10:10:00 |
