class ViewTeamHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): teamDao = DaoFactory.create_rw_teamDao() playerDao = DaoFactory.create_rw_playerDao() profileDao = DaoFactory.create_rw_profileDao() mediaDao = DaoFactory.create_ro_mediaDao() eventDao = DaoFactory.create_rw_eventDao() @user_required def get(self, team_id=None): params = {} params['players'] = self.profileDao.query_by_all(self.user_info) if team_id is not None and len(team_id) > 1: team_info = self.teamDao.get_record(long(team_id)) logger.debug('team_info : ' + str(team_info)) #if team_info.logo: #params['team_logo'] = images.get_serving_url(team_info.logo) if team_info.players: players = [] sel_players = [] #for player in team_info.players: for x in xrange(len(team_info.players)): players.append(self.profileDao.get_record(long(team_info.players[x].id()))) sel_players.append(team_info.players[x].id()) logger.debug('team_players : ' + str(players)) params['team_players'] = players params['sel_players'] = sel_players if team_info.owners: owners = [] for owner in team_info.owners: owners.append(self.user_model.get_by_id(long(owner.id()))) params['team_owners'] = owners logger.debug('team_owners : ' + str(owners)) params['user_info'] = self.user_info params['team_info'] = team_info params['title'] = str(team_info.name) + ' Team' upload_url = self.uri_for('edit-team-logo') params['media_upload_url'] = blobstore.create_upload_url(upload_url) upload_gallery_url = self.uri_for('upload-team-gallery') params['upload_gallery_url'] = blobstore.create_upload_url(upload_gallery_url) params['team_gallery'] = self.mediaDao.get_all_media(team_info.key, constants.TEAM) recommend_events = self.eventDao.get_recommend(self.user_info.locality, self.user_info.sport, 4) params['recommend_events'] = recommend_events event_media = self.mediaDao.get_primary_media(recommend_events, constants.EVENT) params['event_media'] = event_media return self.render_template('/cms/team_detail.html', **params) @webapp2.cached_property def form(self): return forms.TeamForm(self)
class DashboardHandler(BaseHandler): businessDao = DaoFactory.create_rw_businessDao() eventDao = DaoFactory.create_rw_eventDao() childeventDao = DaoFactory.create_rw_childeventDao() playgroundDao = DaoFactory.create_rw_playgroundDao() trainingcentreDao = DaoFactory.create_rw_trainingCentreDao() matchDao = DaoFactory.create_rw_matchDao() teamDao = DaoFactory.create_rw_teamDao() playerDao = DaoFactory.create_rw_playerDao() @user_required def get(self, business_id=None): params = {} params['title'] = 'Dashboard' params['owner_business'] = self.businessDao.query_by_owner( self.user_info) params['owner_playgrounds'] = self.playgroundDao.query_by_owner( self.user_info) params['owner_events'] = self.eventDao.query_by_owner(self.user_info) params['owner_childevents'] = self.childeventDao.query_by_owner( self.user_info) params[ 'owner_trainingcentres'] = self.trainingcentreDao.query_by_owner( self.user_info) params['owner_matches'] = self.matchDao.query_by_owner(self.user_info) params['owner_teams'] = self.teamDao.query_by_owner(self.user_info) params['owner_players'] = self.playerDao.query_by_owner(self.user_info) return self.render_template('/cms/dashboard.html', **params)
class EnquireTrainingCentreHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): trainingCentreDao = DaoFactory.create_rw_trainingCentreDao() @user_required def post(self): params = {} enq_id = self.request.get("enq_id") enq_date = self.request.get("enq_date") enq_time = self.request.get("enq_time") data = self.trainingCentreDao.get_record(long(enq_id)) enq_datetime = enq_date + ' ' + enq_time redirect_url = self.request.get("continue").encode('ascii', 'ignore') sent_email = self.send_enquiry_email(constants.TRAINING_CENTRE, data, enq_datetime) if sent_email > 0: logger.info('Enquiry sent successfully to training centre owner.') self.add_message( 'Enquiry sent successfully to training centre owner.', 'success') else: logger.info('Error occured on Enquiry.') self.add_message('Error occured on Enquiry.', 'warning') return self.redirect(redirect_url)
class UploadProfileGalleryHandler(blobstore_handlers.BlobstoreUploadHandler, webapp2.RequestHandler): mediaDao = DaoFactory.create_ro_mediaDao() def post(self): upload_files = self.get_uploads('gallery_images') id = self.request.get("user_id") user = User.get_by_id(long(id)) redirect_url = self.uri_for('profile') logger.info('Uploaded files: ' + str(upload_files)) #logger.info('Get Request: ' + str(self.request.get())) if upload_files is not None and len(upload_files) > 0: files_count = len(upload_files) logger.info('no of files uploaded ' + str(files_count)) for x in xrange(files_count): blob_info = upload_files[x] media_obj = Media() #media_obj.name = self.form.media.__getitem__(x).data['name'] media_obj.type = constants.PHOTO media_obj.status = True #media_obj.primary = self.form.media.__getitem__(x).data['primary'] media_obj.link = blob_info.key() media_obj.url = images.get_serving_url(blob_info.key()) media_obj.entity_id = user.key media_obj.entity_type = constants.PROFILE logger.info('Upload file detail: ' + str(media_obj)) #self.mediaDao.persist(media_obj) media_obj.put() logger.info('Link to picture file ' + images.get_serving_url(media_obj.link)) return self.redirect(redirect_url)
def _get_localities_from_dao(city_name): playgroundDao = DaoFactory.create_ro_playgroundDao() eventDao = DaoFactory.create_ro_eventDao() trainingcentreDao = DaoFactory.create_ro_trainingCentreDao() localities = set() active_playgrounds = playgroundDao.get_active(city_name, no_records=-1) for pg in active_playgrounds: localities.add(str(pg.address.locality)) active_tc = trainingcentreDao.get_active(city_name, no_records=-1) for tc in active_tc: localities.add(str(tc.address.locality)) active_events = eventDao.get_active(city_name, no_records=-1) for event in active_events: localities.add(str(event.address.locality)) return sorted(list(localities))
class TrainingCentreDetailsHandler(BaseHandler): trainingcentreDao = DaoFactory.create_ro_trainingCentreDao() mediaDao = DaoFactory.create_ro_mediaDao() def get(self, city_name, locality_name, entity_id, entity_alias): logger.debug('Training Centre details for city %s, locality %s, id %s, alias %s ' % (city_name, locality_name, entity_id, entity_alias)) if self.request.query_string != '': query_string = '?' + self.request.query_string else: query_string = '' continue_url = self.request.path_url + query_string if entity_id is None: message = ('Invalid Training Centre ID.') self.add_message(message, 'warning') self.redirect_to('home') else: tc = self.trainingcentreDao.get_record(entity_id) if tc is None: message = ('Training Centre could not be retrieved.') self.add_message(message, 'warning') return else: params = {} params['tc'] = tc params['types'] = constants.TRAINING_CENTRE params['sport'] = tc.sport params['city_name'] = tc.address.city params['locality_name'] = tc.address.locality params['media'] = self.mediaDao.get_active_media(tc.key, tc.sport, constants.TRAINING_CENTRE) params['continue_url'] = continue_url params['upload_cover_url'] = blobstore.create_upload_url(self.uri_for('upload-trainingcentre-cover', **{'continue': continue_url})) params['enquire_url'] = self.uri_for('enquire-trainingcentre', **{'continue': continue_url}) params['title'] = tc.name all_media = self.mediaDao.get_all_media(tc.key, constants.TRAINING_CENTRE) current_media = [] for photo in all_media: current_media.append({'name': photo.name, 'url':images.get_serving_url(photo.link), 'status': photo.status, 'primary': photo.primary}) params['current_media'] = current_media if tc.cover: params['tc_cover'] = images.get_serving_url(tc.cover) return self.render_template('/app/tc_details1.html', **params)
class PlaygroundDetailsHandler(BaseHandler): playgroundDao = DaoFactory.create_ro_playgroundDao() mediaDao = DaoFactory.create_ro_mediaDao() def get(self, city_name, locality_name, entity_id, entity_alias): logger.debug('Playground details for city %s, locality %s, id %s, alias %s ' % (city_name, locality_name, entity_id, entity_alias)) if self.request.query_string != '': query_string = '?' + self.request.query_string else: query_string = '' continue_url = self.request.path_url + query_string if entity_id is None: message = ('Invalid Playground ID.') self.add_message(message, 'warning') self.redirect_to('home') else: playground = self.playgroundDao.get_record(entity_id) if playground is None: message = ('Playground could not be retrieved.') self.add_message(message, 'warning') self.redirect_to('home') else: params = {} params['playground'] = playground params['types'] = constants.PLAYGROUND params['sport'] = playground.sport params['city_name'] = playground.address.city params['locality_name'] = playground.address.locality params['media'] = self.mediaDao.get_active_media(playground.key, playground.sport, constants.PLAYGROUND) params['continue_url'] = continue_url params['upload_cover_url'] = blobstore.create_upload_url(self.uri_for('upload-playground-cover', **{'continue': continue_url})) params['enquire_url'] = self.uri_for('enquire-playground', **{'continue': continue_url}) params['title'] = playground.name all_media = self.mediaDao.get_all_media(playground.key, constants.PLAYGROUND) current_media = [] for photo in all_media: current_media.append({'name': photo.name, 'url':images.get_serving_url(photo.link), 'status': photo.status, 'primary': photo.primary}) params['current_media'] = current_media if playground.cover: params['pg_cover'] = images.get_serving_url(playground.cover) return self.render_template('/app/pg_details1.html', **params)
class EditUserLocalityHandler(webapp2.RequestHandler): importDao = DaoFactory.create_rw_importDao() def post(self): logging.info(self.request.body) id = self.request.get("pk") user = User.get_by_id(long(id)) user.locality = utils.stringify(self.request.get("value")) locality_exist = self.importDao.query_by_place_name(user.locality.title()) if locality_exist: user.locality_id = locality_exist.place_id logger.info('Id: %s Value: %s' % (id, user.locality)) user.put() logger.debug('User Data: ' + str(user)) #return json.dumps(result) #or, as it is an empty json, you can simply use return "{}" return
class PlaygroundSearchHandler(BaseHandler): playgroundDao = DaoFactory.create_rw_playgroundDao() mediaDao = DaoFactory.create_ro_mediaDao() importDao = DaoFactory.create_rw_importDao() def get(self, city_name=None, locality_name=None): return self.post(city_name, locality_name) def post(self, city_name=None, locality_name=None): city_str = str(self.request.get('city-name')) locality_nav = str(self.request.get('nav-locality')) locality_home = str(self.request.get('pg-locality')) locality_str = locality_nav if locality_nav != '' else locality_home locality_id_nav = str(self.request.get('nav-locality_id')) locality_id_home = str(self.request.get('pg-locality_id')) locality_id_str = locality_id_nav if locality_id_nav != '' else locality_id_home name = str(self.request.get('name')) sport = str(self.request.get('sport')) pg_sport = str(self.request.get('pg-sport')) sport = pg_sport if pg_sport != '' and pg_sport != 'None' else sport city = city_name if city_name is not None else city_str locality = locality_name if locality_name is not None else locality_str logger.debug('playground search :: city %s, sport %s, locality %s' % (city, sport, locality)) nav_type_str = str(self.request.get('nav')) nav_type = nav_type_str if nav_type_str != '' and nav_type_str != 'None' else None curs_str = str(self.request.get('page')) curs = curs_str if curs_str != '' and curs_str != 'None' else None remote_ip = self.request.remote_addr params = {} search_params = {} playgrounds = [] playground_list = [] playground_media = [] if name != '' and name != 'None': search_params['name'] = name if sport != '' and sport != 'None': search_params['sport'] = sport if city != '' and city != 'None': params['city_name'] = city search_params['address.city'] = city if locality != '' and locality != 'None' and locality != 'all': search_params['address.locality'] = locality #logger.debug('Search Params : ' + str(search_params)) page_id = 1 if curs is not None: page_id = int(curs) else: playground_search = self.playgroundDao.search_index( remote_ip, 'approved', **search_params) playground_keys = self.playgroundDao.get_search_keys( constants.PLAYGROUND + '_' + str(remote_ip)) total_entries = len(playground_keys) logger.debug('NO of playgrounds matched the search %s ' % total_entries) if total_entries > 0: total_pages = (total_entries / PAGE_SIZE) + 1 params['page_range'] = range(1, total_pages + 1) offset = (page_id * PAGE_SIZE) - PAGE_SIZE limit = offset + PAGE_SIZE playground_list = playground_keys[offset:limit] playgrounds = ndb.get_multi(playground_list) playground_media = self.mediaDao.get_primary_media( playgrounds, constants.PLAYGROUND) logger.debug('Displayed Page No.%s Playgrounds from %s to %s' % (page_id, offset + 1, limit)) suggest_params = {} if len(playground_keys) < PAGE_SIZE and (locality_id_str != '' or locality != '' or curs is not None): suggest_playground_keys = [] if curs is None: if locality_id_str != '': locality_data = self.importDao.query_by_place_id( locality_id_str) elif locality != '': locality_data = self.importDao.query_by_place_name( locality.title()) if locality_data: suggest_params['latlong'] = locality_data.latlong suggest_params['address.locality'] = locality_data.name suggest_playground_keys = self.playgroundDao.search_index_suggest( remote_ip, 'approved', **suggest_params) else: suggest_playground_keys = self.playgroundDao.get_suggest_keys( 'suggest_' + str(constants.PLAYGROUND) + '_' + str(remote_ip)) if suggest_playground_keys is not None: suggest_playgrounds = ndb.get_multi(suggest_playground_keys) params['suggest_playgrounds'] = suggest_playgrounds logger.debug('No of Suggested Search Result : %s' % len(suggest_playground_keys)) #logger.debug('Suggested Search Result keys : ' + str(suggest_playground_keys)) suggest_playground_media = self.mediaDao.get_primary_media( suggest_playgrounds, constants.PLAYGROUND) #logger.debug('Suggest Media: ' + str(suggest_playground_media)) if len(suggest_playground_media) > 0: if len(playground_media) > 0: playground_media.update(suggest_playground_media) else: playground_media = suggest_playground_media params['types'] = constants.PLAYGROUND params['sport'] = sport params['locality_name'] = locality params['playgrounds'] = playgrounds params['playground_media'] = playground_media params['title'] = constants.PLAYGROUND logger.debug('Param Results: ' + str(params)) return self.render_template('/app/search_results.html', **params)
class EventSearchHandler(BaseHandler): eventDao = DaoFactory.create_rw_eventDao() mediaDao = DaoFactory.create_ro_mediaDao() def get(self, city_name=None, locality_name=None): return self.post(city_name, locality_name) def post(self, city_name=None, locality_name=None): city_str = str(self.request.get('city-name')) sport = str(self.request.get('sport')) #locality_str = str(self.request.get('se-locality')) locality_nav = str(self.request.get('nav-locality')) locality_home = str(self.request.get('se-locality')) locality_str = locality_nav if locality_nav != '' else locality_home #logger.debug('sporting event search :: locality_nav %s, locality_home %s, locality_str %s' % (locality_nav, locality_home, locality_str)) se_sport = str(self.request.get('se-sport')) sport = se_sport if se_sport != '' and se_sport != 'None' else sport city = city_name if city_name is not None else city_str locality = locality_name if locality_name is not None else locality_str logger.debug( 'sporting event search :: city %s, sport %s, locality %s' % (city, sport, locality)) recent_events = self.eventDao.get_recent(city, sport, locality, -1) ongoing_events = self.eventDao.get_ongoing(city, sport, locality, -1) ongoing_events_future = self.eventDao.get_ongoing_future( city, sport, locality, -1) future_events = self.eventDao.get_upcoming(city, sport, locality, -1) logger.debug(' recent_events %s ' % len(recent_events)) logger.debug(' future_events %s ' % len(future_events)) logger.debug(' ongoing_events %s ' % len(ongoing_events)) logger.debug(' ongoing_events_future %s ' % len(ongoing_events_future)) ongoing_upcoming_events = [] ongoing_upcoming_events = [ val for val in ongoing_events if val in ongoing_events_future ] logger.debug(' ongoing_upcoming_events %s ' % len(ongoing_upcoming_events)) for event in future_events: ongoing_upcoming_events.append(event) #for event in ongoing_events: #ongoing_upcoming_events.append(event) temp_events = [] for event in recent_events: temp_events.append(event) for event in ongoing_upcoming_events: temp_events.append(event) event_media = self.mediaDao.get_primary_media(temp_events, constants.EVENT) logger.debug(' event_media %s ' % len(event_media)) params = {} params['types'] = constants.EVENT params['sport'] = sport params['locality_name'] = locality if city != '' and city != 'None': params['city_name'] = city params['recent_events'] = recent_events params['future_events'] = ongoing_upcoming_events logger.debug(' future_events %s ' % len(ongoing_upcoming_events)) params['event_media'] = event_media params['title'] = constants.EVENT #logger.debug('Params to template ' + str(params)) return self.render_template('/app/events_home.html', **params)
class ManageEventHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): businessDao = DaoFactory.create_rw_businessDao() eventDao = DaoFactory.create_rw_eventDao() mediaDao = DaoFactory.create_rw_mediaDao() #@role_required('business') @user_required def get(self, business_id=None, event_id=None): params = {} upload_url = self.uri_for('select-for-event') continue_url = self.request.get('continue').encode('ascii', 'ignore') params[ 'continue_url'] = continue_url if continue_url != '' else upload_url status = self.request.get('status') event_status = status if status != '' else None params['title'] = 'Create New Event' if business_id is not None and len(business_id) > 1: self.form.business_id = business_id if event_id is not None and len(event_id) > 1: event = self.eventDao.get_record(event_id) params['title'] = 'Update - ' + str(event.name) if event_status is not None: logger.info('current status: %s' % event_status) key = self.eventDao.status_change(event, self.user_info) if key is not None: updated_event = self.eventDao.get_record(long( key.id())) logger.info('updated status : %s' % updated_event.status) if event_status == str(updated_event.status): logger.info('event status could not be changed.') message = ('event status could not be changed.') self.add_message(message, 'error') else: logger.info('event status succesfully changed.') message = ('event status succesfully changed.') self.add_message(message, 'success') return self.redirect(continue_url) else: upload_url = self.uri_for('edit-event', business_id=business_id, event_id=event_id) all_media = self.mediaDao.get_all_media( event.key, constants.EVENT) current_media = [] for photo in all_media: current_media.append({ 'name': photo.name, 'url': images.get_serving_url(photo.link), 'status': photo.status, 'primary': photo.primary }) params['current_media'] = current_media logger.debug('event detail ' + str(event)) self.form = cms_utils.dao_to_form_city_info( event, forms.EventForm(self, event)) self.form = cms_utils.dao_to_form_contact_info( event, self.form) params['media_upload_url'] = blobstore.create_upload_url( upload_url) return self.render_template('/cms/create_event.html', **params) else: upload_url = self.uri_for('create-event', business_id=business_id) params['media_upload_url'] = blobstore.create_upload_url( upload_url) return self.render_template('/cms/create_event.html', **params) params['entity_name'] = 'Event' params['owner_business'] = self.businessDao.query_by_owner( self.user_info) logger.info('Result Params : ' + str(params['entity_name'])) return self.render_template('/cms/select_business.html', **params) #@role_required('business') @user_required def post(self, business_id=None, event_id=None): params = {} if not self.form.validate(): if business_id is not None and len(business_id) > 0: if event_id is not None and len(event_id) > 0: return self.get(business_id, event_id) else: return self.get(business_id) else: return self.get() save = self.request.get('save') next_fill = self.request.get('next') next_tab = next_fill if next_fill != '' else save locality_id = self.request.get('locality_id') event = self.form_to_dao(event_id) if locality_id is not None and len(locality_id) > 0: logger.info('Locality Id: %s ' % locality_id) locality_count = self.process_locality(event.address.locality, locality_id, constants.PLACES_API_KEY) event.address.locality_id = locality_id else: event.address.locality = '' event.address.locality_id = '' logger.debug('event populated ' + str(event)) if business_id != None and business_id != 'user': business = self.businessDao.get_record(business_id) business_key = business.key else: business = self.create_or_update_business(event) business_key = self.businessDao.persist(business, self.user_info) if business_key is not None: logger.info('Business succesfully created for event, ' + business.name) event.business_id = business_key key = self.eventDao.persist(event, self.user_info) logger.debug('key ' + str(key)) if key is not None: self.upload_photos(key) logger.info('event succesfully created/updated') message = ('event succesfully created/updated.') self.add_message(message, 'success') if next_tab is not None: if next_tab != 'save': redirect_url = self.uri_for( 'edit-event', business_id=event.business_id.id(), event_id=key.id()) redirect_url = redirect_url + next_tab logger.info('Url %s' % redirect_url) return self.redirect(redirect_url) else: redirect_url = self.uri_for( 'event-details', city_name=event.address.city, entity_id=key.id(), entity_alias=event.alias) return self.redirect(redirect_url) #return self.redirect_to('dashboard', **params) logger.error('event creation failed') message = ('event creation failed.') self.add_message(message, 'error') self.form = forms.EventForm(self, event) return self.render_template('/cms/create_event.html', **params) @webapp2.cached_property def form(self): return forms.EventForm(self) def upload_photos(self, key): upload_files = self.get_uploads() if upload_files is not None and len(upload_files) > 0: files_count = len(upload_files) logger.info('no of files uploaded ' + str(files_count)) for x in xrange(files_count): blob_info = upload_files[x] media_obj = Media() media_obj.name = self.form.media.__getitem__(x).data['name'] media_obj.type = constants.PHOTO media_obj.status = self.form.media.__getitem__( x).data['status'] media_obj.primary = self.form.media.__getitem__( x).data['primary'] media_obj.link = blob_info.key() media_obj.url = images.get_serving_url(blob_info.key()) media_obj.entity_id = key media_obj.entity_type = constants.EVENT self.mediaDao.persist(media_obj) logger.info('Link to picture file ' + media_obj.name + ', ' + images.get_serving_url(media_obj.link)) def form_to_dao(self, event_id): event = None if event_id is not None and len(event_id) > 1: event = self.eventDao.get_record(long(event_id)) else: event = Event() event.name = self.form.name.data event.sport = self.form.sport.data #Create an automatic alias for the event event.alias = utils.slugify(self.form.name.data) event.caption = self.form.caption.data event.description = self.form.description.data event.featured = self.form.featured.data event.start_datetime = datetime( *(self.form.start_datetime.data.timetuple()[:6])) event.end_datetime = datetime( *(self.form.end_datetime.data.timetuple()[:6])) self.form.address.city.data = self.form.city.data #for city from basic info to address event = cms_utils.form_to_dao_address(self.form, event) event = cms_utils.form_to_dao_contact_info(self.form, event) return event def create_or_update_business(self, event): if event.business_id is not None: business = self.businessDao.get_record(long( event.business_id.id())) else: business = Business() business.name = event.name business.description = event.description business.alias = event.alias business.contact_info = event.contact_info return business
class ManageRegisterHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): eventDao = DaoFactory.create_rw_eventDao() mediaDao = DaoFactory.create_rw_mediaDao() teamDao = DaoFactory.create_rw_teamDao() profileDao = DaoFactory.create_rw_profileDao() registerDao = DaoFactory.create_rw_registerDao() @user_required def get(self): params = {} return True @user_required def post(self, record_id=None): params = {} continue_url = self.request.get('continue').encode('ascii', 'ignore') register = self.form_to_dao(record_id) logger.debug('registration populated ' + str(register)) key = self.registerDao.persist(register, self.user_info) logger.debug('key ' + str(key)) if key is not None: record = self.registerDao.get_record(key.id()) message = '' if record.team_id: message += ('%s teams ' % len(record.team_id)) if record.player_id: message += ('%s player ' % len(record.player_id)) message += ('registered this event succesfully') logger.info(message) self.add_message(message, 'success') if continue_url: return self.redirect(continue_url) else: return self.redirect_to('profile', **params) logger.error('registration failed') message = ('registration failed.') self.add_message(message, 'error') return self.redirect_to('profile', **params) def form_to_dao(self, record_id=None): register = None if record_id is not None and len(record_id) > 1: register = self.registerDao.get_record(long(record_id)) else: register = Register() event_id = self.request.get('event_id') event_data = self.eventDao.get_record(long(event_id)) register.reg_id = event_data.key register.reg_type = self.request.get('participant_type') register.user_id = self.user_info.key sel_team = self.request.get_all('team') sel_player = self.request.get_all('player') logger.debug('sel_team: ' + str(sel_team)) logger.debug('sel_player: ' + str(sel_player)) payment = 0 if len(sel_team) > 0: teams = [] teams_count = len(sel_team) logger.debug('Teams Count: ' + str(teams_count)) for x in xrange(teams_count): teams.append(self.teamDao.get_record(sel_team[x]).key) logger.debug('Teams ' + str(teams)) payment += teams_count * constants.REG_PRICE register.team_id = teams if len(sel_player) > 0: players = [] players_count = len(sel_player) logger.debug('Players Count: ' + str(players_count)) for x in xrange(players_count): players.append(self.profileDao.get_record(sel_player[x]).key) logger.debug('Players ' + str(players)) payment += players_count * constants.REG_PRICE register.player_id = players register.payment = payment return register '''def send_register_email(self, record_id):
class SearchUpdateHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): eventDao = DaoFactory.create_rw_eventDao() playgroundDao = DaoFactory.create_rw_playgroundDao() trainingCentreDao = DaoFactory.create_rw_trainingCentreDao() @user_required def get(self): params = {} upload_url = self.uri_for('search-update') params['title'] = 'Search Update' params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/search_update.html', **params) @user_required def post(self): params = {} datas = [] datas_count = 0 type = self.request.get('type') logger.info('Type: %s' % type) if type != 'None': if type == 'event': datas = Event.query().fetch() elif type == 'playground': datas = Playground.query().fetch() elif type == 'trainingcentre': datas = TrainingCentre.query().fetch() for data in datas: if data.address.latlong is None: latitude, longitude = get_latlong_from_address( data.address) if latitude is not None and longitude is not None: data.address.latlong = ndb.GeoPt(latitude, longitude) logger.info('New Lat Long: ' + str(data.address.latlong)) logger.info('Populated Data: ' + str(data)) if type == 'event': key = self.eventDao.persist(data, self.user_info) elif type == 'playground': key = self.playgroundDao.persist(data, self.user_info) elif type == 'trainingcentre': key = self.trainingCentreDao.persist(data, self.user_info) if key is not None: datas_count += 1 logger.info(str(key.id()) + ' succesfully search updated') logger.info('%s %s Entities Updated Search Successfully' % (datas_count, type)) message = ('%s %s Entities Updated Search Successfully' % (datas_count, type)) self.add_message(message, 'success') return self.redirect_to('search-update') logger.error('Select anyone of Type') message = ('Select anyone of Type') self.add_message(message, 'error') return self.redirect_to('search-update')
class ManageTrainingCentreHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): businessDao = DaoFactory.create_rw_businessDao() trainingCentreDao = DaoFactory.create_rw_trainingCentreDao() mediaDao = DaoFactory.create_rw_mediaDao() #@role_required('business') @user_required def get(self, business_id=None, trainingcentre_id=None): params = {} upload_url = self.uri_for('select-for-trainingcentre') continue_url = self.request.get('continue').encode('ascii', 'ignore') status = self.request.get('status') tc_status = status if status != '' else None params['title'] = 'Create New Training Centre' if business_id is not None and len(business_id) > 1: self.form.business_id = business_id params['continue_url'] = continue_url if trainingcentre_id is not None and len(trainingcentre_id) > 1: trainingcentre = self.trainingCentreDao.get_record( trainingcentre_id) params['title'] = 'Update - ' + str(trainingcentre.name) if tc_status is not None: logger.info('current status: %s' % tc_status) key = self.trainingCentreDao.status_change( trainingcentre, self.user_info) if key is not None: updated_tc = self.trainingCentreDao.get_record( long(key.id())) logger.info('updated status : %s' % updated_tc.status) if tc_status == str(updated_tc.status): logger.info( 'trainingcentre status could not be changed.') message = ( 'trainingcentre status could not be changed.') self.add_message(message, 'error') else: logger.info( 'trainingcentre status succesfully changed.') message = ( 'trainingcentre status succesfully changed.') self.add_message(message, 'success') return self.redirect(continue_url) else: upload_url = self.uri_for( 'edit-trainingcentre', business_id=business_id, trainingcentre_id=trainingcentre_id) all_media = self.mediaDao.get_all_media( trainingcentre.key, constants.TRAINING_CENTRE) current_media = [] for photo in all_media: current_media.append({ 'name': photo.name, 'url': images.get_serving_url(photo.link), 'status': photo.status, 'primary': photo.primary }) params['current_media'] = current_media self.form = cms_utils.dao_to_form_locality_info( trainingcentre, forms.TrainingCentreForm(self, trainingcentre)) self.form = cms_utils.dao_to_form_contact_info( trainingcentre, self.form) params['media_upload_url'] = blobstore.create_upload_url( upload_url) return self.render_template('/cms/create_trainingcenter.html', **params) else: upload_url = self.uri_for('create-trainingcentre', business_id=business_id) params['media_upload_url'] = blobstore.create_upload_url( upload_url) return self.render_template('/cms/create_trainingcenter.html', **params) params['continue_url'] = upload_url params['entity_name'] = 'Training Centre' params['owner_business'] = self.businessDao.query_by_owner( self.user_info) return self.render_template('/cms/select_business.html', **params) #@role_required('business') @user_required def post(self, business_id=None, trainingcentre_id=None): params = {} if not self.form.validate(): if business_id is not None and len(business_id) > 0: if trainingcentre_id is not None and len( trainingcentre_id) > 0: return self.get(business_id, trainingcentre_id) else: return self.get(business_id) else: return self.get() save = self.request.get('save') next_fill = self.request.get('next') next_tab = next_fill if next_fill != '' else save locality_id = self.request.get('locality_id') trainingcentre = self.form_to_dao(trainingcentre_id) logger.info('This is debugging for %s' % trainingcentre) if locality_id is not None: logger.info('Locality Id: %s ' % locality_id) locality_count = self.process_locality( trainingcentre.address.locality, locality_id, constants.PLACES_API_KEY) trainingcentre.address.locality_id = locality_id logger.debug('trainingcentre populated ' + str(trainingcentre)) if business_id != None and business_id != 'user': business = self.businessDao.get_record(business_id) business_key = business.key else: business = self.create_or_update_business(trainingcentre) business_key = self.businessDao.persist(business, self.user_info) if business_key is not None: logger.info('Business succesfully created for trainingcentre, ' + business.name) trainingcentre.business_id = business_key key = self.trainingCentreDao.persist(trainingcentre, self.user_info) logger.debug('key ' + str(key)) if key is not None: self.upload_photos(key) logger.info('trainingcentre succesfully created/updated') message = ('trainingcentre succesfully created/updated.') self.add_message(message, 'success') if next_tab is not None: if next_tab != 'save': redirect_url = self.uri_for( 'edit-trainingcentre', business_id=trainingcentre.business_id.id(), trainingcentre_id=key.id()) logger.debug('this is redirect value: %s' % redirect_url) redirect_url = redirect_url + next_tab logger.info('Redirect Url %s' % redirect_url) return self.redirect(redirect_url) else: redirect_url = self.uri_for( 'tc-details', city_name=trainingcentre.address.city, locality_name=trainingcentre.address.locality, entity_id=key.id(), entity_alias=trainingcentre.alias) return self.redirect(redirect_url) #return self.redirect_to('dashboard', **params) logger.error('trainingcentre creation failed') message = ('trainingcentre creation failed.') self.add_message(message, 'error') self.form = forms.TrainingCentreForm(self, trainingcentre) return self.render_template('/cms/create_trainingcentre.html', **params) @webapp2.cached_property def form(self): return forms.TrainingCentreForm(self) def upload_photos(self, key): upload_files = self.get_uploads() if upload_files is not None and len(upload_files) > 0: files_count = len(upload_files) logger.info('no of files uploaded ' + str(files_count)) for x in xrange(files_count): blob_info = upload_files[x] media_obj = Media() media_obj.name = self.form.media.__getitem__(x).data['name'] media_obj.type = constants.PHOTO media_obj.status = self.form.media.__getitem__( x).data['status'] media_obj.primary = self.form.media.__getitem__( x).data['primary'] media_obj.link = blob_info.key() media_obj.url = images.get_serving_url(blob_info.key()) media_obj.entity_id = key media_obj.entity_type = constants.TRAINING_CENTRE self.mediaDao.persist(media_obj) logger.info('Link to picture file ' + media_obj.name + ', ' + images.get_serving_url(media_obj.link)) def form_to_dao(self, trainingcentre_id): trainingcentre = None if trainingcentre_id is not None and len(trainingcentre_id) > 1: trainingcentre = self.trainingCentreDao.get_record( long(trainingcentre_id)) else: trainingcentre = TrainingCentre() trainingcentre.name = self.form.name.data trainingcentre.sport = self.form.sport.data #Create an automatic alias for the trainingcentre trainingcentre.alias = utils.slugify(self.form.name.data) trainingcentre.description = self.form.description.data trainingcentre.featured = self.form.featured.data self.form.address.locality.data = self.form.locality.data #for locality from basic info to address self.form.address.city.data = self.form.city.data #for city from basic info to address trainingcentre = cms_utils.form_to_dao_address(self.form, trainingcentre) trainingcentre = cms_utils.form_to_dao_contact_info( self.form, trainingcentre) return trainingcentre def create_or_update_business(self, trainingcentre): if trainingcentre.business_id is not None: business = self.businessDao.get_record( long(trainingcentre.business_id.id())) else: business = Business() business.name = trainingcentre.name business.description = trainingcentre.description business.alias = trainingcentre.alias business.contact_info = trainingcentre.contact_info return business
class ManageChildEventHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): childeventDao = DaoFactory.create_rw_childeventDao() eventDao = DaoFactory.create_rw_eventDao() mediaDao = DaoFactory.create_rw_mediaDao() @role_required('business') def get(self, event_id=None, childevent_id=None): params = {} upload_url = self.uri_for('select-for-childevent') if event_id is not None and len(event_id) > 1: self.form.parent_event_id = event_id if childevent_id is not None and len(childevent_id) > 1: upload_url = self.uri_for('edit-child-event', event_id=event_id, childevent_id=childevent_id) childevent = self.childeventDao.get_record(childevent_id) all_media = self.mediaDao.get_all_media( childevent.key, constants.EVENT) current_media = [] for photo in all_media: current_media.append({ 'name': photo.name, 'url': images.get_serving_url(photo.link), 'status': photo.status, 'primary': photo.primary }) params['current_media'] = current_media self.form = cms_utils.dao_to_form_contact_info( childevent, forms.ChildEventForm(self, childevent)) params['media_upload_url'] = blobstore.create_upload_url( upload_url) return self.render_template('/cms/create_childevent.html', **params) else: upload_url = self.uri_for('create-child-event', event_id=event_id) params['media_upload_url'] = blobstore.create_upload_url( upload_url) return self.render_template('/cms/create_childevent.html', **params) params['continue_url'] = upload_url params['entity_name'] = 'Child Event' params['owner_event'] = self.eventDao.query_by_owner(self.user_info) return self.render_template('/cms/select_event.html', **params) @role_required('business') def post(self, event_id=None, childevent_id=None): params = {} if not self.form.validate(): if event_id is not None and len(event_id) > 0: if childevent_id is not None and len(childevent_id) > 0: return self.get(event_id, childevent_id) else: return self.get(event_id) else: return self.get() childevent = self.form_to_dao(childevent_id) logger.debug('childevent populated ' + str(childevent)) event = self.eventDao.get_record(event_id) event_key = event.key if event_key is not None: logger.info('Event succesfully created for childevent') childevent.parent_event_id = event_key key = self.childeventDao.persist(childevent, self.user_info) logger.debug('key ' + str(key)) if key is not None: self.upload_photos(key) logger.info('childevent succesfully created/updated') message = ('childevent succesfully created/updated.') self.add_message(message, 'success') return self.redirect_to('dashboard', **params) logger.error('childevent creation failed') message = ('childevent creation failed.') self.add_message(message, 'error') self.form = forms.ChildEventForm(self, childevent) return self.render_template('/cms/create_childevent.html', **params) @webapp2.cached_property def form(self): return forms.ChildEventForm(self) def upload_photos(self, key): upload_files = self.get_uploads() if upload_files is not None and len(upload_files) > 0: files_count = len(upload_files) logger.info('no of files uploaded ' + str(files_count)) for x in xrange(files_count): blob_info = upload_files[x] media_obj = Media() media_obj.name = self.form.media.__getitem__(x).data['name'] media_obj.type = constants.PHOTO media_obj.status = self.form.media.__getitem__( x).data['status'] media_obj.primary = self.form.media.__getitem__( x).data['primary'] media_obj.link = blob_info.key() media_obj.event_id = key self.mediaDao.persist(media_obj) logger.info('Link to picture file ' + media_obj.name + ', ' + images.get_serving_url(media_obj.link)) def form_to_dao(self, childevent_id): childevent = None if childevent_id is not None and len(childevent_id) > 1: childevent = self.childeventDao.get_record(long(childevent_id)) else: childevent = Event() childevent.name = self.form.name.data #Create an automatic alias for the childevent childevent.alias = utils.slugify(self.form.name.data) childevent.description = self.form.description.data childevent.start_datetime = self.form.start_datetime.data childevent.end_datetime = self.form.end_datetime.data childevent = cms_utils.form_to_dao_contact_info(self.form, childevent) return childevent
class ImportHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): eventDao = DaoFactory.create_rw_eventDao() businessDao = DaoFactory.create_rw_businessDao() playgroundDao = DaoFactory.create_rw_playgroundDao() trainingCentreDao = DaoFactory.create_rw_trainingCentreDao() @user_required def get(self): params = {} upload_url = self.uri_for('import') params['title'] = 'Import' params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/import.html', **params) @user_required def post(self): if not self.form.validate(): return self.get() start_record = int(str(self.request.get('linenum'))) upload_files = self.get_uploads( 'importfile') # 'file' is file upload field in the form blob_info = upload_files[0] upload_count = self.process_csv(blob_info, start_record) self.add_message( str(upload_count) + ' entities created successfully.', 'success') return self.redirect_to('import') def process_csv(self, blob_info, start_record): update = {} upload_count = 0 row_count = 0 blob_reader = blobstore.BlobReader(blob_info.key()) datareader = csv.reader(blob_reader) for row in datareader: row_count += 1 if row_count >= (start_record + 1): #to skip the header row logger.info('Starting to parse %s, %s' % (row_count, row[1])) entity_type = row[0].lower() update['name'] = utils.stringify(row[1]) # Name is mandatory for all entities if update['name'] == '': logger.error('Name is empty. Skipping this record') continue update['locality'] = utils.stringify(row[5]).lower() update['city'] = utils.stringify(row[8]).lower() #Locality and city mandatory for playground and trainingcentre if entity_type != 'event': if update['locality'] == '' or update['city'] == '': logger.error( 'Locality or city is empty. Skipping this record') continue alias_name = utils.slugify(update['name'].lower()) try: update['description'] = utils.stringify(row[2]) update['sport'] = utils.stringify(row[3]).lower() update['person_name'] = utils.stringify(row[10]) update['phone'] = utils.stringify(row[11]) update['email'] = utils.stringify(row[12]) update['website'] = utils.stringify(row[13]) update['facebook'] = utils.stringify(row[18]) update['twitter'] = utils.stringify(row[19]) update['youtube'] = utils.stringify(row[20]) update['gplus'] = utils.stringify(row[21]) update['line1'] = utils.stringify(row[6]) update['line2'] = utils.stringify(row[7]) update['pin'] = int( row[9].strip()) if row[9] != '' else None #update['start_datetime'] = row[22] #update['end_datetime'] = row[23] logger.debug('Constructed Structure for upload ' + str(update)) logger.info('Entity type to be created, ' + entity_type) if entity_type == 'ground': import_data = self.form_to_dao_ground( alias_name, **update) elif entity_type == 'club': import_data = self.form_to_dao_center( alias_name, **update) elif entity_type == 'event': import_data = self.form_to_dao_event( alias_name, **update) # for add locality table if import_data.address.locality != '': place_name = import_data.address.locality logger.info('Place: %s' % place_name) newfeed_url = 'https://maps.googleapis.com/maps/api/place/autocomplete/xml?types=(regions)&input=' + urllib.quote( place_name) + '&key=' + constants.PLACES_API_KEY logging.info('newfeed url %s' % newfeed_url) newroot = self.parse(newfeed_url) auto_status = newroot.getElementsByTagName( 'status')[0].firstChild.data logger.info('Auto Status: %s ' % auto_status) if auto_status == 'OK': items = newroot.getElementsByTagName( 'prediction')[0] place_id = items.getElementsByTagName( 'place_id')[0].firstChild.data place_name = items.getElementsByTagName( 'value')[0].firstChild.data #description logger.info('Place Name: %s Place Id: %s ' % (place_name, place_id)) import_data.address.locality_id = place_id logger.info('Locality Id: %s ' % import_data.address.locality_id) locality_add = self.process_locality( place_name, place_id, constants.PLACES_API_KEY) #if import_data.address.latlong == '': #locality = self.importDao.query_by_place_id(place_id) #import_data.address.latlong = locality.latlong #logger.info('Geo Location New: %s ' % import_data.address.latlong) else: logger.error('Error: %s' % auto_status) logger.debug('Populated File Data ' + str(import_data)) business_key = self.create_or_update_business( alias_name, import_data) import_data.business_id = business_key if entity_type == 'ground': ground = self.playgroundDao.query_by_alias(alias_name) if ground is not None: self.playgroundDao.copy_playground_model( ground, import_data) key = self.playgroundDao.persist( ground, self.user_info) upload_count += 1 logger.info( 'Playground updated for %s with key %s' % (alias_name, key)) else: key = self.playgroundDao.persist( import_data, self.user_info) upload_count += 1 logger.info('New playground created for %s' % (update['name'])) elif entity_type == 'club': tc = self.trainingCentreDao.query_by_alias(alias_name) if tc is not None: self.trainingCentreDao.copy_trainingCentre_model( tc, import_data) key = self.trainingCentreDao.persist( tc, self.user_info) upload_count += 1 logger.info( 'TrainingCentre updated for %s with key %s' % (alias_name, key)) else: key = self.trainingCentreDao.persist( import_data, self.user_info) upload_count += 1 logger.info('New training centre created for %s' % (update['name'])) elif entity_type == 'event': event = self.eventDao.query_by_alias(alias_name) if event is not None: self.eventDao.copy_event_model(event, import_data) key = self.eventDao.persist(event, self.user_info) upload_count += 1 logger.info('Event updated for %s with key %s' % (alias_name, key)) else: key = self.eventDao.persist( import_data, self.user_info) upload_count += 1 logger.info('Event created for %s' % (update['name'])) if key is not None: logger.info( str(entity_type) + ' succesfully created/updated') else: logger.error('Already Exist of %s:%s' % (entity_type, update['name'])) except StandardError as e: #skipping to next record logger.error('Error occured, %s, for %s' % (str(e), alias_name)) else: logger.info("skipping record number, %s " % row_count) return upload_count @webapp2.cached_property def form(self): return forms.ImportForm(self) def upload_photos(self, photos): upload_files = self.get_uploads() if upload_files is not None and len(upload_files) > 0: files_count = len(upload_files) logger.info('no of files uploaded ' + str(files_count)) for x in xrange(files_count): blob_info = upload_files[x] media_obj = Media() media_obj.name = self.form.media.__getitem__(x).data['name'] media_obj.status = self.form.media.__getitem__( x).data['status'] media_obj.link = blob_info.key() photos.append(media_obj) logger.info('Link to picture file ' + media_obj.name + ', ' + images.get_serving_url(media_obj.link)) return photos def create_or_update_business(self, alias_name, import_data): business = self.businessDao.query_by_alias(alias_name) if business is not None: business_key = business.key import_data.business_id = business_key logger.info('Business Already Exist with Key %s' % str(business_key)) else: try: business = Business() business.name = import_data.name business.description = import_data.description business.alias = import_data.alias business.contact_info = import_data.contact_info business_key = self.businessDao.persist( business, self.user_info) import_data.business_id = business_key logger.info('New Business Created for %s with key %s' % (alias_name, str(business_key))) except StandardError as e: #Skip the error and continue logger.error('Error occured, %s, for %s' % (str(e), alias_name)) raise return business_key def form_to_dao_ground(self, alias_name, **update): try: playground = Playground() playground.name = update['name'] #Create an automatic alias for the playground playground.alias = alias_name playground.description = update['description'] playground.sport = update['sport'] playground = self.form_to_dao_address_import(playground, **update) playground = self.form_to_dao_contact_info_import( playground, **update) #if playground.photos is None: #playground.photos = [] #self.upload_photos(playground.photos) except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return playground def form_to_dao_center(self, alias_name, **update): try: trainingcentre = TrainingCentre() trainingcentre.name = update['name'] #Create an automatic alias for the trainingcentre trainingcentre.alias = alias_name trainingcentre.description = update['description'] trainingcentre.sport = update['sport'] trainingcentre = self.form_to_dao_address_import( trainingcentre, **update) trainingcentre = self.form_to_dao_contact_info_import( trainingcentre, **update) #if trainingcentre.photos is None: #trainingcentre.photos = [] #self.upload_photos(trainingcentre.photos) except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return trainingcentre def form_to_dao_event(self, alias_name, **update): try: event = Event() event.name = update['name'] #Create an automatic alias for the event event.alias = alias_name event.description = update['description'] event.sport = update['sport'] #event.start_datetime = update['start_datetime'] #event.end_datetime = update['end_datetime'] event = self.form_to_dao_contact_info_import(event, **update) #if event.photos is None: #event.photos = [] #self.upload_photos(event.photos) except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return event def form_to_dao_business(self, **update): business = Business() business.name = update['name'] #Create an automatic alias for the business business.alias = utils.slugify(update['name']) business.description = update['description'] business = self.form_to_dao_contact_info_import(business, **update) return business def form_to_dao_address_import(self, entity, **update): #entity = playground try: if update['locality'] == '' or update['city'] == '': raise StandardError('Locality is empty. Cannot create entity') entity.address = Address() entity.address.line1 = update['line1'].lower() entity.address.line2 = update['line2'].lower() entity.address.locality = update['locality'].lower() entity.address.city = update['city'].lower() entity.address.pin = update['pin'] lattitude, longitude = get_latlong_from_address(entity.address) if lattitude is not None and longitude is not None: entity.address.latlong = ndb.GeoPt(lattitude, longitude) except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return entity def form_to_dao_contact_info_import(self, entity, **update): try: entity.contact_info = ContactInfo() if len(update['person_name']) > 0: entity.contact_info.person_name = [ x.strip() for x in update['person_name'].split(',') ] if len(update['email']) > 0: entity.contact_info.email = [ x.strip() for x in update['email'].split(',') ] if len(update['phone']) > 0: entity.contact_info.phone = [ x.strip() for x in update['phone'].split(',') ] entity.contact_info.website = update['website'] entity.contact_info.facebook = update['facebook'] entity.contact_info.twitter = update['twitter'] entity.contact_info.youtube = update['youtube'] entity.contact_info.gplus = update['gplus'] except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return entity
class ImportTeamHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): eventDao = DaoFactory.create_rw_eventDao() matchDao = DaoFactory.create_rw_matchDao() teamDao = DaoFactory.create_rw_teamDao() playerDao = DaoFactory.create_rw_playerDao() @user_required def get(self): params = {} event_id = self.request.get('event_id') upload_field = self.request.get('importfile') continue_url = self.request.get('continue').encode('ascii', 'ignore') logger.info('Continue Url: ' + str(continue_url)) if upload_field != '': upload_files = self.get_uploads('importfile') logger.info('Upload Datas: ' + str(upload_files)) blob_info = upload_files[0] start_record = 1 upload_count = self.process_csv(blob_info, start_record, event_id) self.add_message( str(upload_count) + ' entities created successfully.', 'success') if continue_url: return self.redirect(continue_url) else: return self.redirect_to('dashboard') upload_url = self.uri_for('import-team') params['title'] = 'Import Team' params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/import.html', **params) @user_required def post(self): if not self.form.validate(): return self.get() start_record = int(str(self.request.get('linenum'))) upload_field = self.request.get('importfile') continue_url = self.request.get('continue').encode('ascii', 'ignore') if upload_field != '': upload_files = self.get_uploads( 'importfile') # 'file' is file upload field in the form logger.info('Upload Datas: ' + str(upload_files)) blob_info = upload_files[0] start_record = start_record if start_record != '' else 1 upload_count = self.process_csv(blob_info, start_record) self.add_message( str(upload_count) + ' entities created successfully.', 'success') if continue_url: return self.redirect(continue_url) else: return self.redirect_to('import-team') logger.error('Empty upload file field select correct file') message = ('Empty upload file field select correct file') self.add_message(message, 'error') return self.redirect_to('import-team') def process_csv(self, blob_info, start_record, event_id=None): update = {} upload_count = 0 row_count = 0 blob_reader = blobstore.BlobReader(blob_info.key()) datareader = csv.reader(blob_reader) for row in datareader: row_count += 1 if row_count >= (start_record + 1): #to skip the header row logger.info('Starting to parse %s, %s' % (row_count, row[1])) entity_type = row[0].lower() update['name'] = utils.stringify(row[1]) # Name is mandatory for all entities if update['name'] == '': logger.error('Name is empty. Skipping this record') continue alias_name = utils.slugify(update['name'].lower()) # Event Id check for matches if event_id is not None and len(event_id) > 1: event_data = self.eventDao.get_record(event_id) event_alias_name = event_data.alias else: event_alias_name = '' try: update['sport'] = utils.stringify(row[2]).lower() if entity_type == 'match': update['start_datetime'] = datetime.strptime( row[3], '%d-%m-%Y %I:%M%p') update['end_datetime'] = datetime.strptime( row[4], '%d-%m-%Y %I:%M%p') update['result'] = utils.stringify(row[5]) event_alias_name = utils.slugify(row[6].lower( )) if row[6] != '' else event_alias_name update['participant_type'] = utils.stringify( row[7]).lower() elif entity_type == 'player': update['email'] = utils.stringify(row[3]) update['phone'] = utils.stringify(row[4]) update['teamName'] = utils.stringify(row[5]) team_alias_name = utils.slugify( update['teamName'].lower()) logger.debug('Constructed Structure for upload ' + str(update)) logger.info('Entity type to be created, ' + entity_type) if entity_type == 'match': import_data = self.form_to_dao_match( alias_name, **update) elif entity_type == 'team': import_data = self.form_to_dao_team( alias_name, **update) elif entity_type == 'player': import_data = self.form_to_dao_player( alias_name, **update) logger.debug('Populated File Data ' + str(import_data)) if entity_type == 'match': event = self.eventDao.query_by_alias(event_alias_name) if event is not None: match_exist = self.matchDao.query_by_alias( alias_name, event.key, update['sport']) if match_exist is None: import_data.event_id = event.key key = self.matchDao.persist( import_data, self.user_info) upload_count += 1 logger.info( 'New Match Created for %s with key %s' % (alias_name, key)) else: logger.error('Already Exist of %s:%s' % (entity_type, update['name'])) else: logger.error('Event Name %s doesnot exist' % (event_alias_name)) elif entity_type == 'team': team_exist = self.teamDao.query_by_alias( alias_name, update['sport']) logger.info('Team Exist Data: ' + str(team_exist)) if team_exist is None: key = self.teamDao.persist(import_data, self.user_info) upload_count += 1 logger.info('New Team Created for %s with key %s' % (alias_name, key)) else: logger.error('Already Exist of %s:%s' % (entity_type, update['name'])) elif entity_type == 'player': player_exist = self.playerDao.query_by_email( update['email']) logger.info('Player Exist Data: ' + str(player_exist)) if player_exist is None: team_exist = self.teamDao.query_by_team_alias( team_alias_name, self.user_info) logger.info('Exist Team for player: ' + str(team_exist)) if team_exist is None: team_import_data = self.form_to_dao_team_auto( team_alias_name, **update) team_key = self.teamDao.persist( team_import_data, self.user_info) logger.info( 'New Team Created for %s with key %s' % (team_alias_name, team_key)) import_data.teams = team_key else: import_data.teams = team_exist.key key = self.playerDao.persist( import_data, self.user_info) upload_count += 1 logger.info( 'New Player Created for %s with key %s' % (alias_name, key)) else: logger.error('Already Exist of %s:%s' % (entity_type, update['name'])) if key is not None: logger.info( str(entity_type) + ' succesfully created/updated') else: logger.error('Already Exist of %s:%s' % (entity_type, update['name'])) except StandardError as e: #skipping to next record logger.error('Error occured, %s, for %s' % (str(e), alias_name)) else: logger.info("skipping record number, %s " % row_count) return upload_count @webapp2.cached_property def form(self): return forms.ImportForm(self) def form_to_dao_match(self, alias_name, **update): try: match = Match() match.name = update['name'] #Create an automatic alias for the match match.alias = alias_name match.sport = update['sport'] match.participant_type = update['participant_type'] match.start_datetime = update['start_datetime'] match.end_datetime = update['end_datetime'] match.result = update['result'] except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return match def form_to_dao_team(self, alias_name, **update): try: team = Team() team.name = update['name'] #Create an automatic alias for the team team.alias = alias_name team.sport = update['sport'] except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return team def form_to_dao_team_auto(self, team_alias_name, **update): try: team = Team() team.name = update['teamName'] #Create an automatic alias for the team team.alias = team_alias_name team.sport = update['sport'] except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return team def form_to_dao_player(self, alias_name, **update): try: player = Player() player.name = update['name'] player.email = update['email'] player.phone = update['phone'] player.sport = update['sport'] except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return player
class EditTeamPlayerHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): teamDao = DaoFactory.create_rw_teamDao() playerDao = DaoFactory.create_rw_playerDao() profileDao = DaoFactory.create_rw_profileDao() @user_required def post(self, team_id=None): params = {} team = self.form_to_dao(team_id) logger.debug('team populated ' + str(team)) key = self.teamDao.persist(team, self.user_info) logger.debug('key ' + str(key)) if key is not None: logger.info('team succesfully created/updated') message = ('team succesfully created/updated.') self.add_message(message, 'success') redirect_url = self.uri_for('view-team', team_id = key.id()) if redirect_url: return self.redirect(redirect_url) else: return self.redirect_to('dashboard', **params) logger.error('team creation failed') message = ('team creation failed.') self.add_message(message, 'error') return self.render_template('/cms/team_detail.html', **params) @webapp2.cached_property def form(self): return forms.TeamForm(self) def upload_players(self): players = [] new_player_count = len(self.form.new_player) logger.info('No of New players %s' % new_player_count) sport = self.request.get('sport') for x in xrange(new_player_count): player_obj = Player() player_obj.name = self.form.new_player.__getitem__(x).data['name'] player_obj.email = self.form.new_player.__getitem__(x).data['email'] #player_obj.phone = self.form.new_player.__getitem__(x).data['phone'] player_obj.sport = sport logger.info('New Player Data: ' + str(player_obj)) if player_obj.email != '': player_exist = self.playerDao.query_by_email(player_obj.email) logger.info('Exist Player Data: ' + str(player_exist)) if player_exist is None: key = self.playerDao.persist(player_obj, self.user_info) players.append(key) logger.info('Add New Player %s' % player_obj.name) else: players.append(player_exist.key) logger.info('Skipped Already Exist of Player %s' % player_obj.name) else: logger.info('Skipped Empty Player Data') return players def form_to_dao(self, team_id): team = None players = [] if team_id is not None and len(team_id) > 1: team = self.teamDao.get_record(long(team_id)) else: team = Team() players = self.upload_players() sel_player = self.request.get_all('player') logger.debug('sel_player: ' + str(sel_player)) if len(sel_player) > 0: players_count = len(sel_player) logger.debug('No of Selected Players %s' % players_count) for x in xrange(players_count): players.append(self.profileDao.get_record(sel_player[x]).key) logger.info('Total No of Players Mapped %s' % len(players)) logger.debug('Total Players Data: ' + str(players)) team.players = players return team
class ManageMatchHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): eventDao = DaoFactory.create_rw_eventDao() matchDao = DaoFactory.create_rw_matchDao() teamDao = DaoFactory.create_rw_teamDao() playerDao = DaoFactory.create_rw_playerDao() @role_required('business') def get(self, event_id=None, match_id=None): params = {} import_url = self.uri_for('import-team') params['import_url'] = blobstore.create_upload_url(import_url) upload_url = self.uri_for('select-for-match') continue_url = self.request.get('continue').encode('ascii', 'ignore') #params['continue_url'] = continue_url if continue_url != '' else upload_url status = self.request.get('status') match_status = status if status != '' else None params['title'] = 'Create New Match' if event_id is not None and len(event_id) > 1: self.form.event_id = event_id params['event_id'] = event_id params['teams'] = self.teamDao.query_by_owner(self.user_info) params['players'] = self.playerDao.query_by_owner(self.user_info) params['continue_url'] = continue_url #logger.debug('teams: ' + str(params['teams'])) if match_id is not None and len(match_id) > 1: match = self.matchDao.get_record(match_id) params['title'] = 'Update - ' + str(match.name) participants = [] for x in xrange(len(match.participants)): participants.append(match.participants[x].id()) params['participants'] = participants logger.info('select participants: ' + str(params['participants'])) if match_status is not None: logger.info('current status: %s' % match_status) key = self.matchDao.status_change(match, self.user_info) if key is not None: updated_match = self.matchDao.get_record(long( key.id())) logger.info('updated status : %s' % updated_match.status) if match_status == str(updated_match.status): logger.info('match status could not be changed.') message = ('match status could not be changed.') self.add_message(message, 'error') else: logger.info('match status succesfully changed.') message = ('match status succesfully changed.') self.add_message(message, 'success') return self.redirect(continue_url) else: upload_url = self.uri_for('edit-match', event_id=event_id, match_id=match_id) params['media_upload_url'] = blobstore.create_upload_url( upload_url) self.form = forms.MatchForm(self, match) return self.render_template('/cms/create_match.html', **params) else: upload_url = self.uri_for('create-match', event_id=event_id) params['media_upload_url'] = blobstore.create_upload_url( upload_url) return self.render_template('/cms/create_match.html', **params) params['continue_url'] = upload_url params['entity_name'] = 'Match' params['owner_event'] = self.eventDao.query_by_owner(self.user_info) return self.render_template('/cms/select_event.html', **params) @role_required('business') def post(self, event_id=None, match_id=None): params = {} if not self.form.validate(): if event_id is not None and len(event_id) > 0: if match_id is not None and len(match_id) > 0: return self.get(event_id, match_id) else: return self.get(event_id) else: return self.get() continue_url = self.request.get('continue').encode('ascii', 'ignore') match = self.form_to_dao(match_id) logger.debug('match populated ' + str(match)) event = self.eventDao.get_record(event_id) event_key = event.key if event_key is not None: logger.info('Event succesfully created for match') match.event_id = event_key key = self.matchDao.persist(match, self.user_info) logger.debug('key ' + str(key)) if key is not None: logger.info('match succesfully created/updated') message = ('match succesfully created/updated.') self.add_message(message, 'success') if continue_url: return self.redirect(continue_url) else: return self.redirect_to('dashboard', **params) logger.error('match creation failed') message = ('match creation failed.') self.add_message(message, 'error') self.form = forms.MatchForm(self, event) return self.render_template('/cms/create_match.html', **params) @webapp2.cached_property def form(self): return forms.MatchForm(self) def form_to_dao(self, match_id): match = None if match_id is not None and len(match_id) > 1: match = self.matchDao.get_record(long(match_id)) else: match = Match() match.name = self.form.name.data match.sport = self.form.sport.data #Create an automatic alias for the match match.alias = utils.slugify(self.form.name.data) match.start_datetime = self.form.start_datetime.data match.end_datetime = self.form.end_datetime.data match.result = self.form.result.data match.summary = self.form.summary.data match.participant_type = self.form.participant_type.data sel_team = self.request.get_all('team') sel_player = self.request.get_all('player') logger.debug('sel_team: ' + str(sel_team)) logger.debug('sel_player: ' + str(sel_player)) if match.participant_type == 'team': if len(sel_team) > 0: teams = [] teams_count = len(sel_team) logger.debug('Teams Count: ' + str(teams_count)) for x in xrange(teams_count): teams.append(self.teamDao.get_record(sel_team[x]).key) logger.debug('Participants ' + str(teams)) match.participants = teams else: if len(sel_player) > 0: players = [] players_count = len(sel_player) logger.debug('Teams Count: ' + str(players_count)) for x in xrange(players_count): players.append( self.playerDao.get_record(sel_player[x]).key) logger.debug('Participants ' + str(players)) match.participants = players return match
class ProfileHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): eventDao = DaoFactory.create_rw_eventDao() playgroundDao = DaoFactory.create_rw_playgroundDao() trainingcentreDao = DaoFactory.create_rw_trainingCentreDao() mediaDao = DaoFactory.create_ro_mediaDao() profileDao = DaoFactory.create_rw_profileDao() teamDao = DaoFactory.create_rw_teamDao() @user_required def get(self, user_id=None): params = {} if user_id is not None and len(user_id) > 1: user_info = self.user_model.get_by_id(long(user_id)) upload_url = self.uri_for('edit-profile', user_id=user_id) logger.debug('upload_url : ' + upload_url) if user_info.image: params['current_image'] = images.get_serving_url(user_info.image) if user_info.sport: params['sel_sport'] = [x.strip() for x in user_info.sport.split(',')] params['sports_list'] = constants.SPORTS_LIST params['media_upload_url'] = blobstore.create_upload_url(upload_url) self.form = forms.UserProfileForm(self, user_info) return self.render_template('/cms/edit_profile.html', **params) '''logger.debug('User Id: ' + str(self.user_id)) logger.debug('User Info: ' + str(self.user_info)) logger.debug('User Type: ' + str(self.user_type))''' if self.user_info.image: params['current_image'] = images.get_serving_url(self.user_info.image) elif self.user_type[0] == 'facebook': params['current_image'] = 'https://graph.facebook.com/'+str(self.user_type[1])+'/picture?type=large' upload_url = self.uri_for('edit-user-image') params['media_upload_url'] = blobstore.create_upload_url(upload_url) upload_gallery_url = self.uri_for('upload-profile-gallery') params['upload_gallery_url'] = blobstore.create_upload_url(upload_gallery_url) params['title'] = self.user_info.name params['want_list'] = constants.WANT_DICT params['owner_info'] = self.user_info params['profile_gallery'] = self.mediaDao.get_all_media(self.user_info.key, constants.PROFILE) params['owner_playgrounds'] = self.playgroundDao.query_by_owner(self.user_info) params['owner_events'] = self.eventDao.query_by_owner(self.user_info) params['owner_trainingcentres'] = self.trainingcentreDao.query_by_owner(self.user_info) params['owner_teams'] = self.teamDao.query_by_owner(self.user_info, 'all', 4) recommend_events = self.eventDao.get_recommend(self.user_info.locality, self.user_info.sport, 4) params['recommend_events'] = recommend_events recommend_playgrounds = self.playgroundDao.get_recommend(self.user_info.locality, self.user_info.sport, 4) params['recommend_playgrounds'] = recommend_playgrounds recommend_trainingcentres = self.trainingcentreDao.get_recommend(self.user_info.locality, self.user_info.sport, 4) params['recommend_trainingcentres'] = recommend_trainingcentres event_media = self.mediaDao.get_primary_media(recommend_events, constants.EVENT) params['event_media'] = event_media playground_media = self.mediaDao.get_primary_media(recommend_playgrounds, constants.PLAYGROUND) params['playground_media'] = playground_media trainingcentre_media = self.mediaDao.get_primary_media(recommend_trainingcentres, constants.TRAINING_CENTRE) params['trainingcentre_media'] = trainingcentre_media logger.debug(' event_media %s ' % len(event_media)) logger.debug(' playground_media %s ' % len(playground_media)) logger.debug(' trainingcentre_media %s ' % len(trainingcentre_media)) return self.render_template('/cms/profile.html', **params)
class BaseHandler(webapp2.RequestHandler): importDao = DaoFactory.create_rw_importDao() profileDao = DaoFactory.create_rw_profileDao() """ BaseHandler for all requests Holds the auth and session properties so they are reachable for all requests """ def __init__(self, request, response): """ Override the initialiser in order to set the language. """ self.initialize(request, response) self.locale = i18n.set_locale(self, request) self.view = ViewClass() def dispatch(self): """ Get a session store for this request. """ self.session_store = sessions.get_store(request=self.request) try: # csrf protection if self.request.method == "POST" and not self.request.path.startswith( '/taskqueue'): token = self.session.get('_csrf_token') if not token or token != self.request.get('_csrf_token'): self.abort(403) # Dispatch the request. webapp2.RequestHandler.dispatch(self) finally: # Save all sessions. self.session_store.save_sessions(self.response) @webapp2.cached_property def user_model(self): """Returns the implementation of the user model. Keep consistency when config['webapp2_extras.auth']['user_model'] is set. """ return self.auth.store.user_model @webapp2.cached_property def auth(self): return auth.get_auth() @webapp2.cached_property def session_store(self): return sessions.get_store(request=self.request) @webapp2.cached_property def session(self): # Returns a session using the default cookie key. return self.session_store.get_session() @webapp2.cached_property def messages(self): return self.session.get_flashes(key='_messages') def add_message(self, message, level=None): self.session.add_flash(message, level, key='_messages') @webapp2.cached_property def auth_config(self): """ Dict to hold urls for login/logout """ return { 'login_url': self.uri_for('login'), 'logout_url': self.uri_for('logout') } @webapp2.cached_property def user(self): return self.auth.get_user_by_session() @webapp2.cached_property def user_id(self): return str(self.user['user_id']) if self.user else None @webapp2.cached_property def user_info(self): if self.user: return self.user_model.get_by_id(long(self.user_id)) return None @webapp2.cached_property def user_type(self): if self.user: user_info = self.user_model.get_by_id(long(self.user_id)) return user_info.auth_ids[0].split(':') return None @webapp2.cached_property def user_key(self): if self.user: user_info = self.user_model.get_by_id(long(self.user_id)) return user_info.key return None @webapp2.cached_property def email(self): if self.user: try: user_info = self.user_model.get_by_id(long(self.user_id)) return user_info.email except AttributeError, e: # avoid AttributeError when the session was delete from the server logging.error(e) self.auth.unset_session() self.redirect_to('home') return None
class ManageBulkDataHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): bulkdataDao = DaoFactory.create_rw_bulkdataDao() businessDao = DaoFactory.create_rw_businessDao() mediaDao = DaoFactory.create_rw_mediaDao() @user_required def get(self, masterdata_id=None): params = {} upload_url = self.uri_for('create-bulk-data') continue_url = self.request.get('continue').encode('ascii', 'ignore') status = self.request.get('status') pg_status = status if status != '' else None params['title'] = 'Create Bulk Data' params['weekdays'] = constants.DAYS_LIST if masterdata_id is not None and len(masterdata_id) > 1: masterdata = self.playgroundDao.get_record(masterdata_id) params['title'] = 'Update - ' + str(masterdata.name) params['continue_url'] = continue_url if pg_status is not None: logger.info('current status: %s' % pg_status) key = self.playgroundDao.status_change(masterdata, self.user_info) if key is not None: updated_pg = self.playgroundDao.get_record(long(key.id())) logger.info('updated status : %s' % updated_pg.status) if pg_status == str(updated_pg.status): logger.info('masterdata status could not be changed.') message = ('masterdata status could not be changed.') self.add_message(message, 'error') else: logger.info('masterdata status succesfully changed.') message = ('masterdata status succesfully changed.') self.add_message(message, 'success') return self.redirect(continue_url) else: upload_url = self.uri_for('edit-masterdata', masterdata_id=masterdata_id) all_media = self.mediaDao.get_all_media( masterdata.key, constants.PLAYGROUND) current_media = [] for photo in all_media: current_media.append({ 'name': photo.name, 'url': images.get_serving_url(photo.link), 'status': photo.status, 'primary': photo.primary }) params['current_media'] = current_media self.form = cms_utils.dao_to_form_locality_info( masterdata, forms.BulkPlaygroundForm(self, masterdata)) self.form = cms_utils.dao_to_form_contact_info( masterdata, self.form) params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/create_bulk_data.html', **params) @user_required def post(self, masterdata_id=None): params = {} if not self.form.validate(): if masterdata_id is not None and len(masterdata_id) > 1: return self.get(masterdata_id) else: return self.get() save = self.request.get('save') next = self.request.get('next') next_tab = next if next != '' else save locality_id = self.request.get('locality_id') masterdata = self.form_to_dao(masterdata_id) if locality_id is not None: logger.info('Locality Id: %s ' % locality_id) locality_count = self.process_locality(masterdata.address.locality, locality_id, constants.PLACES_API_KEY) masterdata.address.locality_id = locality_id logger.debug('masterdata populated ' + str(masterdata)) key = self.bulkdataDao.persist(masterdata, self.user_info) logger.debug('key ' + str(key)) if key is not None: self.upload_photos(key) logger.info('masterdata succesfully created/updated') message = ('masterdata succesfully created/updated.') self.add_message(message, 'success') return self.redirect_to('create-bulk-data', **params) logger.error('masterdata creation failed') message = ('masterdata creation failed.') self.add_message(message, 'error') self.form = forms.MasterDataForm(self, masterdata) return self.render_template('/cms/create_bulk_data.html', **params) @webapp2.cached_property def form(self): return forms.MasterDataForm(self) def upload_photos(self, key): upload_files = self.get_uploads() if upload_files is not None and len(upload_files) > 0: files_count = len(upload_files) logger.info('no of files uploaded ' + str(files_count)) for x in xrange(files_count): blob_info = upload_files[x] media_obj = Media() media_obj.name = self.form.media.__getitem__(x).data['name'] media_obj.type = constants.PHOTO media_obj.status = self.form.media.__getitem__( x).data['status'] media_obj.primary = self.form.media.__getitem__( x).data['primary'] media_obj.link = blob_info.key() media_obj.url = images.get_serving_url(blob_info.key()) media_obj.entity_id = key media_obj.entity_type = constants.PLAYGROUND self.mediaDao.persist(media_obj) logger.info('Link to picture file ' + media_obj.name + ', ' + images.get_serving_url(media_obj.link)) def form_to_dao(self, masterdata_id): masterdata = None if masterdata_id is not None and len(masterdata_id) > 1: masterdata = self.playgroundDao.get_record(long(masterdata_id)) else: masterdata = MasterData() masterdata.pg_name = self.form.pg_name.data masterdata.sport = self.form.sport.data.lower() masterdata.public = self.form.public.data masterdata.booking_days = self.form.booking_days.data masterdata.regular_time = self.form.regular_time.data masterdata.ground_type = self.form.ground_type.data.lower() masterdata.surface_type = self.form.surface_type.data.lower() masterdata.tot_fields = self.form.tot_fields.data masterdata.ground_rules = self.form.ground_rules.data.lower() masterdata.tc_name = self.form.tc_name.data masterdata.tc_open_days = self.form.tc_open_days.data.lower() masterdata.age_limit = self.form.age_limit.data masterdata.tc_participants = self.form.tc_participants.data masterdata.se_name = self.form.se_name.data if self.form.start_datetime.data is not None: masterdata.start_datetime = datetime( *(self.form.start_datetime.data.timetuple()[:6])) if self.form.end_datetime.data is not None: masterdata.end_datetime = datetime( *(self.form.end_datetime.data.timetuple()[:6])) masterdata = cms_utils.form_to_dao_address(self.form, masterdata) masterdata = cms_utils.form_to_dao_contact_pg(self.form, masterdata) masterdata = cms_utils.form_to_dao_contact_tc(self.form, masterdata) masterdata = cms_utils.form_to_dao_contact_se(self.form, masterdata) return masterdata def create_or_update_business(self, playground): if playground.business_id is not None: business = self.businessDao.get_record( long(playground.business_id.id())) else: business = Business() business.name = playground.name business.alias = playground.alias business.description = playground.description business.contact_info = playground.contact_info return business
class ManagePlaygroundHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): playgroundDao = DaoFactory.create_rw_playgroundDao() businessDao = DaoFactory.create_rw_businessDao() mediaDao = DaoFactory.create_rw_mediaDao() @user_required def get(self, playground_id=None): params = {} upload_url = self.uri_for('create-playground') continue_url = self.request.get('continue').encode('ascii', 'ignore') status = self.request.get('status') pg_status = status if status != '' else None params['title'] = 'Create New Playground' if playground_id is not None and len(playground_id) > 1: playground = self.playgroundDao.get_record(playground_id) params['title'] = 'Update - ' + str(playground.name) params['continue_url'] = continue_url if pg_status is not None: logger.info('current status: %s' % pg_status) key = self.playgroundDao.status_change(playground, self.user_info) if key is not None: updated_pg = self.playgroundDao.get_record(long(key.id())) logger.info('updated status : %s' % updated_pg.status) if pg_status == str(updated_pg.status): logger.info('playground status could not be changed.') message = ('playground status could not be changed.') self.add_message(message, 'error') else: logger.info('playground status succesfully changed.') message = ('playground status succesfully changed.') self.add_message(message, 'success') return self.redirect(continue_url) else: upload_url = self.uri_for('edit-playground', playground_id = playground_id) all_media = self.mediaDao.get_all_media(playground.key, constants.PLAYGROUND) current_media = [] for photo in all_media: current_media.append({'name': photo.name, 'url':images.get_serving_url(photo.link), 'status': photo.status, 'primary': photo.primary}) params['current_media'] = current_media self.form = cms_utils.dao_to_form_locality_info(playground, forms.PlaygroundForm(self, playground)) self.form = cms_utils.dao_to_form_contact_info(playground, self.form) params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/create_playground.html', **params) @user_required def post(self, playground_id=None): params = {} if not self.form.validate(): if playground_id is not None and len(playground_id) > 1: return self.get(playground_id) else: return self.get() save = self.request.get('save') next = self.request.get('next') next_tab = next if next != '' else save locality_id = self.request.get('locality_id') playground = self.form_to_dao(playground_id) if locality_id is not None: logger.info('Locality Id: %s ' % locality_id) locality_count = self.process_locality(playground.address.locality, locality_id, constants.PLACES_API_KEY) playground.address.locality_id = locality_id logger.debug('playground populated ' + str(playground)) business = self.create_or_update_business(playground) business_key = self.businessDao.persist(business, self.user_info) if business_key is not None: logger.info('Business succesfully created for playground, ' + business.name) playground.business_id = business_key key = self.playgroundDao.persist(playground, self.user_info) logger.debug('key ' + str(key)) if key is not None: self.upload_photos(key) logger.info('playground succesfully created/updated') message = ('playground succesfully created/updated.') self.add_message(message, 'success') if next_tab is not None: if next_tab != 'save': redirect_url = self.uri_for('edit-playground', playground_id = key.id()) redirect_url = redirect_url + next_tab logger.info('Redirect Url %s' % redirect_url) return self.redirect(redirect_url) else: redirect_url = self.uri_for('pg-details', city_name = playground.address.city, locality_name = playground.address.locality, entity_id = key.id(), entity_alias = playground.alias) return self.redirect(redirect_url) #return self.redirect_to('dashboard', **params) logger.error('playground creation failed') message = ('playground creation failed.') self.add_message(message, 'error') self.form = forms.PlaygroundForm(self, playground) return self.render_template('/cms/create_playground.html', **params) @webapp2.cached_property def form(self): return forms.PlaygroundForm(self) def upload_photos(self, key): upload_files = self.get_uploads() if upload_files is not None and len(upload_files) > 0: files_count = len(upload_files) logger.info('no of files uploaded ' + str(files_count)) for x in xrange(files_count): blob_info = upload_files[x] media_obj = Media() media_obj.name = self.form.media.__getitem__(x).data['name'] media_obj.type = constants.PHOTO media_obj.status = self.form.media.__getitem__(x).data['status'] media_obj.primary = self.form.media.__getitem__(x).data['primary'] media_obj.link = blob_info.key() media_obj.url = images.get_serving_url(blob_info.key()) media_obj.entity_id = key media_obj.entity_type = constants.PLAYGROUND self.mediaDao.persist(media_obj) logger.info('Link to picture file ' + media_obj.name + ', ' + images.get_serving_url(media_obj.link)) def form_to_dao(self, playground_id): playground = None if playground_id is not None and len(playground_id) > 1: playground = self.playgroundDao.get_record(long(playground_id)) else: playground = Playground() playground.name = self.form.name.data playground.sport = self.form.sport.data.lower() #Create an automatic alias for the playground playground.alias = utils.slugify(self.form.name.data) playground.description = self.form.description.data playground.featured = self.form.featured.data self.form.address.locality.data = self.form.locality.data #for locality from basic info to address self.form.address.city.data = self.form.city.data #for city from basic info to address playground = cms_utils.form_to_dao_address(self.form, playground) playground = cms_utils.form_to_dao_contact_info(self.form, playground) return playground def create_or_update_business(self, playground): if playground.business_id is not None: business = self.businessDao.get_record(long(playground.business_id.id())) else: business = Business() business.name = playground.name business.description = playground.description business.alias = playground.alias business.contact_info = playground.contact_info return business
class CityHomeHandler(BaseHandler): mediaDao = DaoFactory.create_ro_mediaDao() eventDao = DaoFactory.create_ro_eventDao() playgroundDao = DaoFactory.create_ro_playgroundDao() trainingcentreDao = DaoFactory.create_ro_trainingCentreDao() def get(self, city_name=None, sport=None): params = {} logger.debug('home for city %s, and sport %s ' % (city_name, sport)) # if city_name is None: # city_name = get_default_city() # if sport is not None and sport != 'None' and sport != '': # return self.render_template('/cms/dashboard.html') recent_playgrounds = self.playgroundDao.get_recent(city_name, sport) featured_playgrounds = self.playgroundDao.get_featured(city_name, sport) popular_playgrounds = self.playgroundDao.get_popular(city_name, sport) logger.debug(' recent_playgrounds %s ' % len(recent_playgrounds)) logger.debug(' featured_playgrounds %s ' % len(featured_playgrounds)) logger.debug(' popular_playgrounds %s ' % len(popular_playgrounds)) playgrounds = recent_playgrounds + featured_playgrounds + popular_playgrounds playground_media = self.mediaDao.get_primary_media(playgrounds, constants.PLAYGROUND) logger.debug(' playground_media %s ' % len(playground_media)) recent_trainingcentres = self.trainingcentreDao.get_recent(city_name, sport) featured_trainingcentres = self.trainingcentreDao.get_featured(city_name, sport) popular_trainingcentres = self.trainingcentreDao.get_popular(city_name, sport) logger.debug(' recent_trainingcentres %s ' % len(recent_trainingcentres)) logger.debug(' featured_trainingcentres %s ' % len(featured_trainingcentres)) logger.debug(' popular_trainingcentres %s ' % len(popular_trainingcentres)) trainingcentres = recent_trainingcentres + featured_trainingcentres + popular_trainingcentres trainingcentre_media = self.mediaDao.get_primary_media(trainingcentres, constants.TRAINING_CENTRE) logger.debug(' trainingcentre_media %s ' % len(trainingcentre_media)) recent_events = self.eventDao.get_recent(city_name, sport) featured_events = self.eventDao.get_featured(city_name, sport) ongoing_events = self.eventDao.get_ongoing(city_name, sport) upcoming_events = self.eventDao.get_upcoming(city_name, sport) logger.debug(' recent_events %s ' % len(recent_events)) logger.debug(' featured_events %s ' % len(featured_events)) logger.debug(' ongoing_events %s ' % len(ongoing_events)) logger.debug(' upcoming_events %s ' % len(upcoming_events)) events = recent_events + featured_events + ongoing_events + upcoming_events event_media = self.mediaDao.get_primary_media(events, constants.EVENT) logger.debug(' event_media %s ' % len(event_media)) params['recent_playgrounds'] = recent_playgrounds params['featured_playgrounds'] = featured_playgrounds params['popular_playgrounds'] = popular_playgrounds params['playground_media'] = playground_media params['recent_events'] = recent_events params['featured_events'] = featured_events params['ongoing_events'] = ongoing_events params['upcoming_events'] = upcoming_events params['event_media'] = event_media params['recent_trainingcentres'] = recent_trainingcentres params['featured_trainingcentres'] = featured_trainingcentres params['popular_trainingcentres'] = popular_trainingcentres params['trainingcentre_media'] = trainingcentre_media if city_name is None: city_name = get_default_city() params['city_name'] = city_name params['sport'] = sport params['home'] = 'true' params['title'] = 'Sports Home' return self.render_template('/app/homenew.html', **params)
class ManageBusinessHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): businessDao = DaoFactory.create_rw_businessDao() @role_required('business') def get(self, business_id=None): params = {} params['title'] = 'Create New Business' upload_url = self.uri_for('create-business') if business_id is not None and len(business_id) > 1: upload_url = self.uri_for('edit-business', business_id=business_id) business = self.businessDao.get_record(business_id) params['title'] = 'Update - ' + str(business.name) if business.logo: params['current_logo'] = images.get_serving_url(business.logo) self.form = cms_utils.dao_to_form_contact_info( business, forms.BusinessForm(self, business)) logger.debug('upload_url' + upload_url) params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/create_business.html', **params) @role_required('business') def post(self, business_id=None): params = {} if not self.form.validate(): if business_id is not None and len(business_id) > 1: return self.get(business_id) else: return self.get() business = self.form_to_dao(business_id) upload_files = self.get_uploads( 'logo') # 'logo' is file upload field in the form if upload_files is not None and len(upload_files) > 0: blob_info = upload_files[0] business.logo = blob_info.key() logger.info('Link to logo ' + images.get_serving_url(business.logo)) logger.debug('business populated ' + str(business)) key = self.businessDao.persist(business, self.user_info) logger.debug('key ' + str(key)) if key is not None: logger.info('Business succesfully created/updated') message = ('Business succesfully created/updated.') self.add_message(message, 'success') return self.redirect_to('dashboard', **params) else: logger.error('business creation failed') message = ('Business creation failed.') self.add_message(message, 'error') self.form = forms.BusinessForm(self, business) return self.render_template('/cms/create_business.html', **params) @webapp2.cached_property def form(self): return forms.BusinessForm(self) def form_to_dao(self, business_id): business = None if business_id is not None and len(business_id) > 1: business = self.businessDao.get_record(long(business_id)) logger.debug('business ' + str(business)) else: business = Business() logger.debug('business 2 ' + str(business)) business.name = self.form.name.data #Create an automatic alias for the business business.alias = utils.slugify(self.form.name.data) business.description = self.form.description.data return cms_utils.form_to_dao_contact_info(self.form, business)
class ManageTeamHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): teamDao = DaoFactory.create_rw_teamDao() playerDao = DaoFactory.create_rw_playerDao() profileDao = DaoFactory.create_rw_profileDao() @user_required def get(self, team_id=None): params = {} import_url = self.uri_for('import-team') params['import_url'] = blobstore.create_upload_url(import_url) upload_url = self.uri_for('create-team') continue_url = self.request.get('continue').encode('ascii', 'ignore') params['continue_url'] = continue_url #params['continue_url'] = continue_url if continue_url != '' else upload_url #params['players'] = self.playerDao.query_by_owner(self.user_info) params['players'] = self.profileDao.query_by_all(self.user_info) params['title'] = 'Create New Team' if team_id is not None and len(team_id) > 1: upload_url = self.uri_for('edit-team', team_id = team_id) team = self.teamDao.get_record(team_id) params['title'] = 'Update - ' + str(team.name) if team.logo: params['current_logo'] = images.get_serving_url(team.logo) self.form = forms.TeamForm(self, team) players = [] for x in xrange(len(team.players)): players.append(team.players[x].id()) params['sel_players'] = players params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/create_team.html', **params) else: params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/create_team.html', **params) params['entity_name'] = 'Team' params['owner_teams'] = self.teamDao.query_by_owner(self.user_info) return self.render_template('/cms/dashboard.html', **params) @user_required def post(self, team_id=None): params = {} if not self.form.validate(): if team_id is not None and len(team_id) > 0: return self.get(team_id) else: return self.get() upload_files = self.get_uploads('logo') # 'logo' is file upload field in the form logger.debug('upload_files ' + str(upload_files)) continue_url = self.request.get('continue').encode('ascii', 'ignore') team = self.form_to_dao(team_id) if upload_files is not None and len(upload_files) > 0: blob_info = upload_files[0] team.logo = blob_info.key() team.logo_url = images.get_serving_url(blob_info.key()) logger.info('Link to logo ' + images.get_serving_url(team.logo)) logger.debug('team populated ' + str(team)) key = self.teamDao.persist(team, self.user_info) logger.debug('key ' + str(key)) if key is not None: logger.info('team succesfully created/updated') message = ('team succesfully created/updated.') self.add_message(message, 'success') redirect_url = self.uri_for('view-team', team_id = key.id()) if continue_url: return self.redirect(continue_url) else: return self.redirect(redirect_url) logger.error('team creation failed') message = ('team creation failed.') self.add_message(message, 'error') self.form = forms.TeamForm(self) return self.render_template('/cms/create_team.html', **params) @webapp2.cached_property def form(self): return forms.TeamForm(self) def upload_players(self): players = [] new_player_count = len(self.form.new_player) logger.info('No of New players %s' % new_player_count) for x in xrange(new_player_count): player_obj = Player() player_obj.name = self.form.new_player.__getitem__(x).data['name'] player_obj.email = self.form.new_player.__getitem__(x).data['email'] #player_obj.phone = self.form.new_player.__getitem__(x).data['phone'] player_obj.sport = self.form.sport.data #player_obj.teams = key logger.info('New Player Data: ' + str(player_obj)) if player_obj.email != '': player_exist = self.playerDao.query_by_email(player_obj.email) logger.info('Exist Player Data: ' + str(player_exist)) if player_exist is None: key = self.playerDao.persist(player_obj, self.user_info) players.append(key) logger.info('Add New Player %s' % player_obj.name) else: players.append(player_exist.key) logger.info('Skipped Already Exist of Player %s' % player_obj.name) else: logger.info('Skipped Empty Player Data') return players def form_to_dao(self, team_id): team = None players = [] if team_id is not None and len(team_id) > 1: team = self.teamDao.get_record(long(team_id)) else: team = Team() team.name = self.form.name.data team.alias = utils.slugify(self.form.name.data) team.sport = self.form.sport.data team.category = self.form.category.data players = self.upload_players() sel_player = self.request.get_all('player') logger.debug('sel_player: ' + str(sel_player)) if len(sel_player) > 0: players_count = len(sel_player) logger.debug('No of Selected Players %s' % players_count) for x in xrange(players_count): players.append(self.profileDao.get_record(sel_player[x]).key) logger.info('Total No of Players Mapped %s' % len(players)) logger.debug('Total Players Data: ' + str(players)) team.players = players return team
class EventDetailsHandler(BaseHandler): eventDao = DaoFactory.create_ro_eventDao() mediaDao = DaoFactory.create_ro_mediaDao() matchDao = DaoFactory.create_ro_matchDao() teamDao = DaoFactory.create_rw_teamDao() registerDao = DaoFactory.create_rw_registerDao() def get(self, city_name, entity_id, entity_alias): logger.debug('Event details for city %s, id %s, alias %s ' % (city_name, entity_id, entity_alias)) if self.request.query_string != '': query_string = '?' + self.request.query_string else: query_string = '' continue_url = self.request.path_url + query_string if entity_id is None: message = ('Invalid Event ID.') self.add_message(message, 'warning') self.redirect_to('home') else: event = self.eventDao.get_record(entity_id) if event is None: message = ('Event could not be retrieved.') self.add_message(message, 'warning') return else: past_events = [] future_events = [] other_events = self.eventDao.get_business_events(event.business_id) if other_events and len(other_events) > 0: for other_event in other_events: if other_event.key.id() != event.key.id(): if get_event_state(other_event) == 'past': past_events.append(other_event) else: future_events.append(other_event) event_media = self.mediaDao.get_primary_media(other_events, constants.EVENT) params = {} params['event'] = event params['types'] = constants.EVENT params['sport'] = event.sport params['city_name'] = event.address.city params['locality_name'] = event.address.locality params['past_events'] = past_events if len(past_events) > 0 else None params['future_events'] = future_events if len(future_events) > 0 else None params['event_media'] = event_media params['media'] = self.mediaDao.get_active_media(event.key, event.sport, constants.EVENT) params['matches'] = self.matchDao.get_matches_for_event(event.key, self.user_info) params['continue_url'] = continue_url params['event_state'] = get_event_state(event) params['title'] = event.name if self.user_info: register_url = self.uri_for('event-register') params['teams'] = self.teamDao.query_by_owner(self.user_info) event_reg = self.registerDao.query_by_reg_user_id(event.key, self.user_info) logger.info('Event Registered Details: ' + str(event_reg)) if event_reg: params['reg_type'] = event_reg.reg_type register_url = self.uri_for('edit-event-register', record_id = event_reg.key.id(), **{'continue': continue_url}) if event_reg.team_id: params['reg_teams'] = [x.id() for x in event_reg.team_id] logger.info('Event Registered Teams : ' + str(params['reg_teams'])) if event_reg.player_id: params['reg_players'] = [x.id() for x in event_reg.player_id] logger.info('Event Registered Players : ' + str(params['reg_players'])) params['register_url'] = register_url if event.sport == "cricket": return self.render_template('/app/event_details_cricket.html', **params) else: return self.render_template('/app/event_details.html', **params)
class ManagePlayerHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): teamDao = DaoFactory.create_rw_teamDao() playerDao = DaoFactory.create_rw_playerDao() @user_required def get(self, player_id=None): params = {} import_url = self.uri_for('import-team') params['import_url'] = blobstore.create_upload_url(import_url) upload_url = self.uri_for('create-player') continue_url = self.request.get('continue').encode('ascii', 'ignore') params['continue_url'] = continue_url #params['continue_url'] = continue_url if continue_url != '' else upload_url params['teams'] = self.teamDao.query_by_owner(self.user_info) params['title'] = 'Create New Player' if player_id is not None and len(player_id) > 1: upload_url = self.uri_for('edit-player', player_id = player_id) player = self.playerDao.get_record(player_id) params['title'] = 'Update - ' + str(player.name) self.form = forms.NewPlayerForm(self, player) teams = [] for x in xrange(len(player.teams)): teams.append(player.teams[x].id()) params['sel_teams'] = teams return self.render_template('/cms/create_player.html', **params) else: return self.render_template('/cms/create_player.html', **params) params['entity_name'] = 'Player' params['all_players'] = self.playerDao.query_by_all(self.user_info) return self.render_template('/cms/dashboard.html', **params) @user_required def post(self, player_id=None): params = {} if not self.form.validate(): if player_id is not None and len(player_id) > 0: return self.get(player_id) else: return self.get() continue_url = self.request.get('continue').encode('ascii', 'ignore') player = self.form_to_dao(player_id) logger.debug('player populated ' + str(player)) team_alias_name = utils.slugify(self.request.get('teamName')) if team_alias_name != '': team_exist = self.teamDao.query_by_team_alias(team_alias_name, self.user_info) logger.info('Exist Team for player: ' + str(team_exist)) if team_exist is None: team_import_data = self.form_to_dao_team_auto(player) team_key = self.teamDao.persist(team_import_data, self.user_info) logger.info('New Team Created for %s with key %s' % (team_alias_name, team_key)) player.teams = team_key else: player.teams = team_exist.key key = self.playerDao.persist(player, self.user_info) logger.debug('key ' + str(key)) if key is not None: logger.info('player succesfully created/updated') message = ('player succesfully created/updated.') self.add_message(message, 'success') if continue_url: return self.redirect(continue_url) else: return self.redirect_to('dashboard', **params) logger.error('player creation failed') message = ('player creation failed.') self.add_message(message, 'error') self.form = forms.NewPlayerForm(self) return self.render_template('/cms/create_player.html', **params) @webapp2.cached_property def form(self): return forms.NewPlayerForm(self) @webapp2.cached_property def importform(self): return forms.ImportTeamForm(self) def form_to_dao(self, player_id): player = None if player_id is not None and len(player_id) > 1: player = self.playerDao.get_record(long(player_id)) else: player = Player() player.name = self.form.name.data player.email = self.form.email.data #player.phone = self.form.phone.data player.sport = self.form.sport.data sel_team = self.request.get_all('team') logger.debug('sel_team: ' + str(sel_team)) if len(sel_team) > 0: teams = [] teams_count = len(sel_team) logger.debug('Teams Count: ' + str(teams_count)) for x in xrange(teams_count): teams.append(self.teamDao.get_record(sel_team[x]).key) logger.debug('Teams ' + str(teams)) player.teams = teams return player def form_to_dao_team_auto(self, player): try: team = Team() team.name = self.form.teamName.data #Create an automatic alias for the team team.alias = utils.slugify(self.form.teamName.data) team.sport = self.form.sport.data except StandardError as e: logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name'])) raise return team
class SaveLocalityHandler(blobstore_handlers.BlobstoreUploadHandler, BaseHandler): importDao = DaoFactory.create_rw_importDao() @user_required def get(self): params = {} upload_url = self.uri_for('save-locality') params['title'] = 'Save Locality' params['media_upload_url'] = blobstore.create_upload_url(upload_url) return self.render_template('/cms/save_locality.html', **params) @user_required def post(self): params = {} locality_count = 0 if not self.form.validate(): return self.get() lat = self.request.get('lat') long = self.request.get('long') radius = self.request.get('radius') limit = self.request.get('limit') api_key = self.request.get('key') feed_url = 'http://www.geoplugin.net/extras/nearby.gp?lat=' + lat + '&long=' + long + '&limit=' + limit + '&radius=' + radius + '&format=xml' logging.info('feed url %s' % feed_url) root = self.parse(feed_url) for item in root.getElementsByTagName('geoPlugin_nearby'): try: place_name = unicodedata.normalize( 'NFKD', unicode( item.getElementsByTagName('geoplugin_place') [0].firstChild.data)).encode('ascii', 'ignore') logger.info('Place: %s' % place_name) newfeed_url = 'https://maps.googleapis.com/maps/api/place/autocomplete/xml?types=(regions)&input=' + urllib.quote( place_name) + '&key=' + api_key logging.info('newfeed url %s' % newfeed_url) newroot = self.parse(newfeed_url) auto_status = newroot.getElementsByTagName( 'status')[0].firstChild.data logger.info('Auto Status: %s ' % auto_status) if auto_status == 'OK': for items in newroot.getElementsByTagName('prediction'): try: place_id = items.getElementsByTagName( 'place_id')[0].firstChild.data place_name = items.getElementsByTagName( 'value')[0].firstChild.data #description logger.info('Place Name: %s Place Id: %s ' % (place_name, place_id)) locality_count = self.process_locality( place_name, place_id, api_key) except IndexError, ValueError: pass else: logger.error('Error: %s' % auto_status) except IndexError, ValueError: pass