Example #1
0
def initialize_redis():

    global redis
    redis = None
    # Get the credentials from the Bluemix environment
    if 'VCAP_SERVICES' in os.environ:
        app.logger.info("Using VCAP_SERVICES...")
        VCAP_SERVICES = os.environ['VCAP_SERVICES']
        services = json.loads(VCAP_SERVICES)
        creds = services['rediscloud'][0]['credentials']
        app.logger.info("Conecting to Redis on host %s port %s" %
                        (creds['hostname'], creds['port']))
        redis = connect_to_redis(creds['hostname'], creds['port'],
                                 creds['password'])
    else:
        app.logger.info(
            "VCAP_SERVICES not found, checking localhost for Redis")
        redis = connect_to_redis('127.0.0.1', 6379, None)
        if not redis:
            app.logger.info("No Redis on localhost, using: redis")
            redis = connect_to_redis('redis', 6379, None)
    if not redis:
        # if you end up here, redis instance is down.
        app.logger.error(
            '*** FATAL ERROR: Could not connect to the Redis Service')
    # Have the Wishlist model use Redis
    Wishlist.use_db(redis)
Example #2
0
    def _createWishlistObject(self, request):
        """Create Wishlist object,
         returning WishlistForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.websafeSessionKey:
            raise endpoints.BadRequestException(
                "Session 'websafeSessionKey' field required")

        # copy WishlistForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }

        data['user'] = user_id

        p_key = ndb.Key(Profile, user_id)
        w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
        w_key = ndb.Key(Wishlist, w_id, parent=p_key)
        data['key'] = w_key
        Wishlist(**data).put()

        return request
    def addSessionToWishlist(self, request):
        """ Add a session to the current user's Wishlist """
        # get current user
        user = endpoints.get_current_user()
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)

        try:
            # get the session to be wishlisted
            session = ndb.Key(urlsafe=request.websafeSessionKey).get()
        except ProtocolBufferDecodeError:
            raise endpoints.NotFoundException(
                'No session found with key: %s' % request.websafeSessionKey)
        # first try to find wishlist of the current user
        wishlist = Wishlist.query(ancestor=p_key).get()
        if not wishlist:
            # create a wishlist if nothing was found
            wishlist = Wishlist(userId = user_id)
            w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
            w_key = ndb.Key(Wishlist, w_id, parent=p_key)

        # Add session key to wishlist
        wishlist.sessionKey.append(session.key)
        wishlist.put()

        # Update the session wishlist counter
        session.wishlistCount += 1
        session.put()

        return self._copyWishlistToForm(wishlist)
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # get Profile from datastore
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()
        # create new Profile if not there
        if not profile:
            profile = Profile(
                key = p_key,
                displayName = user.nickname(),
                mainEmail= user.email(),
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
            )

            w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
            w_key = ndb.Key(Wishlist, w_id, parent=p_key)

            wishlist = Wishlist(
                key = w_key,
                sessionKeys = []
            )

            profile.put()
            wishlist.put()

        return profile      # return Profile
    def _createWishlistObject(self, request):
        """Create or update Wishlist object, returning WishlistForm/request."""
        user_id = self._getUser()
        p_key = self._getUserProfileKey(user_id)

        wssk = request.websafeSessionKey
        sess = ndb.Key(urlsafe=wssk).get()
        if not sess:
            raise endpoints.NotFoundException("No session found with key: %s" % wssk)

        w = {}

        # Create a unique key
        w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
        w_key = ndb.Key(Wishlist, w_id, parent=p_key)
        w["key"] = w_key

        # Check for an existing wishlist
        wish = Wishlist.query(ancestor=p_key).get()

        # If there is already a wishlist record, append this session to it,
        # otherwise create a new wishlist (unless its already in the wishlist)
        if not wish:
            w["sessions"] = [wssk]
            Wishlist(**w).put()
        elif wssk in wish.sessions:
            raise ConflictException("You have already placed this session in your wishlist")
        else:
            wish.sessions.append(wssk)
            wish.put()
            w["sessions"] = [self._retrieveSession(cs_id) for cs_id in wish.sessions]

        return self.toWishlistForm(w)
Example #6
0
    def _createWishlistObject(self, request):
        """Create Wishlist object, returning WishlistForm/request."""
        
        # as usual make sure user is logged in
        user = self._getAuthUser()
        user_id = getUserId(user)

        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
            
        sess  = ndb.Key(urlsafe=request.websafeSessionKey).get()
        p_key = ndb.Key(Profile, user_id)
            
        q = Wishlist.query(ancestor=p_key). \
                filter(Wishlist.websafeSessionKey==request.websafeSessionKey).get()

        if q:
            raise endpoints.BadRequestException('Session already in Wishlist')

        data['sessionName'] = sess.name
        data['userId'] = user_id
        data['duration'] = sess.duration
            
        # create Wishlist key with logged in user as the parent
        w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]          
        w_key = ndb.Key(Wishlist, w_id, parent=p_key)
            
        data['key'] = w_key
            
        # create Wishlist entry
        wishlist = Wishlist(**data)
        wishlist.put()
        
        return self._copyWishlistToForm(wishlist)
    def _createWishlistObject(self, request):
        """ Create or update Wishlist object, returning WishlistForm
        """
        # Preload and validate necessary data items
        user = self.get_authed_user()
        user_id = getUserId(user)
        prof_key = ndb.Key(Profile, user_id)

        if not request.websafeKey:
            raise endpoints.BadRequestException('Session websafeKey required')

        session = ndb.Key(urlsafe=request.websafeKey)
        if not session:
            raise endpoints.NotFoundException(
                'No session found with key: {}'.format(request.websafeKey))

        # copy WishlistForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeKey']

        sess_key = ndb.Key(urlsafe=request.websafeKey)
        data['session'] = sess_key

        wishlist_id = Wishlist.allocate_ids(size=1, parent=prof_key)[0]
        wishlist_key = ndb.Key(Wishlist, wishlist_id, parent=prof_key)
        data['key'] = wishlist_key

        Wishlist(**data).put()

        return self._copyWishlistToForm(wishlist_key.get())
