def read_data_from_excel(excel_file): # reads data from an excel_file file_path = str(excel_file) # create a workbook using the excel file received w_book = xlrd.open_workbook(file_path) # open the excel_sheet with the data sheet = w_book.sheet_by_index(0) # import the database model Albums from music.models import Album # instantiate a state state = StateService().get(name='Active') # loop through the data printing all the data for row in range(1, sheet.nrows): # print (str(sheet.cell_value(row, col))), obj = Album(artist=sheet.cell_value(row, 0), album_title=sheet.cell_value(row, 1), genre=sheet.cell_value(row, 2), state=state) print('album added') obj.save() return 'Success'
def add_to_library(request, album_id): profile = get_object_or_404(User, id=request.user.id) album = Album.objects.get(pk=album_id) albumsongs = album.song_set.all() print ('--------',album.artist) album_copy = Album() album_copy = copy.deepcopy(album) album_copy.users.add(profile) # # album_copy.song.add(album_songs) # print ('dddddddd',album_copy.song_set.all()) # album_copy # album_copy.albums.add(album_copy) # profile.album print ('#####',type(album_copy)) # print ("#########",album_copy.users.all()) # album_copy.users = None # print ('@@@@@@@@@@',album_copy.user) album_copy.save() return render(request, 'music/my_library.html', {'profile': profile })
def create_album(sp_album, client): #print(json.dumps(sp_album, sort_keys=True, indent=4, separators=(',', ': '))) client = client sp_unique = sp_album['id'] client_unique = sp_unique sp_uri = sp_album['uri'] uri = sp_uri sp_name = sp_album['name'] name = sp_name sp_href = sp_album['href'] href = sp_href sp_popularity = sp_album['popularity'] popularity = sp_popularity sp_release_date = sp_album['release_date'] sp_release_date_precision = sp_album['release_date_precision'] if sp_release_date_precision == "year": strp_string = "%Y" elif sp_release_date_precision == "month": strp_string = "%Y-%m" elif sp_release_date_precision == "day": strp_string = "%Y-%m-%d" release_date = datetime.datetime.strptime(sp_release_date, strp_string).strftime('%Y-%m-%d') if len(sp_album['images'])==0: image_url=None image_width=None image_height=None else: for image in sp_album['images']: image_width = image['width'] image_height = image['width'] if image_width <= 700 and image_height <= 700: image_url = image['url'] break new_album = Album( client=client, client_unique=client_unique, uri=uri, name=name, href=href, popularity=popularity, release_date=release_date, image_url=image_url, image_width=image_width, image_height=image_height ) new_album.save() return new_album
def CreateAlbum(): a = Album( artist="Taylor swift", album_title="red", genre="Country", album_logo="/Users/fanjialiang2401/Desktop/Imag/1_12.jpg", ) a.save()
def sync_album(self, album_title): album_by_title = Album.objects.filter(title=album_title) if not album_by_title: new_album = Album() new_album.title = album_title new_album.save() return new_album return album_by_title[0]
def make_album(request): error_msg = [] context = { 'title': 'Create Album', 'error_msg': error_msg, } if request.method == 'GET': #print(request.method) return render(request, 'music/album/create_album.html', context) else: is_form_valid = True #print(request.POST) album_title = request.POST['album_title'] artist = request.POST['artist'] img = None file_path = None if request.FILES and (not request.FILES['album_cover'].content_type. __contains__('image/')): #check valid file context['error_msg'].append('Upload an image file') is_form_valid = False elif request.FILES and request.FILES[ 'album_cover'].content_type.__contains__('image/'): img = request.FILES['album_cover'] if not (album_title and artist): #check all fields filled context['error_msg'].append('Fill up all fields') is_form_valid = False if is_form_valid: if img: img_folder = save_file_to_firebase(file=img, type='image', path='album_covers/' + album_title) img = img_folder[0] file_path = img_folder[1] album = Album(album_title=album_title, artist=artist, image=img, file_path=file_path) album.save() return get_album_details(request, album.id) return render(request, 'music/album/create_album.html', context)
def setUp(self): song = Song() song.title = "Basket Case" song.file_path = "burgle/data/pandora/Basket Case.mp3" artist = Artist() artist.name = 'Green Day' artist.save() song.artist = artist album = Album() album.title = 'Dookie' album.save() song.album = album song.station_id = int('21312') song.save() genre = Genre() genre.name = 'Rock' genre.save() song.genres.add(genre)
def set_song(tags, timestamp, user, path, song): # if song == None, returns a new Song object. # song must be explicitly saved after that function # returns changed or new Song object instance # also creates corresponding foreign key dependencies album = None if tags['album']: try: album = Album.objects.get(name=tags['album']) except Album.DoesNotExist: album = Album(name = tags['album']) try: album.save() except: album = None except Exception, e: print("Error checking for existing album:", tags['album'], e)
def setUp(self): album = Album(album_name='Anti', artist='Rihanna') album.save() self.album_id = album.id track1 = Track(title='Desperado', order=1, album=album, duration=4) track1.save() self.track1_id = track1.id track2 = Track(title='Love on the brain', order=2, album=album, duration=3) track2.save() self.track2_id = track2.id
def setUp(self): seed = str(random.randint(1, 100000)) song = Song() song.title = 'Basket Case' pandora_url = 'http://audio-dc6-t1-1.pandora.com/access/6394738923373318898?version=4&lid=55475035&token=ltvKtTCJqaVK0%2FRsqx6FVl92LrWl3riBZtqhXMaoAQGBaZ5CflwAEnJO%2B7CSl%2FFyxIkYLmsL31krBpS3lnPj0PBX0UkSU0BFmh6BBO2wsUwUWvwFu2hyUHpWaJLcL7eJtEl08SKzQswNULEPr3V0R5JD64rB0ANyYc4YeDVSMs9m%2Fo5PITxWQlermntRbN1B2cGg4mi%2BOxQEHWnbwwoRKeQG6c0mv1qHasdMQXJrXc%2FxoUJM7az1yklTPW8LUnmaRho%2BxYBWhmJ5XBjMQtBt89moJVNfi9Cx08fUBf2GU369d63N1HACf86Nt1rcKRgS6NhaBngwjBPeJY0XBR76JesF%2BBQJHUKR' song.audio_url = pandora_url artist = Artist() artist.name = 'Green Day' artist.save() song.artist = artist album = Album() album.title = 'TestAlbum-' + str(seed) album.save() song.album = album song.station_id = int(seed) song.save() genre = Genre() genre.name = 'Rock' genre.save() song.genres.add(genre)
def setUp(self): for i in range(10): seed = str(random.randint(1, 100000)) song = Song() song.title = 'Demo' song.audio_url = 'test/music/demo.mp3' artist = Artist() artist.name = 'TestArtist-' + seed artist.save() song.artist = artist album = Album() album.title = 'TestAlbum-' + seed album.save() song.album = album song.station_id = int(seed) song.save() genre = Genre() genre.name = 'TestGenre-' + seed genre.save() song.genres.add(genre) self.test_songs.append(song)
def create(self, validated_date): tracks_data = validated_date.get("tracks") a = Album() a.title = validated_date.pop("title") a.year = validated_date.pop("year") a.publisher = validated_date.pop("publisher") a.description = validated_date.pop("description") a.save() if tracks_data != None: for track_id in tracks_data: m = Music.objects.get(pk=track_id) m.album = a m.save() return a
COMMIT; #save the changes kendavar@uecb1d74a93b158e48e11:~/kendavar/Django/website$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, music, sessions Running migrations: Rendering model states... DONE Applying music.0001_initial... OK #operation on the python manage.py shell.insert/update db. $python manage.py shell from music.models import Album, Song Album.objects.all() a = Album(artist="Taylor Swift", album_title="Red",genre="country",album_logo="asdfsdsfa") a.save() a.artist a.id a.pk #a.id or a.pk -primary key #second way to input values to db b=Album() b.artist= "Myth" b.album_title="High school" b.album_logo="/home/local/ANT/kendavar/kendavar/" b.save() Album.objects.all() #dunter/string representaion of the object.It gives a name to the object class Album(models.Model): artist = models.CharField(max_length=250)
a = Album(artist="The Nelsonions", album_title="Bluish-blue", genre="Rock", album_logo="http://schmoesknow.com/wonder-woman-movie-review/50254/") ## above code is all on one line a.save() # writes into the database a.id # show the ID (primary key) a = Album( artist="The Bill-Browns", album_title="Ready or not", genre="Rock", album_logo= "http://schmoesknow.com/wp-content/uploads/2017/05/Wonder-Woman-Movie-Artwork.jpg" ) # above code is all on one line ## a.save() # writes into the database ## a.id # show the ID (primary key) a = Album( artist="DJ Cool-cumber", album_title="Ignite the night", genre="Rock", album_logo= "http://schmoesknow.com/wp-content/uploads/2017/05/Wonder-Woman-Movie-Artwork.jpg" ) # above code is all on one line ## a.save() # writes into the database
#different ways of adding rows in the table from music.models import Album ,Song Album.objects.all() a = Album(artist = "Taylor Swift", album_title = "Red",genre = "Country" ,album_logo = "https://upload.wikimedia.org/wikipedia a.save() b=Album() b.artist = "One direction" b.album_title = "once a day" b.genre = "punk" b.album_logo = "http://cdn01.cdn.justjared.com/wp-content/uploads/2014/02/stewart-whoa/kristen-stewart-if-i-do-a-good-scene-i-say-whoa-thats-dope-01.jpg" b.save() Album.objects.all() Album.objects.filter(id =1) #prints the first one Album.objects.filter(artist__startswith='Taylor') #adding songs to database In [1]: from music.models import Album,Song In [2]: album1 = Album.objects.get(pk = 1) In [3]: album1.artist Out[3]: 'Taylor Swift' In [4]: song = Song()
from music.models import Ablum, Song from music.models import Album, Song Album.objects.all() a = Album(artist='Taylor Swift',album_title='Red',genre='Country',album_logo="https://imgchr.com/i/Kb9vFO") a.save() a.artist a.album_title a.id a.pk b = Album() b.artist = "Myth" b.album_title = "High School" b.genre = "Punk" b.album_logo = "" b.album_logo = "" b.album_logo = "https://imgchr.com/i/KbC100" b.saz b.save() a.artist b.artist b.album_title = "Middle School" b.album_title Album.objects.all() %hist -f Create_Albums.py
# Lookup if the artist exists artist_match = Artist.objects.filter(stage_name=artist) artist_obj = "" if artist_match: artist_obj = Artist.objects.get(stage_name=artist) else: artist_obj = Artist(stage_name=artist) artist_obj.save() # Lookup if the album exists album_match = Album.objects.filter(album_name=album, artist=artist_obj) album_obj = "" if album_match: album_obj = Album.objects.get(album_name=album, artist=artist_obj) else: album_obj = Album(album_name=album, artist=artist_obj, uploader_id=1) album_obj.save() # Lookup if the song exists song_match = Song.objects.filter(song_name=title, artist=artist_obj) song_obj = "" if song_match: song_obj = Song.objects.get(song_name=title, artist=artist_obj) song_obj.save() else: # save the peaks file song_obj = Song(peaks_file="../media/peaks/" + genId + ".json", song_duration_seconds=file.info.length,song_file=song_file, track_art=art_file,track_art_dominant_color=dominant_color_hex, uploader_id=1, song_name=title, artist=artist_obj, album=album_obj) song_obj.save() index = index + 1
def upload_handler(request): if request.method == "POST": f = request.FILES["upload"] filename = str(f) f_ext = os.path.splitext(str(f))[1] # If file is a compatible music file, build a filesystem structure for # it (media/artist-name/album-name), then write it to that location and # add details of the file to the database. if f_ext in [".mp3", ".MP3"]: with open(MEDIA_ROOT + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) filename = eyed3.load(MEDIA_ROOT + filename) dir_struct = MEDIA_ROOT + "music" + "/" + filename.tag.artist + "/" + filename.tag.album + "/" try: if not os.path.isdir(dir_struct): os.makedirs(dir_struct) shutil.move(MEDIA_ROOT + str(f), dir_struct) except OSError as ose: if ose.errno != 17: raise # Need to pass on Errno 17, due to race conditions caused # by making directories that already exist. pass except Exception as e: # File already exists. Remove the duplicate copy. os.remove(MEDIA_ROOT + str(f)) return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the artist or album doesn't exist in the database, create # table(s) for them. If they already exists, perform a query to # obtain an Artist or Album object for use as a foreign key. if not Artist.objects.filter(name=filename.tag.artist).exists(): artist = Artist(name=filename.tag.artist) artist.save() else: artist_set = Artist.objects.filter(name=filename.tag.artist) artist = [a for a in artist_set][0] if not Album.objects.filter(title=filename.tag.album).exists(): album = Album(title=filename.tag.album, artist=artist) album.save() else: album_set = Album.objects.filter(title=filename.tag.album) album = [a for a in album_set][0] if not Track.objects.filter(title=filename.tag.title).exists(): track = Track( title=filename.tag.title, album=album, artist=artist, fspath=dir_struct + str(f), media_url=MEDIA_URL + (dir_struct + str(f)).split(MEDIA_ROOT)[1], ) track.save() print "Added to DB: " + filename.tag.title return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) elif f_ext in [".jpg", ".JPG"]: if not os.path.exists(MEDIA_ROOT + "pictures/" + str(f)): with open(MEDIA_ROOT + "pictures/" + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) else: # File already exists. Remove the duplicate copy. return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the picture doesn't exist in the database, add it. if not Picture.objects.filter(name=str(f)).exists(): picture = Picture( name=os.path.splitext(str(f))[0], filename=str(f), fspath=MEDIA_ROOT + "pictures/" + str(f), media_url=MEDIA_URL + (MEDIA_ROOT + "pictures/" + str(f)).split(MEDIA_ROOT)[1], ) picture.save() print "Added to DB: " + str(f) return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) elif f_ext in [".mp4", ".MP4", ".m4v", ".M4V"]: if not os.path.exists(MEDIA_ROOT + "videos/" + str(f)): with open(MEDIA_ROOT + "videos/" + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) else: # File already exists. Remove the duplicate copy. return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the video doesn't exist in the database, add it. if not Video.objects.filter(title=str(f)).exists(): video = Video( title=os.path.splitext(str(f))[0], filename=str(f), fspath=MEDIA_ROOT + "videos/" + str(f), media_url=MEDIA_URL + (MEDIA_ROOT + "videos/" + str(f)).split(MEDIA_ROOT)[1], ) video.save() print "Added to DB: " + str(f) return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) return render_to_response("errors/upload_failure.html", locals(), context_instance=RequestContext(request))
import os import django sys.path.append(".") # here store is root folder(means parent). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mosaic_api.settings") django.setup() import spotipy import spotipy.util as util from music.models import Album if len(sys.argv) > 1: username = sys.argv[1] else: print("Usage: %s username" % (sys.argv[0],)) sys.exit() scope = 'user-library-read' token = util.prompt_for_user_token(username, scope) if token: sp = spotipy.Spotify(auth=token) results = sp.current_user_saved_albums(limit=50) for item in results['items']: album_record = item['album'] album = Album(released=2017, title=album_record['name'], artist=album_record['artists'][0] ['name'], spotify_URL=album_record['id'], cover_art=album_record['images'][0]['url']) print(album) album.save() else: print("Can't get token for", username)