Пример #1
0
 def post(self):
     req_data = request.get_json()
     errors = events_schema.validate(req_data)
     data = events_schema.load(req_data)
     event = Events(data)
     event.create()
     return {'message': 'Evento ' + event.name + " creado."}, 200
Пример #2
0
def insert():
    global user

    if request.method == 'POST':
        date = request.form['date']
        time = request.form['time']
        title = request.form['title']
        event_content = request.form['event_content']

        data_event = Events(date, time, title, event_content)
        data_event.author = user
        db.session.add(data_event)
        db.session.commit()

        email_data = {
            'subject': title,
            'to': user.email,
            'body': event_content
        }

        date_time = date + " " + time
        datetime_object = datetime.strptime(date_time, '%Y-%m-%d %H:%M') - timedelta(hours=4)
        eta_date = datetime.utcfromtimestamp(datetime_object.timestamp()).strftime('%Y-%m-%d %H:%M:%S')
        send_async_email.apply_async(args=[email_data], eta=eta_date)

        flash('New event inserted successfully')

        return redirect(url_for('Index'))
Пример #3
0
    def get(self):
        user = users.get_current_user()
        email = self.request.get('email')
        template_values = get_generic_template_values(self)
        eventsQuery = Events().query()
        results = eventsQuery.fetch()
        if user:

            #self.response.write(json.dumps(results))
            # for mobile
            #         serialized_results = filter_results(results)
            #         self.response.headers['Content-Type'] = 'application/json'
            #         self.response.write(json.dumps(serialized_results))

            template_values['results'] = results
            #template = JINJA_ENVIRONMENT.get_template('/views/viewThemes.html')
            #self.response.write(template.render(template_values))
        elif email:
            serialized_results = filter_results(results)
            l = []
            for r in serialized_results:
                #d = serialized_results[0]
                r.pop('theme_id')
                r.pop('tag')
                r.pop('image_urls')
                l.append(r)
            self.response.headers['Content-Type'] = 'application/json'
            self.response.write(json.dumps(l))
Пример #4
0
    def post_event(jwt):

        try:
            event_data = request.get_json()

            team_id = event_data.get('team_id')
            team_id_two = event_data.get('team_id_two')
            venue_id = event_data.get('venue_id')
            start_time = event_data.get('start_time')
            team_one_score = event_data.get('team_one_score') or 0
            team_two_score = event_data.get('team_one_score') or 0

            event = Events(
                team_id=team_id,
                team_id_two=team_id_two,
                venue_id=venue_id,
                start_time=start_time,
                team_one_score=team_one_score,
                team_two_score=team_two_score
            )

            event.insert()

            formatted_event = paginated_events(request, [event])

            return jsonify({
                'success': True,
                'event': formatted_event[0]
            }), 200

        except Exception:
            print(sys.exc_info())
            abort(400)
Пример #5
0
def update_event_info(event_id):
    title = request.json.get("title")
    description = request.json.get("description")
    event_datetime = request.json.get("start_datetime")
    event_location = request.json.get("location")
    attendance_price = request.json.get("price")
    event_type_id = request.json.get("event_type_id")
    image_url = request.json.get("image_url")

    if not title or not description or not event_datetime \
            or not event_location or not event_type_id:
        raise BadRequest("Invalid body parameters")

    try:
        event = Events.query.filter_by(id=event_id).first()
    except Exception as e:
        print(e)
        raise InternalServerError(
            "Internal Server Error! Could not retrieve events.")
    if not event:
        raise NotFound(f"Event with Id = {event_id} not found")
    else:
        event.title = title
        event.description = description
        event.start_date_time = event_datetime
        event.location = event_location
        event.price = attendance_price
        event.event_type_id = event_type_id
        event.image = image_url

        Events.update(event)
        return jsonify({"success": True, "data": event.serialize})
Пример #6
0
def new_event():
    title = request.json.get("title", None)
    description = request.json.get("description", None)
    event_datetime = request.json.get("start_datetime", None)
    event_location = request.json.get("location", None)
    image_url = request.json.get("image_url", None)
    event_type_id = request.json.get("event_type_id", None)
    organizer_id = request.json.get("organizer_id", None)

    if not title or not description or not event_datetime \
            or not event_location or not event_type_id:
        raise BadRequest("Invalid body parameters")

    try:
        new_event = Events(title=title,
                           description=description,
                           start_date_time=event_datetime,
                           event_location=event_location,
                           image=image_url,
                           organizer_id=organizer_id,
                           event_type_id=event_type_id)
        Events.insert(new_event)
        return jsonify({"success": True, "data": new_event.serialize})
    except Exception as e:
        print(e)
        db.session.rollback()
        raise InternalServerError(f"Something went wrong on server")
