def process_event_mood_log(): """ Add event log to db""" # get user inputs event_name = request.form.get('event-name') event_date = datetime.strptime(request.form.get('today-event-date'), '%Y-%m-%d').date() # end_date = datetime.strptime(request.form.get('end-date'), '%Y-%m-%d').date() user_id, overall_mood, min_mood, max_mood, notes = get_mood_rating() # create event event = Event(event_name=event_name, user_id=user_id, overall_mood=overall_mood, max_mood=max_mood, min_mood=min_mood, notes=notes) db.session.add(event) db.session.commit() # event.associate_days(start_date, end_date) if not event_date in [day.date for day in event.user.days]: event.create_dummy_day(event_date) flash('Event %s on today (%s) successfully created' % (event_name, event_date)) return redirect('/user_profile')
def sign(event: Event): """ signs an event :return: signed Event """ signed_event = auth.sign_event(event.to_json_dict()) return Event.parse(signed_event)
def get(handler, response): lat = handler.request.get('lat') lon = handler.request.get('lng') response.events = Event.proximity_fetch( Event.all(), geotypes.Point(float(lat),float(lon)), )
def generate_event(max_possible_id, ev_id=None): if ev_id is None: ev_id = randint(0, max_possible_id) ev = Event("/some/dummy/path%d" % ev_id) ev.id = ev_id return ev
def load_all(self): with open(self.event_file, 'r') as evfile: data = evfile.read() events = [] raw_events = data.split("# New Event") for e in raw_events: if len(e) > 0: ev_dict = yaml.load(e) ev_id = ev_dict["id"] new_event = Event(ev_id, self.directory) xhits = ev_dict["xhits"] yhits = ev_dict["yhits"] new_event.hits = [Hit(x, y) for x, y in zip(xhits, yhits)] events.append(new_event) with open(self.track_file, 'r') as trfile: data = trfile.read() raw_tracks = data.split("---") tracks = [yaml.load(t) for t in raw_tracks if t.split()] for t in tracks: t.displayed = True t.parameters = {} if not hasattr(t, "color"): t.color = get_color(t.id) event_id = t.event_id filt_events = filter(lambda ev: ev.id == event_id, events) if len(filt_events) > 0: event = filt_events[0] event.add_track(t) return events
def post(handler, response): people_yaml = handler.request.get('people') import logging people = yaml.load(people_yaml) for person in people: user = User.get_or_insert(key_name=person.get('email') or person['name']) user.name = person['name'] user.link = person.get('link') user.private = bool(person['private']) user.city = person['city'] user.distance = person['distance'] if 'location' in person: match = re.match('^(.*), (.*)$', person['location']) if match: (lat, lon) = match.groups() user.location = db.GeoPt(lat, lon) user.update_location() user.put() for slug in person['organizing']: event = Event.all().filter('slug =', slug).get() if event: user.add_event(event, bool(1)) for slug in person['attending']: event = Event.all().filter('slug =', slug).get() if event: user.add_event(event)
def merge_dupe(self, old_id, new_id): old = Event.get(old_id) new = Event.get(new_id) Event.merge(old, new) for artist in new.artists: if not artist.approved: artist.approved = datetime.now() util.redirect("/importers/reviewdupes")
def get(handler, response): lat1 = handler.request.get('lat1') lon1 = handler.request.get('lng1') lat2 = handler.request.get('lat2') lon2 = handler.request.get('lng2') response.events = Event.bounding_box_fetch( Event.all(), geotypes.Box(float(lat1),float(lon2),float(lat2),float(lon1)), )
def load_event(self, file_path): with open(file_path) as infile: _, file_name = ntpath.split(file_path) ev_id = self.get_new_event_id(file_name, "Event", ".txt") ev = Event(ev_id, file_path) for line in infile: x, y = (float(n) for n in line.split()) ev.add_hit(Hit(x, y)) return ev
def example_data(): """Create some sample data for tests file to use.""" # Create some fake users u1 = User(user_id=1, email="*****@*****.**", name="Jessi DiTocco", password="******") u2 = User(user_id=2, email="*****@*****.**", name="Liz Lee", password="******") # Create some fake events e1 = Event(event_id="43104373341", name="Aristophanes @ Cafe du Nord", start_time="Friday, February 16 at 9:30PM+", end_time="Saturday, February 17 at 2:00AM", address="2174 Market Street, San Francisco, CA 94114", latitude=37.7649659, longitude=-122.431, venue_name="Slate") e2 = Event(event_id="41465350981", name="Funk", start_time="Friday, February 15 at 9:30PM+", end_time="Saturday, February 18 at 2:00AM", address="4123 Market Street, San Francisco, CA 94114", latitude=39.7649659, longitude=-122.431, venue_name="The Jam") # Create some bookmark types bt1 = BookmarkType(bookmark_type_id=1, bookmark_type="going") bt2 = BookmarkType(bookmark_type_id=2, bookmark_type="interested") # Create some fake bookmarks b1 = Bookmark(bookmark_id=1, user_id=1, event_id="43104373341", bookmark_type_id=2) b2 = Bookmark(bookmark_id=2, user_id=2, event_id="43104373341", bookmark_type_id=1) # Create some fake Comments c1 = Comment(comment_id=1, user_id=1, event_id="43104373341", comment="HI!") c2 = Comment(comment_id=2, user_id=2, event_id="43104373341", comment="HI!") db.session.add_all([u1, u2, e1, e2, bt1, bt2, b1, b2, c1, c2]) db.session.commit()
def method_specification_success(user_id, relatp_id): """Add the methods specified to the relationship.""" # Grab the recommendation list specified for the relationship. desired_list = request.form.getlist('rcmdn') # Add the customized list to the respective relationship. update_relatp = Relationship.query.filter_by(user_id=user_id, id=relatp_id).first() update_relatp.rcmdn_list = desired_list # The created_at column should be placed in the Relationship table. created_at = db.session.query( Relationship.created_date).filter_by(id=relatp_id).one() # Turn the query result (a tuple of datetime) into an Arrow-friendly format. arrow_created_at = arrow.get(created_at[0]) # The start date of all events will be a month from the date he/she was added. start_date = arrow_created_at.replace(months=+1) # Events will be scheduled for a max of a year for demo purposes. yr_from_now = start_date.replace(years=+1) # Create events for the duration of the year. # Friends and family should have an event a month. # Professional contacts should have an event per quarter. while start_date < yr_from_now: for desired_item in desired_list: if update_relatp.relatp_type == 'fr' or update_relatp.relatp_type == 'fam': # Convert from arrow format to datetime format for db storage. new_event = Event(user_id=user_id, relatp_id=relatp_id, rcmdn=desired_item, scheduled_at=start_date.datetime) db.session.add(new_event) start_date = start_date.replace(months=+1) else: new_event = Event(user_id=user_id, relatp_id=relatp_id, rcmdn=desired_item, scheduled_at=start_date.datetime) db.session.add(new_event) start_date = start_date.replace(months=+4) db.session.commit() return render_template('reach_out_added.html', user_id=user_id, desired_list=desired_list)
def example_data(): phone = os.environ.get('MY_NUMBER') email = os.environ.get('MY_EMAIL') fb_at = os.environ.get('FB_AT') fb_uid = os.environ.get('FB_UID') # ADD USERS jane = User(email='*****@*****.**', password='******', fname='Jane', lname='Hacks', phone='+11234567890') bob = User(email='*****@*****.**', password='******', fname='Bob', lname='Baller', phone='+10987654321') db.session.add_all([jane, bob]) # db.session.add(inny) db.session.commit() # ADD CONTACTS john = Contact(name='John Recruitor', email='*****@*****.**', user_id=jane.id) sally = Contact(name='Sally Secretary', email='*****@*****.**', user_id=bob.id) ian = Contact(name='Ian Interviewer', email='*****@*****.**', user_id=bob.id) db.session.add_all([john, sally, ian]) db.session.commit() # ADD TEMPLATES fup = Template(name='follow up', text='hello there') ty = Template(name='thank you', text='thank you for meeting!') ty2 = Template(name='thank you', text='thank you for meeting!') fup2 = Template(name='follow up', text='hello there') db.session.add_all([ty, ty2, fup, fup2]) db.session.commit() # ADD EVENTS e1 = Event(contact_id=ian.id, date=datetime.datetime(2017, 12, 30), template_id=fup.id) e2 = Event(contact_id=john.id, template_id=ty.id) e3 = Event(contact_id=ian.id, template_id=ty2.id) e4 = Event(contact_id=sally.id, date=datetime.datetime(2018, 1, 1), template_id=fup2.id) db.session.add_all([e1, e2, e3, e4]) db.session.commit() # ADD CONTACTEVENT ASSOCIATIONS ce1 = ContactEvent(contact_id=e1.contact_id, event_id=e1.id) ce2 = ContactEvent(contact_id=e2.contact_id, event_id=e2.id) ce3 = ContactEvent(contact_id=e3.contact_id, event_id=e3.id) ce4 = ContactEvent(contact_id=e4.contact_id, event_id=e4.id) db.session.add_all([ce1, ce2, ce3, ce4]) db.session.commit()
def edit_event(id): event_selected = Event.query.filter(Event.id == id).first() found_players_number = JoinedEvent.query.filter( JoinedEvent.event_id == id).count() - 1 if found_players_number == 0: found_players_number = 1 session['sport_selected'] = event_selected.sport_id create_event_form = CreateEvent() if create_event_form.is_submitted(): Event.query.filter(Event.id == id).delete() db.session.commit() if create_event_form.sport_club.data == "other": event = Event(id=id, town_id=create_event_form.town.data, sport_id=create_event_form.sport.data, place=create_event_form.place.data, date_start=create_event_form.date_start.data, date_end=create_event_form.date_end.data, wanted_players_number=create_event_form. wanted_players_number.data, creator_id=session['user_id']) db.session.add(event) db.session.commit() else: event = Event(id=id, town_id=create_event_form.town.data, sport_id=create_event_form.sport.data, sport_club_id=create_event_form.sport_club.data, date_start=create_event_form.date_start.data, date_end=create_event_form.date_end.data, wanted_players_number=create_event_form. wanted_players_number.data, creator_id=session['user_id']) db.session.add(event) db.session.commit() return redirect(url_for('event', id=id)) towns = Town.query.all() sports = Sport.query.all() sportclubs = User.query.filter(User.role_id == 3).all() details = SportClubDetails.query.all() practicable_sports = FavouriteSport.query.all() return render_template('edit_event.html', create_event_form=create_event_form, towns=towns, sports=sports, sportclubs=sportclubs, details=details, practicable_sports=practicable_sports, event_selected=event_selected, found_players_number=found_players_number)
def testThird(self): e = Event(self.et) e.title = 'First event' e.source_type = EventSourceType.EMPTY session.add(e) session.commit() e.event_status_list.append(EventStatus(EventStatus.EMPTY)) e.event_status_list.append(EventStatus(EventStatus.LIVE_BE_HERE)) self.assertEquals(e.last_status, EventStatus.LIVE_BE_HERE) session.delete(e) session.commit()
def post(self): snapshot = self.get_uploads("snapshot") snapshot_key = str(snapshot[0].key()) if snapshot else None name = self['name'] type = self['type'] description = self['description'] date_time = self['date_time'] duration = int(self['duration']) link = self['link'] attendees = int(self['attendees'] if self['attendees'] else 0) Event.get_or_insert(type+date_time, name=name, type=type, description=description, duration=duration, link=link, date_time=datetime.strptime(date_time,"%Y-%m-%dT%H:%M"), snapshot=snapshot_key, attendees=attendees) self.redirect("/")
def member_update(): """Member updation process""" first_name = request.form.get("Member_Firstname") last_name = request.form.get("Member_Lastname") email = request.form.get("Member_Email") phonenumber = request.form.get("Member_Phonenumber") date_of_birth_str = request.form.get("Member_Birthday") date_of_birth = datetime.strptime(date_of_birth_str, '%Y-%m-%d') marriage_date_str = request.form.get("Member_Marriage_Anniversary") if marriage_date_str != '': marriage_date = datetime.strptime(marriage_date_str, '%Y-%m-%d') else: marriage_date = None relation = request.form.get("Member_Relation") user_profile = get_profile() member_profile = Member(profile_id=user_profile.profile_id, first_name=first_name, last_name=last_name, email=email, phonenumber=phonenumber, date_of_birth=date_of_birth, marriage_date=marriage_date, relation=relation) db.session.add(member_profile) db.session.commit() #Add birthday and marriage anniversary to events text = f"Birthday for {first_name} {last_name}" member_db_event = Event(profile_id=user_profile.profile_id, member_id=member_profile.member_id, event_type='Birthday', event_date=date_of_birth, event_text=text) db.session.add(member_db_event) if marriage_date is not None: text = f"Marriage Anniversary for {first_name} {last_name} and {user_profile.fullname()}" marriage_event = Event(profile_id=user_profile.profile_id, member_id=member_profile.member_id, event_type='Marriage_Anniversary', event_date=marriage_date, event_text=text) db.session.add(marriage_event) db.session.commit() return redirect("/member")
def comment(): event = Event() event.type = MeetingEventType.JOIN event.timestamp = int(time.time()) event.by = public_key event.meeting_id = meeting_id event.ref_event = ref_event comment_str = click.prompt("comment?", type=str) event.content = {"comment": comment_str} signed_event = auth.sign_event(event.to_json_dict()) sio.emit('room-message', json.dumps(signed_event), callback=server_reply)
def create_event(): create_event_form = CreateEvent() if create_event_form.is_submitted(): if create_event_form.sport_club.data == "other": event = Event(town_id=create_event_form.town.data, sport_id=create_event_form.sport.data, place=create_event_form.place.data, date_start=create_event_form.date_start.data, date_end=create_event_form.date_end.data, wanted_players_number=create_event_form. wanted_players_number.data, creator_id=session['user_id']) db.session.add(event) db.session.commit() else: event = Event(town_id=create_event_form.town.data, sport_id=create_event_form.sport.data, sport_club_id=create_event_form.sport_club.data, date_start=create_event_form.date_start.data, date_end=create_event_form.date_end.data, wanted_players_number=create_event_form. wanted_players_number.data, creator_id=session['user_id']) db.session.add(event) db.session.commit() last_event = Event.query.filter( Event.creator_id == session['user_id']).order_by( Event.date_added.desc()).first() je = JoinedEvent(user_id=session['user_id'], event_id=last_event.id) db.session.add(je) db.session.commit() return redirect("events") towns = Town.query.all() sports = Sport.query.all() sportclubs = User.query.filter(User.role_id == 3).all() details = SportClubDetails.query.all() practicable_sports = FavouriteSport.query.all() return render_template('create_event.html', create_event_form=create_event_form, towns=towns, sports=sports, sportclubs=sportclubs, details=details, practicable_sports=practicable_sports)
def deserialise_event(dic) -> Event: id = UUID(dic[K_ID]) title = dic[K_TITLE] desc = dic.get(K_DESC, None) timespec_se = dic.get(K_TIMESPEC, None) timespec = deserialise_reltimespec(timespec_se) return Event(id=id, title=title, desc=desc, timespec=timespec)
def event(id=0): if request.method == 'POST': eve_data = json.loads(request.data) if (id == 0): try: event = Event(**eve_data) event.save() return json.dumps({'success': True}), 200 except: return json.dumps({'success': False}), 400 else: try: event = Event.update(**eve_data).where(Event.id == id).execute() return json.dumps({'success': True}), 200 except: return json.dumps({'success': False}), 400
def review(self): try_to_show = 100 result = Event.select(Event.q.approved == None, orderBy=(Event.q.name,)) total = result.count() shown = min(total, try_to_show) events = result[:shown] return dict(events=events, shown=shown, total=total, importer=mercury)
def process_user_shows(): """processes selected shows and redirects to display shows user is attending""" user = get_user_object() shows = request.args.getlist('shows') if shows: for show in shows: show_there = db.session.query(Event).filter( Event.eventbrite_event_id == show).first() if show_there and show not in [ event.eventbrite_event_id for event in user.events ]: user.events.append(show_there) else: new_show = Event( eventbrite_event_id=request.args.get( show + "_eventbrite_event_id"), event_name=request.args.get(show + "_event_name"), venue_id=request.args.get(show + "_venue_id"), eventbrite_url=request.args.get(show + "_eventbrite_url"), logo_url=request.args.get(show + "_logo_url"), start=request.args.get(show + "_start"), end=request.args.get(show + "_end"), users=[user], ) db.session.add(new_show) db.session.commit() return redirect("/account/shows/attending")
def put(self, event_id): """ Un-RSVP to an event. """ from app import db from model import Event event = Event.get_event_by_id(event_id) if event.locations.spaces_remaining: if event.participant_count > 0: event.participant_count -=1 # If the event has a capacity cap, subtract one from spaces remaining # **NOTE: I am assuming that if number_spaces_remaining is None, there # is no capacity cap. if event.locations.number_spaces_remaining: event.locations.number_spaces_remaining += 1 # Flip boolean because now there are spots left again event.locations.spaces_remaining = True db.session.add(event) db.session.commit() return [{ 'id': event.id, 'participant_count': int(event.participant_count) if event.participant_count else 0, 'are_spaces_remaining': event.locations.spaces_remaining, }] return { 'error': 'Unable to process your RSVP. Please try again.' }, 400
def edit(self, id=0, **kw): form_vals = {} template = ".templates.event.add" if id: try: e = Event.get(id) form_vals = util.so_to_dict(e) form_vals['artists'] = "\n".join([a.name for a in e.artists]) form_vals['venue'] = dict(text=e.venue.name) template = ".templates.event.edit" except SQLObjectNotFound: pass else: form_vals = dict(id=id) try: a = Artist.get(int(kw['artist_prefill'])) form_vals['artists'] = a.name except (SQLObjectNotFound, KeyError): pass try: v = Venue.get(int(kw['venue_prefill'])) flash(form_vals) form_vals['venue'] = dict(text=v.name) except (SQLObjectNotFound, KeyError): pass return dict(tg_template=template, event_form=event_form, form_vals=form_vals)
def saving_event_results(): """save a specific event to the database""" e_name = request.form.get('name') e_link = request.form.get('url') e_description = request.form.get('description') e_catergory_id = request.form.get('category_id') e_location = request.form.get('address') new_event = Event(e_name=e_name, e_link=e_link, e_description=e_description, e_catergory_id=e_catergory_id, e_location=e_location) db.session.add(new_event) #commit() is a two way interaction. Sends event info to my db and can return the event_id. db.session.commit() user_id = session.get("user_id") new_no_table = NightOut(user_id=user_id, event_id=new_event.event_id) db.session.add(new_no_table) db.session.commit() return jsonify({"sucess": True})
def load_events(event_filename): """Load events from event_data.csv into DB.""" print("Events") for i, row in enumerate(open(event_filename)): row = row.rstrip() event_id, host, category, title, start_str, end_str, created_str = row.split( "|") host = int(host) start_on = datetime.strptime(start_str, "%m/%d/%Y %H:%M") end_on = datetime.strptime(end_str, "%m/%d/%Y %H:%M") created_on = datetime.strptime(created_str, "%m/%d/%Y %H:%M") # Instantiate event event = Event(host=host, category=category, title=title, start_on=start_on, end_on=end_on, created_on=created_on) # Add event to session db.session.add(event) # Commit all event instances to DB db.session.commit()
def load_events(): """Load events from u.event into database.""" print "Events" # Delete all rows in table, so if we need to run seed.py multiple times, # won't add duplicate events Event.query.delete() # Read u.event file and insert data for row in open("seed_data/u.event"): row = row.rstrip() # row = row.split('|') # row = row[1:] animal_id, time, long_location, lat_location = row.split('|') timestamp = datetime.strptime(time, '%Y-%m-%d %H:%M:%S') long_location = float(long_location) lat_location = float(lat_location) event = Event(animal_id=animal_id, timestamp=timestamp, long_location=long_location, lat_location=lat_location) db.session.add(event) db.session.commit()
def create_event(): """Add a new event into database.""" # POST reqs have a body, so you can extract out the parsed JSON data # req_body = request.get_json() req_body = { 'title': request.form.get('title'), 'start_on': request.form.get('startTime'), 'end_on': request.form.get('endTime') } datetime_format = "%Y-%m-%dT%H:%M" req_body['start_on'] = datetime.strptime(req_body['start_on'], datetime_format) req_body['end_on'] = datetime.strptime(req_body['end_on'], datetime_format) req_body['created_on'] = datetime.now() req_body['host'] = session['user_id'] # Note: ** is used to "spread" an object into keyword arguments, where (key=argument name), and (value=argument value) event = Event(**req_body) db.session.add(event) db.session.commit() # Need to refresh db.session to obtain the newly created event instance # Useful for extracting out the event id to redirect to another API db.session.refresh(event) return jsonify(event.event_id)
def load_seed_events(): """Load sample events from seed_events.csv""" for row in open("seed_data/seed_events.csv"): row = row.rstrip() user_id, haz_id, event_title, active, datetime_seen, event_start, event_end, description, last_edited, last_edited_user, latitude, longitude = row.split( ",") if active == 'TRUE': active = True else: active = False event = Event(user_id=user_id, haz_id=haz_id, event_title=event_title, active=active, datetime_seen=datetime_seen, event_start=event_start, event_end=event_end, description=description, last_edited=last_edited, last_edited_user=last_edited_user, latitude=latitude, longitude=longitude) db.session.add(event) db.session.commit() print("Successfully seeded into the events table!")
def load_events(): """Load events from u.event into database.""" print "Events" # Delete db to avoid duplicates Event.query.delete() # Read u.event file and insert data for row in open("seed_data/u.event"): row = row.rstrip() start_at, end_at, image_url, link, podcast_id = row.split("|") event = Event(start_at=start_at, end_at=end_at, image_url=image_url, link=link, podcast_id=podcast_id) # add event to session db.session.add(event) # Commit the add of an event db.session.commit()
def add_event(title,start, end, descrip, picfile): """ Add a event to the database """ event = Event(name=title, start=start, end = end, desc=descrip,image=picfile) session.add(event) session.commit()
def load_events(): """Load goals from goal.txt into database.""" print "Seeding events" # Delete all rows in table, so if we need to run this a second time, # we won't be trying to add duplicate users Event.query.delete() # Read u.user file and insert data for row in open("seed_data/event.txt"): row = row.rstrip() event_id, start_time, stop_time, user_id, timer_id \ = row.split("|") event = Event(event_id=event_id, start_time=start_time, stop_time=stop_time, user_id=user_id, timer_id=timer_id, status='active') db.session.add(event) db.session.commit()
def get(handler, response): next = handler.request.get('next') if next: event = Event.get(next) if not event: return events = Event.all()\ .filter('name >=', event.name)\ .order('name')\ .fetch(MAX_RESULTS+1) else: events = Event.all()\ .order('name')\ .fetch(MAX_RESULTS+1) response.events = events[:MAX_RESULTS] if len(events) > MAX_RESULTS: response.next = events[-1]
def createEvent(): if request.method == 'POST': if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] else: ip = request.remote_addr if verifyCaptcha(request.form['g-recaptcha-response'], ip).status_code != 200: flash(u'You Are Not A Human. Gain A Corpeal Form And Try Again') redirect(url_for('home')) event_type = request.form['event_type'] title = request.form['title'] description = request.form['description'] print 'b' signup_email = request.form['signup_email'] signup_email = True if signup_email == 'on' else False reminder_email = request.form['reminder_email'] reminder_email = True if reminder_email == 'Yes' else False reminder_time = request.form['reminder_time'] country = request.form['country'] address1 = request.form['address1'] address2 = request.form['address2'] city = request.form['city'] state = request.form['state'] zipCode = request.form['zipCode'] venue = request.form['venue'] capacity = request.form['capacity'] directions = request.form['directions'] date = request.form['date'] date = date.split('-') time_hour = int(request.form['time_hour']) time_minutes = request.form['time_minutes'] time_day = request.form['time_day'] if time_day == 'pm': time_hour += 12 event_time = datetime.datetime(int(date[0]), int(date[1]), int(date[2]), int(time_hour), int(time_minutes), 0) length = request.form['length'] length_unit = request.form['length_unit'] phone = request.form['phone'] public_phone = request.form['public_phone'] host = request.form['host'] email = request.form['email'] loc = address1 + " " + address2 + " " + city + ", " + state + " " + zipCode print loc geolocator = Nominatim() location = geolocator.geocode(loc) print(location.address) print((location.latitude, location.longitude)) lat = location.latitude lng = location.longitude newEvent = Event(event_type=event_type, title=title, description= description, signup_email=signup_email, reminder_email=reminder_email, reminder_time=reminder_time, country=country, address1=address1, address2=address2, city=city, state=state, zipCode=zipCode, venue=venue, capacity=capacity, directions=directions, event_time = event_time, length=length, length_unit=length_unit, phone=phone, public_phone=public_phone, host=host, email=email, lat = lat, lng =lng) session.add(newEvent) session.commit() flash(u'You Have Created a New Event') return redirect(url_for('home')) else: resp = make_response(render_template('event.html', captcha=True)) return resp
def create_events(event_name,location, date,time,limitations): events = Event(event_name = event_name,location = location,date = date,time = time,limitations =limitations) db.session.add(events) db.session.commit() return events
def put(self, event_id): """ RSVP to an event. """ from app import db from model import Event event = Event.get_event_by_id(event_id) if event.locations.spaces_remaining: event.participant_count += 1 # If the event has a capacity cap, subtract one from spaces remaining # **NOTE: I am assuming that if number_spaces_remaining is None, there # is no capacity cap. if event.locations.number_spaces_remaining: event.locations.number_spaces_remaining -= 1 # If no spaces left, flip boolean if event.locations.number_spaces_remaining == 0: event.locations.spaces_remaining = False db.session.add(event) db.session.commit() return [{ 'id': event.id, 'participant_count': int(event.participant_count) if event.participant_count else 0, 'are_spaces_remaining': event.locations.spaces_remaining, }] # Safeguard, but the front-end should not attempt the XHR # if the event is full return { 'error': 'This event is already full!' }, 400
def load_events(): "Load events from dataeventbrite.json into database" # print ("*")*20, "loading event bright!", ("*")*20 data = open("seed_data/data.json").read() data = json.loads(data) counter = 0 # event_data = {} for event in data: # row = row.rstrip() # event_id, title, date, location, event_category, picture, organizer = row.split(",") #check if event at title is type ascii ,if it is event then "contiune" # if type(event["title"]) == ascii: # contiune print event['title'] event_db = Event(title=event["title"], date=event["date"], address=event["address"], picture=event["picture"], lat=event["lat"], longi=event["long"]) print event_db #add to the session db.session.add(event_db) counter = counter + 1 print counter #commit the work db.session.commit()
def get(self, target_time): all_events = Event.all().filter('start_time =',datetime.datetime.fromtimestamp(int(target_time))).order('start_time') events = [] event_days = set() for e in all_events: events.append(e.to_dict()) render_template(self, 'time.html', {'events':events})
def get_all_events(driver, debug=True): print("\nScanning for new events:") while True: group_count = Group.select().where( Group.fetched_events == False).count() if group_count == 0: break group = Group.get(Group.fetched_events == False) print("Processing {} groups. Fetching events.".format(group_count), flush=True) group_events = get_group_events(driver, group.id) for event_id, data in group_events.items(): event = Event.get_or_create(id=event_id)[0] event.name = data["name"] event.location = data["location"] event.image = data["image"] event.save() print("Found {} events".format(len(group_events)), flush=True) group.fetched_events = True group.last_fetched = datetime.datetime.utcnow() group.events_found = len(group_events) group.save() if debug and len(group_events) > 0: break
def get(self): data = memcache.get('newjson') if data is None: prefix = "" postfix = "" if self.request.get('callback'): prefix = "%s(" % self.request.get('callback') postfix = ");" all_events = Event.all().order('start_time') days = collections.defaultdict(list) slots = collections.defaultdict(list) events = [] for e in all_events: days[e.day.toordinal()] = e.day.strftime("%A, %d %b") slots[int(time.mktime(e.start_time.timetuple())*1000)]={'day':e.day.toordinal(),'text':e.start_time.strftime('%H:%M')} events.append(e.to_dict()) d = { 'days':days, 'slots':slots, 'events': events, } data = prefix+json.dumps(d)+postfix memcache.add('newjson', data, 5) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(data)
def get(self): all_events = Event.all().order('start_time') events = [] event_days = set() for e in all_events: events.append(e.to_dict()) event_days.add(e.start_time.date()) render_template(self, 'front.html', {'events':events, 'event_days':sorted(event_days)})
def delete(self, id): try: e = Event.get(id) e.destroySelf() flash("Deleted") except SQLObjectNotFound: flash("Delete failed") util.redirect("/events/list")
def get(self, target_date): all_events = Event.all().filter('day =',datetime.date.fromordinal(int(target_date))).order('start_time') events = [] event_slots = set() for e in all_events: events.append(e.to_dict()) event_slots.add(e.start_time) render_template(self, 'day.html', {'event_slots':sorted(event_slots)})
def show(self, id): try: e = Event.get(id) is_tracked = identity.current.user and e in identity.current.user.events except SQLObjectNotFound: flash("Event not found") util.redirect("/events/list") return dict(event=e, artist_list=artist_list, googlemap=googlemap, description=util.desc_format(e.description), is_tracked=is_tracked)
def get(self): template_values = {} upcoming_events, past_events = Event.get_paged_events() template_values['past_events'] = past_events template_values['upcoming_events'] = upcoming_events template_values['is_member'] = True if 'member' in self.session else False if 'member' in self.session: template_values['member'] = Member.get_member_json(self.session['member']) self.render_template(template_name='events.html', template_values=template_values)
def facebook_authorized(resp): if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) # get user and token session['oauth_token'] = (resp['access_token'], '') me = facebook.get('/me') u = User.query.filter_by(fbid=me.data['id']).first() group_alias = request.args.get('group_alias') # see if user is new user_is_new = False if not u: pton_info = get_pton_info(me) if True or pton_info: # TODO this is a temporary hack b/c for some reason it doesn't always work... FIXME u = User.create_pton_student(me, pton_info) user_is_new = True else: return "Access denied. If you're a Princeton student, \ connect your Princeton email to Facebook." # set session variables session['user_id'] = u.id session['user_first_name'] = u.first_name session['user_last_name'] = u.last_name session['logged_in'] = True # import user events Event.import_user_facebook_events(user, session['oauth_token'][0]) if user_is_new: # here we show the prompt if not group_alias: return redirect(url_for("index")) else: return redirect(url_for("index", group_alias=group_alias)) else: if not group_alias: return redirect(url_for("index")) else: return redirect(url_for("index", group_alias=group_alias))
def review_delete(self, **kw): e_counter = 0 while True: try: e_id = kw["eid"+str(e_counter)] except KeyError: break e_counter += 1 if not kw.has_key("accept"+e_id): continue e = Event.get(e_id) self.delete_event(e)
def get_by(row): if row.table_name == "artist_event": try: e = Event.get(row.table_id) link = ElementTree.Element("a", href="/events/%d" % e.id) link.text = str(e.id) except SQLObjectNotFound: return "none" else: link = ElementTree.Element("a", href="/%ss/%d" % (row.table_name, row.table_id)) link.text = str(row.table_id) return link
def testFirst(self): first_query = self.first_query session.query(Event).delete() session.commit() session.flush() e = Event(self.et) e.title = 'First event' e.time_start = datetime(1970, 1, 1, 0, 0) e.time_end = datetime(1970, 1, 1, 3, 0) e.description = 'First description' e.source_type = EventSourceType.EMPTY session.add(e) session.commit() all_first = first_query.all() self.assertEquals(len(all_first), 1) e = all_first[0] self.assertEquals(e.title, 'First event'); self.assertEquals(e.time_start, datetime(1970, 1, 1, 0, 0)) self.assertEquals(e.time_end, datetime(1970, 1, 1, 3, 0)) self.assertEquals(e.description, 'First description') self.assertEquals(e.source_type, EventSourceType.EMPTY) self.assertEquals(e.event_type.name, 'first') all_date_empty = session.query(Event).filter(Event.time_start == date(1971, 1, 1)).all() self.assertEquals(len(all_date_empty), 0) all_date_fine = session.query(Event).filter(Event.time_start == date(1970, 1, 1)).all() self.assertEquals(len(all_date_fine), 1) session.delete(e) session.commit()
def post(self): snapshot = self.get_uploads("snapshot") snapshot_key = str(snapshot[0].key()) if snapshot else None name = self['name'] description = self['description'] duration = int(self['duration']) link = self['link'] attendees = int(self['attendees'] if self['attendees'] else 0) key = self['key'] event = Event.get(key) if event: event.update(name=name, description=description, duration=duration, link=link, snapshot=snapshot_key, attendees=attendees) self.redirect("/events/search_event")
def post(handler, response): slug = handler.url_arg(0) if not slug: return handler.redirect('/events') event = Event.all().filter('slug =', slug).get() if not event: return handler.redirect('/events') user = handler.current_user() organizer = bool(handler.request.get('organizer')) if user: user.add_event(event, organizer) response.redirect = event.permalink() return handler.redirect(event.permalink())
def untrack(self, id, viewing="no"): u = identity.current.user try: e = Event.get(id) atts = Attendance.selectBy(user=u, event=e) for att in atts: att.destroySelf() except SQLObjectNotFound: flash("Event not found") redirect("/") if viewing == "no": util.redirect_previous() else: util.redirect("/events/%s" % e.id)
def post(self): pattern = r""" (\d+)/(\d+)/(\d+) # month, day, year """ reg = re.compile( pattern, re.VERBOSE ) match = reg.search( self.request.get( 'datepicker' ) ) d = datetime( int( match.group(3) ), int( match.group(1) ), \ int( match.group( 2 ) ) ) # adding event event = Event( date = d, detailed_date = self.request.get( 'alternate' ), name = self.request.get( 'name' ), time = self.request.get( 'time' ), location = self.request.get('loc'), ) event.put() self.redirect( "/events" )
def get(self): data = memcache.get('json') if data is None: prefix = "" postfix = "" if self.request.get('callback'): prefix = "%s(" % self.request.get('callback') postfix = ");" all_events = Event.all().order('start_time') events = [e.to_dict() for e in all_events] data = prefix+json.dumps(events)+postfix memcache.add('json', data, 300) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(data)
def review_import(self, **kw): e_counter = 0 now = datetime.now() while True: try: e_id = kw["eid"+str(e_counter)] except KeyError: break e_counter += 1 if not kw.has_key("accept"+e_id): continue e = Event.get(e_id) e.approved = now e.venue.approved = now for artist in e.artists: artist.approved = now
def post(handler, response): key = handler.request.get('key') response.event = event = Event.get(key) if key else Event() event.name = handler.request.get('name') event.link = handler.request.get('link') event.city = handler.request.get('city') event.date = handler.request.get('date') event.slug = handler.request.get('slug') lat = handler.request.get('lat') lon = handler.request.get('lon') if lat and lon: event.location = db.GeoPt(lat, lon) event.update_location() event.put() response.redirect=event.permalink() handler.redirect(event.permalink())
def get(handler, response): slug = handler.url_arg(0) if not slug: return handler.redirect('/events') response.event = event = Event.all().filter('slug =', slug).get() if not event: return handler.redirect('/events') response.attending = list(event.attending()) response.organizers = list(event.organizers()) response.interested = event.interested() if response.interested: response.interested_count = sum(len(d) for d in response.interested.values()) else: response.interested_count = 0 response.attendee_count = len(response.attending) response.organizers_count = len(response.organizers)
def get(self): events = Event.query().fetch() print events self.response.headers['Content-Type'] = 'application/json' # if events.count() == 0: # empty_reminder = {"Empty Event List": "No events for " + event_id + " available"} # self.response.out.write(json.dumps(empty_reminder)) # else: # forecast = requests.get("https://api.forecast.io/forecast/" + # FORECAST_APIKEY +"/37.8267,-122.423") event_list = [] for e in events: e_dict = e.to_dict() # result = forecast.json() # a_dict["weather"] = result event_list.append(e_dict) self.response.out.write(json.dumps(event_list, cls=MyEncoder))
def post(handler, response): events_yaml = handler.request.get('events') import logging events = yaml.load(events_yaml) for event in events: obj = Event.all().filter('slug =', event['slug']).get() or Event() obj.name = event['name'] obj.link = event.get('link') obj.city = event['city'] obj.date = event['date'] obj.slug = event['slug'] if 'location' in event: match = re.match('^(.*), (.*)$', event['location']) if match: (lat, lon) = match.groups() obj.location = db.GeoPt(lat, lon) obj.update_location() obj.put()