コード例 #1
0
ファイル: event.py プロジェクト: MansM/microservices-poc
def create_event(data):
    date = data.get('date')
    event_id = data.get('id')
    title = data.get('title')
    location = data.get('location')
    description = data.get('description')
    maxpeople = data.get('maxpeople')

    # event = Event(title, date, location, description, maxpeople)
    event = Event(title, date, location, description, maxpeople)

    if event_id:
        event.id = event_id

    db.session.add(event)
    db.session.commit()
コード例 #2
0
def create_event(request):
    if request.method == 'GET':
        something = base_views.search(request)
        if something:
            return something
    if request.method == 'POST':
        form = createEventForm(request.POST, request.FILES)
        assoc_name = form.data['association_name']
        title = form.data['title']
        description = form.data['description']
        price = form.data['price']
        place = form.data['place']
        size_intern = form.data['size_intern']
        size_extern = form.data['size_extern']
        date_begin = form.data['date_begin']
        date_end = form.data['date_end']
        date_deadline = form.data['date_deadline']
        photo = request.FILES['photo']
        boutique = form.data['boutique']  #TODO
        token = form.data['token']
        assoc = Association.objects.get(id=assoc_name)
        newEvent = Event(association_id=assoc,
                         title=title,
                         date_begin=date_begin,
                         date_end=date_end,
                         date_deadline=date_deadline,
                         validated=True,
                         description=description,
                         price=price,
                         boutique=boutique,
                         place=place,
                         photo=photo,
                         size_intern=size_intern,
                         size_extern=size_extern,
                         token_staff=token)
        newEvent.save()
        creer = True
    else:
        form = createEventForm()
    assos = Association.objects.all()
    return render(request, 'event/create_event.html', locals(),
                  {'assos': assos})
コード例 #3
0
ファイル: event.py プロジェクト: TELLifon/tellifon-backend
 def post(self, id):
     body = request.form
     args = self.reqparse.parse_args()
     event = Event(**body)
     event.is_public = args['is_public']
     event.category_id = Category.objects().get(id=id).id
     event.save()
     if 'image' in request.files:
         file = request.files['image']
         s3 = session.client
         s3.put_object(Body=file,
                       Bucket="devbucket0",
                       ContentType=file.content_type,
                       Key=str(event.id))
         event.img_src = '/api/events/{}/image'.format(str(event.id))
         event.save()
     return {'id': str(event.id)}, 200
コード例 #4
0
def scrape_events():
    soup = BeautifulSoup(getPageSource(SF_EVENTS_URL), 'html.parser')

    rows = soup.find('table').find_all('tr')
    event_date = EMPTY_DATE
    for row in rows:
        maybe_date = row.find('h2')
        if maybe_date:
            event_date = maybe_date.get_text(strip=True)

        columns = row.find_all('td')
        if len(columns) == 3:
            time = columns[0].get_text(strip=True)
            desc = columns[1].get_text(strip=True)
            price = columns[2].get_text(strip=True)

            if event_date == EMPTY_DATE:
                raise Exception('Date not found for event: ' + desc)

            # Create hash of all info about this event
            # to detect duplicates in DB
            id = int(sha256((event_date + time + desc + price).encode('utf-8')
                            ).hexdigest(), 16) % sys.maxsize

            event = db.session.query(Event).filter_by(id=id).first()

            # TODO handle creation of 'all day' events
            if time == 'All Day':
                continue

            datetime_start = formatDatetime(event_date, time)
            datetime_end = createDefaultEndTime(event_date, time)

            # Only add event to the DB if it doesn't already exist
            if event is None:
                event = Event(
                    id=id,
                    date=event_date,
                    datetime_end=datetime_end,
                    datetime_start=datetime_start,
                    description=desc,
                    price=price,
                    time=time
                )

                db.session.add(event)
                db.session.commit()
コード例 #5
0
def scrape_events():
    soup = BeautifulSoup(getPageSource(AUSTIN_EVENTS_URL), 'html.parser')

    events = soup.find_all('div', class_='ds-listing event-card')

    datetime_start = EMPTY_DATE
    for event in events:
        maybe_date = event.find('meta', attrs={'itemprop': 'startDate'})
        if maybe_date:
            datetime_start = maybe_date.datetime
            datetime_end = createDefaultEndTime(datetime_start, time)

        # FIXME parse the actual time
        time = '?'
        desc = event.find(class_='ds-listing-event-title-text').get_text(
            strip=True)
        # FIXME parse the actual price
        price = '?'

        if datetime_start == EMPTY_DATE:
            raise Exception('Date not found for event: ' + desc)

        # Create hash of all info about this event
        # to detect duplicates in DB
        id = int(
            sha256((datetime_start + time + desc +
                    price).encode('utf-8')).hexdigest(), 16) % sys.maxsize

        event = db.session.query(Event).filter_by(id=id).first()

        # TODO handle creation of 'all day' events
        if time == 'All Day':
            continue

        # Only add event to the DB if it doesn't already exist
        if event is None:
            event = Event(id=id,
                          date=datetime_start,
                          datetime_end=datetime_end,
                          datetime_start=datetime_start,
                          description=desc,
                          price=price,
                          time=time)

            db.session.add(event)
            db.session.commit()
