def update_event_type(id): data = { "name": querystring_get("name"), "description": querystring_get("description") } if not data["name"]: Alert.bad("The <strong>name</strong> field is required") return render_template("event_type/view.html", **data) create = str(id).lower() == "create" item = None if create: item = EventType() else: item = api.get(EventType, id) if not item: Alert.bad("Could not find <strong>Event Type</strong> {}; {}".format(id, api.error)) return render_template("event_type/view.html", **data) item.name = data["name"] item.description = data["description"] item = api.update(EventType, item) if not item: Alert.bad(api.error) return render_template("event_type/view.html", **data) Alert.good("Event Type <strong>{}</strong> {}".format(item.name, "created" if create else "updated")) return redirect("/eventtypes/{}".format(item.id))
def create_event_type(): data = request.get_json() validate(data, post_create_event_type_schema) event_type = EventType(**data) dao_create_event_type(event_type) return jsonify(event_type.serialize()), 201
def test_create_event_invalid_input(self): """Test sending invalid input to the create event view function.""" EventType.insert_event_types() EventCategory.insert_event_categories() role = Role.query.filter_by(name="Event Organizer").first() user = TestModelFactory.create_user(password="******") user.role = role db.session.add(user) db.session.commit() # Should be redirected if not logged in response = self.client.get("/events/create", follow_redirects=True) self.assertTrue(response.status_code, 200) self.assertTrue( "Please log in to access this page" in response.get_data( as_text=True)) with self.client: # log the user in response = self.client.post( "/auth/login", data={ "email": user.email, "password": "******" }, follow_redirects=True, ) for data in ViewFunctionTestData.INVALID_EVENT_DATA: with self.subTest(data=data): response = self.client.post( "/events/create", data={ "title": data["title"], "event_type": data["event_type"], "category": data["category"], "venue_name": data["venue_name"], "address": data["address"], "city": data["city"], "state": data["state"], "zip_code": data["zip_code"], "start_date": data["start_date"], "end_date": data["end_date"], "start_time": data["start_time"], "end_time": data["end_time"], }, follow_redirects=True, ) self.assertTrue(data["error_message"] in response.get_data( as_text=True)) self.assertIsNone(user.events.first())
def create_event( cls, title, status, event_type="Conference", event_category="Music", id=None ): """Return an instance of the Event class.""" event = Event( title=title, description="The best description ever", event_type=EventType(name=event_type), event_category=EventCategory(name=event_category), ) if status.lower() in EventStatus.LIVE: event.published = True event.start_datetime = datetime.now() event.end_datetime = datetime.now() + timedelta(days=1) elif status.lower() == EventStatus.PAST: event.published = True event.start_datetime = datetime.now() - timedelta(days=3) event.end_datetime = datetime.now() - timedelta(days=1) elif status.lower() == EventStatus.DRAFT: event.published = False start_datetime = (datetime.now(),) end_datetime = datetime.now() + timedelta(days=1) if ( id is not None ): # used for elasticsearch tests where the model isn't added to the db event.id = id return event
def deploy(fake_data): """Run the below set of tasks before deployment.""" # migrate database to latest revision upgrade() # create or update roles, event types, categories, and image types Role.insert_roles() EventType.insert_event_types() EventCategory.insert_event_categories() ImageType.insert_image_types() es_client = ElasticsearchClient(app.config["ELASTICSEARCH_URL"]) es_client.create_index("events") # add fake data to the database if there isn't already fake data in the tables if fake_data: fake = FakeDataGenerator(48, 48) fake.add_all()
def setup_environment(fake_data): """Cli command to setup the development environment. Starts up Elasticsearch, sets up the database and inserts fake data into the database if request. """ app.sqlalchemy_search_middleware._elasticsearch_client.delete_index( Event.__tablename__) db.drop_all() db.create_all() # create or update roles, event types, categories, and image types Role.insert_roles() EventType.insert_event_types() EventCategory.insert_event_categories() ImageType.insert_image_types() # add fake data to the database if fake_data: fake = FakeDataGenerator(48, 48) fake.add_all()
def create_event_type(old_id=1, event_type='talk', event_desc='test talk', event_filename=None, duration=45, repeat=1, repeat_interval=0): data = { 'old_id': old_id, 'event_type': event_type, 'event_desc': event_desc, 'event_filename': event_filename, 'duration': duration, 'repeat': repeat, 'repeat_interval': repeat_interval } event_type = EventType(**data) dao_create_event_type(event_type) return event_type
def import_event_types(): data = request.get_json(force=True) validate(data, post_import_event_types_schema) event_types = [] for item in data: event_type = EventType.query.filter( EventType.old_id == item['id']).first() if not event_type: event_type = EventType( old_id=item['id'], event_type=item['EventType'], event_desc=item['EventDesc'], event_filename=item['EventFilename'], ) event_types.append(event_type) dao_create_event_type(event_type) else: current_app.logger.info('event type already exists: {}'.format( event_type.event_type)) return jsonify([e.serialize() for e in event_types]), 201
locations_data = csv.DictReader(open('import_data/locations.csv')) event_types_data = csv.DictReader(open('import_data/event_types.csv')) event_categories_data = csv.DictReader( open('import_data/event_categories.csv')) events_data = csv.DictReader(open('import_data/events.csv')) for location in locations_data: session.add( Location(code=location.get('code'), title=location.get('title'))) session.commit() for event_type in event_types_data: session.add( EventType(code=event_type.get('code'), title=event_type.get('title'))) session.commit() for event_category in event_categories_data: session.add( EventCategory(code=event_category.get('code'), title=event_category.get('title'))) session.commit() for event_item in events_data: event_type = session.query(EventType).filter( EventType.code == event_item.get('type')).first() locations_list = event_item.get('location').split(', ')
def create_event(current_user): if request.content_type == 'application/json': user = User.get_by_id(current_user.id) data = request.get_json() #eventType parsing event_type_value = data.get('eventType') if not event_type_value: return response('failed', 'Missing eventType attribute', 400) try: event_type = EventType(int(event_type_value)) except ValueError: return response('failed', "EventType not found", 404) #event parsing event_value = data.get('event') if not event_value: return response('failed', 'Missing event attribute', 400) if not isinstance(event_value, dict): return response('failed', 'Wrong event attribute format', 400) #title parsing title = event_value.get('title') if not title: return response('failed', 'Missing title attribute', 400) description = event_value.get('description') #activity parsing activity_value = event_value.get('activity') if not activity_value: return response('failed', 'Missing activity attribute', 400) try: activity = Activity(int(activity_value)) except ValueError: return response('failed', "Activity not found", 404) if not event_type in activity.eventTypes: response('failed', 'Wrong eventType for given activity', 400) #participants_level parsing participants_level_value = event_value.get('participantsLevel') if not participants_level_value: return response('failed', 'Missing participantsLevel attribute', 400) try: participants_level = EventParticipantsLevel( int(participants_level_value)) except ValueError: return response('failed', "EventParticipantsLevel not found", 404) #participants_age_from and participants_age_to parsing participants_age_from = event_value.get('participantsAgeFrom') participants_age_to = event_value.get('participantsAgeTo') if not participants_age_from or not participants_age_to: return response('failed', 'Missing participantsAge range attributes', 400) if not isinstance(participants_age_from, int) or not isinstance( participants_age_to, int): return response('failed', 'Wrong participantsAge range attributes types', 400) #begin_at parsing try: begin_at_value = event_value.get('beginAt') begin_at = isoparse(str(begin_at_value)) except ValueError: return response('failed', 'Wrong beginAt attribute type', 400) #end_at parsing try: end_at_value = event_value.get('endAt') end_at = isoparse(str(end_at_value)) except ValueError: return response('failed', 'Wrong endAt attribute type', 400) if not begin_at < end_at: return response('failed', 'Begin time should be less than end time', 400) #ground parsing ground_id = event_value.get('groundId') if not ground_id: return response('failed', 'Missing groundId attribute', 400) if not isinstance(ground_id, int): return response('failed', 'Wrong groundId attribute type', 400) ground = Ground.get_by_id(ground_id) if not ground: return response('failed', 'Ground not found', 404) if not activity in ground.activities: return response('failed', 'Ground isn\'t design for given activity', 400) if not Event.datetime_interval_free(begin_at, end_at, ground): return response('failed', 'Ground is busy at given time interval', 400) #parsing specified type attributes if event_type is EventType.training: participants_count = event_value.get('participantsCount', 5) try: int(participants_count) except ValueError: return response('failed', "Wrong participantsCount attribute type", 400) event = Event.init_training(user, title, description, activity, participants_level, participants_age_from, participants_age_to, begin_at, end_at, participants_count) event.ground = ground event.save() else: teams_size = event_value.get('teamsSize', 5) try: int(teams_size) except ValueError: return response('failed', "Wrong teamsSize attribute type", 400) if event_type is EventType.match: event = Event.init_match(user, title, description, activity, participants_level, participants_age_from, participants_age_to, begin_at, end_at, teams_size) event.ground = ground event.save() elif event_type is EventType.tourney: teams_count = event_value.get('teamsCount', 3) try: int(teams_count) except ValueError: return response('failed', "Wrong teamsCount attribute type", 400) event = Event.init_tourney(user, title, description, activity, participants_level, participants_age_from, participants_age_to, begin_at, end_at, teams_size, teams_count) event.ground = ground event.save() return response_for_created_event(event.json(user), 201) return response('failed', 'Content-type must be json', 202)
def paginate_events(page, ground_id, status_value, type_value, activity_value, owner_id, participant_id): ground = Ground.get_by_id(ground_id) if ground_id else None status = EventStatus(status_value) if status_value else None activity = Activity(activity_value) if activity_value else None type = EventType(type_value) if type_value else None owner = User.get_by_id(owner_id) if owner_id else None participant = User.get_by_id(participant_id) if participant_id else None events_query = Event.query if participant: training_events_query = Event.query.join(TrainingEvent).join( Team).join(Team.participants).filter(User.id == participant_id) match_events_query = Event.query.join(MatchEvent).join( Team, or_(Team.id == MatchEvent.team_a_id, Team.id == MatchEvent.team_b_id)).join( Team.participants).filter(User.id == participant_id) tourney_events_query = Event.query.join(TourneyEvent).join(Team).join( Team.participants).filter(User.id == participant_id) events_query = training_events_query.union(match_events_query).union( tourney_events_query) if ground: events_query = events_query.filter_by(ground_id=ground.id) if activity: events_query = events_query.filter_by(activity=activity) if type: events_query = events_query.filter_by(type=type) if owner: events_query = events_query.filter_by(owner=owner) if status: events_query = events_query.filter(Event.status == status.value) if status is EventStatus.scheduled or status is EventStatus.processing: events_query = events_query.order_by(Event.begin_at) elif status is EventStatus.ended: events_query = events_query.order_by(Event.end_at.desc()) else: events_query = events_query.order_by(Event.status) pagination = events_query.paginate(page=page, per_page=app.config['EVENTS_PER_PAGE'], error_out=False) previous = None if pagination.has_prev: previous = url_for('event.events', groundId=ground_id, status=status_value, activity=activity_value, type=type_value, ownerId=owner_id, participantId=participant_id, page=page - 1, _external=True) nex = None if pagination.has_next: nex = url_for('event.events', groundId=ground_id, status=status_value, activity=activity_value, type=type_value, ownerId=owner_id, participantId=participant_id, page=page + 1, _external=True) items = pagination.items return items, nex, pagination, previous
def test_create_event_valid_input(self): """Test sending valid inputs to the create event view function.""" # create user EventType.insert_event_types() EventCategory.insert_event_categories() role = Role.query.filter_by(name="Event Organizer").first() user = TestModelFactory.create_user(password="******") user.role = role db.session.add(user) db.session.commit() # Should be redirected if not logged in response = self.client.get("/events/create", follow_redirects=True) self.assertTrue(response.status_code, 200) self.assertTrue( "Please log in to access this page" in response.get_data( as_text=True)) with self.client: # log the user in response = self.client.post( "/auth/login", data={ "email": user.email, "password": "******" }, follow_redirects=True, ) # GET request should be successful response = self.client.get("/events/create", follow_redirects=True) self.assertTrue(response.status_code, 200) self.assertTrue("Basic Info" in response.get_data(as_text=True)) self.assertTrue("Location" in response.get_data(as_text=True)) self.assertTrue("Date and Time" in response.get_data(as_text=True)) # POST request should be successful response = self.client.post( "/events/create", data={ "title": ViewFunctionTestData.VALID_EVENT_DATA["title"], "event_type": ViewFunctionTestData.VALID_EVENT_DATA["event_type"], "category": ViewFunctionTestData.VALID_EVENT_DATA["category"], "venue_name": ViewFunctionTestData.VALID_EVENT_DATA["venue_name"], "address": ViewFunctionTestData.VALID_EVENT_DATA["address"], "city": ViewFunctionTestData.VALID_EVENT_DATA["city"], "state": ViewFunctionTestData.VALID_EVENT_DATA["state"], "zip_code": ViewFunctionTestData.VALID_EVENT_DATA["zip_code"], "start_date": ViewFunctionTestData.VALID_EVENT_DATA["start_date"], "end_date": ViewFunctionTestData.VALID_EVENT_DATA["end_date"], "start_time": ViewFunctionTestData.VALID_EVENT_DATA["start_time"], "end_time": ViewFunctionTestData.VALID_EVENT_DATA["end_time"], }, follow_redirects=True, ) self.assertEqual(response.status_code, 200) # sidebar text self.assertTrue("Basic Info" in response.get_data(as_text=True)) self.assertTrue("Event Details" in response.get_data(as_text=True)) self.assertTrue("Demographics" in response.get_data(as_text=True)) self.assertTrue("Media" in response.get_data(as_text=True)) self.assertTrue("Packages" in response.get_data(as_text=True)) # form headers self.assertTrue("Main Event Image" in response.get_data( as_text=True)) self.assertTrue("Description & Pitch" in response.get_data( as_text=True)) # check that event was created event = Event.query.get(1) self.assertIsNotNone(event) self.assertEqual(event.title, ViewFunctionTestData.VALID_EVENT_DATA["title"]) self.assertEqual(event.venue.name, ViewFunctionTestData.VALID_EVENT_DATA["venue_name"]) self.assertEqual(event.user, user) self.assertFalse(event.published ) # published attribute should be defaulted to False
def importDataFromExcel(file, year=2019): wb = openpyxl.load_workbook(file, data_only=True, read_only=True) sheet = wb._sheets[0] locale.setlocale(locale.LC_ALL, 'sv_SE') events = dict() eventTypes = dict() activityTypes = dict() n = 0 et_name = None try: for cols in sheet.rows: n += 1 if n <= 9: continue if cols[0].value is None and et_name is None: continue et_name = cols[0].value or et_name et = eventTypes.get(et_name) if et is None: #logger.info(f"Event type {et_name}") try: et = EventType.objects.get(name=et_name) except EventType.DoesNotExist: et = EventType(name=et_name) et.save() eventTypes[et_name] = et if cols[2].value is None: break event_name = f"{et_name} vecka {cols[1].value}" date = cols[2].value if year is not None: date = date.replace(year=year) event = events.get((event_name, date)) if event is None: #logger.info(f"Event {event_name} {date}") try: event = Event.objects.get(name=event_name, start_date=date, type=et) except Event.DoesNotExist: event = Event(name=event_name, start_date=date, end_date=date, type=et) event.save() coord = cols[19].value if coord is not None: if ' ' in coord: first, last = coord.split(' ', maxsplit=1) else: first = coord try: coordinator = Member.objects.get( user__first_name=first, user__last_name=last) event.coordinators.add(coordinator) except Member.DoesNotExist: print( f"Failed to find member {coord} to use as coordinator for {event_name}" ) events[event_name] = event at_name = cols[5].value at = activityTypes.get(at_name) if at is None: #logger.info(f"Activity Type: {at_name}") try: at = ActivityType.objects.get(name=at_name) except ActivityType.DoesNotExist: at = ActivityType(name=at_name) at.save() activityTypes[at_name] = at ebd = cols[18].value activity = Activity( name=f"{at_name} {calendar.day_name[date.weekday()]}", event=event, type=at, earliest_bookable_date=ebd) interval = cols[4].value.replace('—', '-').replace('–', '-') \ .replace(' ', '').replace('.', ':') try: (start_time, end_time) = interval.split('-') except ValueError as e: logger.error(e) logger.error(interval) #logger.info(f'{activity.name} {interval}') (sh, sm) = start_time.split(':') (eh, em) = end_time.split(':') activity.start_time = datetime.time(hour=int(sh), minute=int(sm)) activity.end_time = datetime.time(hour=int(eh), minute=int(em)) activity.full_clean() activity.save() print(f'''Database row count: {EventType.objects.all().count()} event types {ActivityType.objects.all().count()} activity types {Event.objects.all().count()} events {Activity.objects.all().count()} activities'''.replace( ' ', ' ')) except: print(f"Error on row {n}") raise