def addSessionToWishlist(self, request): """Adds a session to the users wishlist""" # Check that user has authorization user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) session = ndb.Key(urlsafe=request.sessionKey).get() if not session: raise endpoints.UnauthorizedException('No session exists with the ' 'specified sessionKey') # Filter by property value so that only the WishList entity # belonging to the authorized user is returned. # Check to see if a wishList entity already exists in the # datastore. Create one if needed. # Only one WishList entity is to be created per user. wishList = WishList.query(WishList.userID == user_id).get() if not wishList: wishList = WishList( sessionName = [session.name], userID = user_id ) elif wishList.userID == user_id: wishList.sessionName.append(session.name) # Put the wishlist entity into the datastore # Create and return an empty WishListForm entity. wishList.put() wishListForm = WishListForm() #return self._copyWishListToForm(wishList, wishListForm) return StringMessage(data="Successfully added session to WishList.")
def _handleWishList(self, request, rem=False): """ add and delete sessions from wish list in datastore""" prof = self._getProfileFromUser() mainEmail = prof.mainEmail wishes = WishList.query() wishes = wishes.filter(WishList.mainEmail == mainEmail) wish = wishes.get() # check if its a request for removing the session from wishlist if rem: for s_key in request.sessionKeys: if ndb.Key(urlsafe=s_key) not in wish.sessionKeys: # request to remove sessions that does not exist raise ConflictException("session %s not present in your wish list"% s_key) else : wish.sessionKeys.remove(ndb.Key(urlsafe=s_key)) else : if not wish: # request to add a new seesion for user adding firsttime in wishlist wish = WishList( mainEmail= mainEmail, sessionKeys= [ndb.Key(urlsafe=s_key) for s_key in request.sessionKeys],) else : # reqeust to add a new session for user already have a wishlist for s_key in request.sessionKeys: if ndb.Key(urlsafe=s_key) in wish.sessionKeys : raise ConflictException("%s Session is already added in your WishList."% s_key) else: wish.sessionKeys.append(ndb.Key(urlsafe=s_key)) wish.put() sessions = [s_key.get() for s_key in wish.sessionKeys] return SessionForms( sessions = [self._copySessionToForm(session) for session in sessions])
def addSessionToWishlist(self, request): """Add session to the logged in user's wish list""" # Check that session exists session = ndb.Key(urlsafe=request.sessionKey).get() if not session: raise endpoints.NotFoundException( 'No session found with key: %s' % request.sessionKey) # Check that user is logged in user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) # Use the user_id as ancestor key, if the session is already # in the wich list, return False if WishList.query(ancestor=p_key).filter(WishList.sessionKey == request.sessionKey).get(): return BooleanMessage(data=False) # Create new key and insert the session in wich list w_id = WishList.allocate_ids(size=1, parent=p_key)[0] w_key = ndb.Key(WishList, w_id, parent=p_key) WishList(key=w_key, sessionKey=request.sessionKey).put() return BooleanMessage(data=True)
def _createWishlist(self, user_key): ''' Creates a wishlist for a user ''' wishlist_id = WishList.allocate_ids(size=1, parent=user_key)[0] wishlist_key = ndb.Key(WishList, wishlist_id, parent=user_key) wishlist = WishList() wishlist.key = wishlist_key return wishlist
def addSessionToWishlist(self, request): """Add a Session to a wish list. the session is taken by its websafeKey and inserted in the WishList entity""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) safe_key = request.websafeSessionKey # Get the session entity session = ndb.Key(urlsafe=safe_key).get() # define the required fields from the session in the wishlist. data = {'name': '', 'speaker': ''} data['name'] = session.name data['speaker'] = session.speaker p_key = ndb.Key(Profile, user_id) # Create the WishList entity wish = WishList( sessionName=data['name'], sessionSpeaker=data['speaker'], sessionKey=safe_key, parent=p_key ) wish.put() return WishListForm( sessionName=data['name'], sessionSpeaker=data['speaker'], sessionKey=safe_key )
def _createAddWishListObject(self,request): """Add to or create new WishList""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) wishList=WishList.query(ancestor=p_key) wish=wishList.get() #raise endpoints.NotFoundException(str(wishList)) wishExists=True # check that conference exists if not wish: wishExists=False # if the wish list for the user doesn't exist create and add if not wishExists: data = {field.name: getattr(request, field.name) for field in request.all_fields()} 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() # if the wishlist does exist for the user just add unique session keys else: for session in request.session_websafekey: if session not in wish.session_websafekey: wish.session_websafekey.append(session) wish.put() return request
def addToWishList(self, userID, product, productID): try: user = User.objects.get(pk = userID) p = Product.objects.get(Q(pk = productID), Q(name = product)) if WishList.objects.filter(Q(owner = user), Q(product = p)).count() != 0: #check if item already exist return dataBaseModel.ERR_WISHLIST_ALREADY_EXIST newOne = WishList(owner = user, product = p) # create a new wishlist item newOne.save() return dataBaseModel.SUCCESS except: return dataBaseModel.ERR_BAD_PRODUCT
def addToWishList(self, userID, product, productID): try: user = User.objects.get(pk=userID) p = Product.objects.get(Q(pk=productID), Q(name=product)) if WishList.objects.filter(Q(owner=user), Q( product=p)).count() != 0: #check if item already exist return dataBaseModel.ERR_WISHLIST_ALREADY_EXIST newOne = WishList(owner=user, product=p) # create a new wishlist item newOne.save() return dataBaseModel.SUCCESS except: return dataBaseModel.ERR_BAD_PRODUCT
def add_to_wishlist(book_pk, username): """This function add a book to the wish if not duplicate.""" try: wishlist = WishList.get((WishList.username == username) & (WishList.book == book_pk)) except DoesNotExist: book = BookToRent.get(BookToRent.id == book_pk) if not book.username.username == username: WishList.create( book=book_pk, username=username, ) else: raise SelfBook else: raise DuplicateEntry
def getSessionsInWishlistByConference(self, request): """ List the wishlist items for the specified conference. """ # validate the websafe conference key conference_key = validate_websafe_key(request.websafeConferenceKey, 'Conference') # confirm the user user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required.') user_id = getUserId(user) user_key = ndb.Key(Profile, user_id) # get the user's wishlist sessions as a projection q_wishlist = WishList.query(ancestor=user_key) # wl_sessions = q_wishlist.fetch(1, projection=[WishList.sessions]) wishlist = q_wishlist.fetch(1)[0] wishlist_session_keys = [] # for session in wl_sessions: for session in wishlist.sessions: wishlist_session_keys.append(ndb.Key(urlsafe=session)) # query Sessions where the specified Conference is the ancestor session_q = Session.query(ancestor=conference_key) # filter the Sessions to include only the sessions in the wishlist session_q = session_q.filter(Session.key.IN(wishlist_session_keys)) # get the keys of those sessions, which are the ones we're looking for conf_session_keys = session_q.fetch(keys_only=True) # create a wishlist short_wishlist = WishList() # copy the found Session keys into the wishlist as websafe keys for key in conf_session_keys: short_wishlist.sessions.append(key.urlsafe()) # return the reduced wishlist as a message return self._copyWishListToForm(short_wishlist)
def deleteSessionInWishlist(self, request): """Delete sessions in users wishlist.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # item = WishList.query(ndb.Key(urlsafe=request.sessionKey)) # item.delete() # key = ndb.Key(urlsafe=request.data) # print key # print "I just used the key" testQ = WishList.query() filtered = testQ.filter(WishList.sessionKey == request.data) # print filtered # p = testQ.filter(WishList.sessionKey == request.data and WishList.userID == user_id) for t in filtered: t.key.delete() websafeKey = StringMessage() # Fedback to user, confirming item in wishlist was deleted. websafeKey.data = "wishlist item deleted" return websafeKey
def deleteSessionInWishlist(self, request): """Delete a particular Session from Wishlist.""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # Get the session of this user from wishlist userID = getUserId(user) w = WishList.query(ndb.AND( WishList.userId == userID, WishList.sessionKey == request.sessionKey) ).fetch() retval = True # Check if the session which is asked to delate exists or not if not w: raise ConflictException("You dont have this session in the wishlist") retval=False else: # if session exists then delete from wishlist for tmp in w: tmp.key.delete() retval=True return BooleanMessage(data=retval)
def _createWishListObject(self, request): """Create or update WishList object, returning WishListForm/request. A session can only be created by a user who has created a conference""" # preload necessary data items user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # Get the conference from websafeConferenceKey p_key = ndb.Key(Profile, user_id) session = ndb.Key(urlsafe=request.sessionKey).get() wlquery = WishList.query(ancestor=p_key) wlist = wlquery.filter(WishList.sessionKey == session.key).fetch() is_wishlist_not_exist = True if wlist is not None: for wl in wlist: if wl.sessionKey == session.key: is_wishlist_not_exist = False if is_wishlist_not_exist: # generate Profile Key based on user ID and Conference wishlist_id = WishList.allocate_ids(size=1, parent=p_key)[0] wishlist_key = ndb.Key(WishList, wishlist_id, parent=p_key) # copy WishlistForm/ProtoRPC Message into dict data dict_data = {field.name: getattr(request, field.name) for field in request.all_fields()} # convert session key to key property if dict_data['sessionKey']: dict_data['sessionKey'] = ndb.Key(urlsafe=request.sessionKey) else: print ("Something is wrong with the session key") dict_data['userID'] = user_id # Save session data to datastore WishList(**dict_data).put() return request
def getSessionInWishList(self, request): """Return requested wishlist by user.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) wishlists = WishList.query(ancestor=ndb.Key(Profile, user_id)) return WishListForms(items=[self._copyWishListToForm(w)\ for w in wishlists])
def removeAllSessionsFromWishlist(self, request): """Resets the users wishlist""" # Check that user has authorization user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) wishList = WishList.query(WishList.userID == user_id).get() wishList.key.delete() return StringMessage(data="Your wishlist has been reset.")
def getSessionInWishlist(self, request): """returns all sessions in a users wishlist""" # Check that user has authorization user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) wishList = WishList.query(WishList.userID == user_id).get() wishListForm = WishListForm() return self._copyWishListToForm(wishList, wishListForm)
def addSessionToWishlist(self, request): """Adds conference to users wishlist.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) p_key = ndb.Key(urlsafe=request.sessionKey) print p_key wishItem = WishList(parent=p_key) #Assign the wishlist item to have both a sessionkey to get he session and the user_id to correctly call it #back uniquely to that user. wishItem.sessionKey = request.sessionKey wishItem.userID = user_id wishItem.put() # This is just setting up the message to return to the user websafeKey = StringMessage() websafeKey.data = "Successfully added to wishlist: " + request.sessionKey testQ = WishList.query() #Just return the message confirming that the session was added to the wishlist return websafeKey
def getSessionsInWishlist(self, request): """Return sessions in users wishlist.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) key_array = [] print user_id wlist = WishList.query() filtered = wlist.filter(WishList.userID == user_id) for w in filtered: key_array.append(w.sessionKey) #loop through this as urlsafekey # array to hold all ancestor keys for sessions in the wishlist to call all the relevant sessions items = [] for key in key_array: item = WishList.query(ancestor=ndb.Key(urlsafe=key)) print item.ancestor items.append(item.ancestor) # Calls specific session in query from all the encoded keys in the key_array Forms = [] for key in key_array: item = ndb.Key(urlsafe=key) print item print "another item" session = item.get() if session: Forms.append(self._copySessionToForm(session)) # return all the sessions in the wishlist return SessionForms(items=Forms)
def getSessionsInWishlist(self, request): """ List all of the sessions in the logged in user's wishlist """ user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required.') user_id = getUserId(user) user_key = ndb.Key(Profile, user_id) # Get the user's wishlist wishlist = WishList.query(ancestor=user_key).fetch(1) if wishlist: wishlist = wishlist[0] # Return the wishlist return self._copyWishListToForm(wishlist)
def getSessionsInWishlist(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) wishList=WishList.query(ancestor=p_key) wish=wishList.get() sessions=[] for sessionkey in wish.session_websafekey: sessions.append(ndb.Key(urlsafe=sessionkey).get()) return SessionForms( items=[self._copySessionToForm(session) for session in sessions] )
def _createWishListObject(self, request): """Create or update Session object, returning SessionForm/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.session_key: raise endpoints.BadRequestException("'session_key' field required") data = {} # generate Profile Key based on user ID and Conference # ID based on Profile key get Conference key from ID u_key = ndb.Key(Profile, user_id) w_sid = WishList.allocate_ids(size=1, parent=u_key)[0] w_key = ndb.Key(WishList, w_sid, parent=u_key) data['key'] = w_key data['user_id'] = user_id data['session_key'] = request.session_key WishList(**data).put() return self._copyWishListToForm(w_key.get())
def getSessionsInWishlist(self, request): """Get the list of sessions in a wishlist""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) parent_key = ndb.Key(Profile, user_id) qs = WishList.query(ancestor=parent_key) # Get all the sessions in the user wishlist. qs.fetch() return WishListForms( items=[self._copyWishListToForm(sess) for sess in qs] )
def getSessionsInWishlist(self, request): """ Used to get all sessions in users WishList""" prof = self._getProfileFromUser() mainEmail = prof.mainEmail wishes = WishList.query() wishes = wishes.filter(WishList.mainEmail == mainEmail) wish = wishes.get() if wish: sessions = [s_key.get() for s_key in wish.sessionKeys] else: sessions = [] return SessionForms( sessions = [self._copySessionToForm(session) for session in sessions])
def getSessionsInWishlist(self, request): """Return sessions under this users wishlist.""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get users wishlist userID = getUserId(user) wishLists = WishList.query(WishList.userId == userID).fetch() # Return wishlistforms return WishListForms( items=[self._copyWishListToForm(w) for w in wishLists] )
def removeSessionFromWishList(self, request): """Removes the specific Session from the wishlist""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) parent_key = ndb.Key(Profile, user_id) qw = WishList.query(ancestor=parent_key) # Filter the result finding the session in the wishlist qw = qw.filter(WishList.sessionKey == request.websafeSessionKey) for wl in qw: # Delete the entity from data store. wl_ent = wl.key.delete() return StringMessage(data='Session removed from wishlist')
def save(self): name = self.cleaned_data.get('name') description = self.cleaned_data.get('description', None) instance_id = self.cleaned_data.get('instance_id', None) wishlist = WishList(user=self.request.user, name=name, description=description) wishlist.full_clean() wishlist.save() if instance_id: try: product_instance = ProductInstance.objects.get(id=instance_id) wishlist.add_product(product_instance) except ProductInstance.DoesNotExist: pass return wishlist
def getSessionsInWishlist(self, request): """query for all the sessions in a conference that the user is interested in""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # Get the conference from websafeConferenceKey p_key = ndb.Key(Profile, user_id) wlquery = WishList.query() wishlists = wlquery.filter(WishList.userID == user_id).fetch() sessions =[] for wl in wishlists: sessions.append(wl.sessionKey.get()) return SessionForms( items=[self._copySessionToForm(sess) for sess in sessions] )
def getSessionsInWishlist(self, request): """Get sessions from the logged in user's wish list""" # Check that user is logged in user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) # Query WishList using user_id ancestor key wish_list = WishList.query(ancestor=p_key) return SessionForms( items=[self._copySessionToForm(ndb.Key(urlsafe=w.sessionKey).get()) for w in wish_list] )
def addSessionToWishlist(self, request): """Add particular Session to users wishlist""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # make sure session Key is provided if not request.sessionKey: raise endpoints.BadRequestException("Session 'key' field required") # make sure the session Key provided is already there in datastore skey = request.sessionKey sess = ndb.Key(urlsafe=skey).get() if not sess: raise endpoints.NotFoundException( 'No Session found with key: %s' % sess) # Check if the user has already added this session in wishlist earlier userID = getUserId(user) w = WishList.query(ndb.AND( WishList.userId == userID, WishList.sessionKey == request.sessionKey) ).fetch() if w: raise ConflictException("You have already added this session to wishlist") # copy WishListForm/ProtoRPC Message into dict data= {} data['userId'] = userID data['sessionKey'] = request.sessionKey # Store the data in data store WishList(**data).put() # return WishListForm wlf = WishListForm() wlf.userId = userID wlf.sessionKey = request.sessionKey wlf.check_initialized() return wlf
def removeSessionFromWishlist(self, request): """Removes the selected session from the wishlist""" # Check that user has authorization user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) wishList = WishList.query(WishList.userID == user_id).get() session = ndb.Key(urlsafe=request.sessionKey).get() if not session: raise endpoints.UnauthorizedException('You cannot remove a session from your ' 'wishlist that is not already present.') for name in wishList.sessionName: if name == session.name: wishList.sessionName.remove(name) wishList.put() return StringMessage(data="Session %s has been removed from your wishlist" % \ session.name)
def deleteSessionInWishList(self, request): """Remove requested wishlist by user.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) wishlists = WishList.query(ancestor=ndb.Key(Profile, user_id)) ws = wishlists.filter(WishList.session_key == request.session_key) wrpt = WishListReport() if ws.count(): for w in ws: w.key.delete() setattr(wrpt, 'rpt', 'OK') else: setattr(wrpt, 'rpt', 'Not Found') wrpt.check_initialized() return wrpt
def _createWishListObject(self, request): """Create or update Session object, returning SessionForm/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.session_key: raise endpoints.BadRequestException("'session_key' field required") data = {} # generate Profile Key based on user ID and Conference # ID based on Profile key get Conference key from ID u_key = ndb.Key(Profile, user_id) w_sid = WishList.allocate_ids(size=1, parent=u_key)[0] w_key = ndb.Key(WishList, w_sid, parent=u_key) data['key'] = w_key data['user_id'] = user_id data['session_key'] = request.session_key WishList(**data).put() return self._copyWishListToForm(w_key.get());
def updateWishlist(self, request): """ Add or remove sessions to the logged in user's wishlist """ user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required.') # Validate the websafe session key to add ws_add_key = None ws_remove_key = None if request.add: ws_add_key = validate_websafe_key(request.add, 'Session', False) # Validate the websafe session key to remove if request.remove: ws_remove_key = validate_websafe_key(request.remove, 'Session', False) # Get the user wishlist user_id = getUserId(user) user_key = ndb.Key(Profile, user_id) wishlist = WishList.query(ancestor=user_key).fetch(1) # If there wasn't previously a wishlist, create it if not wishlist: wishlist = self._createWishlist(user_key) else: wishlist = wishlist[0] # If there is a session to add, add it if ws_add_key: if ws_add_key not in wishlist.sessions: wishlist.sessions.append(ws_add_key) # If there is a session to remove, remove it if ws_remove_key: if ws_remove_key in wishlist.sessions: wishlist.sessions.remove(ws_remove_key) # Save the wishlist to db wishlist.put() # Create a message of the newly created wishlist wishlist_form = self._copyWishListToForm(wishlist) return wishlist_form