コード例 #6
0
def create_event(data):
    title = data.get('title')
    importance = data.get('importance')
    sensor = data.get('sensor')
    try:
        get_sensor(sensor)
    except:
        raise SensorNotFoundException(
            'No event can be associated with a sensor with id ' + str(id) +
            ' because it does not exist.')
    ended = data.get('ended')
    if Sensor.query.filter(Sensor.id == sensor).count() == 1:
        event = Event(title, importance, sensor, ended)
        db.session.add(event)
        db.session.commit()
        return event
    else:
        raise SensorNotFoundException('There is no sensor with id ' + str(id) +
                                      '.')
コード例 #7
0
def test_model_user():
    """
    GIVEN a User model
    WHEN a new User is created
    THEN check the email, hashed_password, authenticated, and role fields are defined correctly
    """

    new_event = Event("event1", "Description", "1996-11-14T18:21:35.433Z",
                      "1996-11-14T18:21:35.433Z", 12345,
                      "1996-11-14T18:21:35.433Z", "1996-11-14T18:21:35.433Z",
                      "barcelona", 1)
    assert new_event.name == "event1"
    assert new_event.description == "Description"
    assert new_event.funding_start_date == "1996-11-14T18:21:35.433Z"
    assert new_event.funding_end_date == "1996-11-14T18:21:35.433Z"
    assert new_event.goal == 12345
    assert new_event.event_start_date == "1996-11-14T18:21:35.433Z"
    assert new_event.event_end_date == "1996-11-14T18:21:35.433Z"
    assert new_event.location == "barcelona"
    assert new_event.user_creator == 1
コード例 #8
0
    async def create(self, ctx, name: str, date: str, time: str='0:00am'):
        '''Creates an event with specified name and date
            example: !create party 12/22/2017 1:40pm
        '''

        date_time = '{} {}'.format(date, time)
        event_date = datetime.strptime(date_time, '%m/%d/%Y %I:%M%p')
        try:
            existing = session.query(Event).filter(Event.name == name, Event.date == event_date).first()
            if not existing:
                event = Event(name=name, date=event_date)
                session.add(event)
                session.commit()
                await ctx.send('Event {} created successfully for {}'.format(name, event.date))
            else:
                await ctx.send('Event {} was already created'.format(name))

        except Exception as e:
            await ctx.send('Could not complete your command')
            print(e)
コード例 #9
0
    def test_end_event(self):
        """
		Test case for end_event
		"""
        with self.app.app_context():
            sensor = Sensor("name", "mac", "type", "model", 0)
            db.session.add(sensor)
            db.session.commit()
            event = Event("title", 5, sensor.id)
            db.session.add(event)
            db.session.commit()

            # OK
            found_event = ser.end_event(event.id)
            self.assertEqual(event.id, found_event.id)
            self.assertIsNotNone(found_event.end)
            self.assertTrue(found_event.ended)

            db.session.delete(event)
            db.session.delete(sensor)
            db.session.commit()
コード例 #10
0
ファイル: app.py プロジェクト: younggeeks/Bright-events
 def post(self):
     """Handles event registration,
         checks if event with same name is registered first
        If event exists error message is sent with status
         400 otherwise event is added to
        Events list"""
     data = request.get_json()
     event = [found_event for found_event in DataMocks.events
              if found_event.name == data["name"]]
     if not event:
         event = Event(id=uuid.uuid4(), price=data["price"], name=data["name"],
                       address=data["address"], start_date=data["start_date"],
                       end_date=data["end_date"], user=data["user"],
                       description=data["description"],
                       category=data["category"])
         DataMocks.events.append(event)
         resp = jsonify({"message": "Event Successfully Created!", "event": event_parser(event)})
         resp.status_code = 201
         return resp
     else:
         return make_response(status=400, message="Event Name Must Be unique")
コード例 #11
0
 def get(self, id):
     timefilter = datetime.now() - timedelta(hours=2)
     category = Category.objects.get(id=id)
     response = json.loads(category.to_json())
     events = json.loads(
         Event.objects(
             __raw__={
                 'category_id': category.id,
                 'endtime': {
                     '$gt': timefilter
                 },
                 'img_src': {
                     '$ne': ''
                 },
                 'is_public': {
                     '$eq': True
                 }
             }).order_by('+starttime').to_json())
     response["events"] = events
     return Response(json.dumps(response),
                     mimetype="application/json",
                     status=200)
コード例 #12
0
    def test_get_event(self):
        """
		Test case for get_event
		"""
        with self.app.app_context():
            # Invalid id
            with self.assertRaises(EventNotFoundException):
                ser.get_event(0)

            sensor = Sensor("name", "mac", "type", "model", 0)
            db.session.add(sensor)
            db.session.commit()
            event = Event("title", 5, sensor.id)
            db.session.add(event)
            db.session.commit()

            # OK
            found_event = ser.get_event(event.id)
            self.assertEqual(event, found_event)

            db.session.delete(event)
            db.session.delete(sensor)
            db.session.commit()
