# imports {{{ # import math import os import urllib import pprint from datetime import datetime from django.shortcuts import render, redirect from django.http import HttpResponseBadRequest from .models import * from .utils import * # }}} imports # TIME_FORMAT = '%Y-%m-%d-%H-%M-%S' TRACKS_TO_QUERY = 200 AUTH_SCOPE = ['user-library-read', 'user-read-recently-played', ] # ROOT_URL = 'http://localhost:8000' ROOT_URL = 'http://spotify-lib-vis.ml' # index {{{ # def index(request): return render(request, 'login/index.html') # }}} index # # spotify_login {{{ # def spotify_login(request): """ Step 1 in authorization flow: Have your application request authorization; the user logs in and authorizes access. """ # 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 payload = { 'client_id': os.environ['SPOTIFY_CLIENT_ID'], 'response_type': 'code', 'redirect_uri': ROOT_URL + '/login/callback', 'state': state_str, 'scope': " ".join(AUTH_SCOPE), 'show_dialog': False } params = urllib.parse.urlencode(payload) # turn the payload dict into a query string authorize_url = "https://accounts.spotify.com/authorize/?{}".format(params) return redirect(authorize_url) # }}} spotify_login # # callback {{{ # def callback(request): """ Step 2 in authorization flow: Have your application request refresh and access tokens; Spotify returns access and refresh tokens. """ # Attempt to retrieve the authorization code from the query string try: code = request.GET['code'] except KeyError: return HttpResponseBadRequest("