def make_default_user_connections( ): # Used in reset_db() MUST CALL ADD_OBJECTS FIRST!!! user1 = User.objects(username='******').first() user2 = User.objects(username='******').first() user3 = User.objects(username='******').first() albany_artist = Artist.objects(name='Artist 3').first() artist1 = Artist.objects(name='Artist 1').first() add_member(user1, artist1) add_member(user3, albany_artist) follow_band(user2, artist1)
def create_artist_submission(): error = False data = request.form try: artist = Artist() artist.name = data['name'] artist.city = data['city'] artist.state = data['state'] artist.phone = data.get('phone', '') artist.facebook_link = data.get('facebook_link', '') artist.genres = [ ArtistGenres(genre=GenreEnum[genre]) for genre in data.getlist('genres') ] db.session.add(artist) db.session.commit() except: error = True db.session.rollback() finally: data = artist.to_dict() db.session.close() if not error: flash(f'Artist {data["name"]} was successfully listed!', 'alert-success') else: flash( f'An error occurred. Artist {data["name"]} could not be listed. \ Does the artist exist already?', 'alert-danger') return render_template('pages/home.html')
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = Artist(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def populate_db(): c1 = City(name='Ithaca, NY') c2 = City(name='Binghamton, NY') c3 = City(name='Syracuse, NY') c4 = City(name='Rochester, NY') db.session.add_all([c1, c2, c3, c4]) db.session.commit() a1 = Artist(name="Driftwood", description="Folk Rock", cityID=c2.id) a2 = Artist(name="Quail", description="Funk and Brass", cityID=c1.id) a3 = Artist(name="VeeDaBee", description="Rock Band", cityID=c1.id) a4 = Artist(name="Danielle Ponder", description="Soul", cityID=c4.id) db.session.add_all([a1, a2, a3, a4]) db.session.commit() v1 = Venue(name='The Haunt', cityID=c2.id) v2 = Venue(name='State Theater', cityID=c1.id) v3 = Venue(name='Stewart Park', cityID=c1.id) v4 = Venue(name='University', cityID=c2.id) v5 = Venue(name='Oncenter', cityID=c3.id) db.session.add_all([v1, v2, v3, v4, v5]) db.session.commit() e1 = Event(name='Ithaca Porchfest', time=datetime(2020, 11, 5, 20, 00), venueID=v3.id) e2 = Event(name='2020 Tour', time=datetime(2020, 10, 20, 18, 00), venueID=v5.id) e3 = Event(name='Anniversary Concert', time=datetime(2020, 10, 20, 19, 00), venueID=v1.id) e4 = Event(name='2020 Tour', time=datetime(2020, 10, 29, 18, 00), venueID=v2.id) e5 = Event(name='2020 Tour', time=datetime(2020, 10, 20, 12, 00), venueID=v4.id) db.session.add_all([e1, e2, e3, e4, e5]) db.session.commit() x1 = ArtistToEvent(artistID=a1.id, eventID=e3.id) x2 = ArtistToEvent(artistID=a2.id, eventID=e3.id) x3 = ArtistToEvent(artistID=a1.id, eventID=e1.id) x4 = ArtistToEvent(artistID=a3.id, eventID=e4.id) x5 = ArtistToEvent(artistID=a4.id, eventID=e5.id) x6 = ArtistToEvent(artistID=a3.id, eventID=e2.id) db.session.add_all([x1, x2, x3, x4, x5, x6]) db.session.commit() u1 = User(username='******', email=('*****@*****.**'), password_hash='Password') db.session.add(u1) db.session.commit() return render_template('base.html', title='Populate DB')
def test_put_errors(server): with server.app_context(): artist = Artist("a") db.session.add(artist) artist2 = Artist("b") db.session.add(artist2) db.session.commit() assert Artist.query.count() == 2 r = requests.put(server.url + "/artist/{}".format(artist.id), data={ "name": "b" }) assert r.status_code == 422
def test_show_up_lyric_by_artist(self): a1 = Artist('ARTIST 1', self.user.get_id()) db.session.add(a1) db.session.commit() al1 = Album('album 1', datetime.now(), self.user.get_id(), a1.get_id()) db.session.add(al1) db.session.commit() l1 = Lyric('song 1', 'test 1', self.user.get_id(), al1.get_id()) db.session.add(l1) db.session.commit() response = self.client.get('/lyrics/artist1/1') self.assertIn(b'Flask Lyric - song 1', response.data) self.assertIn(b'ARTIST 1 LYRICS', response.data) self.assertIn(b'test 1', response.data)
def add_song(self, **kwargs): artist_name = kwargs.get('title')[0] artist = Artist.objects(name=artist_name) song_name = kwargs.get('title')[-1] if not artist or Song.objects(name=song_name): self.add_artist(**kwargs) if self.is_song_exist(song_name): Log(type_added='song', name_added=song_name).save() return False self.download(kwargs.get('download_url')) size = kwargs.get('duration_size') size = ' '.join((size[2], size[3])) song = Song(artist=artist.get(), name=song_name, duration=kwargs.get('duration_size')[0], download_url=kwargs.get('download_url'), size=size) with open(TEMP_FILE, 'rb') as binary_file: song.audio_file.put(binary_file) shutil.rmtree(TEMP) if song: song.save() Log(type_added='song', name_added=song_name, added=True).save() return True Log(type_added='song', name_added=song_name).save() return False
def setAlbumArtist(album, artist_name): app.logger.info('setAlbumArtist') if not artist_name: raise Exception('Album has no artist name given') # update model artist = Artist.query.filter_by(name=artist_name).first() if not artist: artist = Artist(artist_name) db.session.add(artist) db.session.commit() app.logger.info('{} <= {}'.format(artist, artist_name)) album.artist_id = artist.id # update tag app.logger.info('Updating artist {} for album {}'.format( artist_name, album)) for song in album.songs: if song.path_name.lower().endswith('mp3'): tags = ID3(song.abs_path) tags["TPE1"] = TPE1(encoding=3, text=u'{}'.format(artist_name)) tags.save(song.abs_path) elif song.path_name.lower().endswith('m4a'): tags = MP4(song.abs_path) raise Exception('Do song info for mp4') db.session.commit() app.logger.info('Update album with artist in db')
def test_add_objects(self): db.connection.drop_database('porchfest_radio_test') add_objects() u1 = User.objects(username='******').first() self.assertIsNotNone(u1) # default user added a1 = Artist.objects(name='Artist 1').first() self.assertIsNotNone(a1) # default artist added
def create_artist(): '''create new artist''' form = ArtistForm() if request.method == "POST": # import ipdb # ipdb.set_trace() if form.validate_on_submit(): artist = Artist( name=form.name.data, genres=",".join(form.genres.data), city=form.city.data, state=form.state.data, phone=form.phone.data, website=form.website.data, facebook_link=form.facebook_link.data, seeking_venue=form.seeking_venue.data, seeking_description=form.seeking_description.data, image_link=form.image_link.data ) db.session.add(artist) db.session.commit() flash('Artist ' + artist.name + ' was successfully listed!') return redirect(url_for('artists')) else: flash("Found errors: {}".format(form.errors)) return render_template('forms/new_artist.html', form=form)
def manageArtistAdd(): """ 新增歌手 """ if request.method == "POST": artistName = request.form.get("artistName") style = request.form.get("style") imgURL = request.form.get("imgURL") isHot = request.form.get("isHot") # 判断歌手是否存在 artist = Artist.query.filter_by(artistName=artistName).first() res = {} if artist: res["status"] = -2 res["message"] = "歌手已经存在" return jsonify(res) # 写入到Artist表 try: artist = Artist( artistName = artistName, style = int(style), imgURL = imgURL, isHot = int(isHot) ) db.session.add(artist) db.session.commit() res["status"] = 1 res["message"] = "新增成功" except Exception as e: res["status"] = -1 res["message"] = "新增失败" return jsonify(res) return render_template("home/manageArtistAdd.html")
def _make_db_artist(artist): db_artist = Artist( id=artist['id'], name=artist['name'], ) db.session.add(db_artist) return db_artist
def json(): """"Method for inital importation of data.""" data = request.data.decode("utf-8") data = loads(data) if data['key'] == app.config['SECRET_KEY']: data = data['data'] for i in data: u = Artist(name=i['name'], life=i['life'], school=i['school'], timeframe=i['timeframe']) db.session.add(u) u = Artist.query.filter_by(name=i['name']).first_or_404() for j in i['art']: a = Art(title=j['title'], date=j['date'], technique=j['technique'], location=j['location'], url=j['url'], form=j['form'], type=j['painting_type'], img_url=j['img'], artist_id=u.id) db.session.add(a) db.session.commit() return "Thanks for the data" else: return "Please provide Auth"
def add_artist_member(artist_name): artist = Artist.objects(name=artist_name).first_or_404() if current_user not in artist.members: flash('You are not authorized to add members to {}'.format( artist.name)) return redirect(url_for('main.artist', artist_name=artist.name)) form = AddArtistMemberForm() if form.validate_on_submit(): for member in artist.members: if form.username.data == member.username: flash('Cannot add a current member to your band!') return render_template('add_artist_member.html', form=form, artist=artist, title='Add Member') new_member = User.objects(username=form.username.data).first() if new_member is None: flash('User with that username does not exist!') return render_template('add_artist_member.html', form=form, artist=artist, title='Add Member') else: add_member(new_member, artist) flash('Added {} to {}'.format(new_member.username, artist.name)) return redirect(url_for('main.artist', artist_name=artist_name)) return render_template('add_artist_member.html', form=form, artist=artist, title='Add Member')
def manageArtistAdd(): ''' 新增歌手 ''' if request.method == "POST": # 提交注册表单 artistName = request.form.get("artistName") style = request.form.get("style") imgURL = request.form.get("imgURL") isHot = request.form.get("isHot") # 判断歌手是否存在 artist = Artist.query.filter_by( artistName=artistName).first() # 获取用户信息 if artist: res = {} res['status'] = -2 res['message'] = '该歌手已存在' return jsonify(res) # 写入到Artist表 try: # 为Artist类属性赋值 artist = Artist(artistName=artistName, style=int(style), imgURL=imgURL, isHot=int(isHot)) db.session.add(artist) # 添加数据 db.session.commit() # 提交数据 res = {} res['status'] = 1 res['message'] = '添加成功' except: res = {} res['status'] = -1 res['message'] = '添加失败' return jsonify(res) return render_template('home/manageArtistAdd.html')
def edit_artist(artist_name): artist = Artist.objects(name=artist_name).first_or_404() if current_user not in artist.members: flash('You are not authorized to edit {}\'s information'.format( artist.name)) return redirect(url_for('main.artist', artist_name=artist.name)) form = EditArtistForm() form.location.choices = [(location.id, location.city + ', ' + location.state) for location in Location.objects()] form.genre.choices = [(genre.id, genre.name) for genre in Genre.objects.order_by('name')] if form.validate_on_submit(): artist.name = form.name.data artist.description = form.description.data artist.location = Location.objects(id=form.location.data).first() artist.genre = [ Genre.objects(id=genre).first() for genre in form.genre.data ] artist.save(cascade=True) flash('{} Edits Complete'.format(artist.name)) return redirect(url_for('main.artist', artist_name=artist.name)) elif request.method == 'GET': form.name.data = artist.name form.description.data = artist.description form.genre.data = [genre.id for genre in artist.genre] form.location.data = artist.location.id return render_template('edit_artist.html', form=form, title='Edit {}'.format(artist.name))
def add_update_db(url): track_id = url[-22:] track_uri = str("spotify:track:") + track_id search = sp.track(track_uri) track_name = search['name'] track_popularity = search['popularity'] duration = search['duration_ms'] explicit = search['explicit'] release_date = search['album']['release_date'] year = release_date[:3] artist_idx = search['artists'][0]['id'] search = sp.artist(artist_idx) genres = json.dumps(search['genres']) artist_name = search['name'] artist_uri = search['uri'] artist_popularity = search['popularity'] search = sp.audio_features(track_id) danceability = search[0]['danceability'] energy = search[0]['energy'] key = search[0]['key'] loudness = search[0]['loudness'] mode = search[0]['mode'] speechiness = search[0]['speechiness'] acousticness = search[0]['acousticness'] instrumentalness = search[0]['instrumentalness'] liveness = search[0]['liveness'] valence = search[0]['valence'] tempo = search[0]['tempo'] x = Artist(id=artist_idx, name=artist_name, uri=artist_uri, genres=genres, popularity=artist_popularity) y = Track(id=track_id, name=track_name, uri=track_uri, popularity=track_popularity, duration=duration, explicit=explicit, release_date=release_date, year=year, artist_id=artist_idx, danceability=danceability, energy=energy, key=key, loudness=loudness, mode=mode, speechiness=speechiness, acousticness=acousticness, instrumentalness=instrumentalness, liveness=liveness, valence=valence, tempo=tempo) sess.merge(x) sess.merge(y) sess.commit()
def get_artist_by_song(song_name): song = Song.objects(name=song_name) if not song: return False artist = Artist.objects(_id=song.get().artist) if not artist: return False return artist
def artist(artist_name): artist = Artist.objects(name=artist_name).first_or_404() shows_for_artist = Show.objects(artist=artist, start_time__gt=datetime.utcnow) return render_template('artist.html', artist=artist, shows=shows_for_artist, title='{} Info'.format(artist.name))
def create_artist(name): artist = Artist.query.filter_by(name=name).first() if artist is None: artist = Artist(name=name) db.session.add(artist) db.session.commit() click.echo("The artist {} has been created!".format(name)) else: click.echo("The artist {} was used!".format(name))
def create_data(): for i in range(100): db.session.add(Artist()) for j in range(1000): date = datetime.date.today() - datetime.timedelta(j) value = (1000 - j) / (i + 1) db.session.add( Metric(artist_id=i + 1, date=date, value=value)) db.session.commit()
def get_artist_tracklist(artist_name): artist = Artist.objects(name=artist_name) if not artist: return False artist_id = artist.get().id tracklist = Song.objects(artist=artist_id) if not tracklist: raise False return tracklist
def test_show_up_artists_list_lyrics(self): a1 = Artist('ARTIST 1', self.user.get_id()) db.session.add(a1) db.session.commit() al1 = Album('album 1', datetime.now(), self.user.get_id(), a1.get_id()) al2 = Album('album 2', datetime.now(), self.user.get_id(), a1.get_id()) db.session.add_all([al1, al2]) db.session.commit() l1 = Lyric('song to test 1', '', self.user.get_id(), al1.get_id()) l2 = Lyric('song to test 2', '', self.user.get_id(), al2.get_id()) db.session.add_all([l1, l2]) db.session.commit() response = self.client.get('/artist/artist1') self.assertIn(b'Flask Lyrics - artist 1', response.data) self.assertIn(b'album 1', response.data) self.assertIn(b'album 2', response.data) self.assertIn(b'song to test 1', response.data) self.assertIn(b'song to test 2', response.data)
def reset_db(): flash( "Resetting database: deleting old data and repopulating with dummy data" ) meta = db.metadata for table in reversed(meta.sorted_tables): print('Clear table {}'.format(table)) db.session.execute(table.delete()) db.session.commit() artist1 = Artist(name="Drake", description="Soon to be added") artist2 = Artist(name='Kendrick Lamar', description="Added after Drake") venue1 = Venues(location='Baltimore Soundstage, Maryland', date='01/24/2018') venue2 = Venues(location='The 20th Century Theater, Ohio', date='04/28/2018') venue3 = Venues(location='The New Parish, California', date='04/29/2018') event1 = Events(name='Aubrey & The Three Migos ', price='$350', venue_id=1, event_date=datetime.utcnow()) event2 = Events(name='Leeds Festival 2018', price='$170', venue_id=2, event_date=datetime.utcnow()) a2e = ArtistToEvent(Artist_id=1, Event_id=1) a2e1 = ArtistToEvent(Artist_id=2, Event_id=2) db.session.add(artist1) db.session.add(artist2) db.session.add(venue1) db.session.add(venue2) db.session.add(venue3) db.session.add(event1) db.session.add(event2) db.session.add(a2e) db.session.add(a2e1) db.session.commit() return redirect(url_for('index'))
def populate_database(session): artist = Artist() artist.name = "Test Artist" artist.spotify_uri = "spotify:artist:arn" session.add(artist) album = Album() album.name = "Test Album" album.artists.append(artist) album.spotify_uri = "spotify:album:arn" session.add(album) media = Media() media.tmdb_id = "TMDB_ID" media.name = "Test media" media.type = 1 session.add(media) session.commit()
def search_artists(): search_term = request.form.get('search_term', '') artists = Artist.get_artists_by_partial_name(search_term) response = { "count": len(artists), "data": [artist.summary for artist in artists] } return render_template('pages/search_artists.html', results=response, search_term=search_term)
def newArtists(): form = NewArtistForm() if form.validate_on_submit(): flash('Artist info entered for name {}'.format( form.name.data, form.hometown.data, form.description.data)) a = Artist(name=form.name.data, hometown=form.hometown.data) db.session.add(a) db.session.commit() return redirect(url_for("artists")) return render_template('newArtists.html', title='New Artists', form=form)
def unfollow_artist(artist_name): artist = Artist.objects(name=artist_name).first_or_404() user = User.objects(username=current_user.username).first() if artist is None: flash('Artist {} does not exist!'.format(artist_name)) elif current_user not in artist.followers: flash('You are not currently following {}'.format(artist.name)) else: unfollow_band(user, artist) flash('Successfully unfollowed {}'.format(artist.name)) return redirect(url_for('main.artist', artist_name=artist.name))
def test_get_one(server): with server.app_context(): artist = Artist("a") db.session.add(artist) db.session.commit() assert Artist.query.count() == 1 r = requests.get(server.url + "/artist/{}".format(artist.id)) assert r.status_code == 200 assert r.json()['name'] == artist.name
def add_artist(self, **kwargs): artist_name = kwargs['title'][0] artist = Artist.objects(name=artist_name) if artist.count(): Log(type_added='artist', name_added=artist_name).save() return False self.download(kwargs.get('img')) artist = Artist(name=artist_name) if artist: Log(type_added='artist', name_added=artist_name, added=True).save() with open(TEMP_FILE, 'rb') as binary_file: artist.image.put(binary_file) shutil.rmtree(TEMP) artist.save() return True Log(type_added='artist', name_added=artist_name).save() return False
def enterartist(): form = ArtistForm() if form.validate_on_submit(): artist = Artist(artistname=form.artistname.data, artistlogo=form.artistlogo.data) db.session.add(artist) db.session.commit() flash('You Submitted {}'.format(form.artistname.data)) return redirect('/music') return render_template('enter_artist.html', title='Music', form=form)
def test_get_many(server, arguments, names): with server.app_context(): for name in ("a", "b", "c"): db.session.add(Artist(name)) db.session.commit() r = requests.get(server.url + "/artists?{}".format(urlencode(arguments))) assert r.status_code == 200 items = r.json() assert len(items) == len(names) assert list(map(lambda x: x["name"], items)) == names
def artists_by_letter(letter): if len(letter) == 1 and letter.isalpha(): artists = Artist.get_artists_by_letter(letter) left = [] right = [] for i, artist in enumerate(artists): if i % 2 == 0: left.append(artist) else: right.append(artist) return render_template('artists.html', title='Flask Lyrics - Artists', left=left, right=right, letter=letter) return redirect(url_for('home.home_'))
from app import app, login_manager