Пример #7
0
 def post(self):
     tagName = self.request.get('tag')
     eventQuery = Events().query(Events.tag == tagName)
     events = eventQuery.fetch()
     template_values = get_generic_template_values(self)
     template_values['events'] = events
     template = JINJA_ENVIRONMENT.get_template('/views/search.html')
     self.response.write(template.render(template_values))
Пример #8
0
def parser():

    xmlPage = 'http://datos.madrid.es/portal/site/egob/menuitem.ac61933d6ee3c31cae77ae7784f1a5a0/?vgnextoid=00149033f2201410VgnVCM100000171f5a0aRCRD&format=xml&file=0&filename=206974-0-agenda-eventos-culturales-100&mgmtid=6c0b6d01df986410VgnVCM2000000c205a0aRCRD'

    soup = BeautifulSoup(urlopen(xmlPage),'xml')
    content = soup.findAll('contenido')

    update = time.strftime("%Y-%m-%d %H:%M")
    fh = upDate(dateUpDate = update)
    fh.save()
    for tag in content:
        #Titulos actividad
        title = tag.find(nombre = 'TITULO').string
        #Tipo de evento, si no lo encuentra añado Sin titulo
        try:
            typeEvent = tag.find(nombre = 'TIPO').string.split('actividades/')[1]       
        except:
            typeEvent = "Sin tipo"
        #Busco los precios, si no tiene es gratuito
        try:
            prize = tag.find(nombre = 'PRECIO').string        
        except:
            prize = "Gratis"
        #Busco fecha de eventos
        date = tag.find(nombre = 'FECHA-EVENTO').string
        #Hora del evento
        hour = tag.find(nombre = 'HORA-EVENTO').string
        #Creo la fecha para el campo datefield
        date = date.replace('00:00:00.0',hour)
        #Si el valor devuelto es 1 sustituyo por larga duracion, si es 0 no
        try:
            longDuration = tag.find(nombre = 'EVENTO-LARGA-DURACION').string
        except:
            longDuration = 'Sin informacion de larga duracion'

        if longDuration == '0':
            longDuration = longDuration.replace('0','Corta')

        elif longDuration == '1':
            longDuration = longDuration.replace('1','Larga')
        #Busco urls con informacion adicional
        try:
            Url = tag.find(nombre = 'CONTENT-URL-ACTIVIDAD').string       
        except:
            Url = "Sin URL informacion"
        #Busco comentarios
        try:
            coment = tag.find(nombre = 'DESCRIPCION').string       
        except:
            coment = "Sin descripcion"
        #Busco fecha y hora finalizacion
        fechaFin = tag.find(nombre = 'FECHA-FIN-EVENTO').string       
                
                        
        tableEvents = Events( titulo =title, tipo = typeEvent , fecha = date , precio = prize , largaDuracion = longDuration , url = Url ,likes = 0,comentario = coment , fin = fechaFin)    
        tableEvents.save()

    return None
Пример #9
0
def do_login():
        username = request.forms.get('username','').strip()  # username
        password = request.forms.get('password','').strip()  # password

        if check_login(username,password):
            Events.log_info(' "%s" load in' % username)
            return '<p> log in succeed </p>'
        else:
            return '<p>please check your username and password</p>'
Пример #10
0
def createEvent():
    form = EventForm(request.form)

    if request.method == "POST" and form.validate():
        Events.insert(name=form.name.data,
                      icon=base64.b64encode(
                          request.files[form.icon.name].read()),
                      date=form.date.data,
                      description=form.description.data)
        return redirect(url_for("home"))
    return render_template("auth/events/create.html", form=form)
Пример #11
0
 def post(self):
     event = Events(author=self.request.get('inputAuthor'),
                    title=self.request.get('inputTitle'),
                    description=self.request.get('inputDescription'),
                    type=self.request.get('inputType'),
                    location=self.request.get('inputLocation'),
                    image=self.request.get('inputImage'),
                    date=datetime.strptime(self.request.get('inputDate'),
                                           '%Y-%m-%dT%H:%M'))
     event.put()
     return webapp2.redirect('/')
Пример #12
0
def event_insert(request):
    variables = {}
    print "hello event"
    if request.POST:
        event = Events()
        event.eve_name = request.POST.get('event_name')
        event.eve_location = request.POST.get('event_location')
        event.eve_date = request.POST.get('event_date')
        event.eve_entry_fee = request.POST.get('event_entryfee')
        event.eve_discription = request.POST.get('event_discription')
        event.eve_isused = 0
        event.save()
    return render(request, 'clients/new_event.html', variables)
