[PYTHON] Try hitting the Spotify API in Django.

Introduction

This article is for Django Advent Calendar 2019. The target audience is for those who are new to Django.

The previous article was about @ yuu-eguci's 500 error. https://qiita.com/yuu-eguci/items/a1e4b0a2f238d5ccc985

This article is about running Spotify's API in Django.

Advance preparation

I need to create a Spotify user account, but the following article by Class Method is very helpful. https://dev.classmethod.jp/etc/about-using-of-spotify-api/

If you want to execute the sample code of the article, please download the chart data in CSV format from the following. https://spotifycharts.com/regional/jp/daily/latest

Server-side implementation

It's very bad manners, but I want you to check the operation easily, so I've summarized everything in views.py. I'm sorry if it makes you feel uncomfortable. .. ..


class SpotifySong:
    def __init__(self, song_name, uri):
        self.song_name = song_name
        self.uri = uri

def spotify(request) :
    #Spotify Client ID,Enforce authorization using Secret
    client_id = ''
    client_secret = ''
    client_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(client_id, client_secret)
    #Create a Spotify instance
    spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

    #Read CSV file downloaded from Spotify
    songs = pd.read_csv(BASE_DIR + '/regional-jp-daily-latest.csv', index_col=0, header=1)

    #Get song information from Spotify
    spotify_songs_list = []
    for url in songs['URL']:
        spotify_songs_list.extend(spotify.audio_features(url))

    #Attach song titles
    response_list = []
    for i,spotify_song in enumerate(spotify_songs_list):
        response_list.append(SpotifySong(songs.iat[i,0],spotify_song['uri']))

    #Specify template
    template = loader.get_template('spotify/spotify_base.html')
    context = {
        'response_list': response_list,
    }
    return HttpResponse(template.render(context, request))

Please refer to the following for the response returned by spotify.audio_features. Not only the playing time and keys, but also indicators such as how acoustic the song is and how much you can dance are returned. I will omit it in this article, but it seems that I can make a service to learn the tendency of songs that are preferred depending on the season! https://developer.spotify.com/documentation/web-api/reference/tracks/get-audio-features/

Client-side implementation


{% if response_list %}
    <h1>daily ranking</h1>
    <ul>
    {% for response in response_list %}
    <li><a href="https://embed.spotify.com/?uri={{ response.uri }}"> {{response.song_name}} </a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>Failed to get music from Spotify.</p>
{% endif %}

Although it is simple HTML, you can make a daily ranking like the following. It's a simple screen that you can click to jump to the Spotify song page, but I think it would be great for beginners to make it.

スクリーンショット 2019-12-01 19.09.13.png

What you need to know to understand the sample code

There are a few things to keep in mind when working with Templates in Django. Click here for the manual. https://docs.djangoproject.com/en/2.2/ref/templates/language/#templates

  1. When you want to get the size of the collection

You need to get it by writing {{variable | length}}. You cannot write the variable .length.

スクリーンショット 2019-12-01 19.18.01.png
  1. When you want to specify the index of the collection and get it

You can only get it by directly specifying the index number, such as {{variable .0}}. You cannot write {{variable [[0]]}}.

スクリーンショット 2019-12-01 19.19.56.png

For the above reasons, this sample code defines its own class to get the song title. It is possible to pass the return value of SpotifyAPI and the result of CSV reading, but it is difficult to get it using the index number, so it is troublesome to handle the data with the objects separated.

Bonus troubleshooting

If you type the following command, the Port is being used error may occur.

python3 manage.py runserver

Django version 2.2.7, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Error: That port is already in use.

The easiest way to solve the above is to kill the process by following the steps below.

  1. Check the port
lsof -i -P | grep 8000
Python    71504 user    4u  IPv4 0x2cdb3e922e88888      0t0  TCP localhost:8000 (LISTEN)
  1. Execute the kill command by specifying the PID
kill -9 71504

At the end

The hurdles for the final release date of Django 3.0 haven't been exceeded, but I hope it helps someone. .. .. Tomorrow's Django Advent Calendar is @ shimayu22. Thank you!!

Recommended Posts

Try hitting the Spotify API in Django.
Try using the Kraken API in Python
Try using the BitFlyer Ligntning API in Python
Tips for hitting the ATND API in Python
Try using the DropBox Core API in Python
Try using the Twitter API
Try using the Twitter API
Try using the PeeringDB 2.0 API
Getting the arXiv API in Python
Hit the Sesami API in Python
Try Ajax on the Django page
Switch the language displayed in Django 1.9
Hit the web API in Python
The meaning of ".object" in Django
Cython to try in the shortest
GraphQL API with graphene_django in Django
Access the Twitter API in Python
Get the query string (query string) in Django
Play by hitting the Riot Games API in Python First half
Get the client's IP address in Django
Django ~ Let's display it in the browser ~
Try using the HL band in order
Try the Microsoft Cognitive Services Face API
Tweet using the Twitter API in Python
Quickly try Microsoft's Face API in Python
Create an application using the Spotify API
The _authenticate_with_backend function was obsolete in django auth.autenticate
I tried hitting the Qiita API from go
Try to build a pipeline to store the result in Bigquery by hitting the Youtube API regularly using Cloud Composer
Models in Django
[Cloudian # 7] Try deleting the bucket in Python (boto3)
Specify the view URL in your Django template
The story of viewing media files in Django
How to create a Rest Api in Django
[Django] css in the project cannot be read
Try implementing the Monte Carlo method in Python
Hit the Firebase Dynamic Links API in Python
Try accessing the YQL API directly from Python 3
Forms in Django
Try using ChatWork API and Qiita API in Python
Second half of the first day of studying Python Try hitting the Twitter API with Bottle
Learning notes for the migrations feature in the Django framework (2)
Initial settings when using the foursquare API in python
[Django] Perform Truncate Table (delete all data in the table)
Set the form DateField to type = date in Django
Try loading the image in a separate thread (OpenCV-Python)
Try to delete tweets in bulk using Twitter API
Learning notes for the migrations feature in the Django framework (1)
Try to decipher the login data stored in Firefox
Using the National Diet Library Search API in Python
Play music by hitting the unofficial API of Google Play Music
The story around the time acquisition API in programming languages
I tried hitting the API with echonest's python client
Creating an API that returns negative-positive inference results using BERT in the Django REST framework
Try Debian + Python 3.4 + django1.7 ...
Model changes in Django
Try gRPC in Python
Try using Django templates.html
C API in Python 3
Try 9 slices in Python
Try NNabla's C ++ API