def test_expired(self):
        user = Mock()
        id = randrange(1, 100)
        user.id = id
        user.is_admin = False

        secret = faker.sentence()
        expire_time = time.time() - 2 * (60 * 60 * 24) + randrange(1, 100)

        with patch('tahelka.auth.token_generator.current_app') as app:
            with patch(
                'tahelka.auth.token_authenticator.time.time'
            ) as mock_time:
                mock_time.return_value = expire_time
                app.config = {'JWT_SECRET': secret}

                generator = TokenGenerator(user)
                token = generator.generate()

        with patch('tahelka.auth.token_authenticator.current_app') as app:
            app.config = {'JWT_SECRET': secret}
            with patch('tahelka.auth.token_authenticator.g') as g:
                auth_header = f'Bearer {token}'
                authenticator = TokenAuthenticator(auth_header, False)
                with self.assertRaises(Unauthorized):
                    authenticator.authenticate()
    def test_wrong_token(self):
        with patch('tahelka.auth.token_authenticator.current_app') as app:
            with patch('tahelka.auth.token_authenticator.g') as g:
                app.config = {'JWT_SECRET': faker.sentence()}

                auth_header = f'Bearer {faker.sentence()}'
                authenticator = TokenAuthenticator(auth_header, True)
                with self.assertRaises(Unauthorized):
                    authenticator.authenticate()
    def post(self):
        '''
        Creates a new property in the dataset.
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, True).authenticate()

        lga = request.json['lga']
        p_type = request.json['property_type']
        r_type = request.json['room_type']
        g_count = request.json['guest_count']
        b_count = request.json['bed_count']
        price = request.json['price']

        if is_all_none(lga, price, p_type, g_count, b_count, r_type):
            raise BadRequest

        new_property = Property(lga, p_type, r_type, g_count, b_count, None,
                                price)
        session = Session()
        session.add(new_property)
        session.commit()

        # Analytics
        status_code = 201
        record = Recorder('property_create', status_code)
        record.recordUsage()

        response = {'message': 'Property Added.'}
        return response, status_code
    def patch(self, id):
        '''
        Updates a property in the dataset.
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, True).authenticate()

        session = Session()
        prop = session.query(Property).filter(Property.id == id).first()

        # Resource not found
        if prop is None:
            raise NotFound

        lga = request.json.get('lga')
        p_type = request.json.get('property_type')
        r_type = request.json.get('room_type')
        g_count = request.json.get('guest_count')
        b_count = request.json.get('bed_count')
        price = request.json.get('price')

        # Empty request
        if is_all_none(lga, price, p_type, g_count, b_count, r_type):
            raise BadRequest

        if lga is not None:
            prop.lga = lga

        if p_type is not None:
            prop.property_type = p_type

        if r_type is not None:
            prop.room_type = r_type

        if g_count is not None:
            prop.guest_count = g_count

        if b_count is not None:
            prop.bed_count = b_count

        if price is not None:
            prop.price = price

        session.commit()

        # Analytics
        status_code = 200
        record = Recorder('property_patch', status_code)
        record.recordUsage()

        msg = {'message': 'Property ' + str(id) + ' updated successfully.'}
        return msg, status_code
    def test_happy_non_admin(self):
        user = Mock()
        id = randrange(1, 100)
        user.id = id
        user.is_admin = False

        secret = faker.sentence()

        with patch('tahelka.auth.token_generator.current_app') as app:
            app.config = {'JWT_SECRET': secret}

            generator = TokenGenerator(user)
            token = generator.generate()

        with patch('tahelka.auth.token_authenticator.current_app') as app:
            with patch('tahelka.auth.token_authenticator.g') as g:
                app.config = {'JWT_SECRET': secret}

                auth_header = f'Bearer {token}'
                authenticator = TokenAuthenticator(auth_header, False)
                authenticator.authenticate()
                self.assertEqual(g.user_id, id)
Exemple #6
0
    def put(self):
        '''
        Replaces the current machine learning model by retraining a new model.
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, True).authenticate()

        Trainer().train()

        msg = {
            'message' : 'The ML Model has been retrained successfully.'
        }

        status_code = 200
        record = Recorder('train_model', status_code)
        record.recordUsage()

        return msg, status_code
Exemple #7
0
    def get(self):
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, False).authenticate()

        lga = request.args['lga']
        p_type = request.args['property_type']
        r_type = request.args['room_type']
        g_count = request.args['guest_count']
        b_count = request.args['bed_count']

        p = Predictor(lga, p_type, r_type, g_count, b_count)
        msg = p.predict()

        status_code = 200
        record = Recorder('predictions', status_code)
        record.recordUsage()

        return msg, status_code
Exemple #8
0
    def get(self):
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, False).authenticate()

        limit = request.args.get('limit', 5)
        order = str(request.args.get('order', 'ascending'))

        order = order == "ascending"  #order is true for ascending, false otherwise

        limit = limitCheck(limit)

        data = UnemploymentRanker(limit, order).rank()

        status_code = 200
        record = Recorder('unemployment_rankings', status_code)
        record.recordUsage()

        resp = {'data': data}
        return resp, status_code
Exemple #9
0
    def get(self):
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, True).authenticate()

        start_date_string = request.args.get('start_date')
        end_date_string = request.args.get('end_date')
        user_id = request.args.get('user_id')

        start_date = DateConverter(start_date_string).convert()
        end_date = DateConverter(end_date_string).convert()

        summarizer = Summarizer(user_id=user_id,
                                start_date=start_date,
                                end_date=end_date)
        summary = summarizer.summarize()

        status_code = 200
        record = Recorder('analytics', status_code)
        record.recordUsage()

        return summary, status_code
    def get(self, id):
        '''
        Shows detail of a property in the dataset.
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, True).authenticate()

        session = Session()
        prop = session.query(Property).filter(Property.id == id).first()

        if prop is None:
            raise NotFound

        prop = prop.__dict__
        prop.pop('_sa_instance_state', None)

        # Analytics
        status_code = 200
        record = Recorder('property_show', status_code)
        record.recordUsage()

        return prop, status_code