Пример #13
0
def delete_event(event_id):
    try:
        event = Events.query.filter_by(id=event_id).first()
    except Exception as e:
        print(e)
        raise InternalServerError(
            "Internal Server Error! Could not retrieve events.")
    if not event:
        raise NotFound(f"Event with Id {event_id} not found")
    else:
        Events.delete(event)
        return jsonify({
            "success": True,
            "deleted": event_id,
        }), 200
Пример #14
0
def getEventById(eid):
    user = get_mobile_or_web_user()
    event = db.session.query(Events).get(eid)
    if event.endTime > datetime.utcnow():
        return jsonify(Events=Events.build_event_dict(event, user))
    else:
        return jsonify(msg='Event not found'), 404
Пример #15
0
    def setUp(self):
        self.engine = create_engine('mysql+pymysql://')
        self.session = Session(engine)
        Base.metadata.create_all(self.engine)

        self.characters_instance = Characters(1009610, "Spider-Man")
        self.session.add(self.character_instance)

        self.comics_instance = Comics(30885, "Age of Heroes (Trade Paperback)")
        self.session.add(self.comics_instance)

        self.creators_instance = Creators(9799, "David Baldeon")
        self.session.add(self.creators_instance)

        self.events_instance = Events(116, "Acts of Vengeance!")
        self.session.add(self.events_instance)

        self.series_instance = Series(10235, "Age of Heroes (2011)")
        self.session.add(self.series_instance)

        self.stories_instance = Stories(483, "Interior #483")
        self.session.add(self.stories_instance)

        self.images_instance = Images(
            1, 0, "http://i.annihil.us/u/prod/marvel/i/mg/3/40/4c06c8261544e")
        self.session.add(self.images_instance)

        self.session.commit()
Пример #16
0
    def put(self, id_receiver):
        req_data = request.get_json()
        events = []
        if 'events' in request.get_json():
            for event_id in request.get_json()['events']:
                events.append(Events.get_one(event_id))
            req_data.pop('events')
        errors = receiver_schema.validate(req_data)
        if errors:
            return errors, 500
        data = receiver_schema.load(req_data, partial=True)

        try:
            receiver = ReceiverModel.get_one_receiver(id_receiver)
            receiver.events.clear()
            for event in events:
                receiver.events.append(event)
            receiver.update(data)
            ser_receiver = receiver_schema.dump(receiver)

            return {
                'message':
                'Beneficiario {} editado'.format(ser_receiver['curp'])
            }, 200
        except (sqlalchemy.exc.SQLAlchemyError,
                sqlalchemy.exc.DBAPIError) as e:
            return render_template('500.html', error=e), 500
Пример #17
0
def createEvent(e_info):
    newEvent = Events(e_info["e_t_id"], e_info["s_id"], e_info["name"],
                      e_info["location"], e_info["description"])
    db.session.add(newEvent)
    db.session.commit()

    return newEvent.e_id
Пример #18
0
    def post(self):
        req_data = request.get_json()
        events = []
        if 'events' in request.get_json():
            for event_id in request.get_json()['events']:
                events.append(Events.get_one(event_id))
        req_data.pop('events')
        req_data.update({'created_user': current_user.id})
        errors = receiver_schema.validate(req_data)
        if errors:
            return errors, 500
        data = receiver_schema.load(req_data)
        try:
            if ReceiverModel.find_by_curp(data['curp']):
                return {
                    'message':
                    'El benificiario {} ya existe'.format(data['curp'])
                }, 500
            receiver = ReceiverModel(data)
            receiver.events.clear()
            for event in events:
                receiver.events.append(event)

            receiver.create()
            return {'message': 'Beneficiario {} creado'.format(data['curp'])}
        except (sqlalchemy.exc.SQLAlchemyError,
                sqlalchemy.exc.DBAPIError) as e:
            return render_template('500.html', error=e), 500
def generateevent():    
    us = extractUser()
    print(us)
    u = Users(fullname=None,username=None,email=None)
    index = random.randint(1,51)
    s = session.query(Establishments).filter(Establishments.id == str(index))
    ev = Events(dt.datetime.now(), dt.datetime.now(), 'Evennt ' + str(random.randint(1,100000)),random.randint(1,1000),s[0].id)
