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())
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 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
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()
def create_wishlist(): """ Creates a Wishlist object based on the JSON posted Will create a wishlist with an auto incremented id --- tags: - Wishlist parameters: - name: body in: body required: true schema: id: wishlist_entries required: true - customer_id - wishlist_name properties: customer_id: type: integer description: customer_id default: "34" wishlist_name: type: string description: name of the wishlist default: "water Bottles" responses: 201: description: Successfully Created wishlist """ check_content_type('application/json') wishlist = Wishlist() json_post = request.get_json() wishlist.deserialize(json_post) wishlist.save() message = wishlist.serialize() location_url = url_for('get_wishlist', wishlist_id=wishlist.id, _external=True) return make_response(jsonify(message), status.HTTP_201_CREATED, { 'Location': location_url })
def wishlist(id): if request.method=='POST': title=request.form['title'] description=request.form['description'] url=request.form['url'] thumbnail=request.form['thumbnail'] obj={'error':'null','data':{'wishes':{'title':title,'description':description,'url':url,'thumbnail':thumbnail},'message':'sucess'},} new_wishlist=Wishlist(title,description,url,thumbnail,id) db.session.add(new_wishlist) db.session.commit() return jsonify(obj) if request.method =='GET': wishlist=Wishlist.query.get(id) if wishlist is None: obj={'error':'1','data':{},'message':'No such wishlist exist'} else: obj={'error':'null','data':{'wishes':{'title':wishlist.title,'description':wishlist.description,'url':wishlist.url,'thumbnail':wishlist.thumbnail},'message':'sucess'},} return jsonify(obj)
def addSessionToWishlist(self, request): """This function adds given session to wishlist.""" # check for authentication user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # check for SessionKey if not request.SessionKey: raise endpoints.BadRequestException("'SessionKey' field required") # Try and get the session object s_key = ndb.Key(urlsafe=request.SessionKey) sess = s_key.get() if not sess: raise endpoints.NotFoundException('No Session found with key: %s' % request.SessionKey) # Add to wishlist # get Profile from datastore p_key = ndb.Key(Profile, user_id) profile = p_key.get() if not profile: raise endpoints.NotFoundException('No profile found') # Check that the session does not already exist # Prevent the same session from being added to wishlist query = Wishlist.query(ancestor=p_key) query = query.filter(Wishlist.sessionKey == request.SessionKey) if len(query.fetch()) != 0: raise endpoints.BadRequestException( "That session is already in your wishlist") # generate Wishlist ID based on User ID w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0] w_key = ndb.Key(Wishlist, w_id, parent=p_key) # save new wishlist to datastore newWish = Wishlist(sessionKey=request.SessionKey) newWish.key = w_key newWish.put() return request
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
def add_wishlist(): """ The route for adding new wishlists, specified by userID and name of the wishlist. You can check the POST requests using CURL. Example: curl -i -H 'Content-Type: application/json' -X POST -d '{"name":"Xynazog","user_id":123}' http://127.0.0.1:5000/wishlists H is for headers, X is used to specify HTTP Method, d is used to pass a message. In location headers, if _external set to True, an absolute URL is generated. """ data = request.get_json() if is_valid(data, 'wishlist'): wishl = Wishlist() wishl.deserialize_wishlist(data) wishl.save_wishlist() message = wishl.serialize_wishlist() return make_response(jsonify(message), status.HTTP_201_CREATED, {'Location': wishl.self_url()}) else: message = {'error': 'Wishlist data was not valid'} return make_response(jsonify(message), status.HTTP_400_BAD_REQUEST)
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 parse(result): return Wishlist(result[1], result[2], result[0])
def data_load_wishlist(data): Wishlist().deserialize_wishlist(data).save_wishlist()
def add_wishlist(): """ Creates a Wishlist This endpoint will create a Wishlist based on the data in the body that is posted --- tags: - Wishlists consumes: - application/json produces: - application/json parameters: - in: body name: body required: true schema: id: data required: - name - category properties: name: type: string description: name for the Wishlist user_id: type: string description: Unique ID of the user(created by the user) responses: 201: description: Wishlist created 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 description: Original ID of the item item_description: type: string description: Description of the item description: Dictionary to store objects in a wishlist id: type: integer description: Unique ID of the wishlist assigned internally by the server 400: description: Bad Request (the posted data was not valid) """ data = request.get_json() if is_valid(data, 'wishlist'): wishl = Wishlist() wishl.deserialize_wishlist(data) wishl.save_wishlist() message = wishl.serialize_wishlist() return make_response(jsonify(message), status.HTTP_201_CREATED, {'Location': wishl.self_url()}) else: message = {'error': 'Wishlist data was not valid'} return make_response(jsonify(message), status.HTTP_400_BAD_REQUEST)
def insertWishlistItems(user_id, property_id): wishlist = Wishlist(user_id=user_id, property_id=property_id) db.session.add(wishlist) db.session.commit() return {'id': wishlist.id, 'user_id': user_id, 'property_id': property_id}