def add_to_db(audio_files): for audio_file in audio_files: audio_file_id3 = eyed3.load(audio_file) # If the artist, album or track doesn't exist in the database, create # table(s) for them. try: if not Artist.objects.filter(name=audio_file_id3.tag.artist).exists(): artist = Artist(name=audio_file_id3.tag.artist) artist.save() if not Album.objects.filter(title=audio_file_id3.tag.album).exists(): album = Album(title=audio_file_id3.tag.album, \ artist=artist) album.save() if not Track.objects.filter(title=audio_file_id3.tag.title).exists(): track = Track(title=audio_file_id3.tag.title, \ album=album, \ artist=artist, \ fspath=audio_file, \ media_url=MEDIA_URL + audio_file.split(MEDIA_ROOT)[1]) track.save() print 'Added to DB: ' + audio_file_id3.tag.title except Exception as e: print 'Error: ' + e
def add_movie_tastes(user_id, movie_id, taste): taste = float(taste) user = User.get_by_id(user_id) movie = Movie.get_by_id(movie_id) for actor in movie.actors: artist = Artist.get_by_id(actor.id()) user.add_taste_artist(artist, ACTOR_WEIGHT * taste) for director in movie.directors: artist = Artist.get_by_id(director.id()) user.add_taste_artist(artist, DIRECTOR_WEIGHT * taste) for writer in movie.writers: artist = Artist.get_by_id(writer.id()) user.add_taste_artist(artist, WRITER_WEIGHT * taste) for genre in movie.genres: user.add_taste_genre(genre, GENRE_WEIGHT * taste) user.remove_proposal() user.put() taskqueue.add(url='/api/proposal/' + user.key.id(), method='GET') return 'OK'
def search_artist_from_name(artist_name, movie=None, director_name=None): """ Retrieve artist info from IMDB by name of artist. :param artist_name: name of the actor to retrieve info :type artist_name: string :return: Actor's key :rtype: ndb.Key :raise RetrieverError: if there is an error from MYAPIFILMS """ url = BASE_URL_MYAPIFILMS + 'imdb?name=' + artist_name + '&format=JSON&filmography=0&limit=1&lang=en-us&exactFilter=0&bornDied=0&starSign=0&uniqueName=0&actorActress=0&actorTrivia=0&token=307cccfe-d20b-4b69-b976-d6a024538864' json_page = get(url).encode('utf-8') json_data = json.loads(json_page) if type(json_data) is not list: # If it is not a list there is a problem raise RetrieverError(json_data['code'], json_data['message']) try: photo = clear_url(json_data[0]['urlPhoto']) except Exception: logging.info("Photo not found") photo = "None" artist = Artist(id=json_data[0]['idIMDB'], name=json_data[0]['name'], photo=photo) if movie is not None: if director_name is not None: movie.add_director(artist) else: movie.add_actor(artist) return artist.put()
def fetch(service, artist): if service not in services: return False try: metadata = utils.fetch(service, artist) db.connect('testing') artist_count = Artist.objects(name=artist, service=service).count() if not artist_count: mongo_artist = Artist(name=artist, service=service).save() else: mongo_artist = Artist.objects(name=artist, service=service).first() for track in metadata[artist]['tracks']: track_title = track track_album = metadata[artist]['tracks'][track_title]['album'] track_encoding = metadata[artist]['tracks'][track_title]['encoding'] track_url = metadata[artist]['tracks'][track_title]['url'] track_folder = metadata[artist]['tracks'][track_title]['track_folder'] track_filename = metadata[artist]['tracks'][track_title]['track_filename'] media_count = Media.objects(artist=mongo_artist, title=track_title).count() if not media_count: data = open(track_folder + '/' + track_filename, 'rb') f = File(name=track_filename, data=data).save() media = Media(artist=mongo_artist, title=track_title, data=f).save() return True except: err = sys.exc_info()[0] return False
def upload(request): context = {"status": "norm"} if request.method == "POST": rb = xlrd.open_workbook(settings.BASE_DIR + '/Orders/cat.xls', formatting_info=True) sheet = rb.sheet_by_index(0) base = {} for rownum in range(sheet.nrows): row = sheet.row_values(rownum) row[0] = int(row[0]) if sheet.cell(rownum, 1).ctype == 3: row[1] = xlrd.xldate_as_tuple(row[1], 0) tmp = str(row[1][4]) if tmp == "0": tmp = "00" row[1] = str(row[1][3]) + ":" + tmp if sheet.cell(rownum, 1).ctype == 2: row[1] = int(row[1]) b1 = Artist(name=row[2]) try: b1.save() except: b1 = Artist.objects.filter(name=row[2])[0] s = Song(number=row[0], tittle=row[1], minus_quality=row[4], back_vocal=row[3], karaoke_system="test", artist=b1) s.save() return render(request, 'Orders/upload.html', context) return render(request, 'Orders/upload.html', context)
def add_record(release): from models import Record, Artist, Track release_discogs_id = release.id try: # Check if we already have this album existing = Record.objects.get(discogs_id=release_discogs_id) return existing except Record.DoesNotExist: # Process record record_title = release.title if (len(record_title.split('- '))>1): record_title = record_title.split('- ')[1] record = Record(discogs_id = release_discogs_id, title = record_title, year = release.year, thumb = release.thumb, notes = release.notes) record.save() # Process artists for release_artist in release.artists: artist = Artist(discogs_id=release_artist.id, name=release_artist.name) artist.save() record.artists.add(artist) # Process tracklist for release_track in release.tracklist: track = Track() track.position = release_track.position track.title = release_track.title track.duration = release_track.duration track.save() record.tracklist.add(track) record.save() return record
def artist_insert(self, request): if request.from_datastore: my_quote = request else: my_quote = Artist(fname=request.fname, lname=request.lname, website_url=request.website_url, description=request.description, image=request.image) my_quote.put() return my_quote
def untaste_movie(user_id, movie_id): movie = Movie.get_by_id(movie_id) user = User.get_by_id(user_id) for actor in movie.actors: artist = Artist.get_by_id(actor.id()) taste_artist = TasteArtist.get_by_id(actor.id() + user.key.id()) if taste_artist is not None: taste_artist.update_taste(-ACTOR_WEIGHT) else: user.add_taste_artist(artist, -ACTOR_WEIGHT) if taste_artist.taste == 0: user.remove_taste_artist(artist) for director in movie.directors: artist = Artist.get_by_id(director.id()) taste_artist = TasteArtist.get_by_id(director.id() + user.key.id()) if taste_artist is not None: taste_artist.update_taste(-DIRECTOR_WEIGHT) else: user.add_taste_artist(artist, -DIRECTOR_WEIGHT) if taste_artist.taste == 0: user.remove_taste_artist(artist) for writer in movie.writers: artist = Artist.get_by_id(writer.id()) taste_artist = TasteArtist.get_by_id(writer.id() + user.key.id()) if taste_artist is not None: taste_artist.update_taste(-WRITER_WEIGHT) else: user.add_taste_artist(artist, -WRITER_WEIGHT) if taste_artist.taste == 0: user.remove_taste_artist(artist) for genre in movie.genres: taste_genre = TasteGenre.get_by_id(genre + user.key.id()) if taste_genre is not None: taste_genre.update_taste(-GENRE_WEIGHT) else: user.add_taste_genre(genre, -GENRE_WEIGHT) if taste_genre.taste == 0: user.remove_taste_genre(genre) user.remove_proposal() user.put() taskqueue.add(url='/api/proposal/' + user.key.id(), method='GET') return 'OK'
def retrieve_artists(movie, actors_list, directors_list, writers_list): """ Retrieve all artist in a movie from actors, directors and writers lists. :param movie: Movie object in order to add actors, directors and writers :type movie: Movie :param actors_list: list of actors :type actors_list: list of dict :param directors_list: list of directors :type directors_list: list of dict :param writers_list: list of writers :type writers_list: list of dict """ for json_data in actors_list: actor = Artist(id=json_data['actorId'], name=json_data['actorName'], photo=clear_url(json_data['urlPhoto'])) actor.put() movie.add_actor(actor) for json_data in directors_list: director = Artist(id=json_data['nameId'], name=json_data['name']) director.put() movie.add_director(director) for json_data in writers_list: writer = Artist(id=json_data['nameId'], name=json_data['name']) writer.put() movie.add_writer(writer)
def add_artists(request, data): dajax = Dajax() data = simplejson.loads(data) count = int(data['count']) for i in range(count): artistName = ("test_artist_%d") % (uuid.uuid4()) artist = Artist(name=artistName) artist.save() successMessage = "Successfully added [%d] artists!" % count dajax.assign('#message', 'innerHTML', successMessage) return dajax.json()
def test(request): access_token = "" # token_info = sp_oauth.get_cached_token() # if token_info: # print "Found cached token!" # access_token = token_info['access_token'] # else: code = request.GET.get('code') if code: print "Found Spotify auth code in Request URL! Trying to get valid access token..." token_info = sp_oauth.get_access_token(code) access_token = token_info['access_token'] if access_token: print "Access token available! Trying to get user information..." sp = spotipy.Spotify(access_token) current_user = sp.current_user() artists = sp.current_user_top_artists(limit=50) username = current_user['id'] current_users = SpotifyUser.objects.filter(username=username) if current_users: print current_users else: new_user = SpotifyUser(username=username) new_user.save() i = 1 for item in artists['items']: artist_id = item['id'] print item['name'] + ": " + artist_id matching_artists = Artist.objects.filter(spotify_id=artist_id) if matching_artists: the_artist = matching_artists[0] else: the_artist = Artist(spotify_id=artist_id, name=item['name']) the_artist.save() user_artist = UserArtist(artist=the_artist, user=new_user, rank=i) user_artist.save() i = i + 1 results_string = "<ol>" for item in artists['items']: results_string += "<li><img src='" + item['images'][1]['url'] + "'/>" + item['name'] + "</li>" results_string += "</ol>" return HttpResponse(results_string) else: return HttpResponse(htmlForLoginButton())
def fetch_artist(): '''Fetches live music archive page, scrapes artist info, and saves to db''' result = urlfetch.fetch(ARTISTS_URL) if result.status_code != 200: return soup = BeautifulSoup(result.content.decode('utf-8')) artists_table = soup.find(id='browse') items = artists_table.findAll('a') for i in range(len(items)-1)[::2]: name = items[i].contents[0] identifier = items[i].get('href').split('/')[-1] shows = int(items[i+1].string.split(' ')[0].replace(',','').encode('utf-8')) artist = Artist(name=name, show_count=shows, identifier=identifier) artist.put_async()
def update_artists(artist_ids): for artist in artist_ids: payload = {'api_key': ECHONEST, 'id': 'songkick:artist:'+str(artist)+'', 'format': 'json', 'bucket': ['genre', 'id:spotify-WW', 'familiarity', 'discovery', 'hotttnesss', 'artist_location', 'years_active']} url = 'http://developer.echonest.com/api/v4/artist/profile?' r = requests.get(url, params=payload) data = r.json() # retrieve the artist record from the db artist = Artist.get(artist_id=artist) try: results = data['response']['artist'] except KeyError, error: print '%s: No data for artist %s %s' % (error, artist.name, artist.artist_id) continue try: echonest_response = results genres = results['genres'] spotify_id = results['foreign_ids'][0]['foreign_id'] familiarity = results['familiarity'] hotttnesss = results['hotttnesss'] years_active = results['years_active'] location = results['artist_location'] discovery = results['discovery'] except KeyError, error: print 'An error has occured %s' % error pass
def get_tastes_artists_list(user, page=0): """ Get a readable taste artists list. :param user: user :type user: Models.User :return: list of tastes {"code": 0, "data": {"tastes": [{"idIMDB": id,"name": name, "photo": photo_url}], "type": type, "userId": user_id} :rtype: JSON """ tastes_artists_id = user.tastes_artists # Get all taste_artists' keys artists = [] for taste_artist_id in tastes_artists_id: taste_artist = TasteArtist.get_by_id(taste_artist_id.id()) # Get taste if taste_artist.taste >= 1 and taste_artist.added: artist_id = taste_artist.artist.id() # Get artist id from taste artist = Artist.get_by_id(artist_id) # Get artist by id artists.append({"idIMDB": artist_id, "name": artist.name.encode('utf-8') if artist.name is not None else None, "tasted": 1, "photo": artist.photo}) return jsonify(code=0, data={"userId": user.key.id(), "type": "artist", "tastes": artists})
def rawGet(self, ballotID, voteID): vote = self.getVote(ballotID, voteID) if not vote: self.response.out.write('No such vote: ' + ballotID + '/' + voteID) return render = dict(v=vote) title = self.request.get('title', default_value=vote.title) render['title'] = title mbArtistid = self.request.get('artist.mbid', default_value=None) artistid = self.request.get('artist.id', default_value=None) name = self.request.get('name', default_value=vote.artist) artist = None if artistid: artist = Artist.get_by_id(int(artistid)) elif mbArtistid: artist = Artist.gql('WHERE mbid = :1', mbArtistid).get() if artist: if artist.mbid: mbArtistid = artist.mbid name = artist.name render['artist'] = artist render['releases'] = [r for r in artist.release_set if not vote.release or r.key() != vote.release.key()] else: if mbArtistid: artist = mb.Artist(mbArtistid) render['mbArtist'] = artist render['artists'] = [a for a in Artist.gql('WHERE name = :1', name)] render['releases'] = [r for r in Release.gql('WHERE title = :1', title) if not vote.release or r.key() != vote.release.key()] render['name'] = name search = dict(title=title) if mbArtistid: search['artistid'] = mbArtistid else: search['artist'] = name rgs = mb.ReleaseGroup.search(**search) if rgs: render['rgs'] = rgs elif mbArtistid: render['rgs'] = mb.ReleaseGroup.search(artistid=mbArtistid) else: render['mbArtists'] = mb.Artist.search(name=name) self.render('canon.html', **render)
def new_song(request): if request.method == "POST": form = SongForm(request.POST) if form.is_valid(): data = analyze(form.cleaned_data['lyrics']) try : artist = Artist.objects.all().filter(name=form.cleaned_data['artist-name']) except: artist = Artist(name=form.cleaned_data['artist_name']) artist.save() song = Song(name=form.cleaned_data['song_name'], lyrics = form.cleaned_data['lyrics'], artist=artist, number_of_words= data['total_words'], number_unique_words=data['unique_words'], unique_word_percent=data['percentage'], repeated_rhymes=data['repeated_rhymes'], bad_words=data['bad_words'], thug_rating=data['thug_rating'], avg_syllables=data['thug_rating']) song.save() return redirect("/") form = SongForm() return render(request, 'lyrics/new_song.html', { 'form': form })
def post(self): if self.request.get("entityKey"): artist_key = ndb.Key(urlsafe=self.request.get("entityKey")) artist = artist_key.get() artist.fname = self.request.get("fname") artist.lname = self.request.get("lname") artist.image = self.request.get("image") artist.website_url = self.request.get("website_url") artist.description = self.request.get("description") artist.put() else: new_artist = Artist(fname = self.request.get("fname"), lname = self.request.get("lname"), image = self.request.get("image"), website_url = self.request.get("website_url"), description = self.request.get("description")) new_artist.put() self.redirect(self.request.referer)
def update_events(venue_ids): for identifier in venue_ids: payload = {'apikey': SONGKICK, 'per_page': 50, 'page': 1} url = 'http://api.songkick.com/api/3.0/venues/'+str(identifier)+'/calendar.json?' r = requests.get(url, params=payload) r.raise_for_status() data = r.json() venue = Venue.get(venue_id=identifier) #venue.save() try: results = data['resultsPage']['results']['event'] except KeyError, error: print 'An error occured: %s: There are no upcoming events for this venue: %s' % (error, venue.name) continue for item in results: try: event_id = item['id'] name = item['displayName'] type = item['type'] status = item['status'] datetime = item['start']['datetime'] url = item['uri'] popularity = item['popularity'] except KeyError, error: print 'An error occured: %s: There is limited data for event: %s' % (error, event_id) pass event, _created = Event.get_or_create(event_id=event_id, venue=venue) event.name = name event.type = type event.status = status event.datetime = datetime event.url = url event.popularity = popularity print event.name event.save() for artist in item['performance']: try: artist_id = artist['artist']['id'] name = artist['artist']['displayName'] performer, _created = Artist.get_or_create(artist_id=artist_id, name=name) billing = artist['billing'] billing_index = artist['billingIndex'] p, _created = Performance.get_or_create(artist=performer, event=event) p.billing = billing p.billing_index = billing_index p.save() except KeyError, error: print 'An error occured %s' % error pass
def get_terms(): genres = [] artist = Artist.select() genre_list = [a.genres for a in artist if a.genres] for l in genre_list: for i in l: genres.append(i['name']) term_count = Counter(genres) return term_count
def videos_by_genre(request, genre): videos = None artists = list(Artist.by_genre(genre)) random.shuffle(artists) for artist in artists: videos = artist.youtube_videos() if len(videos['results']) > 0: videos['country'] = artist.country.name break return HttpResponse(simplejson.dumps(videos), mimetype='application/json')
def get_or_retrieve_by_id(id_imdb): """ This function check if the id is a valid IMDb id and in this case get or retrieve the correct entity. :param id_imdb: a valid IMDb id :type id_imdb: string :return: A model instance :rtype Artist or Movie model """ artist = re.compile('nm\d{7}$') movie = re.compile('tt\d{7}$') if artist.match(id_imdb): # It is an artist's id artist = Artist.get_by_id(id_imdb) # Find artist by id if artist is None: try: artist_key = retrieve_artist_from_id(id_imdb) # Retrieve if is not in the datastore except RetrieverError as retriever_error: raise InternalServerError(retriever_error) artist = Artist.get_by_id(artist_key.id()) # Get artist by id return artist elif movie.match(id_imdb): # It is a movie's id movie = Movie.get_by_id(id_imdb) # Find movie by id if movie is None: try: movie_key = retrieve_movie_from_id(id_imdb) # Retrieve if is not in the datastore except RetrieverError as retriever_error: raise InternalServerError(retriever_error) movie = Movie.get_by_id(movie_key.id()) # Get movie by id return movie else: new_movie = Movie().get_by_id(id_imdb) if new_movie != None: return new_movie else: raise InternalServerError(id_imdb + " is not a valid IMDb id or film.TV id")
def retrieve_artist_from_id(artist_id): """ Retrieve artist info from IMDB by id of artist. :param artist_id: id of the artist to retrieve info :type artist_id: string :return: Artist's key :rtype: ndb.Key :raise RetrieverError: if there is an error from MYAPIFILMS """ logging.info('Retrieving %s', artist_id) url = BASE_URL_MYAPIFILMS + 'imdb?idName=' + artist_id + '&format=JSON&filmography=0&lang=en-us&bornDied=0&starSign=0&uniqueName=0&actorActress=0&actorTrivia=0&actorPhotos=N&actorVideos=N&salary=0&spouses=0&tradeMark=0&personalQuotes=0&token=307cccfe-d20b-4b69-b976-d6a024538864' json_page = get(url).encode('utf-8') json_data = json.loads(json_page) artist = Artist(id=json_data["idIMDB"], name=json_data["name"], photo=clear_url(json_data["urlPhoto"]) if ('urlPhoto' in json_data and json_data['urlPhoto'] != "") else None) return artist.put()
def fetch(service, artist): if service in services: artist_count = Artist.objects(name=artist).count() if not artist_count: a = Artist(name=artist, service=service).save() q = Queue(connection=Redis()) fetch_job = q.enqueue(tap.fetch, service, artist) return render_template('fetch.html', user=login.current_user) else: return "<p>No support for the '{0}' service, or service is not discoverable.</p>".format(service)
def addArtist(id3_artist_name, path): musicbrainz_artist = musicbrainz.getBestArtistMatch(id3_artist_name) if musicbrainz_artist is None: unique_name = id3_artist_name artist_mb_id = None else: unique_name = musicbrainz_artist.getUniqueName() artist_mb_id = utils.extractUuid(musicbrainz_artist.id) try: artist = Artist.get(peewee.Q(musicbrainz_id=artist_mb_id) | peewee.Q(unique_name=unique_name)) except peewee.DoesNotExist: artist = Artist.create( name = id3_artist_name, unique_name = unique_name, location = path, state = 'wanted', musicbrainz_id = artist_mb_id) return artist
def rawPost(self, ballotID, voteID): vote = self.getVote(ballotID, voteID) id = self.request.get('release.id', default_value=None) mbid = self.request.get('release.mbid', default_value=None) if id: vote.release = db.Key.from_path(Release.kind(), int(id)) elif mbid: vote.release = Release.get(mbid) else: id = self.request.get('artist.id', default_value=None) mbid = self.request.get('artist.mbid', default_value=None) if id: artist = db.Key.from_path(Artist.kind(), int(id)) elif mbid: artist = Artist.get(mbid) else: artist = Artist(name=self.request.get('artist'), sortname=self.request.get('sortname')) artisturl = self.request.get('artisturl', default_value=None) if artisturl: artist.url = artisturl artist.put() release = Release(artist=artist, title=self.request.get('title')) releaseurl = self.request.get('releaseurl', default_value=None) if releaseurl: release.url = releaseurl release.put() vote.release = release vote.put() next = Vote.gql('WHERE release = :1 ORDER BY artist', None).get() if next: key = next.key() self.redirect('../%d/%d' % (key.parent().id(), key.id())) else: self.redirect('../..')
def parser_artist(artist_id): create_app() process = Process.get_or_create(id=artist_id) if process.is_success: return print 'Starting fetch artist: {}'.format(artist_id) start = time.time() process = Process.get_or_create(id=artist_id) tree = get_tree(ARTIST_URL.format(artist_id)) artist = Artist.objects.filter(id=artist_id) if not artist: artist_name = tree.xpath('//h2[@id="artist-name"]/text()')[0] picture = tree.xpath( '//div[contains(@class, "n-artist")]//img/@src')[0] artist = Artist(id=artist_id, name=artist_name, picture=picture) artist.save() else: artist = artist[0] song_items = tree.xpath('//div[@id="artist-top50"]//ul/li/a/@href') songs = [] for item in song_items: song_id = item.split('=')[1] song = parser_song(song_id, artist) if song is not None: songs.append(song) artist.songs = songs artist.save() process.make_succeed() print 'Finished fetch artist: {} Cost: {}'.format( artist_id, time.time() - start)
def index(request): #""" print "purging" for e in Event.objects.all(): e.delete() for v in Venue.objects.all(): v.delete() for a in Artist.objects.all(): a.delete() print "purged" artists_names = ['Usher', 'Cage the Elephant', 'Knife Party', 'Steve Aoki', 'The Weeknd', 'Rihanna'] # artists_names = ['Rihanna'] for name in artists_names: Artist.find(name) #""" start = timezone.now() - timedelta(days=7) end = timezone.now() + timedelta(days=0) for artist in Artist.objects.all(): events = artist.get_events_by_dates_range(start.date(), end.date()) for event in events: lat = event.venue.latitude lng = event.venue.longitude recommended_events = artist.get_recommended_events_by_location_and_radius(str(lat) + "," + str(lng), 100) if recommended_events: print "Recommended event for ", event for e in recommended_events: print e # TODO: save recommended events in a proper way return HttpResponse("Hi, you are in BITdataCollector.")
def update_term(): term_counts = get_terms() artist = Artist.select() for a in artist: temp_terms = {} if a.genres: for g in a.genres: if g['name'] in term_counts: temp_terms[g['name']] = term_counts[g['name']] #temp_terms.append({g['name']: term_counts[g['name']]}) #print g['name'], term_counts[g['name']] top_term = max(temp_terms.iterkeys(), key = (lambda k: temp_terms[k])) a.term1 = top_term a.save()
def artists(self, request): '''API endpoint to query for artists''' next_page = request.next_page or 'first_artists_page' cache = memcache.get(next_page) if cache: return ArtistsResponse(artists=cache[0], next_page=cache[1]) query = Artist.query() if next_page is 'first_artists_page': artists, cursor, more = query.fetch_page(300) else: artists, cursor, more = query.fetch_page(300, start_cursor=Cursor.from_websafe_string(next_page)) artists = [artist.to_message() for artist in artists] memcache.add(next_page, (artists, cursor.to_websafe_string())) return ArtistsResponse(artists=artists, next_page=cursor.to_websafe_string())
def artist_application(request): latest_news = NewsItem.objects.all()[0] if request.method == 'POST': form = ArtistApplication(request.POST) if form.is_valid(): artist = Artist(name = form.cleaned_data['name'], description = form.cleaned_data['description'], phone = form.cleaned_data['phone'], website = form.cleaned_data['website'], soundcloud = form.cleaned_data['soundcloud'], facebook = form.cleaned_data['facebook'], myspace = form.cleaned_data['myspace'], lastfm = form.cleaned_data['lastfm'], twitter = form.cleaned_data['twitter'], youtube = form.cleaned_data['youtube'], resident_advisor = form.cleaned_data['resident_advisor']) artist.save() return redirect('/artists/application-successful/') else: form = ArtistApplication() return render_to_response('artist_application.html', {'form': form, 'latest_news': latest_news}, context_instance=RequestContext(request))
def edit_artist(artist_id): """Define Edit-Artist Retrieval.""" form = ArtistForm() artist_query = Artist.query.get(artist_id) artist_details = Artist.details(artist_query) form.name.data = artist_details["name"] form.genres.data = artist_details["genres"] form.city.data = artist_details["city"] form.state.data = artist_details["state"] form.phone.data = artist_details["phone"] form.website.data = artist_details["website"] form.facebook_link.data = artist_details["facebook_link"] form.seeking_venue.data = artist_details["seeking_venue"] form.seeking_description.data = artist_details["seeking_description"] form.image_link.data = artist_details["image_link"] return render_template('forms/edit_artist.html', form=form, artist=artist_details)
def edit_artist(artist_id): form = ArtistForm() data = request.form artist_query = Artist.query.get(artist_id) if artist_query: artist_details = Artist.details(artist_query) form.name.data = artist_details["name"] form.genres.data = artist_details["genres"] form.city.data = artist_details["city"] form.state.data = artist_details["state"] form.phone.data = artist_details["phone"] form.facebook_link.data = artist_details["facebook_link"] return render_template('forms/edit_artist.html', form=form, artist=artist_details) return render_template('errors/404.html')
def show_artist(artist_id): """Establish Individiual Artist Page.""" artist_query = Artist.query.get(artist_id) artist_details = Artist.details(artist_query) current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') new_shows_query = Show.query.options(db.joinedload( Show.Artist)).filter(Show.artist_id == artist_id).filter( Show.start_time > current_time).all() new_shows_list = list(map(Show.venue_details, new_shows_query)) artist_details["upcoming_shows"] = new_shows_list artist_details["upcoming_shows_count"] = len(new_shows_list) past_shows_query = Show.query.options(db.joinedload( Show.Artist)).filter(Show.artist_id == artist_id).filter( Show.start_time <= current_time).all() past_shows_list = list(map(Show.venue_details, past_shows_query)) artist_details["past_shows"] = past_shows_list artist_details["past_shows_count"] = len(past_shows_list) return render_template('pages/show_artist.html', artist=artist_details)
def test_relationship_1(self): newartist = Artist(artist_name='someone', artist_id='00009') db.session.add(newartist) db.session.commit() newartwork = Artwork(title='defgh', artwork_id='00010', painter=newartist) db.session.add(newartwork) db.session.commit() findartwork = db.session.query(Artwork).filter_by( artwork_id='00010').first() self.assertEqual(findartwork.artist_id, '00009') db.session.delete(findartwork) db.session.commit() findartist = db.session.query(Artist).filter_by( artist_id='00009').first() db.session.delete(findartist) db.session.commit()
def get_artist_by_name(_name:str): query = Artist.select().where(Artist.name == _name) try: _artist = { 'id':query[0].id, 'name':query[0].name, 'genre':query[0].genre, 'image_link':query[0].image_link, 'bio':query[0].bio} return _artist except: _artist = { 'id':0, 'name':'not found', 'genre':'not found', 'image_link':'not found', 'bio':'not found'} return _artist
def create_artist_submission(): form = ArtistForm() if form.validate(): try: name = request.form.get('name') city = request.form.get('city') state = request.form.get('state') phone = request.form.get('phone') facebook_link = request.form.get('facebook_link') genres = request.form.getlist('genres') genres = ','.join(genres) image_link = request.form.get('image_link') website = request.form.get('website') if request.form.get('seeking_venue') is None: seeking_venue = False else: seeking_venue = True seeking_description = request.form.get('seeking_description') artist = Artist(name=name, city=city, state=state, phone=phone, facebook_link=facebook_link, genres=genres, image_link=image_link, website=website, seeking_venue=seeking_venue, seeking_description=seeking_description) db.session.add(artist) db.session.commit() flash('Artist ' + artist.name + ' was successfully listed!') except: db.session.rollback() flash('An error occurred. Artist ' + artist.name + ' could not be listed.') finally: return render_template('pages/home.html') else: return redirect(url_for('create_artist_form'))
def create_artist_submission(): # called upon submitting the new artist listing form # TODO: insert form data as a new Venue record in the db, instead # TODO: modify data to be the data object returned from db insertion try: exists = db.session.query( db.exists().where(Artist.name == request.form['name'])).scalar() if exists: flash('This artist is already exist') return render_template('pages/artists.html') artist = Artist() for field in request.form: if field == 'genres': setattr(artist, field, request.form.getlist(field)) elif field == 'seeking_venue': setattr( artist, field, True if request.form.get(field) in ('y', True, 't', 'True') else False) else: setattr(artist, field, request.form.get(field)) try: db.session.add(artist) db.session.commit() flash('Artist ' + request.form['name'] + ' was successfully listed!') except: db.session.rollback() flash('An error occurred. Artist ' + artist.name + ' could not be listed.') return render_template('errors/500.html'), 500 finally: db.session.close() except: return render_template('errors/500.html'), 500 # on successful db insert, flash success # flash('Artist ' + request.form['name'] + ' was successfully listed!') # TODO: on unsuccessful db insert, flash an error instead. # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.') return render_template('pages/home.html')
def create_artist_submission(): # called upon submitting the new artist listing form # TODO: insert form data as a new Venue record in the db, instead # TODO: modify data to be the data object returned from db insertion # on successful db insert, flash success # flash('Artist ' + request.form['name'] + ' was successfully listed!') # TODO: on unsuccessful db insert, flash an error instead. # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.') #return render_template('pages/home.html') try: seeking_venue = False seeking_description = '' if 'seeking_venue' in request.form: seeking_venue = request.form['seeking_venue'] == 'y' if 'seeking_description' in request.form: seeking_description = request.form['seeking_description'] new_artist = Artist( name=request.form['name'], genres=request.form['genres'], city=request.form['city'], state=request.form['state'], phone=request.form['phone'], website=request.form['website'], image_link=request.form['image_link'], facebook_link=request.form['facebook_link'], seeking_venue=seeking_venue, seeking_description=seeking_description, ) print("print(artist_detail(new_artist))") print(artist_detail(new_artist)) db.session.add(new_artist) db.session.commit() # on successful db insert, flash success flash('Artist ' + request.form['name'] + ' was successfully listed!') except SQLAlchemyError as e: print(e) # TODO: on unsuccessful db insert, flash an error instead. # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.') flash('An error occurred. Artist ' + request.form['name'] + 'could not be listed. ') finally: db.session.close() return render_template('pages/home.html')
def create_artist_submission(): # called upon submitting the new artist listing form # TODO: insert form data as a new Venue record in the db, instead # TODO: modify data to be the data object returned from db insertion form = ArtistForm(request.form) if (form.validate()): error = False try: artist = Artist( name=request.form['name'], city=request.form['city'], state=request.form['state'], phone=request.form['phone'], genres=str(request.form.getlist('genres')), facebook_link=request.form['facebook_link'], image_link=request.form['image_link'], seeking_venue=str_to_bool(request.form['seeking_venue']), seeking_description=request.form['seeking_description'], website=request.form['website']) db.session.add(artist) db.session.commit() except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() if not error: # on successful db insert, flash success flash('Artist ' + request.form['name'] + ' was successfully listed!') # TODO: on unsuccessful db insert, flash an error instead. # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.') else: flash('An error occurred. Artist ' + request.form['name'] + ' could not be created.') return render_template('pages/home.html') else: print(form.data) flash(form.errors) return redirect(url_for('create_artist_form'))
def create_artist_submission(): error = False try: name = request.form['name'] city = request.form['city'] state = request.form['state'] phone = request.form['phone'] genres = request.form['genres'] facebook_link = request.form['facebook_link'] image_link = request.form['image_link'] website_link = request.form['website_link'] seeking_venue = request.form.get('seeking_venue') seeking_description = request.form['seeking_description'] if seeking_venue == 'y': seeking_venue = True else: seeking_venue = False artist = Artist(name=name, city=city, state=state, phone=phone, genres=genres, facebook_link=facebook_link, image_link=image_link, website_link=website_link, seeking_venue=seeking_venue, seeking_description=seeking_description) db.session.add(artist) db.session.commit() except (): db.session.rollback() error = True flash('An error occurred. Artist ' + request.form['name'] + ' could not be listed.') finally: db.session.close() if error: abort(500) else: flash('Artist ' + request.form['name'] + ' was successfully listed!') return render_template('pages/home.html')
def parse_artist(entry): name = entry.getText() print(name) wiki = entry.find('a').get('href').split('/')[4:] page = reddit.subreddit('AnimeThemes').wiki['/'.join(wiki)].content_html body = BeautifulSoup(page, 'html.parser') mal_url = body.find('h2').find('a').get('href') if 'myanimelist' not in mal_url: mal_id = None else: mal_id = body.find('h2').find('a').get('href').split('/')[-1] if not mal_id: mal_id = body.find('h2').find('a').get('href').split('/')[-2] mal_id = int("".join(filter(str.isdigit, mal_id))) if name == 'OxT': mal_id = 12596 if name == 'Spira*Spica': mal_id = 51708 return Artist.create(mal_id, name, get_cover(mal_id), parse_themes(body))
def show_artist(artist_id): artist_query = Artist.query.get(artist_id) if artist_query: artist_details = Artist.details(artist_query) current_time = datetime.now() new_shows_query = Show.query.options(db.joinedload( Show.Artist)).filter(Show.artist_id == artist_id).filter( Show.start_time > current_time).all() new_shows_list = list(map(Show.venue_details, new_shows_query)) artist_details["upcoming_shows"] = new_shows_list artist_details["upcoming_shows_count"] = len(new_shows_list) past_shows_query = Show.query.options(db.joinedload( Show.Artist)).filter(Show.artist_id == artist_id).filter( Show.start_time <= current_time).all() past_shows_list = list(map(Show.venue_details, past_shows_query)) artist_details["past_shows"] = past_shows_list artist_details["past_shows_count"] = len(past_shows_list) return render_template('pages/show_artist.html', artist=artist_details) return render_template('errors/404.html')
def edit_artist(artist_id): form = ArtistForm(request.form) artist_data = Artist.query.get(artist_id) if artist_data: artist_details = Artist.details(artist_data) form.name.data = artist_details["name"] form.genres.data = artist_details["genres"] form.city.data = artist_details["city"] form.state.data = artist_details["state"] form.phone.data = artist_details["phone"] form.website.data = artist_details["website"] form.facebook_link.data = artist_details["facebook_link"] form.seeking_venue.data = artist_details["seeking_venue"] form.seeking_description.data = artist_details["seeking_description"] form.image_link.data = artist_details["image_link"] return render_template('forms/edit_artist.html', form=form, artist=artist_details) return render_template('errors/404.html')
def create_artist_submission(): error = False form = ArtistForm(request.form) try: artist = Artist() form.populate_obj(artist) db.session.add(artist) db.session.commit() except: error = True db.session.rollback() finally: db.session.close() if error: flash('An error occured. Artist ' + request.form['name'] + ' could not be listed.') else: flash('Artist ' + request.form['name'] + ' was successfully listed!') return redirect(url_for('index'))
def create_artist_submission(): error = False print("CREATE ARTIST") try: name = request.form['name'] city = request.form['city'] state = request.form['state'] phone = request.form['phone'] website = request.form['website'] image_link = request.form['image_link'] genres = request.form.getlist('genres') facebook_link = request.form['facebook_link'] if 'seeking_venue' in request.form: seeking_venue = request.form['seeking_venue'] == 'y' else: seeking_venue = False seeking_description = request.form['seeking_description'] artist = Artist(name=name, city=city, state=state, phone=phone, website=website, image_link=image_link, genres=genres, facebook_link=facebook_link, seeking_venue=seeking_venue, seeking_description=seeking_description) db.session.add(artist) db.session.commit() except: error = True db.session.rollback() print("FAILURE") finally: db.session.close() if error: flash('An error has occured, failed to create artist ' + name, 'error') else: flash('Artist ' + name + ' was successfully listed!') return render_template('pages/home.html')
def create_artist_submission(): """ Controller to handle artist creation. """ try: request_data = {**request.form} request_data['seeking_venue'] = request_data.get( 'seeking_venue') == 'y' artist = Artist() db.session.add(artist) db.session.commit() flash(f'Artist `{request_data.get("name")}` was successfully listed.') except Exception as ex: db.session.rollback() print(ex) flash(f'Artist `{request_data.get("name")}` couldn\'t be listed.') finally: db.session.close() return render_template('pages/home.html')
def create_artist_submission(): # called upon submitting the new artist listing form # TODO: insert form data as a new Artist record in the db, instead # TODO: modify data to be the data object returned from db insertion error = False form = ArtistForm() if not form.validate(): flash(form.errors) return redirect(url_for('create_artist_submission', form=form)) try: # create new Artist object with recived values new_artist_row = Artist( name=request.form.get('name'), city=request.form.get('city'), state=request.form.get('state'), phone=request.form.get('phone'), genres=request.form.getlist('genres'), facebook_link=request.form.get('facebook_link'), website=request.form.get('website'), image_link=request.form.get('image_link')) db.session.add(new_artist_row) db.session.commit() except: db.session.rollback() error = True print(sys.exc_info()) finally: db.session.close() if error: # on unsuccessful db insert, flash an error instead. flash('An error occurred. Artist ' + request.form.get('name') + ' could not be listed.') else: # on successful db insert, flash success flash('Artist ' + request.form.get('name') + ' was successfully listed!') return redirect(url_for('artists'))
def create_artist_submission(): # called upon submitting the new artist listing form form_data = ArtistForm() genres = ",".join(form_data.genres.data) new_artist = Artist( name=form_data.name.data, city=form_data.city.data, state=form_data.state.data, phone=form_data.phone.data, image_link=form_data.image_link.data, facebook_link=form_data.facebook_link.data, genres=genres, website=form_data.website_link.data, seeking_venue=form_data.seeking_venue.data, seeking_description=form_data.seeking_description.data, ) try: db.session.add(new_artist) db.session.flush() availabilities = [ ArtistAvailability(artist_id=new_artist.id, time_from=d.get('time_from'), day=d.get('day'), time_to=d.get('time_to')) for d in form_data.availabilities.data if d.get('day') and d.get('time_from') and d.get('time_to') ] db.session.add_all(availabilities) except Exception as e: db.rollback() flash("An error occurred. Artist " + form_data.name.data + " could not be listed.") else: db.session.commit() flash('Artist ' + new_artist.name + ' was successfully listed!') finally: db.session.close() return render_template('pages/home.html')
def update_artist_orm(artist_id: int, form: FlaskForm, availability: Availability) -> (bool, str): """ Update an artist in ORM mode :param artist_id: id of the artist to update :param form: form to populate from :param availability: artist availability """ commit_change = False artist = Artist.query.filter(Artist.id == artist_id).first_or_404() artist_name = artist.name updated_artist = populate_artist_orm(Artist(), form) if not updated_artist.equal(artist, IGNORE_ID): # change has occurred update artist populate_artist_orm(artist, form) artist_name = artist.name commit_change = True new_availability = populate_availability_orm(Availability(), form) new_availability.artist_id = artist_id try: if is_available(availability) != is_available(new_availability) or \ not availability.equal(new_availability, IGNORE_ID_DATE): # availability has changed, add new setting db.session.add(new_availability) commit_change = True if commit_change: db.session.commit() success = True else: success = None except: db.session.rollback() print_exc_info() success = False finally: db.session.close() return success, artist_name
def create_artist_submission(): form = ArtistForm() try: new_artist = Artist(name=form.name.data, city=form.city.data, state=form.state.data, phone=form.phone.data, image_link=form.image_link.data, seeking_description=form.seeking_description.data, facebook_link=form.facebook_link.data, website=form.website.data, genres=form.genres.data ) db.session.add(new_artist) db.session.commit() flash('Artist ' + request.form['name'] + ' was successfully listed.') except: flash('Something went wrong. Artist ' + request.form['name'] + ' could not be listed.') return render_template('pages/home.html')
def create_artist_submission(): try: new_artist = Artist( name = request.form.get('name'), city = request.form.get('city'), state = request.form.get('state'), phone = request.form.get('phone'), facebook_link = request.form.get('facebook_link'), genres = request.form.get('genres') ) db.session.add(new_artist) db.session.commit() flash('Artist ' + request.form['name'] + ' was successfully listed!') except: flash('An error occurred. Artist ' + request.form['name'] + ' could not be listed.') db.session.rollback() finally: db.session.close() return render_template('pages/home.html')
def create_artist_submission(): # called upon submitting the new artist listing form try: # on successful db insert, flash success formData = request.form.to_dict() form = NewArtistForm() # used here because formData generes cannot take multiple values formData['genres'] = form.genres.data formData['seeking_venue'] = bool(formData['seeking_venue']) db.session.add(Artist(**formData)) db.session.commit() flash(f"Artist: {formData['name']} was added successfully!") return render_template('pages/home.html') except Exception as e: db.session.close() print(e) flash(f'Error...Artist: {formData["name"]} cannot get added!') return render_template('pages/home.html') finally: db.session.close()
def show_artist(artist_id): # shows the venue page with the given venue_id # TODO: replace with real venue data from the venues table, using venue_id current_artist = db.session.query(Artist).get(artist_id) data = Artist.info(current_artist) current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') new_shows = db.session.query(Show).options(db.joinedload( Show.Artist)).filter(Show.artist_id == artist_id).filter( Show.start_time > current_time).all() new_shows_list = list(map(Show.venue_info, new_shows)) data["upcoming_shows"] = new_shows_list data["upcoming_shows_count"] = len(new_shows_list) past_shows = db.session.query(Show).options(db.joinedload( Show.Artist)).filter(Show.artist_id == artist_id).filter( Show.start_time <= current_time).all() past_shows_list = list(map(Show.venue_info, past_shows)) data["past_shows"] = past_shows_list data["past_shows_count"] = len(past_shows_list) return render_template('pages/show_artist.html', artist=data)
def create_artist_submission(): try: artist = Artist(name=request.form['name'], city=request.form['city'], state=request.form['state'], phone=request.form['phone'], genres=request.form['genres'], facebook_link=request.form['facebook_link']) db.session.add(artist) db.session.commit() # on successful db insert, flash success flash('Artist ' + request.form['name'] + ' was successfully listed!') except: db.session.rollback() print(sys.exc_info()) # On unsuccessful db insert, flash an error instead. flash('There was an issue listing your artist.') finally: db.session.close() return render_template('pages/home.html')
def edit_artist(artist_id): form = ArtistForm() # TODO: populate form with fields from artist with ID <artist_id> aq = Artist.query.get(artist_id) if aq: artist_details = Artist.details(aq) form.name.data = artist_details["name"] form.genres.data = artist_details["genres"] form.city.data = artist_details["city"] form.state.data = artist_details["state"] form.phone.data = artist_details["phone"] form.website.data = artist_details["website"] form.facebook_link.data = artist_details["facebook_link"] form.seeking_venue.data = artist_details["seeking_venue"] form.seeking_description.data = artist_details["seeking_description"] form.image_link.data = artist_details["image_link"] return render_template('forms/edit_artist.html', form=form, artist=artist_details) return render_template('errors/404.html')
def create_artist_submission(): # called upon submitting the new artist listing form # TODO: insert form data as a new Venue record in the db, instead # TODO: modify data to be the data object returned from db insertion error = False artist_info = ArtistForm(request.form, meta={'csrf': False}) if artist_info.validate(): try: name = artist_info['name'].data genres = artist_info['genres'].data city = artist_info['city'].data state = artist_info['state'].data phone = artist_info['phone'].data website = artist_info['website'].data facebook = artist_info['facebook_link'].data if artist_info['seeking_venue'].data == 'True': seeking_venue = True else: seeking_venue = False seeking_description = artist_info['seeking_description'].data image = artist_info['image_link'].data artist = Artist(name=name, genres=genres, city=city, state=state, phone=phone, website=website, facebook_link=facebook, seeking_venue=seeking_venue, seeking_description=seeking_description, image_link=image) db.session.add(artist) db.session.commit() except: db.session.rollback() error = True print(sys.exc_info()) finally: db.session.close() else: error = True if error==False: # on successful db insert, flash success flash('Artist ' + request.form['name'] + ' was successfully listed!') else: # TODO: on unsuccessful db insert, flash an error instead. # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.') flash('An error occurred. Artist ' + artist.name + ' could not be listed.') return render_template('pages/home.html')
def artist_decoder(art, album): assert art != None assert (art['type'] == "artist") # need to get from simplified to full album objects r = requests.get(art['href']) full = json.loads(r.text) r2 = requests.get( "http://api.musicgraph.com/api/v2/artist/search?api_key=7f2f846f462aa5434858477e5957113f&name=" + full['name']) mg = json.loads(r2.text) # need to get image url from array of image objects # need to get country/decade from another api mg_data = mg['data'] country = None decade = None image = None # Grab genre for album from the aritst in music graph try: genre = mg_data[0]['main_genre'] except: genre = "Unavailable" album.genre = genre try: country = mg_data[0]['country_of_origin'] except: country = "Unavailable" try: decade = mg_data[0]['decade'] except: decade = "Unavailable" try: image = full['images'][0]['url'] except: image = None artist = Artist(full['name'], image, country, decade, genre) return artist
def create_artist_submission(): data = request.form form = ArtistForm() # validate input data if not form.validate_on_submit(): flash('invalid input fields') return redirect(url_for('index')) error = False try: artist = Artist( name=data['name'], city=data['city'], state=data['state'], phone=data['phone'], facebook_link=data['facebook_link'], image_link=data['image_link'], website=data['website'], seeking_venue=True if 'seeking_venue' in data.keys() else False, seeking_description=data['seeking_description']) # insert multiple genres for genre_name in form.genres.data: genre = ArtistGenre(name=genre_name) artist.genres.append(genre) db.session.add(artist) db.session.commit() except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() if error: # on unsuccessful db insert, flash an error instead. flash('An error occurred. Artist ' + data['name'] + ' could not be listed.') else: # on successful db insert, flash success flash('Artist ' + request.form['name'] + ' was successfully listed!') return render_template('pages/home.html')
def create_artist_submission(): # called upon submitting the new artist listing form # TODO: insert form data as a new Venue record in the db, instead # TODO: modify data to be the data object returned from db insertion error = False body = {} try: # print(request.form.getlist('genres')) # print(request.form) new_artist = Artist( name=request.form.get('name'), city=request.form.get('city'), state=request.form.get('state'), phone=request.form.get('phone'), image_link=request.form.get('image_link'), facebook_link=request.form.get('facebook_link'), website=request.form.get('website'), genres=request.form.getlist('genres'), seeking_venue=request.form.get('seeking_venue'), seeking_description=request.form.get('seeking_description')) db.session.add(new_artist) db.session.commit() # on successful db insert, flash success flash('Artist ' + request.form.get('name') + ' was successfully listed!') except (): # TODO: on unsuccessful db insert, flash an error instead. db.session.rollback() error = True print(sys.exc_info) flash('An error occurred. Artist ' + request.form.get('name') + ' could not be listed.') finally: db.session.close() if error: abort(500) else: return render_template('pages/home.html')
def create_artist_submission(): # called upon submitting the new artist listing form # TODO: insert form data as a new Venue record in the db, instead # TODO: modify data to be the data object returned from db insertion message = '' try: form = ArtistForm(request.form) genres = form.genres.data genres = ','.join([str(genre) for genre in genres]) # convert genres to string artist = Artist( name=form.name.data, city=form.city.data, state=form.state.data, genres=genres, facebook_link=form.facebook_link.data, website=form.website.data, seeking_venue=bool(form.seeking_venue.data), seeking_description=form.seeking_description.data, image_link=form.image_link.data ) db.session.add(artist) db.session.commit() message = 'Artist ' + form.name.data + ' was successfully listed!' except: db.session.rollback() print(sys.exc_info()) message = 'An error occurred. Artist ' + \ request.form.get('name') + ' could not be listed.' finally: db.session.close() # on successful db insert, flash success flash(message) # TODO: on unsuccessful db insert, flash an error instead. # e.g., flash('An error occurred. Artist ' + # data.name + ' could not be listed.') return render_template('pages/home.html')