Пример #20
0
def events():
    if request.method == "POST":
        my_data = json.loads(request.data.decode('utf-8'))
        name = my_data['eventDate']
        print(name)
        event = Events(
            event_name=my_data['eventName'],
            event_date=my_data['eventDate']
        )

        try:
            db.session.add(event)

            # Need to commit event first so I can use the event_id to link two tables
            db.session.commit()
            attendees = []
            for attendee in my_data['attendees']:
                attendees.append(Attendance(
                    meetup_user_id=attendee['userId'],
                    event_id=event.id,
                    did_attend=attendee['didAttend'],
                    did_rsvp=attendee['didRSVP'],
                    title=attendee['title'],
                    event_host=attendee['eventHost'],
                    rsvp_date=attendee['rsvpDate'],
                    date_joined_group=attendee['dateJoinedGroup']
                ))
            print(attendees)
            print(event)
            db.session.bulk_save_objects(attendees)
            db.session.commit()

        except Exception as exception:
            print(exception)
        return jsonify(my_data)
    else:
        events = []
        for event in Events.query.order_by(Events.event_date.desc()).all():
            try:
                attendees = Attendance.query.filter(
                    Attendance.event_id == event.id, Attendance.did_attend == True).all()
                rsvps = Attendance.query.filter(Attendance.event_id ==
                                                event.id, Attendance.did_rsvp == True).all()
                attendees_who_rsvpd = Attendance.query.filter(Attendance.event_id ==
                                                              event.id, Attendance.did_rsvp == True, Attendance.did_attend == True).all()
                events.append({
                    # Needs to be string here beacuse when front end sends event id back to get attendance data
                    # Database expects getting rows by matching id string, not number
                    "id": event.id,
                    "name": event.event_name,
                    "date": event.event_date,
                    "attendees": len(attendees),
                    "rsvps": len(rsvps),
                    "attendeesWhoRsvpd": len(attendees_who_rsvpd)
                })
            except Exception as exception:
                print(exception)
                return "Could not get the event data"
        return jsonify(data=events)
Пример #21
0
def home():
    all_events = Events.get()
    curr_events = []
    for event in all_events:
        if event.date >= datetime.date.today():
            curr_events.append(event)
    curr_events = sorted(curr_events, key=lambda x: x.date)
    return render_template("auth/home/home.html", events=curr_events)
Пример #22
0
def event_info(hashid):
    event = Events.get_by_hashid(hashid)
    print hashids.decrypt(hashid)
    if event:
        print event.id, event.description, event.amount
    else:
        print 'Event not found'
        print hashids.decrypt(hashid)
Пример #23
0
def add(request):
    data = get_data()
    name = request.POST.get('name')
    date = request.POST.get('date')
    city = request.POST.get('cities')
    if city:
        city = city.capitalize()
    if city == 'Other':
        city = request.POST.get('city1').capitalize()
    info = request.POST['info']
    if city not in data["cities"]:
        data["cities"].append(city)
    manager_instance.update_city(data["cities"])
    event_instance = Events(name=name, date=date, city=city, info=info)
    event_instance.save()
    message = "Event added!"
    return HttpResponse(message)
Пример #24
0
def post_event():
    print("A post request to newEvent was made")

    data = request.json
    new_event = Events(data)
    db.session.add(new_event)
    db.session.commit()
    return jsonify(status="success")
Пример #25
0
    def post(self):
        name = self.request.get('name')
        desc = self.request.get('desc')
        url = self.request.get('url')
        token = self.request.get('token')
        imageUrl = url + '&token=' + token
        correctUrl = imageUrl.replace("images/", "images%2F")
        location = self.request.get('place')
        tags = self.request.get('tagValues')
        themeName = self.request.get('theme')

        email = self.request.get('email')
        #         themeQuery = Theme.query(Theme.name == themeName)
        #         theme_id = themeQuery.fetch(keys_only=True)
        event = Events()
        event.name = name
        event.description = desc
        event.cover_image = correctUrl

        event.created_user_email = email
        #         event.theme_id = theme_id
        #event.image_urls = listOfUrls
        #event.tag = tags
        #event.cover_image = random.choice(listOfUrls)
        #         coordinates = getCoordinates(location)
        #         event.place = coordinates[0]
        #         event.lat = coordinates[1]
        #         event.long = coordinates[2]
        #         event.created_user_email = user.email()

        key = event.put()
        self.response.write('Got post request: ' + name + '  ' + desc + '  ' +
                            location + '  ' + tags + '  ' + correctUrl + ' ' +
                            email + ' ' + themeName + " " + key)
Пример #26
0
    def get(self):

        template_values = get_generic_template_values(self)
        user = users.get_current_user()
        theme = None
        events = None
        if user:
            url_string = self.request.get('val')
            key = ndb.Key(urlsafe=url_string)
            theme = key.get()
            if theme != None:
                eventsQuery = Events().query(Events.theme_id == key)
                events = eventsQuery.fetch()

        template_values['theme'] = theme
        template_values['events'] = events
        template = JINJA_ENVIRONMENT.get_template('/views/singleTheme.html')
        self.response.write(template.render(template_values))