Exemple #11
0
    def get(self):
        '''
        Shows ranking of local government areas around Sydney by average ratings given by Airbnb tenants
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, False).authenticate()

        limit = request.args.get('limit', 5)
        order = str(request.args.get('order', 'descending'))

        order = order == "ascending"  #order is true for ascending, false otherwise

        limit = check_limit(limit)

        data = RatingRanker(limit, order).rank()

        status_code = 200
        record = Recorder('rating_ranking', status_code)
        record.recordUsage()

        resp = {'data': data}
        return resp, status_code
Exemple #12
0
    def get(self):
        '''
        Shows ranking of local government areas around Sydney by monthly average number of crime offences
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, False).authenticate()

        limit = request.args.get('limit', 5)
        order = str(request.args.get('order', 'ascending'))

        order = order == "ascending"  #order is true for ascending, false otherwise

        limit = check_limit(limit)

        data = CrimeRanker(limit, order).rank()

        status_code = 200
        record = Recorder('safety_ranking', status_code)
        record.recordUsage()

        resp = {'data': data}
        return resp, status_code
    def put(self, id):
        '''
        Replaces a property in the dataset.
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, True).authenticate()

        session = Session()
        prop = session.query(Property).filter(Property.id == id).first()

        # Resource not found
        if prop is None:
            raise NotFound

        lga = request.json.get('lga')
        p_type = request.json.get('property_type')
        r_type = request.json.get('room_type')
        g_count = request.json.get('guest_count')
        b_count = request.json.get('bed_count')
        price = request.json.get('price')

        prop.lga = lga
        prop.property_type = p_type
        prop.room_type = r_type
        prop.guest_count = g_count
        prop.bed_count = b_count
        prop.price = price

        session.commit()

        # Analytics
        status_code = 200
        record = Recorder('property_put', status_code)
        record.recordUsage()

        msg = {'message': 'Property ' + str(id) + ' updated successfully.'}
        return msg, status_code
    def get(self):
        '''
        Shows per-night rent price prediction of a property with specified attributes by using a trained machine learning model
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, False).authenticate()

        lga = request.args['lga']
        p_type = request.args['property_type']
        r_type = request.args['room_type']
        g_count = request.args['guest_count']
        b_count = request.args['bed_count']

        g_count = validate_integer_param(g_count)
        b_count = validate_integer_param(b_count)

        p = Predictor(lga, p_type, r_type, g_count, b_count)
        msg = p.predict()

        status_code = 200
        record = Recorder('property_price_prediction', status_code)
        record.recordUsage()

        return msg, status_code
    def delete(self, id):
        '''
        Deletes a property in the dataset.
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, True).authenticate()

        session = Session()
        prop = session.query(Property).filter(Property.id == id).first()

        # Resource not found
        if prop is None:
            raise NotFound

        session.delete(prop)
        session.commit()

        # Analytics
        status_code = 200
        record = Recorder('property_delete', status_code)
        record.recordUsage()

        msg = {'message': 'Property ' + str(id) + ' deleted successfully.'}
        return msg, status_code
    def get(self):
        '''
        Shows list of properties in the dataset.
        '''
        auth_header = request.headers.get('Authorization')
        TokenAuthenticator(auth_header, True).authenticate()

        start = request.args.get('start', 0)
        limit = request.args.get('limit', 100)
        sort = str(request.args.get('sort', ''))
        order = str(request.args.get('order', 'asc'))

        lga = str(request.args.get('lga', ''))
        p_type = str(request.args.get('property_type', ''))
        r_type = str(request.args.get('room_type', ''))
        g_count = request.args.get('guest_count')
        b_count = request.args.get('bed_count')

        property_attributes = [
            'lga',
            'property_type',
            'room_type',
            'bed_count',
            'guest_count',
        ]

        session = Session()
        query = session.query(Property)

        sortText = str()
        if not sort:
            sortText = 'properties.id' + " " + order
        else:
            if sort not in property_attributes:
                raise BadRequest
            if order not in ['asc', 'desc', '']:
                raise BadRequest
            sortText = "properties." + sort + " " + order

        if lga:
            query = query.filter(text("properties.lga = '" + lga + "'"))
        if p_type:
            query = query.filter(
                text("properties.property_type = '" + p_type + "'"))
        if r_type:
            query = query.filter(
                text("properties.room_type = '" + r_type + "'"))
        if b_count is not None:
            b_count = validate_integer_param(b_count)
            query = query.filter(text("properties.bed_count = " +
                                      str(b_count)))
        if g_count is not None:
            g_count = validate_integer_param(g_count)
            query = query.filter(
                text("properties.guest_count = " + str(g_count)))

        start = validate_integer_param(start)
        limit = validate_integer_param(limit)
        end = start + limit
        records = query.order_by(text(sortText))[start:end]

        respJson = list()
        for record in records:
            record = record.__dict__
            record.pop('_sa_instance_state', None)
            respJson.append(record)

        # Analytics
        status_code = 200
        record = Recorder('property_index', status_code)
        record.recordUsage()

        msg = {'data': respJson}

        return msg, status_code