Example #8
0
    def _getWithlistByUserId(self, user_id):

        wishlist_key = ndb.Key(Wishlist, user_id)
        wishlist = wishlist_key.get()

        if not wishlist:
            wishlist = Wishlist(key=wishlist_key)
            wishlist.put()

        return wishlist
    def _makeWishlist(self):
        user = self._getProfileFromUser()
        parent_key = user.key

        new_wish_list = Wishlist(parent=parent_key)
        # set user_id (mainEmail) for ease of query
        new_wish_list.userId = user.mainEmail

        # set wish list as child of current profile
        new_wish_list.put()
Example #10
0
def get_wishlist_list():

    """ 

    Returns the Wishlists by searching the keywords of wishlist_name or the customer_id.

    This function returns a wishlist based on wishlist_name or customer id. If the customer_id and the wishlist id parameters are empty, returns all the wishlists in the database

    ---
    tags:
      - Wishlist

    produces:
        - application/json

    definitions:
        Wishlist:
            type: object
            properties:
                id:
                    type: integer
                customer_id:
                    type: integer
                wishlist_name:
                    type: string

    parameters:
      - name: keyword
        in: query
        description: the name of the wishlist
        type: string
      - name: query
        in: query
        description: the id of the customer
        type: integer

    responses:
        200:
            description: A Wishlist
            schema:
                $ref: '#/definitions/Wishlist'

    """
    query_lists = []
    customer_id = request.args.get('customer_id')
    keyword = request.args.get('keyword')
    if keyword:
        query_lists = Wishlist.find_by_wishlist_name(keyword)
    elif customer_id:
        query_lists = Wishlist.find_by_customer_id(customer_id)
    else:
        """ Returns all of the Wishlists """
        query_lists = Wishlist.all()
    results = [wishlist.serialize() for wishlist in query_lists]
    return make_response(jsonify(results), status.HTTP_200_OK)
    def _deleteSessionToWishlist(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        user_id = getUserId(user)

        # check and see if user currently has wish list
        wl = Wishlist.query(ancestor=ndb.Key(Profile, user_id)).get()

        sessionKeys = request.sessionKeys
        s_keys = []

        if wl:
            # get the session keys and verify if the exist
            try:
                sessionKeys = request.sessionKeys
                for sess in sessionKeys:
                    s_keys.append(ndb.Key(urlsafe=sess).get().key)
            except:
                raise endpoints.BadRequestException("Invalid 'session' value")
            for key in s_keys:
                if key in wl.sessionKeys:
                    wl.sessionKeys.remove(key)
            wl.put()
            return self._copyWishlistToForm(wl)
        else:
            raise endpoints.BadRequestException("User does not "
                                                "have a Wishlist")
    def deleteConference(self, request):
        """Delete conference."""
        wsck = request.websafeConferenceKey
        conf = self._retrieveConference(wsck)
        if not conf:
            raise endpoints.NotFoundException('No conference found with key: %s' % wsck)

        # Remove the link between the sessions and this conference
        conf_sess = ConferenceSession.query(ancestor=conf.key)
        if conf_sess:
            for sess in conf_sess:
                wssk = sess.key.urlsafe()

                # Get all the wishlists that have this session in them and remove this session from them
                wishes = Wishlist.query(ndb.AND(Wishlist.sessions == wssk))
                for wish in wishes:
                    if wish and wssk in wish.sessions:
                        wish.sessions.remove(wssk)
                        wish.put()

                sess.key.delete()

        # Unregister the users from this conference if they are registered for it
        registered_users = Profile.query(ndb.AND(Profile.conferenceKeysToAttend == wsck))
        if registered_users:
            for reg_user in registered_users:
                if reg_user and wsck in reg_user.conferenceKeysToAttend:
                    reg_user.conferenceKeysToAttend.remove(wsck)
                    reg_user.put()

        conf.key.delete()

        return BooleanMessage(data=True)
Example #13
0
def remove_wishlist_item(wishlist_id, item_id):
    """
	Delete a Wishlist item
    This endpoint will delete an item based on the id specified in the path
    ---
    tags:
      - Wishlist Items
    description: Deletes a Wishlist Item from the database
    parameters:
      - name: wishlist_id
        in: path
        description: ID of the wishlist
        type: string
        required: true
      - name: item_id
      	in: path
      	description: ID of the item to be deleted
      	type: string
      	required: true
    responses:
      204:
        description: Item deleted
	"""
    wl = Wishlist.find(wishlist_id)
    if not wl:
        return make_response(
            jsonify(message='Wishlist with id %d could not be found' %
                    wishlist_id), status.HTTP_204_NO_CONTENT)
    try:
        wl.remove_item(item_id)
        wl.save_wishlist()
        return make_response('', status.HTTP_204_NO_CONTENT)
    except ItemException:
        message = {'error': 'Item %s was not found' % item_id}
        return make_response(jsonify(message), status.HTTP_204_NO_CONTENT)
Example #14
0
def delete_wishlist(wishlist_id):
    """
    Delete a Wishlist

    This endpoint will delete a Wishlist based on the id specified in
    the path
    
    ---
    tags:
      - Wishlist

    parameters:
      - name: wishlist_id
        in: path
        description: the id of the wishlist
        type: integer
        required: true

    responses:
        204:
            description: returns no content

    """
    wishlist = Wishlist.get(wishlist_id)
    if wishlist:
        items = Item.find_by_wishlist_id(wishlist_id)
        for item in items:
            item.delete()
        wishlist.delete()
    return make_response('', status.HTTP_204_NO_CONTENT)
Example #15
0
def add_to_wishlist(client_id, product_id):
    app.logger.info('add product {} to wishlist of client {}'.format(product_id, client_id))
    client = clientDAO.get(client_id)
    if client is None:
        app.logger.warning('client not found')
        return jsonify({'message': 'client not found'}), 404

    if wishlistDAO.exists(client.id, product_id):
        app.logger.warning('product already exists')
        return jsonify({'message': 'product already added on wishlist'}), 409

    product = ProductService.get(product_id)
    if product is None:
        app.logger.warning('product not found')
        return jsonify({'message': 'product not found'}), 404

    favorite_list = favoriteListDAO.get(client.id)
    if favorite_list is None:
        app.logger.warning('creating favorite list')
        favorite_list = FavoriteList(client.id)
        favoriteListDAO.save(client, favorite_list)

    wishlist = Wishlist(favorite_list.id, product_id)
    wishlistDAO.save(wishlist)
    app.logger.info('successfully to add product on wishlist')
    return jsonify(wishlist.__dict__), 201
Example #16
0
def delete_wishlist(wishlist_id):
    """
	Delete a Wishlist
    This endpoint will delete a Wishlist based on the id specified in the path
    ---
    tags:
      - Wishlists
    description: Deletes a Wishlist from the database
    parameters:
      - name: wishlist_id
        in: path
        description: ID of the wishlist to delete
        type: integer
        required: true
    responses:
      204:
        description: Wishlist deleted
	"""

    wl = Wishlist.find(wishlist_id)
    if wl:
        wl.delete()
        return make_response('', status.HTTP_204_NO_CONTENT)
    else:
        return make_response(
            jsonify(message='Wishlist with id %d could not be found' %
                    wishlist_id), status.HTTP_204_NO_CONTENT)
    def _createWishlistObject(self, request):
        """ Create or update Wishlist object, returning WishlistForm
        """
        # Preload and validate necessary data items
        user = self.get_authed_user()
        user_id = getUserId(user)
        prof_key = ndb.Key(Profile, user_id)

        if not request.websafeKey:
            raise endpoints.BadRequestException('Session websafeKey required')

        session = ndb.Key(urlsafe=request.websafeKey)
        if not session:
            raise endpoints.NotFoundException(
                'No session found with key: {}'.format(request.websafeKey)
            )

        # copy WishlistForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['websafeKey']

        sess_key = ndb.Key(urlsafe=request.websafeKey)
        data['session'] = sess_key

        wishlist_id = Wishlist.allocate_ids(size=1, parent=prof_key)[0]
        wishlist_key = ndb.Key(Wishlist, wishlist_id, parent=prof_key)
        data['key'] = wishlist_key

        Wishlist(**data).put()

        return self._copyWishlistToForm(wishlist_key.get())
Example #18
0
def update_wishlist_item(wishlist_id, item_id):
    """
	The route for modifying the description of an item in a specific wishlist.
	Example: curl -i -H 'Content-Type: application/json' -X PUT -d '{"description":"update product!"}' http://127.0.0.1:5000/wishlists/1/items/i123
	H is for headers, X is used to specify HTTP Method, d is used to pass a message.
	"""
    try:
        data = request.get_json()
        data['id'] = item_id
    except TypeError:
        (jsonify("Invalid input data type"), status.HTTP_400_BAD_REQUEST)

    if is_valid(data, 'item'):
        try:
            wl = Wishlist.find_or_404(wishlist_id)
            wl.update_item(data)
            wl.save_wishlist()
            new_wl = wl.find(wishlist_id)
            return make_response(jsonify(new_wl.serialize_wishlist()),
                                 status.HTTP_200_OK)
        except WishlistException:
            message = {'error': 'Wishlist %s was not found' % wishlist_id}
            return make_response(jsonify(message), status.HTTP_404_NOT_FOUND)
        except ItemException:
            message = {'error': 'Item %s was not found' % item_id}
            return make_response(jsonify(message), status.HTTP_404_NOT_FOUND)
    else:
        message = {'error': 'Item data was not valid'}
        return make_response(jsonify(message), status.HTTP_400_BAD_REQUEST)
Example #19
0
    def getSessionWishList(self, request):
        """This function gets all wishlists of user."""
        # check for authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # get Profile from datastore
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()
        if not profile:
            raise endpoints.NotFoundException(
                'No profile found')

        # Output all sessions in profile
        query = Wishlist.query(ancestor=p_key)
        query = query.fetch()

        slist = []
        for q in query:
            s_key = ndb.Key(urlsafe=q.sessionKey)
            slist.append(self._copySessionToForm(s_key.get()))

        return SessionForms(
            items=slist)
Example #20
0
    def getSessionsInWishlist(self, request):
        """Get user's wishlist's sessions in the conference. """
        
        # Get conference key for urlsafekey.
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)

        # Get current user key.
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = _getUserId()
        user_key = ndb.Key(Profile, user_id)

        # Get wishlist of the user.
        user_wish = Wishlist.query(Wishlist.userKey==user_key).fetch()

        # Put all wishlist sessionkey into wish_s_list.
        wish_s_keys = [w.sessionKey for w in user_wish]

        # Add the sessionkeys which belong to the conference to s_list. 
        s_list = []
        for s_key in wish_s_keys:
            if s_key.parent() == c_key:
                s_list.append(s_key)

        # Get sesssion entity by session key in s_list, and copy to sessionForm. 
        return SessionForms(
            items=[self._copySessionToForm(s.get()) for s in s_list])
