def clean_tracks(self): if not self.cleaned_data.get('tracks'): return [] try: lines = json.loads(self.cleaned_data.get('tracks')) tracks = [] for line in lines: _id = line.get('properties').get('id') if _id: track = models.Track.objects.get(id=_id) else: track = models.Track() track.track = LineString([c for c in line.get('coordinates')]) track.start = line.get('properties').get('start') track.end = line.get('properties').get('end') tracks.append(track) return tracks except ValueError, e: raise forms.ValidationError(e.message)
def download_user_library(user): """ Saves a user's spotify library to the track table in our DB """ client = get_api_client(user) # Each item is a Saved Track item from Spotify's api resp_items = [] response = client.current_user_saved_tracks(limit=50) resp_items += response['items'] # Number of tracks in the user's library not returned yet # If the number is 0 or less we've already retrieved all the user's songs tracks_remaining = response['total'] - 50 offset = 50 while(tracks_remaining > 0): print("Finished another batch of requests", tracks_remaining, "tracks remaining") response = client.current_user_saved_tracks(limit=50, offset=offset) resp_items += response['items'] offset += 50 tracks_remaining -= 50 # Turning response items into entries in the track table in our database user.tracks = [] library = [] for item in resp_items: t = item['track'] # Checking if there's an existing track in our Tracks table whose id matches our response items existing_track = models.Track.query.filter_by(track_id=t['id']).first() if existing_track: user.tracks.append(existing_track) else: new_track = models.Track(track_id=t['id'], title=t['name'], artist=t['artists'][0]['name'], preview_url=t['preview_url']) user.tracks.append(new_track) db.session.commit()
def get_track_from_dict(track_dict): title = track_dict.get('title') url = track_dict.get('url') body = track_dict.get('body') discogs_url = track_dict.get('discogsUrl') media_not_available = track_dict.get('mediaNotAvailable', False) return models.Track(title=title, url=url, discogs_url=discogs_url, media_not_available=media_not_available)
def write_track_to_datastore(track, user, location): """ Get a list of tracks and save them to the database Return the number of track saved """ logging.info("Saving track \"%s\" by \"%s\" (id: %s, created at: %s) to datastore ..." % \ (track['title'], user.username, track['id'], track['created_at'])) created_at = datetime.datetime.strptime(track['created_at'], "%Y/%m/%d %H:%M:%S +0000") try: release_date = datetime.date(year=int(track['release_year'] or 1900), month=int(track['release_month'] or 1), day=int(track['release_day'] or 1)) except ValueError: release_date = datetime.date(year=1900, month=1, day=1) if track['genre']: genre = track['genre'].strip().lower() else: genre = '' new_track = models.Track( \ track_id = int(track['id']), permalink = track['permalink'], permalink_url = track['permalink_url'], title = track['title'], \ stream_url = track['stream_url'], waveform_url = track['waveform_url'], artwork_url = track['artwork_url'], purchase_url = track['purchase_url'], \ created_at = created_at, downloadable = track['downloadable'], original_format = track['original_format'], release_date = release_date, release = track['release'], isrc = track['isrc'], label_name = track['label_name'], label_id = track['label_id'], license = track['license'], genre = genre, bpm = track['bpm'], key_signature = track['key_signature'], duration = track['duration'], description = track['description'], \ user = user.key(), location = location.key()) new_track.put() logging.info("Track saved to datastore.")
def save_track(self): geo_json = self.cleaned_data.get('geo_json') line = geo_json.get('track') if not line: return track = models.Track() track.user = self.instance.requester track.track = LineString([c for c in line.get('coordinates')]) track.start = line.get('properties').get('start') track.end = line.get('properties').get('end') track.save() return track
import os import pprint from google.appengine.api import users from google.appengine.api import memcache from google.appengine.api import mail from google.appengine.api import urlfetch from google.appengine.ext import db pprint.pprint(os.environ.copy()) import models s = models.Sponsor(name='Burger King').put() t = models.Track(name='Watkins Glen', lap_distance=1.0).put() c = models.Car(make='Volkswagen', model='Rabbit', year='1981', color='red', number='24').put() c = models.Car(make='Audi', model='S4', year='2005', color='silver', number='69').put() cl = models.RaceClass(name='American Iron').put() r = models.Racer(driver=users.User('*****@*****.**'), points=0, car=c, sponsor=s, raceclass=cl).put() best = models.BestLap(driver=r, track=t, time=59.062).put()
def export_account(): auth_manager = spotipy.oauth2.SpotifyOAuth(cache_path=session_cache_path()) if not auth_manager.get_cached_token(): return redirect('/') sp = spotipy.Spotify(auth_manager=auth_manager) user_id = sp.me()['id'] ret = { 'playlists': [], 'tracks': [], 'artists': [], 'user_id': user_id } # enumerate folled artists spotify_artists = sp.current_user_followed_artists() for spotify_artist in spotify_artists['artists']['items']: ret['artists'].append(models.Artist(spotify_artist).to_map()) while spotify_artists['artists']['next'] is not None: spotify_artists = sp.next(spotify_artists['artists']) for spotify_artist in spotify_artists['artists']['items']: ret['artists'].append(models.Artist(spotify_artist).to_map()) # enumerate tracks spotify_tracks = sp.current_user_saved_tracks() for spotify_track in spotify_tracks['items']: ret['tracks'].append(models.Track(spotify_track['track']).to_map()) while spotify_tracks['next']: spotify_tracks = sp.next(spotify_tracks) for spotify_track in spotify_tracks['items']: ret['tracks'].append(models.Track(spotify_track['track']).to_map()) # enumerate playlists spotify_playlists = sp.current_user_playlists() while spotify_playlists is not None: for spotify_playlist in spotify_playlists['items']: # create the playlist model playlist = models.Playlist(user_id, spotify_playlist) # we'll just re-follow when it's public and not owned if not playlist.owned and playlist.public: ret['playlists'].append(playlist.to_map()) continue r = sp.playlist(spotify_playlist['id'], fields="tracks,next") spotify_tracks = r['tracks'] for spotify_track in spotify_tracks['items']: playlist.add_track(spotify_track['track']) while spotify_tracks['next']: spotify_tracks = sp.next(spotify_tracks) for spotify_track in spotify_tracks['items']: playlist.add_track(spotify_track['track']) ret['playlists'].append(playlist.to_map()) if spotify_playlists['next']: spotify_playlists = sp.next(spotify_playlists) else: spotify_playlists = None return Response( json.dumps(ret), mimetype="application/json", headers={"Content-Disposition": "attachment;filename=account_export.json"} )