コード例 #13
0
    def test_get_event_by_sensor_id(self):
        """
		Test case for get_event_by_sensor_id
		"""
        with self.app.app_context():
            # No event for given sensor
            with self.assertRaises(EventNotFoundException):
                ser.get_event_by_sensor_id(0)

            sensor = Sensor("name", "mac", "type", "model", 0)
            db.session.add(sensor)
            db.session.commit()
            event = Event("title", 5, sensor.id)
            db.session.add(event)
            db.session.commit()

            # OK
            events = ser.get_event_by_sensor_id(sensor.id)
            self.assertEqual(1, len(events))
            self.assertEqual(event, events[0])

            db.session.delete(event)
            db.session.delete(sensor)
            db.session.commit()
コード例 #14
0
class DataMocks:
    def __init__(self):
        pass

    users = [
        User(id=2,
             full_name="sam",
             email="*****@*****.**",
             password="******"),
        User(id=4,
             full_name="junior",
             email="*****@*****.**",
             password="******"),
        User(id=5,
             full_name="michael",
             email="*****@*****.**",
             password="******"),
        User(id=6,
             full_name="juma",
             email="*****@*****.**",
             password="******"),
        User(id=7,
             full_name="atanasi",
             email="*****@*****.**",
             password="******"),
        User(id=8,
             full_name="john",
             email="*****@*****.**",
             password="******")
    ]

    rsvps = [{
        "event_id":
        9494,
        "users": [
            User(id=2,
                 full_name="samwel Charles",
                 email="*****@*****.**",
                 password="******")
        ]
    }, {
        "event_id":
        987,
        "users": [
            User(id=2,
                 full_name="samwel Charles",
                 email="*****@*****.**",
                 password="******")
        ]
    }]

    events = [
        Event(
            id=9494,
            price=89389,
            name="WOMEN WHO CODE",
            address="Riverroad, Nairobi",
            start_date="2017-12-16",
            end_date="2017-12-16",
            user="******",
            description=
            "Women Who Code presents a Hackathon designed to showcase women as they take on tech. Join our "
            "community of changemakers for Nairobi Hackathon October 13-15, 2017 to make something great. A "
            "Hackathon like no other the WWCode ",
            category="Hackathon"),
        Event(
            id=894,
            name="Mobile Museum of Art",
            price=100,
            address="kirinyaga, Kenya",
            start_date="2017-12-16",
            end_date="2017-12-16",
            user="******",
            description=
            "Did you know there are 17 museums in Mobile? Let's go visit all of them! We'll start with the Mobile "
            "Museum of Art for their free admission special. MMOFA is celebrating the opening of new art "
            "exhibits. They will have a free concert outdoors",
            category="Meetup"),
        Event(
            id=987,
            name="Fitness boot camp",
            price=2000,
            address="Magomeni, Dar es salaam",
            start_date="2017-12-16",
            end_date="2017-12-16",
            user="******",
            description=
            "A fitness boot camp is a type of group physical training program conducted by gyms, personal trainers,"
            "and former military personnel. These programs are designed to build strength and fitness through a "
            "variety "
            " of intense group intervals over a 1-hour period of time",
            category="Bootcamps"),
        Event(
            id=5221,
            name="2017 Tech Bootcamp",
            price=10009,
            address="Chanika, Dar es salaam",
            start_date="2017-12-16",
            end_date="2017-12-16",
            user="******",
            description=
            "We will be holding a one-week intensive hands-on Kids Tech Bootcamp during the April holidays. "
            "Training will be on: Electronics and Robotics; Web Programming and Design; Minecraft 3D game modding; ",
            category="Code Camps"),
        Event(
            id=5879,
            name="Fit Kenyan Bootcamp",
            price=10009,
            address="Mombasa, Kenya",
            start_date="2017-12-16",
            end_date="2017-12-16",
            user="******",
            description=
            "Fit Kenyan Bootcamp has transformed, inspired and made people sweat since 2013! FKB was founded with "
            "the main aim to create an affordable work out regime with the concept to make use of our beautiful ",
            category="Code Camps"),
    ]

    @staticmethod
    def update_users(new_list):
        """
        Method that will update our users List , When called It will replace current list with new list
        which was passed as an argument , It'll be called when update or delete is called
        :param new_list:
        :return:
        """
        DataMocks.users = new_list

    @staticmethod
    def update_events(new_events):
        """
        Method that will update our events List , When called It will replace current list with new list
        which was passed as an argument , It'll be called when update or delete is called
        :param new_events:
        :return:
        """
        DataMocks.events = new_events

    @staticmethod
    def get_data(data_type, data=None):
        """
        Helper function which will be responsible for converting(parsing) list of either User or Data models
        to list of dictionaries, caller will pass in string argument(data_type) with value of either
        "users" or "events" and optional data argument , if data argument is not specified it will be
        defaulted to None , meaning function will convert users or events list from our dummy data , if data
        argument is passed, data that will be passed will be parsed accordingly .
        :param data_type:
        :param data:
        :return parsed_dictionary:
        """
        if data_type == 'users':
            return fetch_users(data)
        elif data_type == "events":
            print("data from get_data", data)
            return fetch_events(data)