Example #21
0
def get_wishlist(wishlist_id):

    """
    Retrieve a single Wishlist 

    This endpoint will return a Wishlist based on it's ID

    ---
    tags:
      - Wishlist
    produces:
        - application/json
    parameters:
      - name: wishlist_id
        in: path
        type: integer
        required: true

    definitions:
        Wishlist:
            type: object
            properties:
                id:
                    type: integer
                customer_id:
                    type: integer
                wishlist_name:
                    type: string

    definitions:
        Item:
            type: object
            properties:
                id:
                    type: integer
                wishlist_id:
                    type: integer
                product_id:
                    type: integer
                name:
                    type: string
                description:
                    type: string

    responses:
        200:
            description: List of items in the wishlist
            schema:
                $ref: '#/definitions/Wishlist'
        404:
                description: Wishlist with id wishlist_id not found

    """

    wishlist = Wishlist.get(wishlist_id)
    if not wishlist:
        raise NotFound("Wishlist with id '{}' was not found.".format(wishlist_id))
    return make_response(jsonify(wishlist.serialize()), status.HTTP_200_OK)
Example #22
0
 def orderSessionsInWishlist(self, request):
     """Filter Wishlist first by startTime"""
     # get sessions from wishlist
     wish_sessions = Wishlist.query()
     # first order by time by startTime:
     wish_sessions = wish_sessions.order(Wishlist.startTime)
     return SessionForms(
         sessions=[
             self._copySessionToForm(session) for session in wish_sessions])
    def _createWishlistObject(self, request):
        """Create or update Wishlist object, returning WishlistForm/request."""

        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # check sessionName exists
        if not request.sessionName:
            raise endpoints.UnauthorizedException('Name required')
        # get userId
        user_id = getUserId(user)

        # get session key
        this_session = Session.query(Session.name == request.sessionName).get()

        # populate dict
        data = {
            'userId': user_id,
            'sessionName': request.sessionName,
            'sessionKey': this_session.key,
            'typeOfSession': this_session.typeOfSession
        }

        # generate wishlist key from session key
        p_key = this_session.key
        c_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Wishlist, c_id, parent=p_key)
        data['key'] = c_key

        # query wishlist, filter by userId and sessionName, then count
        q = Wishlist.query()
        q = q.filter(Wishlist.userId == user_id)

        # if this session already in user's wishlist, bounce
        for i in q:
            if i.sessionKey == this_session.key:
                raise endpoints.UnauthorizedException(
                    'Session already added to wishlist')

        # save to wishlist
        Wishlist(**data).put()
        return request
