def add_show(id): zipped = requests.get("%s/%s/series/%s/all/en.zip" % (API_PATH, settings.TVDB_API_KEY, id)).content content = zipfile.ZipFile(BytesIO(zipped)).read("en.xml") xml = etree.fromstring(content) series = xml.find("Series") name = series.find("SeriesName").text banner = series.find("banner") if banner is None: banner = "" else: banner = banner.text status = series.find("Status").text first_aired = series.find("FirstAired") if first_aired is not None: first_aired = datetime.strptime(first_aired.text, "%Y-%m-%d") imdb = series.find("IMDB_ID") if imdb is None: imdb = "" else: imdb = imdb.text try: show = Show.objects.get(tvdbid=id) show.tvdbid = id show.name = name show.status = status show.banner = banner show.first_aired = first_aired show.imdb = imdb except Show.DoesNotExist: show = Show(tvdbid=id, name=name, status=status, banner=banner, first_aired=first_aired, imdb=imdb) show.save() for e in xml.findall("Episode"): season_number = e.find("SeasonNumber").text if season_number == "0": # Ignore specials for now continue try: season = Season.objects.get(show=show, number=season_number) except Season.DoesNotExist: season = Season(number=season_number, show=show) season.save() episode_number = e.find("EpisodeNumber").text first_aired = datetime.strptime(e.find("FirstAired").text, "%Y-%m-%d") try: episode = Episode.objects.get(number=episode_number, season=season) episode.air_date = first_aired except Episode.DoesNotExist: episode = Episode(number=episode_number, air_date=first_aired, season=season) episode.save() return show
def calc_ip_show_update_count(count): format_time = datetime.now().strftime("%Y-%m-%d") show = db.session.query(Show).filter_by(format_time=format_time, type='ip').first() if show: show.update_of_count = show.update_of_count + count else: try: show = Show() show.type = 'ip' show.update_of_count = count except Exception as e: logger.warning("计算展示数据更新次数出错" + str(e)) safe_commit(show)
def create_show_submission(): error = False data = request.form try: venue = Venue.query.filter_by(id=data['venue_id']).first() except: error = True flash(f'There is no venue with ID {data["venue_id"]}', 'alert-danger') try: artist = Artist.query.filter_by(id=data['artist_id']).first() except: error = True flash(f'There is no artist with ID {data["artist_id"]}', 'alert-danger') try: starttime = data['start_time'] show = Show(venue=venue, artist=artist, starttime=str(starttime)) print(show) db.session.add(show) db.session.commit() except: error = True flash('Something went wrong. Maybe an invalid start time?', 'alert-danger') finally: db.session.close() if not error: flash('Show was successfully listed!', 'alert-success') return render_template('pages/home.html')
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_show_submission(): try: data = request.form show = Show(artist_id=data['artist_id'], venue_id=data['venue_id'],start_time=data['start_time']) db.session.add(show) db.session.commit() flash('Show was successfully listed!') except: flash('An error occurred. Show could not be listed.') finally: return render_template('pages/home.html')
def create_show_submission(): form = ShowForm() try: show = Show() show.artist_id = form.artist_id.data show.venue_id = form.venue_id.data show.start_time = form.start_time.data db.session.add(show) db.session.commit() # on successful db insert, flash success flash('Show was successfully listed!') except: db.session.rollback() flash('An error occurred. Show could not be listed.') finally: db.session.close() # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/ return render_template('pages/home.html')
def quickadd(): """ Functionality to quickly add a tv show or movie by clicking a button. """ # Retrieve show/movie title and whether it actually is a tv show or movie id = request.form.get('id') type = request.form.get('type') # Search for the show/movie and store the result result = search_by_id(id, type) # Create and add the show/movie if type == 'tv': show_present = Show.query.filter_by(show_id=id, user_id=current_user.id).first() if show_present: flash('Show already in your list!', 'error') return redirect('/index') new_show = Show(show_id=result['id'], show_name=result['name'], user_id=current_user.id) db.session.add(new_show) db.session.commit() flash('Added show successfully!', 'success') else: movie_present = Movie.query.filter_by(movie_id=id, user_id=current_user.id).first() if movie_present: flash('Movie already in your list!', 'error') return redirect('/index') new_movie = Movie(movie_id=result['id'], movie_name=result['title'], user_id=current_user.id) db.session.add(new_movie) db.session.commit() flash('Added movie successfully!', 'success') # Return home return redirect('/index')
def search(): if not g.search_form.validate(): return redirect(url_for('index')) page = request.args.get('page', 1, type=int) posts, total = Show.search(g.search_form.q.data, page, app.config['SHOWS_PER_PAGE']) next_url = url_for('search', q=g.search_form.q.data, page=page + 1) \ if total > page * app.config['SHOWS_PER_PAGE'] else None prev_url = url_for('search', q=g.search_form.q.data, page=page - 1) \ if page > 1 else None return render_template('search.html', title='Search', shows=posts, next_url=next_url, prev_url=prev_url)
def create_show(): '''submits show form to database''' form = ShowForm() if request.method == 'POST': if form.validate_on_submit(): show = Show( artist_id=form.artist_id.data, venue_id=form.venue_id.data, start_time=form.start_time.data) print('------ {0}'.format(request.form)) db.session.add(show) db.session.commit() flash('Show was successfully listed!') return redirect(url_for('shows')) else: flash("Found errors: {}".format(form.errors)) return render_template('forms/new_show.html', form=form)
def loadData(): dir = os.path.dirname(__file__) list = pd.read_csv(dir + "/data/animes.csv", header=0, usecols=["title", "synopsis", "genre", "img_url"]) list_clean = list.drop_duplicates(subset=["title"]) for anime in list_clean.itertuples(index=False, name=None): genres = ast.literal_eval(anime[2]) genres = [n.strip() for n in genres] animeShow = Show(title=anime[0], description=anime[1], genre=genres, image=anime[3], type="anime") db.session.add(animeShow) db.session.commit() return redirect(url_for('index'))
def create_action(kwargs={}): """Creates a Show""" try: if not kwargs: form = ShowForm(request.form) venue = Venue().query.filter( Venue.name == form.venue_id.data).first() artist = Artist().query.filter( Artist.name == form.artist_id.data).first() kwargs = { "venue_id": venue.id, "artist_id": artist.id, "start_time": datetime.datetime.strptime( "{} {}".format(request.form.get('start_date', ''), request.form.get('start_time', '')), "%b %d, %Y %H:%M %p") } model = Show(**kwargs) db.session.add(model) db.session.commit() flash('Show was successfully listed') return redirect(url_for('show.list_page', venue_id=model.id)) except: flash('Whoops. Show could not be listed.') return redirect(url_for('show.create_form_page'))
def add_objects(): times = [ datetime(2019, 6, 26, 9, 0, 0), # start for porchfests datetime(2019, 6, 26, 17, 0, 0), # end for porchfests datetime(2019, 6, 26, 12, 0, 0), # first show end time datetime(2019, 6, 26, 15, 0, 0) # second show end time ] default_users = [ User(username='******', email='*****@*****.**', name='Ithaca One', member_of=[], follows=[]), User(username='******', email='*****@*****.**', name='Ithaca Two', member_of=[], follows=[]), User(username='******', email='*****@*****.**', name='Ithaca Three', member_of=[], follows=[]), User(username='******', email='*****@*****.**', name='Albany One', member_of=[], follows=[]) ] for user in default_users: user.set_password('default') user.save(cascade=True) default_locations = [ Location(city='Ithaca', state='NY', zip_code='14850'), Location(city='Albany', state='NY', zip_code='12203'), ] for location in default_locations: location.save(cascade=True) default_porches = [ Porch(name='Ithaca Porch 1', email='*****@*****.**', address='953 Danby Rd', location=Location.objects(city='Ithaca', state='NY').first(), time_slots=[times[2], times[3]]), Porch(name='Ithaca Porch 2', email='*****@*****.**', address='123 Ithaca Rd', location=Location.objects(city='Ithaca', state='NY').first(), time_slots=[times[0], times[1], times[3]]), Porch(name='Albany Porch 1', email='*****@*****.**', address='1200 Western Ave', location=Location.objects(city='Albany', state='NY').first(), time_slots=[times[0], times[1], times[2], times[3]]) ] for porch in default_porches: porch.save(cascade=True) default_artists = [ Artist(name='Artist 1', description='artist 1 desc', location=Location.objects(city='Ithaca', state='NY').first()), Artist(name='Artist 2', description='artist 2 desc', location=Location.objects(city='Ithaca', state='NY').first()), Artist(name='Artist 3', description='artist 3 desc', location=Location.objects(city='Albany', state='NY').first()) ] for artist in default_artists: artist.save(cascade=True) default_shows = [ Show(artist=Artist.objects(name='Artist 1').first(), porch=Porch.objects(name='Ithaca Porch 1').first(), start_time=times[0], end_time=times[2]), Show(artist=Artist.objects(name='Artist 2').first(), porch=Porch.objects(name='Ithaca Porch 2').first(), start_time=times[2], end_time=times[3]), Show(artist=Artist.objects(name='Artist 3').first(), porch=Porch.objects(name='Albany Porch 1').first(), start_time=times[0], end_time=times[2]) ] for show in default_shows: show.save(cascade=True) default_porchfests = [ Porchfest(location=Location.objects(city='Ithaca', state='NY').first(), start_time=times[0], end_time=times[1], porches=[ Porch.objects(name='Ithaca Porch 1').first(), Porch.objects(name='Ithaca Porch 2').first() ], shows=[ Show.objects(artist=Artist.objects( name='Artist 1').first()).first(), Show.objects(porch=Porch.objects( name='Ithaca Porch 2').first()).first() ]), Porchfest(location=Location.objects(city='Albany', state='NY').first(), start_time=times[0], end_time=times[1], porches=[Porch.objects(name='Albany Porch 1').first()], shows=[ Show.objects(artist=Artist.objects( name='Artist 3').first()).first() ]) ] for porchfest in default_porchfests: porchfest.save(cascade=True)
def seed_shows(): locations = [ '196 Allen St, New York, NY 10002', '541 6th Ave, New York, NY 10011', '407 W 15th St, New York, NY 10011', '147 Bleecker St, New York, NY 10012', '251 W 30th St, New York, NY 10001', '519 2nd Ave, New York, NY 10016', '1650 Broadway, New York, NY 10019', '212 E 52nd St, New York, NY 10022', '44 E 32nd St, New York, NY 10016', '85 Avenue A, New York, NY 10009', '6 Delancey St, New York, NY 10002', '317 E Houston St, New York, NY 10002', '217 E Houston St, New York, NY 10002', '188 Avenue B, New York, NY 10009', '2 6th Avenue The Roxy Hotel, Cellar Level, New York, NY 10013', '277 Church St # A, New York, NY 10013', '25 N Moore St, New York, NY 10013', '25 Cedar St, New York, NY 10005', '160 Pearl St #1, New York, NY 10005', '54 Pearl St, New York, NY 10004', '361 Metropolitan Ave, Brooklyn, NY 11211', '45 S 3rd St, Brooklyn, NY 11249', '367 Bedford Ave, Brooklyn, NY 11211', '152 Metropolitan Ave, Brooklyn, NY 11211', '2 Havemeyer St, Brooklyn, NY 11211', '208 W 4th St suite c, Austin, TX 78701', 'Swift Building, 315 Congress Ave, Austin, TX 78701', '1308 E 4th St, Austin, TX 78702', '912 Red River St, Austin, TX 78701', '2247 Guadalupe St, Austin, TX 78712', ] locations_lats_lngs = [] for location in locations: maps_api_key = os.environ.get('REACT_APP_API_KEY_GOOGLE_MAPS') url = 'https://maps.googleapis.com/maps/api/geocode/json?' params = {'key': maps_api_key, 'address': location} r = requests.get(url =url, params = params) response = r.json()['results'][0]['geometry']['location'] lat, lng = response['lat'], response['lng'] locations_lats_lngs.append((lat, lng)) artist_ids = [] for value in Artist.query.all(): artist_ids.append(value.id) artist_num = 0 location_num = 0 # A year's worth of fake shows for day in range(365): # 3 shows per day for i in range(8): # book artist_num at location_num # print(datetime.date(datetime.now() + 7)) date_and_time = datetime.date(datetime.now()) time_change = timedelta(day) show_date = date_and_time + time_change # Mixes up the show times and cost. The variance looks nice hours = 20 mins = 0 cost = 0 if (i % 3) == 0: mins = 30 hours = 20 cost = 10 elif (i % 3) == 1: mins = 30 hours = 19 cost = 20 show_time = time(hours, mins, 0) new_show = Show( address = locations[location_num], location_lat = locations_lats_lngs[location_num][0], location_lng = locations_lats_lngs[location_num][1], date = show_date, time = show_time, cost = cost, description = 'It\'s gonna be a great show, as per usual. Hope to see you there!', artist_id = artist_ids[artist_num] ) db.session.add(new_show) # Cycle through the artists if artist_num == len(artist_ids) -1: artist_num = 0 else: artist_num += 1 # Cycle through the locations if location_num == len(locations) -1: location_num = 0 else: location_num += 1 db.session.commit()
def admin_shows(): form = ShowForm() shows = db.session.query(Show).all() if form.validate_on_submit(): show = Show() show.title = form.title.data show.slug = form.title.data.translate(translate).replace(' ', '-').lower() show.user_id = current_user.id show.timestamp = form.timestamp.data show.location = form.location.data show.url = form.url.data show.details = form.details.data if form.url.data is not None: show.venue = '<a href="{}" alt="{}" title="{}">{}</a>'.format( form.url.data, form.title.data, form.title.data, form.title.data) else: show.venue = show.location if form.featured_image.data is not None: show.featured_image = upload_file('featured_image', 'post') message = Markup( '<div class="alert alert-success alert-dismissible"><button type="button" class="close" data-dismiss="alert">×</button> {} was posted on the front page</div>' .format(form.title.data)) db.session.add(show) db.session.commit() flash(message) return redirect(url_for('admin_shows')) return render_template('admin/shows.html', form=form, shows=shows)
def seed_db(): with open('shows.csv', newline='') as csvfile: showsreader = csv.DictReader(csvfile) for row in showsreader: venue_query = Venue.query.filter_by(name=row['venue']).first() if venue_query != None: venue_id = venue_query.id else: venue_name = row['venue'][:279] venue = {'name': venue_name} place_req = requests.get( "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=29.9511,-90.0715&rankby=distance&keyword={}&key={}" .format(venue_name, os.environ['GOOGLE_API_KEY'])) try: json = place_req.json() venue['lat'] = json['results'][0]['geometry']['location'][ 'lat'] venue['lng'] = json['results'][0]['geometry']['location'][ 'lng'] except Exception: pass venue_model = Venue(**venue) db.session.add(venue_model) db.session.commit() venue_id = venue_model.id artist_query = Artist.query.filter_by( name=row['performer']).first() if artist_query != None: artist_id = artist_query.id else: artist_name = row['performer'][:279] artist = {'name': artist_name} artist_req = requests.get( "https://www.googleapis.com/youtube/v3/search?maxResults=1&part=snippet&type=video&q={}&key={}" .format(artist_name, os.environ['GOOGLE_API_KEY'])) try: json = artist_req.json() artist[ 'preview_video_url'] = "https://www.youtube.com/watch?v={}".format( json['items'][0]['id']['videoId']) artist['preview_video_thumbnail'] = json['items'][0][ 'snippet']['thumbnails']['medium']['url'] except Exception: pass artist_model = Artist(**artist) db.session.add(artist_model) db.session.commit() artist_id = artist_model.id date_arr = row['date'].split('-') year = int(date_arr[0]) month = int(date_arr[1]) day = int(date_arr[2]) date_obj = datetime.date(year, month, day) time_arr = row['time'].split(':') hour = int(time_arr[0]) minute = int(time_arr[1][:2]) am_or_pm = time_arr[1][-2:] if am_or_pm == "pm": if hour < 12: hour = hour + 12 else: hour = 0 time_obj = datetime.time(hour, minute) show_model = Show(artist_id=artist_id, venue_id=venue_id, date=date_obj, time=time_obj) db.session.add(show_model) db.session.commit() print(row['date']) click.echo('hey!')
def save_to_db(self): if self.id.data: # edit show = Show.query.get(int(self.id.data)) else: show = Show() show.name = self.name.data show.short_description = self.short_description.data show.description = self.description.data show.email = self.email.data show.facebook = self.facebook.data show.instagram = self.instagram.data show.twitter = self.twitter.data show.members = list(map(lambda member_id: Member.query.get(int(member_id)), self.members.data)) if self.show_logo.data: show.logo = upload(self.show_logo.data) db.session.add(show) db.session.commit()
def artistFestSignUp(): form = ArtistPorchfestSignUpForm() porchfests = Porchfest.objects() form.porchfest.choices = [(str(p.id), p.location.city + ", " + p.location.state+" "+p.start_time.strftime("%m-%d-%Y %H:%M")+" to "+p.end_time.strftime("%m-%d-%Y %H:%M")) for p in porchfests] form.porch_selector.choices = [('None', '')] + [(str(p.id), p.address + " " + p.location.city + ", " + p.location.state) for p in Porch.objects()] form.time_slot.choices = [(t, t) for t in get_all_hours()] if form.validate_on_submit(): porchfest = Porchfest.objects(id=form.porchfest.data).first() porchfest_location = porchfest.location porchfest_time = porchfest.start_time form_time = form.time_slot.data hour_int = int(form_time.split()[0]) if 'AM' in form_time: if hour_int is 12: hour = 0 else: hour = hour_int else: if hour_int is 12: hour = hour_int else: hour = hour_int + 12 start_time = datetime(year=int(porchfest_time.year), month=int(porchfest_time.month), day=int(porchfest_time.day), hour=hour) end_time = start_time + timedelta(hours=1) artist = Artist.objects(name=current_user.name).first() if form.porch.data: location = Location.objects(city=form.city.data, state=form.state.data).first() if location is None: location = Location(city=form.city.data, state=form.state.data, zip_code=form.zip.data) location.save(cascade=True) porch = Porch.objects(address=form.address.data).first() if porch is None: time_slots = [] address = form.address.data.split(' ') reqStr = "https://maps.googleapis.com/maps/api/geocode/json?address=" for i in address: reqStr = reqStr + i + "+" reqStr = reqStr[:-1] reqStr = reqStr + location.city + ",+" + location.state + "&key=" + app.config['GOOGLEMAPS_KEY'] res = requests.get(reqStr) resJSON = res.json() data = resJSON['results'][0] lat = data['geometry']['location']['lat'] long = data['geometry']['location']['lng'] porch = Porch(name=form.porch_owner.data, email=form.porch_email.data, address=form.address.data, location=location, time_slots=time_slots, lat=str(lat), long=str(long)) porch.save(cascade=True) else: porch = Porch.objects(id=form.porch_selector.data).first() porch.time_slots.remove(start_time) porch.save(cascade=True) existing_show_for_artist = Show.objects(artist=artist, start_time=start_time).first() existing_show_for_porch = Show.objects(porch=porch, start_time=start_time).first() if existing_show_for_artist is not None or existing_show_for_porch is not None: flash('Show already exists!') else: show = Show(artist=artist, porch=porch, start_time=start_time, end_time=end_time) show.save(cascade=True) porchfest.shows.append(show) porchfest.save(cascade=True) flash('Signed up for ' + porchfest_location.city + ", " + porchfest_location.state + " porchfest!") return redirect(url_for('artist', artist_name=artist.name)) return render_template('artistToPorch.html', form=form)
def reset_db(): db.connection.drop_database('porchfestBAG') for location in Location.objects: location.delete() for artist in Artist.objects: artist.delete() for porch in Porch.objects: porch.delete() for fest in Porchfest.objects: fest.delete() for show in Show.objects: show.delete() times = [ datetime(2018, 12, 26, 9, 0, 0), # start for porchfests datetime(2018, 12, 26, 17, 0, 0), # end for porchfests datetime(2018, 12, 26, 12, 0, 0), # first show end time datetime(2018, 12, 26, 15, 0, 0) # second show end time ] default_locations = [ Location(city='Ithaca', state='NY', zip_code='14850'), Location(city='Binghamton', state='NY', zip_code='13901'), Location(city='Albany', state='NY', zip_code='12203'), Location(city='Winchester', state='MA', zip_code='01890') ] for location in default_locations: location.save(cascade=True) default_porches = [ Porch(name='Ithaca Porch 1', email='*****@*****.**', address='953 Danby Rd', location=Location.objects(city='Ithaca', state='NY').first(), time_slots=[times[2], times[3]], lat='42.4199351', long='-76.4969643'), Porch(name='Ithaca Porch 2', email='*****@*****.**', address='123 Ithaca Rd', location=Location.objects(city='Ithaca', state='NY').first(), time_slots=[times[0], times[1], times[3]], lat='42.438657', long='-76.4800496'), Porch(name='Albany Porch 1', email='*****@*****.**', address='501 Hudson Ave', location=Location.objects(city='Albany', state='NY').first(), time_slots=[times[0], times[1], times[3]], lat='42.662079', long='-73.780703'), ] for porch in default_porches: porch.save(cascade=True) default_artists = [ Artist(email='*****@*****.**', name='Artist 1', description='artist 1 desc', media_links=['https://www.spotify.com/artist1'], location=Location.objects(city='Ithaca', state='NY').first(), image='https://miquon.org/wp-content/uploads/2016/02/GenericUser.png'), Artist(email='*****@*****.**', name='Artist 2', description='artist 2 desc', media_links=['https://myspotify.com'], location=Location.objects(city='Albany', state='NY').first()) ] for artist in default_artists: artist.set_password('default') artist.save(cascade=True) default_shows = [ Show(artist=Artist.objects(name='Artist 1').first(), porch=Porch.objects(name='Ithaca Porch 1').first(), start_time=times[0], end_time=times[2]), Show(artist=Artist.objects(name='Artist 1').first(), porch=Porch.objects(name='Ithaca Porch 2').first(), start_time=times[2], end_time=times[3]), Show(artist=Artist.objects(name='Artist 2').first(), porch=Porch.objects(name='Albany Porch 1').first(), start_time=times[2], end_time=times[3]) ] for show in default_shows: show.save(cascade=True) default_porchfests = [ Porchfest(location=Location.objects(city='Ithaca', state='NY').first(), start_time=times[0], end_time=times[1], porches=[Porch.objects(name='Ithaca Porch 1').first(), Porch.objects(name='Ithaca Porch 2').first()], shows=[Show.objects(artist=Artist.objects(name='Artist 1').first()).first(), Show.objects(porch=Porch.objects(name='Ithaca Porch 2').first()).first()], lat='42.4440', long='-76.5019'), Porchfest(location=Location.objects(city='Binghamton', state='NY').first(), start_time=times[0], end_time=times[1], lat='42.0987', long='-75.9180'), Porchfest(location=Location.objects(city='Albany', state='NY').first(), start_time=times[0], end_time=times[1], lat='42.6526', long='-73.7562', shows=[Show.objects(porch=Porch.objects(name='Albany Porch 1').first()).first()]) ] for porchfest in default_porchfests: porchfest.save(cascade=True) flash("Database has been reset!") return redirect(url_for('index'))
def update_db(time_delta_value): date_to_remove = Show.query.order_by(Show.date).first().date Show.query.filter(Show.date == date_to_remove).delete() db.session.commit() date_obj = (datetime.date.today() + datetime.timedelta(time_delta_value)) date = date_obj.strftime('%Y-%m-%d') search_path = "https://www.wwoz.org/calendar/livewire-music?date={}".format( date) req = requests.get(search_path) page = req.text soup = BeautifulSoup(page, 'html.parser') music_events = [] venues = soup.select(".livewire-listing .panel.panel-default") for v in venues: for listing in v.select(".row"): time.sleep(1) venue_name = v.select('.panel-title')[0].text.strip()[:279] artist_name = listing.select( ".calendar-info p")[0].text.strip()[:279] time_arr = listing.select( ".calendar-info p")[-1].text.strip().split(' ')[-1].split(":") venue_query = Venue.query.filter_by(name=venue_name).first() if venue_query != None: venue_id = venue_query.id else: venue_name = venue_name venue = {'name': venue_name} place_req = requests.get( "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=29.9511,-90.0715&rankby=distance&keyword={}&key={}" .format(venue_name, os.environ['GOOGLE_API_KEY'])) try: json = place_req.json() venue['lat'] = json['results'][0]['geometry']['location'][ 'lat'] venue['lng'] = json['results'][0]['geometry']['location'][ 'lng'] except Exception: pass venue_model = Venue(**venue) db.session.add(venue_model) db.session.commit() venue_id = venue_model.id artist_query = Artist.query.filter_by(name=artist_name).first() if artist_query != None: artist_id = artist_query.id else: artist_name = artist_name artist = {'name': artist_name} artist_req = requests.get( "https://www.googleapis.com/youtube/v3/search?maxResults=1&part=snippet&type=video&q={}&key={}" .format(artist_name, os.environ['GOOGLE_API_KEY'])) try: json = artist_req.json() artist[ 'preview_video_url'] = "https://www.youtube.com/watch?v={}".format( json['items'][0]['id']['videoId']) artist['preview_video_thumbnail'] = json['items'][0][ 'snippet']['thumbnails']['medium']['url'] except Exception: pass artist_model = Artist(**artist) db.session.add(artist_model) db.session.commit() artist_id = artist_model.id hour = int(time_arr[0]) minute = int(time_arr[1][:2]) am_or_pm = time_arr[1][-2:] if am_or_pm == "pm": if hour < 12: hour = hour + 12 else: hour = 0 time_obj = datetime.time(hour, minute) show_model = Show(artist_id=artist_id, venue_id=venue_id, date=date_obj, time=time_obj) db.session.add(show_model) db.session.commit() print(date) for artist in db.session.query(Artist).join( Show, isouter=True).group_by(Artist).having(func.count(Show.id) < 1): db.session.delete(artist) db.session.commit() click.echo('hey!')