-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
701 lines (570 loc) · 20.7 KB
/
app.py
File metadata and controls
701 lines (570 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#
import json
import dateutil.parser
import babel
from flask import Flask, render_template, request, Response, flash, redirect, url_for, abort
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandler
from flask_wtf import Form
from forms import *
from models import db, Venue, Artist, Show
from flask_migrate import Migrate
import sys
#----------------------------------------------------------------------------#
# Application Configuration.
#----------------------------------------------------------------------------#
app = Flask(__name__)
moment = Moment(app)
# connect to a local database
app.config.from_object('config')
db.init_app(app)
migrate = Migrate(app, db)
#----------------------------------------------------------------------------#
# Filters.
#----------------------------------------------------------------------------#
def format_datetime(value, format='medium'):
date = dateutil.parser.parse(value)
if format == 'full':
format="EEEE MMMM, d, y 'at' h:mma"
elif format == 'medium':
format="EE MM, dd, y h:mma"
return babel.dates.format_datetime(date, format, locale='en')
app.jinja_env.filters['datetime'] = format_datetime
#----------------------------------------------------------------------------#
# Controllers.
#----------------------------------------------------------------------------#
@app.route('/')
def index():
return render_template('pages/home.html')
def getLocations():
registeredLocations = Venue.query.with_entities(Venue.state, Venue.city, Venue.name, Venue.phone).distinct().all()
return registeredLocations
def formatLocation():
return
# Venues
# ----------------------------------------------------------------
@app.route('/venues')
def venues():
# TODO: replace with real venues data.
data = []
registeredLocations = getLocations()
city = None
state = None
venues = None
for registeredLocation in registeredLocations:
city = registeredLocation.city
state = registeredLocation.state
venues = Venue.query.filter_by(city=city, state=state).all()
venuesDetails = []
for venue in venues:
venueDetail = {
'id': venue.id,
'name': venue.name,
}
venuesDetails.append(venueDetail)
details = {
"city": city,
"state": state,
"venues": venuesDetails,
"num_upcoming_shows": 1
}
data.append(details)
return render_template('pages/venues.html', areas=data);
def returnSerchVenueresult(search_term):
venues = Venue.query.filter(Venue.name.ilike('%' + search_term + '%'))
return venues
@app.route('/venues/search', methods=['POST'])
def search_venues():
# TODO: implement search on artists with partial string search. Ensure it is case-insensitive.
search_term = request.form.get('search_term', '').strip()
venues = returnSerchVenueresult(search_term)
data = []
for venue in venues:
venueDet = {
"id": venue.id,
"name": venue.name,
"num_upcoming_shows": venue.num_upcoming_shows
}
data.append(venueDet)
response = {
"count": len(data),
"data": data
}
# return render_template('pages/search_venues.html', results=response, search_term=request.form.get('search_term', ''))
return render_template('pages/search_venues.html', results=response, search_term=search_term)
def getVenueById(venue_id):
return Venue.query.get(venue_id)
def getArtistById(artist_id):
return Artist.query.get(artist_id)
def getSearchDetailForVenue(venue, pastEvents, upcoming_shows):
return {
"id": venue.id,
"name": venue.name,
"genres": venue.genres,
"address": venue.address,
"city": venue.city,
"past_shows": pastEvents,
"upcoming_shows": upcoming_shows,
"past_shows_count": venue.num_past_shows,
"upcoming_shows_count": venue.num_upcoming_shows,
"state": venue.state,
"phone": venue.phone,
"website": venue.website_link,
"past_shows": pastEvents,
"upcoming_shows": upcoming_shows,
"facebook_link": venue.facebook_link,
"seeking_talent": True if venue.seeking_talent in (True, 't', 'True', 'y') else False,
"seeking_description": venue.seeking_description,
"image_link": venue.image_link if venue.image_link else "",
"upcoming_shows_count": venue.num_upcoming_shows,
}
@app.route('/venues/<int:venue_id>')
def show_venue(venue_id):
# shows the venue page with the given venue_id
# TODO: replace with real venue data from the venues table, using venue_id
venue = getVenueById(venue_id)
if not venue:
flash("Given venue with the given Id does not exist", category='error')
return redirect(url_for('venues'))
pastEvents = []
for show in venue.past_shows:
artist = getArtistById(show.artist_id)
artistInfo = {
"artist_id": show.artist_id,
"artist_name": artist.name,
"artist_image_link": artist.image_link,
"start_time": str(show.start_time)
}
pastEvents.append(artistInfo)
upcoming_shows = []
for show in venue.upcoming_shows:
artist = getArtistById(show.artist_id)
artistInfo = {
"artist_name": artist.name,
"artist_image_link": artist.image_link,
"artist_id": show.artist_id,
"start_time": str(show.start_time)
}
upcoming_shows.append(artistInfo)
data = getSearchDetailForVenue(venue, pastEvents, upcoming_shows)
return render_template('pages/show_venue.html', venue=data)
# Create Venue
# ----------------------------------------------------------------
@app.route('/venues/create', methods=['GET'])
def create_venue_form():
form = VenueForm()
return render_template('forms/new_venue.html', form=form)
def createVenueRecord(
name,
city,
state,
address,
phone,
genres,
facebook_link,
image_link,
website_link,
seeking_talent,
seeking_description):
error = False
try:
venue = Venue(
name=name,
city=city,
state=state,
address=address,
phone=phone,
genres=genres,
facebook_link=facebook_link,
image_link=image_link,
website_link=website_link,
seeking_talent=seeking_talent,
seeking_description=seeking_description,
)
db.session.add(venue)
db.session.commit()
except:
error = True
db.session.rollback()
print(sys.exc_info())
abort(400)
finally:
db.session.close()
if error:
abort (400)
else:
# on successful db insert, flash success
flash('Venue ' + request.form['name'] + ' was successfully listed!')
return render_template('pages/home.html')
@app.route('/venues/create', methods=['POST'])
def create_venue_submission():
name=request.form['name']
city=request.form['city']
state=request.form['state']
address=request.form['address']
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_talent=request.form['seeking_talent']
seeking_description=request.form['seeking_description']
return createVenueRecord(
name,
city,
state,
address,
phone,
genres,
facebook_link,
image_link,
website_link,
seeking_talent,
seeking_description
)
@app.route('/venues/<venue_id>', methods=['DELETE'])
def delete_venue(venue_id):
# TODO: Complete this endpoint for taking a venue_id, and using
# SQLAlchemy ORM to delete a record. Handle cases where the session commit could fail.
# BONUS CHALLENGE: Implement a button to delete a Venue on a Venue Page, have it so that
# clicking that button delete it from the db then redirect the user to the homepage
return None
def getArtistList():
return Artist.query.with_entities(Artist.id, Artist.name).all()
def formatArtist(allArtist):
return [dict(zip(artist.keys(), artist)) for artist in allArtist]
# Artists
# ----------------------------------------------------------------
@app.route('/artists')
def artists():
allArtist = getArtistList()
data = formatArtist(allArtist)
return render_template('pages/artists.html', artists=data)
def returnSerchArtistresult(search_term):
artist = Artist.query.filter(Artist.name.ilike('%' + search_term + '%'))
return artist
@app.route('/artists/search', methods=['POST'])
def search_artists():
search_term = request.form.get('search_term', '').strip()
artists = returnSerchArtistresult(search_term)
data = []
for artist in artists:
artistDet = {
"id": artist.id,
"name": artist.name,
"num_upcoming_shows": artist.num_upcoming_shows
}
data.append(artistDet)
response = {
"count": len(data),
"data": data
}
return render_template('pages/search_artists.html', results=response, search_term=request.form.get('search_term', ''))
def getArtistDet(artist, pastEvents, upcomingEvents):
return {
"id": artist.id,
"name": artist.name,
"genres": artist.genres,
"city": artist.city,
"state": artist.state,
"phone": artist.phone,
"seeking_venue": True if artist.seeking_venue in ('y', True, 't', 'True') else False,
"seeking_description": artist.seeking_description,
"image_link": artist.image_link,
"facebook_link": artist.facebook_link,
"website": artist.website_link,
"past_shows_count": artist.num_past_shows,
"upcoming_shows_count": artist.num_upcoming_shows,
"past_shows": pastEvents,
"upcoming_shows": upcomingEvents,
}
@app.route('/artists/<int:artist_id>')
def show_artist(artist_id):
artist = getArtistById(artist_id)
if not artist:
flash("Artist not found!", category='error')
return redirect(url_for('artists'))
pastEvents = []
upcomingEvents = []
for show in artist.past_shows:
venue = getVenueById(show.venue_id)
venueDet = {
"venue_id": venue.id,
"venue_name": venue.name,
"venue_image_link": venue.image_link,
"start_time": str(show.start_time)
}
pastEvents.append(venueDet)
for show in artist.upcoming_shows:
venue = getVenueById(show.venue_id)
getEventDetail = {
"venue_id": venue.id,
"venue_name": venue.name,
"venue_image_link": venue.image_link,
"start_time": str(show.start_time)
}
upcomingEvents.append(getEventDetail)
data = getArtistDet(artist, upcomingEvents, pastEvents)
return render_template('pages/show_artist.html', artist=data)
# Update
# ----------------------------------------------------------------
@app.route('/artists/<int:artist_id>/edit', methods=['GET'])
def edit_artist(artist_id):
form = ArtistForm()
# populate form with fields from artist with ID <artist_id>
artist = Artist.query.get(artist_id)
if not artist:
flash('Artist with Id ' + str(artist_id) + ' not found!', category='error')
return redirect(url_for('artists'))
form.name.data = artist.name
form.city.data = artist.city
form.state.data = artist.state
form.facebook_link.data = artist.facebook_link
form.image_link.data = artist.image_link
form.website_link.data = artist.website_link
form.seeking_venue.data = artist.seeking_venue
form.phone.data = artist.phone
form.genres.data = artist.genres
form.seeking_description.data = artist.seeking_description
return render_template('forms/edit_artist.html', form=form, artist=artist)
@app.route('/artists/<int:artist_id>/edit', methods=['POST'])
def edit_artist_submission(artist_id):
# TODO: take values from the form submitted, and update existing
# artist record with ID <artist_id> using the new attributes
status = False
# artist record with ID <artist_id> using the new attributes
artist = Artist.query.get(artist_id)
if not artist:
flash(' Artist with Id ' + str(artist_id) + ' not found!', category='error')
return redirect(url_for('artists'))
try:
artist.genres = request.form.getlist('genres')
artist.image_link = request.form['image_link']
artist.facebook_link = request.form['facebook_link']
artist.name = request.form['name']
artist.city = request.form['city']
artist.state = request.form['state']
artist.phone = request.form['phone']
artist.website_link = request.form['website_link']
artist.seeking_venue = True if 'seeking_venue' in request.form else False
artist.seeking_description = request.form['seeking_description']
db.session.commit()
status = True
except:
db.session.rollback()
status = False
print(sys.exc_info())
finally:
db.session.close()
if not status:
# on unsuccessful db insert, flash an error instead.
flash('Error occurred, Artist ' + request.form['name'] + ' was not edited.', category='error')
return redirect(url_for('edit_artist_submission', artist_id=artist_id))
else:
# on successful db insert, flash success
flash('Artist ' + request.form['name'] + ' Edited successfully!')
return redirect(url_for('show_artist', artist_id=artist_id))
@app.route('/venues/<int:venue_id>/edit', methods=['GET'])
def edit_venue(venue_id):
# TODO: populate form with values from venue with ID <venue_id>
form = VenueForm()
# populate form with values from venue with ID <venue_id>
venue = Venue.query.get(venue_id)
if not venue:
flash('An error occurred. Venue with ID ' + str(venue_id) + ' was not found!', category='error')
return redirect(url_for('venues'))
form.website_link.data = venue.website_link
form.seeking_talent.data = venue.seeking_talent
form.seeking_description.data = venue.seeking_description
form.name.data = venue.name
form.city.data = venue.city
form.genres.data = venue.genres
form.facebook_link.data = venue.facebook_link
form.image_link.data = venue.image_link
form.state.data = venue.state
form.phone.data = venue.phone
form.address.data = venue.address
return render_template('forms/edit_venue.html', form=form, venue=venue)
@app.route('/venues/<int:venue_id>/edit', methods=['POST'])
def edit_venue_submission(venue_id):
# TODO: take values from the form submitted, and update existing
# venue record with ID <venue_id> using the new attributes
# take values from the form submitted, and update existing
status = False
# venue record with ID <venue_id> using the new attributes
venue = Venue.query.get(venue_id)
if not venue:
flash('Error occurred. Venue Id ' + str(venue_id) + ' not found', category='error')
return redirect(url_for('venues'))
try:
venue.address = request.form['address']
venue.phone = request.form['phone']
venue.name = request.form['name']
venue.city = request.form['city']
venue.image_link = request.form['image_link']
venue.facebook_link = request.form['facebook_link']
venue.website_link = request.form['website_link']
venue.state = request.form['state']
venue.genres = request.form.getlist('genres')
venue.seeking_talent = True if 'seeking_talent' in request.form else False
venue.seeking_description = request.form['seeking_description']
db.session.commit()
status = True
except:
db.session.rollback()
status = False
print(sys.exc_info())
finally:
db.session.close()
if not status:
# on unsuccessful db insert, flash an error instead.
flash('Error occurred, venue ' + request.form['name'] + ' was not edited.', category='error')
return redirect(url_for('edit_venue_submission', venue_id=venue_id))
else:
# on successful db insert, flash success
flash('Venue ' + request.form['name'] + ' was edited successfully')
return redirect(url_for('show_venue', venue_id=venue_id))
# Create Artist
# ----------------------------------------------------------------
def createArtistRecord(name,
city,
state,
phone,
genres,
facebook_link,
image_link,
website_link,
seeking_venue,
seeking_description):
error = False
try:
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:
error = True
db.session.rollback()
print(sys.exc_info())
abort(400)
finally:
db.session.close()
if error:
abort (400)
else:
# on successful db insert, flash success
flash('Artist ' + request.form['name'] + ' was successfully listed!')
return render_template('pages/home.html')
@app.route('/artists/create', methods=['GET'])
def create_artist_form():
form = ArtistForm()
return render_template('forms/new_artist.html', form=form)
@app.route('/artists/create', methods=['POST'])
def create_artist_submission():
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['seeking_venue']
seeking_description=request.form['seeking_description']
return createArtistRecord(name,
city,
state,
phone,
genres,
facebook_link,
image_link,
website_link,
seeking_venue,
seeking_description)
# Shows
# ----------------------------------------------------------------
def getShows():
return db.session.query(Show).join(Venue, (Venue.id == Show.venue_id)).join(Artist, (Artist.id == Show.artist_id)).with_entities(Show.venue_id, Venue.name.label('venue_name'), Show.artist_id, Artist.name.label('artist_name'), Artist.image_link.label('artist_image_link'), Show.start_time).all()
def formatShowData(result):
result = dict(zip(result.keys(), result))
result['start_time'] = str(result['start_time'])
return result
@app.route('/shows')
def shows():
data = getShows()
data = [formatShowData(result) for result in data]
return render_template('pages/shows.html', shows=data)
@app.route('/shows/create')
def create_shows():
form = ShowForm()
return render_template('forms/new_show.html', form=form)
def createShowRecord(venue_id, artist_id, start_time):
error = False
try:
show = Show(
venue_id=venue_id,
artist_id=artist_id,
start_time=start_time
)
db.session.add(show)
db.session.commit()
except:
error = True
db.session.rollback()
print(sys.exc_info())
abort(400)
finally:
db.session.close()
if error:
abort (400)
else:
# on successful db insert, flash success
flash('Show was successfully created!')
return render_template('pages/home.html')
@app.route('/shows/create', methods=['POST'])
def create_show_submission():
venue_id=request.form['venue_id'],
artist_id=request.form['artist_id'],
start_time=request.form['start_time'],
return createShowRecord(venue_id, artist_id, start_time)
@app.errorhandler(404)
def not_found_error(error):
return render_template('errors/404.html'), 404
@app.errorhandler(500)
def server_error(error):
return render_template('errors/500.html'), 500
if not app.debug:
file_handler = FileHandler('error.log')
file_handler.setFormatter(
Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
)
app.logger.setLevel(logging.INFO)
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.info('errors')
#----------------------------------------------------------------------------#
# Launch.
#----------------------------------------------------------------------------#
# Default port:
if __name__ == '__main__':
app.run()
# Or specify port manually:
'''
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
'''