Example #24
0
 def test_get_wishlist_item_list(self):
     """ Test getting a list of Items from one specific Wishlist """
     wishlist = Wishlist.find_by_customer_id(1)[0]
     print wishlist.id
     resp = self.app.get('/wishlists/{}/items'.format(wishlist.id),
                         content_type='application/json')
     print json.loads(resp.data)
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     data = json.loads(resp.data)
     self.assertEqual(len(data), 2)
Example #25
0
 def test_update_wishlist_no_name(self):
     """Test updating a existing Wishlist with no name"""
     wishlist = Wishlist.find_by_customer_id(1)[0]
     new_wishlist = {'customer_id': 1}
     '''new_wishlist['items'] = [{"wishlist_id": 3, "product_id": 3, "name": "soda", "description": "I need some soft drinks"}]'''
     data = json.dumps(new_wishlist)
     resp = self.app.put('/wishlists/{}'.format(wishlist.id),
                         data=data,
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
    def _addSessionToWishlist(self, session_key):
        user_id = self._getCurrentUserID()

        key = ndb.Key(Profile, user_id).get()
        wish_list = Wishlist.query(ancestor=key.key).get()
        if wish_list and wish_list.sessionKeys:
            wish_list.sessionKeys.append(session_key)
        else:
            wish_list.sessionKeys = [session_key]
        wish_list.put()
    def _getWishlistFromUser(self):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        user_id = getUserId(user)
        w_key = ndb.Key(Wishlist, user_id)
        wishlist = w_key.get()

        if not wishlist:
            wishlist = Wishlist(
                    key=w_key,
                    ownerId=user_id,
                    public=True,
                )
            wishlist.put()
        print wishlist

        return wishlist
    def _getSessionsInWishlist(self):
        user_id = self._getCurrentUserID()
        wishlist = Wishlist.query(ancestor=ndb.Key(Profile, user_id)).get()

        forms = SessionForms()

        for key in wishlist.sessionKeys:
            query = Session.query(Session.key == key).get()
            forms.items += [self._copySessionToForm(session=query)]

        return forms
Example #29
0
 def test_delete_wishlist(self):
     """ Test deleting a Wishlist """
     wishlist = Wishlist.find_by_customer_id(1)[0]
     # Save the current number of wishlists for assertion
     wishlist_count = self.get_wishlist_count()
     resp = self.app.delete('/wishlists/{}'.format(wishlist.id),
                            content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)
     self.assertEqual(len(resp.data), 0)
     new_count = self.get_wishlist_count()
     self.assertEqual(new_count, wishlist_count - 1)
Example #30
0
    def setUp(self):
        """ Runs before each test """
        server.init_db()
        db.create_all()  # create new tables

        item = Item(wishlist_id=1,
                    product_id=1,
                    name='toothpaste',
                    description='I need a toothpaste').save()
        item = Item(wishlist_id=1,
                    product_id=2,
                    name='toilet paper',
                    description='I need a toilet paper').save()
        item = Item(wishlist_id=2,
                    product_id=3,
                    name='beer',
                    description='I need a drink').save()
        wishlist = Wishlist(customer_id=1, wishlist_name='grocery').save()
        wishlist = Wishlist(customer_id=2, wishlist_name='beverage').save()
        self.app = server.app.test_client()
Example #31
0
def wishlists():
    """
	The route for accessing all wishlist resources or
	creating a new wishlist resource via a POST.
	"""
    wishlistsList = []
    wishlistsList = Wishlist.all()
    wishlistsList = [
        wishlist.serialize_wishlist() for wishlist in wishlistsList
    ]
    return make_response(json.dumps(wishlistsList, indent=4),
                         status.HTTP_200_OK)
Example #32
0
 def addSessionToWishlist(self, request):
     """Copy Session to Wishlist"""
     # first of all there is a need to check if this session is
     # already in wishlist:
     sessInWishlist = Wishlist.query(
         Wishlist.sessionKey == request.SessionKey).count()
     if sessInWishlist != 0:
         raise endpoints.ForbiddenException(
             "Denied, you can't create one session in wishlist twice")
     else:
         # get session and key:
         session_key = ndb.Key(urlsafe=request.SessionKey)
         session = session_key.get()
         # allocating id for session in wishlist:
         sess_wish_id = Wishlist.allocate_ids(size=1, parent=session.key)[0]
         # making key for session in wish, parent is just session:
         sess_wish_key = ndb.Key(Wishlist, sess_wish_id, parent=session.key)
         # in order not to deal with converting
         # dateandtime objects to string setting new
         # variables:
         date, startTime = None, None
         if session.date is not None:
             date = session.date
             del session.date
         if session.startTime is not None:
             startTime = session.startTime
             del session.startTime
         # making form from session to make dict and then give
         # that dict into Wishlist:
         session_form = self._copySessionToForm(session)
         # making dict with all data:
         data = {field.name: getattr(session_form, field.name)
                 for field in session_form.all_fields()}
         data['date'] = date
         data['startTime'] = startTime
         data['sessionKey'] = session_key.urlsafe()
         # adding session_wish key to dict:
         data['key'] = sess_wish_key
         Wishlist(**data).put()
     return session_form
Example #33
0
 def getSessionsInWishlist(self, request):
     """Get all Wishlist entries for the user."""
     
     user = self._getAuthUser()
     user_id = getUserId(user)
     
     # create ancestor query for all key matches for this user
     wishlist = Wishlist.query(ancestor=ndb.Key(Profile, user_id))
     
     # return set of WishlistForm objects per Wishlist Entry
     return WishlistForms(
         items=[self._copyWishlistToForm(wish) for wish in wishlist]
     )
    def _addSessionToWishlist(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        s_keys = []
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)

        # Get the session keys and verify if the exist
        try:
            sessionKeys = request.sessionKeys
            for sess in sessionKeys:
                s_keys.append(ndb.Key(urlsafe=sess).get().key)
        except:
            raise endpoints.BadRequestException("Invalid 'session' value")

        # check and see if user currently has wish list
        wl = Wishlist.query(ancestor=ndb.Key(Profile, user_id)).get()

        # if wishlist exists, check to see if session keys exists in wishlist
        # if not, add
        if wl:
            for key in s_keys:
                if key not in wl.sessionKeys:
                    wl.sessionKeys.append(key)
            wl.put()
            return self._copyWishlistToForm(wl)
        # else create Wishlist object
        else:
            # copy WishlistForm/ProtoRPC Message into dict
            data = {'sessionKeys': s_keys}

            w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
            w_key = ndb.Key(Wishlist, w_id, parent=p_key)
            data['key'] = w_key

            Wishlist(**data).put()
            return request
    def getWishlistBySession(self, request):
        """ given a specific session, return all users that have this session on their wishlist """
        # get wishlists that contain the sessionKey
        wishlists = Wishlist.query(Wishlist.sessionKey == request.websafeSessionKey)

        # get the user keys from the wishlists
        users = [(ndb.Key(Profile, wishlist.userId)) for wishlist in wishlists]

        # lookup the profiles
        profiles = ndb.get_multi(users)

        return ProfileForms(
            items=[self._copyProfileToForm(profile) for profile in profiles])
    def getSessionsInWishlist(self, request):
        """Get sessions in wishlist."""

        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # get userId
        user_id = getUserId(user)
        # query wishlist, filter by userId
        q = Wishlist.query().filter(Wishlist.userId == user_id)

        return WishlistForms(items=[self._copyWishlistToForm(wish) for wish in q])
Example #37
0
def add_item_to_wishlist(wishlist_id):
    """
    Add an Item to an existing wishlist
    This endpoint will add a wishlist item based on the data in the body that is posted

    ---
    tags:
        - Wishlist

    consumes:
        application/json

    parameters:
        - name: wishlist_id
          in: path
          type: integer
          description: the id of the Wishlist to add an item
          required: true
        - name: body
          in: body
          required: true
          schema:
            $ref: '#/definitions/Item'

    responses:
      201:
        description: Successfully added Item to wishlist
      404:
        description: Wishlist with id not found

    """
    check_content_type('application/json')
    wishlist = Wishlist.get(wishlist_id)
    if not wishlist:
        raise NotFound("Wishlist with id '{}' was not found.".format(wishlist_id))
    
    item = Item()
    json_post = request.get_json()
    item.deserialize(json_post,wishlist_id)
    item.save()
    message = item.serialize()
    """
    check if the item.wishlist_id equals to the wishlist.id
    """
    check_wishlist_id = item.wishlist_id

    location_url = url_for('get_wishlist', wishlist_id=wishlist.id, _external=True)
    return make_response(jsonify(message), status.HTTP_201_CREATED,
                         {
                            'Location': location_url
                         })
Example #38
0
def wishlists():
    """
    Retrieve a list of Wishlists
    This endpoint will return all wishlists
    ---
    tags:
      - Wishlists
    responses:
      200:
        description: An array of Wishlists
        schema:
          type: array
          items:
            schema:
              id: Wishlist
              properties:
                user_id:
                  type: string
                  description: Unique ID of the user(created by the user)
                name:
                  type: string
                  description: Wishlist Name(created by the user)
                created:
                  type: string
              	  format: date-time
                  description: The time at which the wishlist was created
                deleted:
                  type: boolean
                  description: Flag to be set when a wishlist is deleted
                items:
              	  type: object
              	  properties:
              	  	wishlist_item_id:
              	  	  type: object
              	  	  properties:
              	  	  	item_id:
              	  	  	  type: string
              	  	  	item_description:
              	  	  	  type: string
                  description: Dictionary to store objects in a wishlist
                id:
                  type: integer
                  description: Unique ID of the wishlist assigned internally by the server
    """
    wishlistsList = []
    wishlistsList = Wishlist.all()
    wishlistsList = [
        wishlist.serialize_wishlist() for wishlist in wishlistsList
    ]
    return make_response(json.dumps(wishlistsList, indent=4),
                         status.HTTP_200_OK)
    def _createWishlistObject(self, request):
        """Create or update Wishlist object, returning WishlistForm/request."""

        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # check sessionName exists
        if not request.sessionName:
            raise endpoints.UnauthorizedException('Name required')
        # get userId
        user_id = getUserId(user)

        # get session key
        this_session = Session.query(Session.name == request.sessionName).get()

        # populate dict
        data = {'userId': user_id, 'sessionName': request.sessionName, 'sessionKey': this_session.key,
                'typeOfSession': this_session.typeOfSession}

        # generate wishlist key from session key
        p_key = this_session.key
        c_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Wishlist, c_id, parent=p_key)
        data['key'] = c_key

        # query wishlist, filter by userId and sessionName, then count
        q = Wishlist.query()
        q = q.filter(Wishlist.userId == user_id)

        # if this session already in user's wishlist, bounce
        for i in q:
            if i.sessionKey == this_session.key:
                raise endpoints.UnauthorizedException('Session already added to wishlist')

        # save to wishlist
        Wishlist(**data).put()
        return request
