def show(self, id, list_all=0): try: a = Artist.get(id) except SQLObjectNotFound: flash("Artist ID not found") util.redirect("/artists/list") except ValueError: try: a = Artist.byNameI(urllib.unquote_plus(id)) except SQLObjectNotFound: flash("Artist ID not found") util.redirect("/artists/list") if identity.current.user and a in identity.current.user.artists: is_tracked = True else: is_tracked = False past_events = a.events.filter(Event.q.date < date.today()).orderBy('-date') if not list_all: past_events = past_events[:5] future_events = a.events.filter(Event.q.date >= date.today()).orderBy('date') return dict(artist=a, past_events=past_events, future_events=future_events, tracked_count=a.users.count(), is_tracked=is_tracked, description=util.desc_format(a.description), artist_list=artist_list)
def test_add_artist_with_artists_in(self): self.add_test_data() artist_count = artworkstore.artist_count() at = Artist(artist_name='aa', artist_email='jill.gmail.com') at.save() self.assertTrue(artworkstore.exact_match(at)) self.assertEqual(artist_count + 1, artworkstore.artist_count())
def artists_create_post(): # 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(): name = form.name.data city = form.city.data state = form.state.data phone = form.phone.data genres = request.form.getlist('genres') facebook_link = form.facebook_link.data image_link = form.image_link.data artist = Artist(name=name, city=city, state=state, phone=phone, genres=genres, facebook_link=facebook_link, image_link=image_link) artist.insert() # db.session.add(artist) # db.session.commit() flash('Artist ' + form.name.data + ' was successfully listed!') else: print(form.errors) flash('An error occurred. Artist ' + form.name.data + ' could not be listed.') return render_template('forms/new_artist.html', form=form) # on successful db insert, flash success # 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 test_when_artist_exists_in_db_fetches_from_db(self): artist = Artist() artist.artist_spotify_id = "abc123" artist.artist_name = "David Bowie" db.session.add(artist) db.session.commit() uri = get_artist_spotify_uri(self.spotify, "David Bowie") self.assertEqual("abc123", uri) self.assertFalse(self.spotify.search_was_called)
def test_add_duplicate_email(self): example = Artist('Example', '*****@*****.**') add_new_artist_to_db.add_artist_test(example) example2 = Artist('Example2', '*****@*****.**') added2 = add_new_artist_to_db.add_artist_test(example2) self.assertFalse(added2) excpeted_rows = [ ('Example', '*****@*****.**')] actual_rows = self.get_all_data_from_artistinfo() self.assertCountEqual(excpeted_rows, actual_rows)
def merge(self, id, other_id): try: old = Artist.get(id) new = Artist.get(other_id) Artist.merge(old, new) # add this to fixup dict, so will never have to merge again artist_fixup_dict[old.name] = new.name artist_fixup_dict.tidy(old.name, new.name) flash("%s merged into %s and learned" % (old.name, new.name)) except SQLObjectNotFound: flash("Could not move") util.redirect("/artists/%s" % other_id)
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 try: data = Artist() data.name = request.form['name'] data.city = request.form['city'] data.state = request.form['state'] data.phone = request.form['phone'] data.genres = request.form.getlist('genres') data.facebook_link = request.form['facebook_link'] if Artist.query.filter_by(name=data.name).filter_by( city=data.city).filter_by(state=data.state).filter_by( phone=data.phone).count() != 0: flash("Artist " + request.form['name'] + " is already in the database") return render_template('pages/home.html') db.session.add(data) db.session.commit() except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() if error: flash('An error occurred. Artist ' + request.form['name'] + ' could not be listed.') if not error: flash('Artist ' + request.form['name'] + ' was successfully listed!') return render_template('pages/home.html')
def create_artist_submission(): form = ArtistForm() if not form.validate(): flash(form.errors) return redirect(url_for('create_artist_form')) error = False try: artist = Artist() artist.name = request.form['name'] artist.city = request.form['city'] artist.state = request.form['state'] artist.phone = request.form['phone'] tmp_genres = request.form.getlist('genres') artist.genres = ','.join(tmp_genres) # convert list to string artist.facebook_link = request.form['facebook_link'] db.session.add(artist) db.session.commit() except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() if error: flash('An error occurred. Artist ' + request.form['name'] + ' could not be listed.') else: flash('Artist ' + request.form['name'] + ' was successfully listed!') return render_template('pages/home.html')
def test_add_artist_errors_case_sensitive(self): at = Artist(artist_name='cc', artist_email='*****@*****.**') at.save() with self.assertRaises(peewee.IntegrityError): at_dup = Artist(artist_name='Cc', artist_email='*****@*****.**') at_dup.save()
def test_add_duplicate_name_artist(self): example = Artist('Example', 25) added = db.add_artist(example) example2 = Artist('Example', 40) # same name added2 = db.add_artist(example2) self.assertFalse(added2) expected_rows = [('Example', 25)] # only one artist actual_rows = self.get_all_data() # assertCountEqual will compare two iterables, e.g. a list of tuples returned from DB self.assertCountEqual(expected_rows, actual_rows)
def save(self, id=0, **kw): if id: try: a = Artist.get(id) a.set(**a.clean_dict(kw)) flash("Updated") except SQLObjectNotFound: flash("Update Error") else: a = Artist(added_by=identity.current.user, **Artist.clean_dict(kw)) if not "admin" in identity.current.groups: identity.current.user.addArtist(a) flash("Artist added") a.approved = datetime.now() util.redirect("/artists/%s" % a.id)
def populateArtist(session, artist_name, album_name): """Populates the artist database table with data from the Spotify API. Keyword arguments: session -- the database session. artist_name -- the name of the artist to search for. album_name -- the name of the album to search for. """ album_result = sp.search(q='artist:' + artist_name + ' album:' + album_name, type='album') album = sp.album(album_result['albums']['items'][0]['uri']) artist = sp.artist(album['artists'][0]['uri']) # Populate artist information based on the album search. existing_artist = session.query(Artist).filter( Artist.uri == artist['uri']).first() if (existing_artist is None): artist_db_obj = Artist(name=artist['name'], uri=artist['uri'], popularity=artist['popularity'], followers=artist['followers']['total']) session.add(artist_db_obj) session.commit() else: artist_db_obj = existing_artist populateAlbum(session, artist_db_obj, album)
def test_artist_will_be_captilized(self): example = Artist('patrick mahomes', '*****@*****.**') add_new_artist_to_db.add_artist_test(example) excpected_rows = [('Patrick Mahomes', '*****@*****.**')] actual_rows = self.get_all_data_from_artistinfo() self.assertCountEqual(excpected_rows, actual_rows)
def create_artist_submission(): try: artistData = request.form artistName = artistData.get('name') artistPhone = artistData.get('phone') artistCity = artistData.get('city') artistState = artistData.get('state') artistFacebookLink = artistData.get('facebook_link') artistGenresList = artistData.getlist('genres') artist = Artist(name=artistName, phone=artistPhone, city=artistCity, state=artistState, facebook_link=artistFacebookLink) for artistGenres in artistGenresList: if Genres.query.filter_by(name=artistGenres).first(): artist.genres.append( Genres.query.filter_by(name=artistGenres).first()) else: genres = Genres(name=artistGenres) artist.genres.append(genres) db.session.add(artist) db.session.commit() flash('artist ' + request.form['name'] + ' was successfully listed!') except: db.session.rollback() 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 form = ArtistForm() # DONE: insert form data as a new Artist record in the db, instead # DONE: modify data to be the data object returned from db insertion if request.method == 'POST': try: artist = Artist( name=form.name.data, city=form.city.data, state=form.state.data, genres=form.genres.data, phone=form.phone.data, image_link=form.image_link.data, facebook_link=form.facebook_link.data ) db.session.add(artist) db.session.commit() # on successful db insert, flash success flash('Artist ' + form.name.data + ' was successfully listed!') except: db.session.rollback() # DONE: on unsuccessful db insert, flash an error instead. flash('An error occurred. Artist ' + form.name.data + ' 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 new_artist = Artist( name=request.form.get('name'), genres=request.form.get('genres'), city=request.form.get('city'), state=request.form.get('state'), phone=request.form.get('phone'), website_link=request.form.get('website_link'), facebook_link=request.form.get('facebook_link'), image_link=request.form.get('image_link'), seeking_venue=request.form.get('seeking_venue'), seeking_description=request.form.get('seeking_description'), past_shows_count=request.form.get('past_shows_count'), upcoming_shows_count=request.form.get('upcoming_shows_count')) try: data = new_artist db.session.add(data) db.session.commit() flash('Artist ' + request.form['name'] + ' was successfully listed!') except: db.session.rollback() flash('An error occurred. Artist ' + data.name + ' could not be listed.') finally: db.session.close() return render_template('pages/home.html')
def lastfm_artist_update(artist): artist_info = lastfm.artist_info(artist.name) artist.img_url = artist_info["img_url"] artist.tags = artist_info["tags"] sims_objs = [] sims_names = artist_info["similars"] for artist_name in sims_names: try: sim_artist = Artist.byNameI(artist_name) except SQLObjectNotFound: # keep out too-short names if len(artist_name) < 3: continue try: sim_artist = Artist(name=artist_name, added_by=UserAcct.get(1)) except SQLObjectIntegrityError: print "trying to add '%s'" % artist_name hub.rollback() hub.begin() # Artists added this way are *not* approved. This keeps them from # also having sims generated (when they could be non-local bands # that we really don't care much about.) # If they have events approved, then of course they are, too. sims_objs.append(sim_artist) artist.similars = sims_objs
def _read(self, path): self._setDefaults() config = ConfigParser.ConfigParser() if len(config.read([path])): for a in config.sections(): if a != "global": try: name = config.get(a, "name") except: continue try: date = config.get(a, "date") except: date = None try: disambiguation = config.get(a, "disambiguation") except: disambiguation = None self._artists.add(Artist(name, date, disambiguation)) else: try: self._interval = config.getint(a, "interval") except: pass try: self._command = config.get(a, "command") except: pass else: raise ReadFailed
def update_artists(count=queries_per_run): refresh_date = datetime.date.today() - datetime.timedelta(artist_refresh_days) artists = Artist.select( AND(Artist.q.approved != None, OR(Artist.q.batch_updated == None, Artist.q.batch_updated < refresh_date)) ) count = min(artists.count(), count) email_txt = "" for artist in artists[:count]: try: lastfm_artist_update(artist) mbz_artist_update(artist) recording_artist_update(artist) artist.batch_updated = datetime.datetime.now() except: import traceback email_txt += "artist error: '%s'\n" % artist.name email_txt += traceback.format_exc() time.sleep(1) if email_txt: util.email("*****@*****.**", "BandRadar <*****@*****.**>", "artist errors", email_txt) return count
def edit(self, id=0, **kw): form_vals = {} template = ".templates.event.add" if id: try: e = Event.get(id) form_vals = util.so_to_dict(e) form_vals['artists'] = "\n".join([a.name for a in e.artists]) form_vals['venue'] = dict(text=e.venue.name) template = ".templates.event.edit" except SQLObjectNotFound: pass else: form_vals = dict(id=id) try: a = Artist.get(int(kw['artist_prefill'])) form_vals['artists'] = a.name except (SQLObjectNotFound, KeyError): pass try: v = Venue.get(int(kw['venue_prefill'])) flash(form_vals) form_vals['venue'] = dict(text=v.name) except (SQLObjectNotFound, KeyError): pass return dict(tg_template=template, event_form=event_form, form_vals=form_vals)
def add_artist(obj): with session_scope() as session: session.add( Artist(name=obj['name'], spotify_id=obj['spotify_id'], image_url=obj['images'][0]['url'], followers=obj['followers'], popularity=obj['popularity']))
def delete(self, id): try: a = Artist.get(id) a.destroySelf() flash("Deleted") except SQLObjectNotFound: flash("Delete failed") util.redirect("/artists/list")
def add_artist(name, email):#adding new artist try: Artist(name = name, email = email).save() print("you added new name") #except IntegrityError as e: #raise ArtError('Error adding artist because' + str(e)) except Exception as err: print(err)
def register_fan(): """Fan Registration page""" fan_info = request.form.get('fan_info') user_id = request.form.get('user_id') artist = Artist(user_id=user_id, bio=bio, statement=statement) db.session.add(artist) db.session.commit() return redirect("/")
def setUp(self): DB.drop_all() DB.create_all() artist1 = Artist( '1', 'Andy Warhol', '1900', 'Male', 'American', 'http://a5.files.biography.com/image/upload/c_fit,cs_srgb,dpr_1.0,h_1200,q_80,w_1200/MTE5NDg0MDU1MTYxNzY3NDM5.jpg' ) DB.session.add(artist1) DB.session.commit()
def test_add_duplicate_errors(self): at = Artist(artist_name='cc', artist_email='*****@*****.**') at.save() with self.assertRaises(peewee.IntegrityError): at_dup = Artist(artist_name='cc', artist_email='hbgmail.com') at_dup.save() aw = Artwork(artwork_name='ccc') aw.save() with self.assertRaises(peewee.IntegrityError): aw_dup = Artwork(artwork_name='cc') aw_dup.save()
def register_artist(): """Artist Registration page""" bio = request.form.get('bio') statement = request.form.get('statement') user_id = request.form.get('user_id') artist = Artist(user_id=user_id, bio=bio, statement=statement) db.session.add(artist) db.session.commit() return redirect("/")
def edit(self, id=0, **kw): form_vals = {} if id: try: a = Artist.get(id) form_vals = util.so_to_dict(a) except SQLObjectNotFound: pass form_vals.update(kw) return dict(artist_form=artist_form, form_vals=form_vals)
def test_add_artist(self): example = Artist('Example', '*****@*****.**') added = add_new_artist_to_db.add_artist_test(example) self.assertTrue(added) expected_rows = [ ('Example', '*****@*****.**')] actual_rows = self.get_all_data_from_artistinfo() self.assertCountEqual(expected_rows, actual_rows) example2 = Artist('Another Example', '*****@*****.**') added2 = add_new_artist_to_db.add_artist_test(example2) self.assertTrue(added2) expected_rows = [ ('Example', '*****@*****.**'), ('Another Example', '*****@*****.**')] actual_rows = self.get_all_data_from_artistinfo() self.assertCountEqual(expected_rows, actual_rows)
def get_related_artists(self, artist_id: str) -> Generator[Artist, None, None]: r = self._spotipy.artist_related_artists(artist_id) for artist_obj in r["artists"]: yield Artist( name=artist_obj["name"], identifier=artist_obj["id"], popularity=artist_obj["popularity"], )
def split(self, id): try: a = Artist.get(id) new_artists = a.split_artist() if len(new_artists) > 1: flash("split into %s" % ", ".join(new_artists.values())) else: flash("Not split") except SQLObjectNotFound: flash("not found") util.redirect("/artists/%s" % new_artists.keys()[0])
def create_artist(artist_id, artist_name, popularity, image_url): """Create and return a new Artist""" artist = Artist(artist_id=artist_id, artist_name=artist_name, popularity=popularity, image_url=image_url) db.session.add(artist) db.session.commit() return artist
def test_add_artist(self): example = Artist('Example', 25) added = db.add_artist(example) self.assertTrue(added) expected_rows = [('Example', 25)] actual_rows = self.get_all_data() # assertCountEqual will compare two iterables, e.g. a list of tuples returned from DB self.assertCountEqual(expected_rows, actual_rows) example2 = Artist('Another Example', 30) added2 = db.add_artist(example2) self.assertTrue(added2) expected_rows = [('Example', 25), ('Another Example', 30)] actual_rows = self.get_all_data() self.assertCountEqual(expected_rows, actual_rows)
def _foo(): """test, do not use""" amazon_src = Source.byName("amazon") done_artists = Artist.select(Artist.q.recordings_updated != None) for artist in done_artists: for record in artist.recordings: if record.source == amazon_src: record.destroySelf() for recording in amazon.recordings(artist.name): Recording( name=recording["name"], by=artist, url=recording["url"], img_url=recording["img_url"], source=amazon_src )
def get_artist_from_context(self, context): """Return an Artist from a Context. Args: context (dict): The Context to convert from. Returns: Artist: The Artist. """ artist_id = id_from_uri(context["uri"]) result = self.get_api_v1("artists/{}".format(artist_id)) return Artist(result or {})
def add_new_artist(): name = input('Enter name: ') age = int(input('Enter age: ')) artist = Artist(name, age) added = db.add_artist(artist) # todo distinguish between added, duplicate, unexpected error if added: print('Added artist') else: print('Duplicate artist')
def untrack(self, id, viewing="no"): u = identity.current.user try: a = Artist.get(id) if a in u.artists: u.removeArtist(a) except SQLObjectNotFound: flash("Artist not found") util.redirect("/") if viewing == "no": util.redirect_previous() else: util.redirect("/artists/%s" % a.id)
def dyntrack(self, id, track): u = identity.current.user ret = "Error" try: a = Artist.get(id) if track == "true" and a not in u.artists: u.addArtist(a) ret = "Tracked" if track == "false" and a in u.artists: u.removeArtist(a) ret = "Untracked" except SQLObjectNotFound: pass return ret
def test_addition_deletion(self): """ Test adding and deleting """ artist2 = Artist( '2', 'Pablo Picasso', '1920', 'Male', 'Spain', 'http://a5.files.biography.com/image/upload/c_fit,cs_srgb,dpr_1.0,h_1200,q_80,w_1200/MTE5NDg0MDU1MTYxNzY3NDM5.jpg' ) DB.session.add(artist2) DB.session.commit() self.assertEqual(len(Artist.query.all()), 2) Artist.query.filter_by(name='Pablo Picasso').delete() DB.session.commit() self.assertEqual(len(Artist.query.all()), 1)
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 data = {} try: 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') genres = request.form.getlist('genres') facebook_link = request.form.get('facebook_link') website = request.form.get('website') seeking_venue = request.form.get('seeking_venue') if seeking_venue == "True": seeking_venue = True else: seeking_venue = False seeking_description = request.form.get('seeking_description') artist = Artist(name=name, city=city, state=state, phone=phone, image_link=image_link, genres=genres, facebook_link=facebook_link, website=website, seeking_venue=seeking_venue, seeking_description=seeking_description) db.session.add(artist) db.session.commit() data = artist print(data) except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() if error: 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(): """ create artist on form submission """ try: request.get_data() genres = request.form.getlist('genres') artist_dict = request.form.to_dict() seeking_venue = artist_dict['seeking_venue'] == "True" artist = Artist(name=artist_dict['name'], city=artist_dict['city'], state=artist_dict['state'],\ phone=artist_dict['phone'],\ facebook_link=artist_dict['facebook_link'],\ website_link=artist_dict['website_link'], image_link=artist_dict['image_link'],\ seeking_venue=seeking_venue, seeking_description=artist_dict['seeking_description']) artist.create(genres) flash('artist ' + request.form['name'] + ' was successfully listed!') except Exception as e: print("Error while creating new artist: ", e) print(traceback.format_exc()) flash('An error occurred. artist ' + request.form['name'] + ' could not be listed.') abort(500) return render_template('pages/home.html')
def add_artist_users_artists(user, items): for item in items: if item['id'] not in [ artist.spotify_artist_id for artist in user.artists ]: artist = Artist(spotify_artist_id=item['id'], name=item['name'], art_url=item['images'][0]['url'], users=[user]) db.session.add(artist) else: artist = db.session.query(Artist).filter( Artist.spotify_artist_id == item['id']).one() artist.users.append(user) db.session.commit()
def add_artist_to_db(artist_name): """Adds artist to db if not already in db. Returns artist db object. >>> add_artist_to_db('boy pablo') <Artist artist_name=boy pablo> """ if not Artist.query.filter_by(artist_name=artist_name).first(): artist = Artist(artist_name=artist_name) db.session.add(artist) db.session.commit() else: artist = Artist.query.filter_by(artist_name=artist_name).first() return artist
def fillData(self, bands, genre): chart = self.readChart(genre) for artistId in bands: x = Artist(key_name=str(artistId)) x.artistId = artistId x.genre = genre try: pos = chart.index('<a href="Artist.asp?action=view&ArtistID=%d">' % artistId) posRank = chart.rindex(' ',0,pos) + 6 x.rank = int(chart[posRank:chart.rindex('</td>',posRank,pos)]) posName = chart.index('">',pos) + 2 x.name = chart[posName:chart.index('</',posName)] except: x.rank = 99999 x.brRank = 999 x.name = "Artista id %s fora do ranking nesta atualização" % artistId self.rank.append(x) self.rank.sort(key=lambda x:x.rank) self.calculateDiff()
def artists_clean(self, artists): artists = [self.artist_name_fix(a) for a in artists] # prev line may result in blank artist names artists = [a for a in artists if len(a)] # break all "john foo & susan bar" into separate artists, if "john foo" # already exists in the db for artist in artists: if artist.find("&") != -1: artist1, artist2 = artist.split("&", 1) try: if not len(artist1.strip()): continue a = Artist.byNameI(artist1) yield artist1.strip() yield artist2.strip() except SQLObjectNotFound: yield artist else: yield artist
def get(self): genre = int(cgi.escape(self.request.get('genre'))) if not auth_genre(genre): self.response.out.write("Acesso negado") return id = int(cgi.escape(self.request.get('id'))) artistList = db.GqlQuery("SELECT * FROM Genre WHERE id = :1", genre).fetch(1)[0] exists = artistList.bands.count(id) > 0 if exists: logging.info("Removendo a banda %d do genero %s" % (id, artistList.name)) artistList.bands.remove(id) removed = Artist(key_name=str(id)) removed.artistId = id removed.genre = 99 removed.brRank = 999 removed.rank = 99999 removed.put() else: logging.info("Adicionando a banda %d para o genero %s" % (id, artistList.name)) artistList.bands.append(id) artistList.put() self.response.out.write("A banda %d foi %s com sucesso!" % (id, "removida" if exists else "adicionada"))
def gets_user_serach_results(): """Converts search into EchoNest GET request and inserts JSON object into database""" artist = request.args['s_artist'] song = request.args['song'] genre = request.args['genre'] artist_pl = request.args['artist'] if artist and song: # Converts search into titles artist_str = str(artist.title()) song_str = str(song.title()) # Need to make sure that str are in correct format for querying artist_and_song = [artist_str, song_str] print "server.py User search artist and song list ", artist_and_song # checks user search for uniqueness and adds to db. # in api_helper.py returns_artist_id = adds_unique_searches_to_database(artist_and_song) yt_playlist_query = creates_yt_playlist_query(artist_and_song) # from api_helper.py, made by echonest print "1111111111111111" new_artists_added = adds_new_artists_to_db_by_en_id(yt_playlist_query) # from seed.py print "2222222222222222" new_songs_added = adds_new_songs_to_db_by_en_id(yt_playlist_query) # from seed.py print "333333333333333" yt_frontend_playlist = creates_yt_frontend_playlist(yt_playlist_query) # from youtube.py print "444444444444444" yt_db_playlist = creates_yt_db_playlist(yt_frontend_playlist, yt_playlist_query) print "555555555555555" added_yt_playlist_info = adds_yt_video_info_to_db(yt_db_playlist) # from seed.py print "66666666666666" if genre: genre = Genre(str(genre)) print genre genre_playlist = genre.creates_genre_en_playlist() yt_search_playlist = genre.extracts_artist_and_song(genre_playlist) yt_frontend_playlist = genre.creates_yt_playlist(yt_search_playlist) if artist_pl: artist_pl = Artist(str(artist_pl)) print artist_pl artist_playlist = artist_pl.creates_artist_en_playlist() yt_search_playlist = artist_pl.extracts_artist_and_song(artist_playlist) yt_frontend_playlist = artist_pl.creates_yt_playlist(yt_search_playlist) yt_playlist_id = create_yt_playlist_id() # creates an empty playlist on youtube account print "#################### ", yt_playlist_id db.session.commit() # yt videoId in a dict to be passed to js playlist page data = json.dumps(yt_frontend_playlist) # adds_video_to_session() # print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!" return render_template('playlist.html', data=data, jinja_data=yt_frontend_playlist)
def save(self, id, **kw): try: v = Venue.byName(kw['venue']['text']) except SQLObjectNotFound: v = Venue(name=kw['venue']['text'], added_by=identity.current.user) artists = kw.pop('artists') if not artists: artists = "" artist_name_list = [artist.strip() for artist in artists.split('\n')] # elim blank items in list artist_name_list = [artist for artist in artist_name_list if artist] if not kw.get('name'): kw['name'] = ", ".join(artist_name_list) # updating if id: try: e = Event.get(id) flash_msg = "updated" except SQLObjectNotFound: flash("Database error, please try again") redirect("/") # inserting else: e = Event(name=kw['name'], date=kw['date'], time=kw['time'], venue=v, added_by=identity.current.user) # mark user as going to all added events by default if not "admin" in identity.current.groups: att = Attendance(user=identity.current.user, event=e, planning_to_go=True) flash_msg = "added, will be reviewed and posted within 24 hrs" del kw['venue'] e.set(**e.clean_dict(kw)) old_venue = e.venue e.venue = v old_venue.destroy_if_unused() old_artists = set([a.name for a in e.artists]) # add new artists artist_list = [] for artist in artist_name_list: try: a = Artist.byNameI(artist) if not a in e.artists: e.addArtist(a) except SQLObjectNotFound: a = Artist(name=artist, added_by=identity.current.user) e.addArtist(a) artist_list.append(a) # remove old artists for artist in e.artists: if artist not in artist_list: e.removeArtist(artist) artist.destroy_if_unused() new_artists = set([a.name for a in e.artists]) # approve all artists at approved events if e.approved: for artist in e.artists: if not artist.approved: artist.approved = datetime.now() # add entry to UpdateLog if old_artists != new_artists and e.approved: u = UpdateLog( changed_by=identity.current.user.id, table_name="artist_event", table_id=e.id, attrib_name="artists", attrib_old_value=old_artists, attrib_new_value=new_artists ) flash("Event %s" % flash_msg) util.redirect("/events/%s" % e.id)
def import_to_db(self, event): flag_for_review = False venue_name = self.venue_name_fix(event['venue']['name']) try: v = Venue.byNameI(venue_name) except SQLObjectNotFound: v = Venue(name=venue_name, added_by=identity.current.user) flag_for_review = True if event['venue'].has_key('phone'): phone = event['venue']['phone'] if not len(phone) >= 8: phone = "503-" + phone p = validators.PhoneNumber() try: event['venue']['phone'] = p.to_python(phone) except: event['venue']['phone'] = None self._set_optional_fields(v, event['venue'], ("address", "phone", "zip_code", "url", "description")) event_name = self.event_name_fix(event['name']) event_date = event["date"] event_time = event.get("time") if event_time: event_time = event_time.lower() # check same venue, date, time db_events = Event.selectBy(date=event_date, time=event_time, venue=v) if db_events.count(): e = db_events[0] new_event = False else: # no time? still could be skippable, if event name is the same db_events = Event.selectBy(date=event_date, name=event_name, venue=v) if db_events.count(): e = db_events[0] new_event = False else: e = Event(venue=v, name=event_name, date=event_date, time=event_time, added_by=identity.current.user) new_event = True try: s = Source.byName(event["source"]) except SQLObjectNotFound: s = Source(name=event["source"]) flag_for_review = True e.addSource(s) self._set_optional_fields(e, event, ("cost", "ages", "url", "description", "ticket_url")) for artist in self.artists_clean(event['artists']): try: a = Artist.byNameI(artist) # artist was a similar, but now it's listed as having an event # so approve it if not a.approved: a.approved = datetime.now() except SQLObjectNotFound: a = Artist(name=artist, added_by=identity.current.user) flag_for_review = True if not e.id in [existing.id for existing in a.events]: a.addEvent(e) # flag all events from certain unreliable sources if event["source"] in ("ticketswest", "upcoming", "lastfm"): flag_for_review = True if new_event and not flag_for_review: e.approved = datetime.now() elif flag_for_review: e.approved = None return (new_event, flag_for_review)
def __init__(self, key, name, date = None, disambiguation = None): Artist.__init__(self, name, date, disambiguation) self._key = key