Пример #27
0
def insert_events():
    event_data = pandas.read_csv('events.csv', quotechar='"')
    for i in range(len(event_data)):
        event = Events(event_data['title'][i],
                event_data['location'][i],
                event_data['dateTime'][i],
                event_data['description'][i],
                event_data['organizer'][i],
                event_data['banner'][i])
        db.session.add(event)
    db.session.commit()
Пример #28
0
def event(event_id):
    event = Events.query.filter_by(id=event_id).one()

    # handles POST method (play button to generate 6 digit code)
    if request.method == "POST":
        pushing_code = Events(secret_code=verify_key())
        db.session.add(pushing_code)
        db.session.commit()

    # returns event specific page
    return render_template('event.html', event=event)
Пример #29
0
def create():
    if request.method == "POST":
        new_event = Events(
            name=request.form.get('name'),
            location=request.form.get('location'),
            #date = request.form.get('date'),
            secret_code="000000",
            society=current_user.name)
        db.session.add(new_event)
        db.session.commit()
    return render_template('newevent.html')
Пример #30
0
def mobile_savedevents():
    username = get_jwt_identity()
    user = db.session.query(Users).filter(Users.email == username).first()
    saved_events = []
    for event in user.savedevents:
        if event.endTime >= datetime.utcnow():
            saved_events.append(event)
    saved_events.sort(key=lambda Events: Events.startTime)
    saved_events = [
        Events.build_event_dict(event, user) for event in saved_events
    ]
    return jsonify(Events=saved_events)
Пример #31
0
def events(request):
    if request.method == 'GET':
        print "hello"
        Event_title = request.GET.get('Event_title')
        print Event_title
        Event_desc = request.GET.get('Event_desc')
        # Event_date =
        Event_date = datetime.strptime(request.GET.get('Event_date'),
                                       '%b %d %Y %I:%M%p')
        print Event_date
        Event_location = request.GET.get('Event_location')
        Event_org = \
            Users.objects.get(user_email=request.GET.get('user_email'))
        new_event = Events(Event_title=Event_title,
                           Event_location=Event_location,
                           Event_date=Event_date,
                           Event_desc=Event_desc,
                           Event_org=Event_org)
        new_event.save()
        return HttpResponse(json.dumps({'success': 'True'}),
                            content_type='application/json')
Пример #32
0
def post_eevnt(payload):
    error = False
    response = {}
    # get and check the user imput
    try:
        body = request.get_json()
        event_name = body.get('event_name')
        event_type = body.get('event_type')
        date = body.get('date')
        rating = body.get('rating')
        provider_id = body.get('provider_id')
        customer_id = body.get('customer_id')
        # if event_name and event_type and date:
        event = Events(id=None,
                       event_name=event_name,
                       event_type=event_type,
                       date=date,
                       rating=rating,
                       provider_id=provider_id,
                       customer_id=customer_id)
        # inser event data into db
        event.insert()
        response['success'] = True
        response['id'] = event.id
        event.sesion_close()
    except BaseException:
        abort(400)
    # return the response
    return jsonify(response)
Пример #33
0
def add(request):
    """Adding event functionality achieved through ajax call."""
    user_is = request.session['username']
    if user_is != "not signed in":
        data = Cities.objects.values("place")
        name = request.POST.get('name')
        date_is = request.POST.get('date')  # variable with name "date" is shadowing inbuilt date()
        city = request.POST.get('cities')
        if city:
            city = city.capitalize()
        if city == 'Other':
            city = request.POST.get('other_city').capitalize()
        info = request.POST.get('info')
        if city not in data:
            city_instance = Cities(place=city)
            city_instance.save()
        user_obj = User.objects.get(user_email=request.session['useremail'])
        event_instance = Events(name=name, date=date_is, city_id=city, info=info, user_id=user_obj.user_email)
        event_instance.save()
        message = "Event added!"
    else:
        message = "Sign in to add events!"
    return HttpResponse(message)
Пример #34
0
def get_events(request, prev_time):
    "возвращает список событий"
    events = Events.get_events(prev_time)
    return int(time()), events
Пример #35
0
def clear_events():
    Events.clear()
Пример #36
0
def event_url(event_id):
    event = Events.get(id=event_id)
    if event:
        print event.description, url_for('event', hashid=event.hashid)
    else:
        print 'Event not found'