Example #40
0
def read_wishlist(wishlist_id):
    """
	The route for reading wishlists, whether one specifically by id
	or all wishlists when no id is specified.
	Example: curl http://127.0.0.1:5000/wishlists/1
	"""
    try:
        wl = Wishlist.find_or_404(wishlist_id)
        return make_response(jsonify(wl.serialize_wishlist()),
                             status.HTTP_200_OK)
    except WishlistException:
        return make_response(
            jsonify(message='Cannot retrieve wishlist with id %s' %
                    wishlist_id), status.HTTP_404_NOT_FOUND)
    def getSessionsInWishlist(self, request):
        """Query for all the sessions in a conference that the user is interested in attending"""
        p_key = self._getUserProfileKey()
        wish = Wishlist.query(ancestor=p_key).get()

        if not wish:
            raise endpoints.NotFoundException('Your wishlist could not be found')

        wf = {'key': p_key, 'sessions': []}

        if len(wish.sessions) and any(s for s in wish.sessions):
            wf['sessions'] = [self._retrieveSession(cs_id) for cs_id in wish.sessions if cs_id is not None]

        return self.toWishlistForm(wf)
    def _addToWishlistObject(self, request):
        """Add a session to a wishlist, return a wishlist form"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Camacho - get the user's wishlist
        wl = Wishlist.query(ancestor=ndb.Key(Profile,user_id))
        wl = wl.get()

        # Camacho - make sure the wishlist exists
        if not wl:
            raise endpoints.NotFoundException(
                'Your user does not have a wishlist!')

        # Camacho - save the current keys
        try:
            currKeys = wl.sessionKeys
        except:
            currKeys = []

        # Camacho - get the key specified to add
        newKey = getattr(request,'sessionKeys')

        # Camacho - make sure the key specified corresponds
        # to an existing session
        try:
            session = ndb.Key(urlsafe=newKey).get()
        except:
            raise endpoints.NotFoundException(
                'Session with this key not found %s' % (newKey))

        currKeys.append(newKey)
        setattr(wl, 'sessionKeys', currKeys)

        wl.put()

        sessions = []

        # Pass a list of the sessions in the wishlist to the
        # _copySessionToForm function to return SessionForm
        # object
        for k in currKeys:
            sessions.append(ndb.Key(urlsafe=k).get())

        return SessionForms(
                items=[self._copySessionToForm(sess) for sess in \
                sessions]
        )
Example #43
0
def update_wishlists(wishlist_id):
    """
    Update a Wishlist

    This endpoint will update a Wishlist based the body that is posted
    """
    check_content_type('application/json')
    wishlist = Wishlist.get(wishlist_id)
    if not wishlist:
        raise NotFound("Wishlist with id '{}' was not found.".format(wishlist_id))
    wishlist.deserialize(request.get_json())
    wishlist.id = wishlist_id
    wishlist.save()
    return make_response(jsonify(wishlist.serialize()), status.HTTP_200_OK)
Example #44
0
def item(wishlist_id):
    """
	The route for getting all items associated with a wishlist
	or making a new item for a wishlist via a POST.
	Example: curl http://127.0.0.1:5000/wishlists/1/items
	"""
    try:
        wl = Wishlist.find_or_404(wishlist_id)
        items = wl.all_items()
        return make_response(jsonify(items), status.HTTP_200_OK)
    except WishlistException:
        return make_response(
            jsonify(message='Cannot retrieve wishlist with id %s' %
                    wishlist_id), status.HTTP_404_NOT_FOUND)
    def getSessionsInWishlist(self, request):
        """Get sessions in wishlist."""

        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # get userId
        user_id = getUserId(user)
        # query wishlist, filter by userId
        q = Wishlist.query().filter(Wishlist.userId == user_id)

        return WishlistForms(
            items=[self._copyWishlistToForm(wish) for wish in q])
    def _getSessionsInWishlist(self):
        """ Helper method to get Sessions from the wishlist
        """
        user = self.get_authed_user()
        user_id = getUserId(user)
        prof_key = ndb.Key(Profile, user_id)

        wish_keys = Wishlist.query(ancestor=prof_key)
        sess_keys = [wish_key.session for wish_key in wish_keys]

        if sess_keys in (None, []):
            raise endpoints.BadRequestException(
                'No wishlist found: {}'.format(sess_keys))
        return ndb.get_multi(sess_keys)
    def _getSessionsInWishlist(self):
        """ Helper method to get Sessions from the wishlist
        """
        user = self.get_authed_user()
        user_id = getUserId(user)
        prof_key = ndb.Key(Profile, user_id)

        wish_keys = Wishlist.query(ancestor=prof_key)
        sess_keys = [wish_key.session for wish_key in wish_keys]

        if sess_keys in (None, []):
            raise endpoints.BadRequestException(
                'No wishlist found: {}'.format(sess_keys))
        return ndb.get_multi(sess_keys)
Example #48
0
    def getSessionsInMostWishlists(self, request):
        """Query top five sessions that are in most wishlists"""

        sessions = Wishlist.query().group_by([Wishlist.sessionKeysToAttend]) Session.query()..filter(Session.typeOfSession == request.typeOfSession)

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        wishlist = self._getWithlistByUserId(getUserId(user))
        keys = [ndb.Key(urlsafe=wkey) for wkey in wishlist.sessionKeysToAttend]
        sessions = ndb.get_multi(keys)

        return SessionForms(items=[self._copySessionToForm(session) for session in sessions])
    def getSessionsInWishlist(self, request):
        """Return all sessions in user Wishlist across all conferences."""

        user = endpoints.get_current_user()

        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        wl = Wishlist.query(ancestor=ndb.Key(Profile, user_id)).get()

        if not wl:
            raise endpoints.NotFoundException(
                'User does not have a Wishlist!')
        return self._copyWishlistToForm(wl)
    def getSessionsInWishlist(self, request):
        """Return sessions for a particular speaker across all conferences."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Camacho - get the user's wishlist
        wl = Wishlist.query(ancestor=ndb.Key(Profile,user_id)).get()

        # Camacho - make sure the wishlist exists
        if not wl:
            raise endpoints.NotFoundException(
                'Your user does not have a wishlist!')
        return self._copyWishlistToForm(wl)
