Browse Source

Obtain tokens from Spotify

Code now successfully obtains tokens from the Spotify API.
master
Chris 7 years ago
parent
commit
a96f429691
  1. 37
      spotifyvis/views.py

37
spotifyvis/views.py

@ -1,10 +1,11 @@
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import HttpResponse, HttpResponseBadRequest
import math import math
import random import random
import requests import requests
import os import os
import urllib import urllib
import datetime
def generate_random_string(length): def generate_random_string(length):
"""Generates a random string of a certain length """Generates a random string of a certain length
@ -24,6 +25,17 @@ def generate_random_string(length):
return rand_str return rand_str
def token_expired(token_obtained_at, valid_for):
"""Returns True if token expired, False if otherwise
Args:
token_obtained_at: datetime object representing the date and time when the token was obtained
valid_for: the time duration for which the token is valid, in seconds
"""
time_elapsed = (datetime.datetime.today() - token_obtained_at).seconds
return time_elapsed >= valid_for
# Create your views here. # Create your views here.
def index(request): def index(request):
return render(request, 'spotifyvis/index.html') return render(request, 'spotifyvis/index.html')
@ -31,8 +43,8 @@ def index(request):
def login(request): def login(request):
state_str = generate_random_string(16)
# use a randomly generated state string to prevent cross-site request forgery attacks # use a randomly generated state string to prevent cross-site request forgery attacks
state_str = generate_random_string(16)
request.session['state_string'] = state_str request.session['state_string'] = state_str
payload = { payload = {
@ -49,4 +61,25 @@ def login(request):
return redirect(authorize_url) return redirect(authorize_url)
def callback(request): def callback(request):
# Attempt to retrieve the authorization code from the query string
try:
code = request.GET['code']
except KeyError:
return HttpResponseBadRequest("<h1>Problem with login</h1>")
payload = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': 'http://localhost:8000/callback',
'client_id': os.environ['SPOTIFY_CLIENT_ID'],
'client_secret': os.environ['SPOTIFY_CLIENT_SECRET'],
}
response = requests.post('https://accounts.spotify.com/api/token', data = payload).json()
# despite its name, datetime.today() returns a datetime object, not a date object
request.session['token_obtained_at'] = datetime.datetime.today()
request.session['access_token'] = response['access_token']
request.session['refresh_token'] = response['refresh_token']
request.session['valid_for'] = response['expires_in']
print(response)
return HttpResponse("At callback") return HttpResponse("At callback")
Loading…
Cancel
Save