Example #51
0
    def addSessionToWishlist(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)

        # see if there is a wishlist already
        query = Wishlist.query(ancestor=p_key)
        session_key = ndb.Key(urlsafe=request.websafeSessionKey)
        if query.count():
            wishlist = query.get()
            wishlist.sessions.append(session_key)
            wishlist.put()
        else:
            w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
            w_key = ndb.Key(Wishlist, w_id, parent=p_key)
            data = {}
            data['key'] = w_key
            data['sessions'] = []
            data['sessions'].append(session_key)
            w_key = Wishlist(**data).put()
            print(w_key)
        return BooleanMessage(data=True)
Example #52
0
def get_wishlist_list():

    """ 

    Returns the Wishlists by searching the keywords of wishlist_name 

    ---
    tags:
      - Wishlist

    produces:
        - application/json

    parameters:
      - name: keyword
        in: query
        description: the name of the wishlist
        type: string
        required: true

    responses:
        200:
            description: An Item
            schema:
                $ref: '#/definitions/Wishlist'

    """
    query_lists = []
    keyword = request.args.get('keyword')
    if keyword:
        query_lists = Wishlist.find_by_wishlist_name(keyword)
    else:
        """ Returns all of the Wishlists """
        query_lists = Wishlist.all()
    results = [wishlist.serialize() for wishlist in query_lists]
    return make_response(jsonify(results), status.HTTP_200_OK)
    def getWishlistByType(self, request):
        """Get wishlist by type."""

        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # get userId
        user_id = getUserId(user)
        # query wishlist, filter by userId and typeOfSession
        q = Wishlist.query()
        q = q.filter(Wishlist.userId == user_id)
        q = q.filter(Wishlist.typeOfSession == request.typeOfSession)

        return WishlistForms(items=[self._copyWishlistToForm(wish) for wish in q])
Example #54
0
def delete_wishlist(wishlist_id):
    """
	The route for deleting a specific wishlist when the wishlist_id is specified.
	This only does a soft delete, i.e. update the deleted flag with "true"
	Example: curl -X DELETE http://127.0.0.1:5000/wishlists/1
	"""

    wl = Wishlist.find(wishlist_id)
    if wl:
        wl.delete()
        return make_response('', status.HTTP_204_NO_CONTENT)
    else:
        return make_response(
            jsonify(message='Wishlist with id %d could not be found' %
                    wishlist_id), status.HTTP_204_NO_CONTENT)
Example #55
0
    def _creatWishlist(self, request):
        "Create a Wishlist, add the session to it."
        # Get the current user, and the its name and key.
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = _getUserId()
        user_key = ndb.Key(Profile, user_id)
        user_name = user_key.get().displayName

        # Get the session key and session name.
        session_key =ndb.Key(urlsafe=request.websafeSessionKey)
        session_name = session_key.get().sessionName

        # Store the user and session data in a wishlist entity.
        wishlist = Wishlist(
            userName=user_name,
            userKey=user_key,
            sessionKey=session_key,
            sessionName=session_name)
        wishlist.put()
        
        # Return user and session name as a tuple.
        return user_name, session_name
    def getWishlistByType(self, request):
        """Get wishlist by type."""

        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # get userId
        user_id = getUserId(user)
        # query wishlist, filter by userId and typeOfSession
        q = Wishlist.query()
        q = q.filter(Wishlist.userId == user_id)
        q = q.filter(Wishlist.typeOfSession == request.typeOfSession)

        return WishlistForms(
            items=[self._copyWishlistToForm(wish) for wish in q])
Example #57
0
def update_wishlists(wishlist_id):
    """
    Update a Wishlist

    This endpoint will update a Wishlist based the body that is posted

    ---
    tags:
        - Wishlist

    parameters:
        - name: wishlist_id
          in: path
          type: integer
          required: true
        - name: body
          in: body
          schema:
            id: wishlist_entries
            required: true
                - customer_id
                - wishlist_name
            properties:
                customer_id:
                    type: integer
                    description: customer_id
                    default: "345"
                wishlist_name:
                    type: string
                    description: name of the wishlist 
                    default: "new name of the wishlist"

    responses:
      200:
        description: Update was successful
      404:
        description: Did not find item with the given id in the wishlist
    """

    check_content_type('application/json')
    wishlist = Wishlist.get(wishlist_id)
    if not wishlist:
        raise NotFound("Wishlist with id '{}' was not found.".format(wishlist_id))
    wishlist.deserialize(request.get_json())
    wishlist.id = wishlist_id
    wishlist.save()
    return make_response(jsonify(wishlist.serialize()), status.HTTP_200_OK)
Example #58
0
def read_wishlist_item(wishlist_id, item_id):
    """
    Retrieve a single Wishlist item
    This endpoint will return a Wishlist item based on it's ID
    ---
    tags:
      - Wishlist Items
    produces:
      - application/json
    parameters:
      - name: wishlist_id
        in: path
        description: ID of wishlist to retrieve from
        type: integer
        required: true
      - name: item_id
      	in: path
      	description: ID of item to be retrieved
      	type: string
      	required: true
    responses:
      200:
        description: Wishlist items matching with the query
        schema:
          id: Wishlist
          properties:
            id:
              type: string
              description: ID of the item matching
            description:
              type: string
              description: Description of the item
      404:
        description: Wishlist not found
    """
    try:
        wl = Wishlist.find_or_404(wishlist_id)
        item = wl.find_item(item_id)
        return make_response(jsonify(item), status.HTTP_200_OK)
    except ItemException:
        return make_response(
            jsonify(message='Item with id %s could not be found' % item_id),
            status.HTTP_404_NOT_FOUND)
    except WishlistException:
        return make_response(
            jsonify(message='Wishlist with id %d could not be found' %
                    wishlist_id), status.HTTP_404_NOT_FOUND)