Ejemplo n.º 1
0
def create(event, context):
    logger.debug(f'Event received: {json.dumps(event)}')
    data = json.loads(event.get('body'))

    item = ItemModel(id=str(uuid4()),
                     name=data.get('name'),
                     description=data.get('description', 'None'),
                     slot=data.get('slot'),
                     quality=data.get('quality'),
                     damage=data.get('damage'),
                     level=data.get('level'),
                     crit_chance=data.get('crit_chance'),
                     stamina=data.get('stamina'),
                     is_warrior=data.get('is_warrior', False),
                     is_sorcerer=data.get('is_sorcerer', False),
                     is_archer=data.get('is_archer', False),
                     is_rogue=data.get('is_rogue', False))

    item.save()

    response = {
        'statusCode': 200,
        'body': json.dumps(item, cls=ModelEncoder),
        'headers': {
            'Access-Control-Allow-Origin': '*'
        }
    }

    logger.debug(f'Response: {json.dumps(response)}')

    return response
Ejemplo n.º 2
0
    def post(self):
        data = Item.parser.parse_args()
        name = data['name']

        if ItemModel.find_by_name(name):
            ItemModel.find_by_name(name).delete()
            return {'message': f'{name} has been deleted'}
        return {'message': 'Failed to delete, item not found'}, 400
Ejemplo n.º 3
0
 def put(self):
     data = parser.parse_args()
     new_item = ItemModel(title=data['title'],
                          description=data['description'],
                          price=data['price'])
     try:
         new_item.save_to_db()
         return {'message': 'Item {} was created'.format(data['title'])}
     except Exception as e:
         return {'message': str(e)}, 500
Ejemplo n.º 4
0
def create_item():

    if request.method == "POST":
        name = request.form['name']
        model_id = request.args.get('model_id')

        #image logic
        username = session['username']
        folder = f"user_{username}"
        # validation and sanity checks

        if model_id is None:
            return "Missing model number"

        if 'file1' not in request.files:
            return "Missing file part"

        if ItemModel.find_by_storeid_and_itemname(model_id, name):
            return gettext("web_items_alredyexists")

        file1 = request.files['file1']

        #data = image_schema.load(file1)

        try:
            #image_path = image_helper.save_image(data["image"], folder=folder)
            image_path = image_helper.save_image(file1,
                                                 folder=os.path.join(
                                                     folder, model_id))
            logger.info(image_path)
            basename = image_helper.get_basename(image_path)
            logger.info(basename)
        except UploadNotAllowed:  # forbidden file type
            extension = image_helper.get_extension(file1)
            return f"Unable to upload the extension {extension}"

        #create item in database
        item = ItemModel(name=name,
                         filename=file1.filename,
                         objname=image_path,
                         store_id=model_id)
        print(item)
        try:
            item.save_to_db()
        except:
            return "Error creating item"

        return redirect(url_for(".index", model_id=model_id))
    #Get implementation
    model_id = request.args.get('model_id')
    return render_template("items/new_item.html", model_id=model_id)
Ejemplo n.º 5
0
def _populate_model(entity):

    if not entity:
        return None

    model = ItemModel()
    model.id = get_resource_id_from_key(entity.key)
    model.item_id = entity.item_id
    model.user_ids = entity.user_ids
    model.total_likes = entity.total_likes
    model.total_dislikes = entity.total_dislikes
    model.total_preferences = entity.total_preferences
    model.created_timestamp = entity.created_timestamp
    model.latest_timestamp = entity.latest_timestamp
    return model
Ejemplo n.º 6
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('fqdn',
                            type=str,
                            required=True,
                            help='FQDN cannot be blank!')
        parser.add_argument('ip_address',
                            type=str,
                            required=True,
                            help='IP Address cannot be blank!')
        parser.add_argument('mac_address',
                            type=str,
                            required=True,
                            help='MAC Address cannot be blank!')
        parser.add_argument('owned_by',
                            type=str,
                            required=True,
                            help='Owned By cannot be blank!')
        parser.add_argument('serial_number',
                            type=str,
                            required=True,
                            help='Serial Number Address cannot be blank!')

        args = parser.parse_args()
        item = ItemModel(fqdn=args['fqdn'],
                         ip_address=args['ip_address'],
                         mac_address=args['mac_address'],
                         owned_by=args['owned_by'],
                         serial_number=args['serial_number'])
        cmdb_manager.insert_item(item)
        #return message, status.HTTP_201_CREATED

        return Response(status=201)
Ejemplo n.º 7
0
	def list_item (self):
		#lib = ndb.Key('LibraryModel','Library')
		# This is for full consistency vs eventual consistency
		#item_query = ItemModel.query(ancestor=lib)
		# no ancestor, so this will be eventual consistency
		# get items for table
		item_query = ItemModel.query()
		return item_query
Ejemplo n.º 8
0
def list(event, context):
    logger.debug(f'Event received: {json.dumps(event)}')

    # query params {level, slot, quality}
    if 'queryStringParameters' in event:
        queryParams = event.get('queryStringParameters', {})

        if queryParams is not None:
            if 'player_class' in queryParams:
                query = None

                if 'level' in queryParams:
                    clause = ItemModel.level == int(queryParams['level'])
                    query = clause if query is None else query & clause

                results = ItemModel.player_class_index.query(
                    int(queryParams['player_class']), query)

            else:
                queryFields = {'slot', 'quality', 'level'}
                query = None

                for fieldName in queryFields:
                    field = getattr(ItemModel, fieldName, None)
                    if field is None or fieldName not in queryParams:
                        continue
                    clause = field == int(queryParams[fieldName])
                    query = clause if query is None else query & clause

                results = ItemModel.scan(query)
        else:
            results = ItemModel.scan()
    else:
        results = ItemModel.scan()

    response = {
        'statusCode': 200,
        'body': json.dumps({"items": [x for x in results]}, cls=ModelEncoder),
        'headers': {
            'Access-Control-Allow-Origin': '*'
        }
    }

    return response
Ejemplo n.º 9
0
 def mutate(self, info, product_id=None):
     cart = CartModel(total=0)
     db_session.add(cart)
     db_session.commit()
     if product_id is not None:
         local_product_id=from_global_id(product_id)[1]
         item = ItemModel(cart_id=cart.id,product_id=local_product_id)
         db_session.add(item)
         db_session.commit()
     return CartCreate(cart=cart)
Ejemplo n.º 10
0
    def delete(self, name):
        """
        The async function that handles DELETE requests.
        :param name: item name to be deleted.
        """

        item = ItemModel.find_by_name(name)
        if item:
            item.delete_from_db()

        return {"message": "Item deleted"}
Ejemplo n.º 11
0
 def put(self, name):
     
     data = Item.parser.parse_args()
     item = ItemModel.find_by_name(name)
     if not item:
         item = ItemModel(name, **data)
     else:
         item.price = data['price']
         item.store_id = data['store_id']
     
     item.save_to_db()
         
     return item.json(), 200           
Ejemplo n.º 12
0
    def get(self, name):
        """
        The async function that handles GET requests.
        :param name: item name to be returned to user.
        :return:
        """
        item = ItemModel.find_by_name(name)
        if item:
            return item.json()

            # If row returns none, 404 status_code is returned with a message.
        return {'message': 'Item not found'}, 404
Ejemplo n.º 13
0
    def post(cls, name):
        """
        The async function that handles POST requests.
        :param name: item name to be created.
        :return:
        """

        # Check whether the request is properly made.
        if ItemModel.find_by_name(name):
            return {
                'message': "An item with name '{}' already exists".format(name)
            }, 400

        # Load data
        request_data = cls.parser.parse_args()

        # Create a new item
        item = ItemModel(name, **request_data)

        try:
            item.save_to_db()
        except Exception as e:
            return {
                'message':
                'An error occured inserting the item. Here is the error {}'.
                format(e)
            }, 500  # Internal Server Error

        # Return "response" with item and status code 201: CREATED
        return item.json(), 201
Ejemplo n.º 14
0
def delete_item(item_id):
    item = ItemModel.find_by_id(item_id)
    model_id = request.args.get('model_id')
    item.delete_from_db()
    try:
        #uploads = os.path.join(current_app.root_path, current_app.config['UPLOADED_IMAGES_DEST'])
        uploads = os.path.join(current_app.config['UPLOADED_IMAGES_DEST'])
        os.remove(os.path.join(uploads, item.objname))
    except:
        traceback.print_exc()
        return "File deletion failed"

    return redirect(url_for(".index", model_id=model_id))
 def post(self, name):
     if ItemModel.find_by_name(name) is not None:
         return {"message": "Item already exists"}, 403
     else:
         data = Item.parser.parse_args()
         item = ItemModel(name, **data)
         item.save_to_db()
         return item.json(), 200
Ejemplo n.º 16
0
    def put(self):
        data = Item.parser.parse_args()
        name = data['name']

        if ItemModel.find_by_name(name):
            _data = {}
            for key in data:
                if data.get(key):
                    _data[key] = data[key]
                    ItemModel.find_by_name(name).update(**_data)
            return {'message': f'{name} has been edited'}

        item = ItemModel(**data)
        item.save_to_db()
        return json.loads(item.to_json())
Ejemplo n.º 17
0
    def post(self, name):

        if ItemModel.find_by_name(name):
            return {'message': 'A item with that name already exists'}, 400

        data = Item.parser.parse_args()
        item = ItemModel(name, **data)

        try:
            item.save()
        except:
            return dict(message="An error occurred inserting the item"), 500

        return {'message': 'Item created successfully'}, 201
Ejemplo n.º 18
0
    def post(self, name):
        if ItemModel.find_by_name(name):
            return {'message': "An item with name '{}' already exists.".format(name)}

        data = Item.parser.parse_args()

        item = ItemModel(name, data['price'])

        try:
            item.insert()
        except:
            return {"message": "An error occurred inserting the item."}

        return item.json()
Ejemplo n.º 19
0
def get(event, context):
    logger.debug(f'Event received: {json.dumps(event)}')
    char_id = event['pathParameters']['id']

    character = ItemModel.get(char_id)

    response = {
        'statusCode': 200,
        'body': json.dumps(character, cls=ModelEncoder),
        'headers': {
            'Access-Control-Allow-Origin': '*'
        }
    }

    return response
Ejemplo n.º 20
0
    def post(self):
        data = Item.parser.parse_args()
        name = data['name']

        if ItemModel.find_by_name(name):
            return {'message': f'Item {name} already exist'}, 400

        item = ItemModel(**data)
        item.save_to_db()
        return json.loads(item.to_json()), 201
Ejemplo n.º 21
0
def download_file(item_id):
    model_id = request.args.get('model_id')
    item = ItemModel.find_by_id(item_id)

    try:
        uploads = os.path.join(current_app.config['UPLOADED_IMAGES_DEST'],
                               os.path.dirname(item.objname))
        return send_from_directory(directory=uploads,
                                   filename=os.path.basename(item.objname),
                                   attachment_filename=item.filename,
                                   as_attachment=True)
    except:
        traceback.print_exc()
        return "File not found!"

    return redirect(url_for(".index", model_id=model_id))
Ejemplo n.º 22
0
    def put(self, name):
        data = Item.parser.parse_args()

        item = ItemModel.find_by_name(name)

        if item is None:
            item = ItemModel(name, **data)
        else:
            item.price = data['price']
            item.store_id = data['store_id']

        try:
            item.save()
        except:
            return dict(message="An error ocurred updating the item"), 500

        return item.json()
Ejemplo n.º 23
0
    def post(self, name):
        data = Item.parser.parse_args()
        if ItemModel.find_by_name(name):
            return {'message': 'Item with name {} already exists.'.format(name)}, 400       
        
        item = ItemModel(name, **data)
        try:
            item.save_to_db()
        except:
            return {'message': 'Internal server error creating item'}, 500

        return item.json(), 201 
Ejemplo n.º 24
0
def addItem():
    print("request", request)
    req = request.get_json()
    print("req", req, type(req))
    print([key for key in ["name", "price"] if key not in req.keys()])
    if len([key for key in ["name", "price"] if key not in req.keys()]) > 0:
        return {"error": "invalid request"}, 400
    if "tag" in req and db.session.query(TagModel.TagModel)\
            .filter_by(name=req["tag"]).scalar() is None:
        return {"error": "invalid tag"}, 400
    try:
        db.session.add(ItemModel.ItemModel(**req))
        db.session.commit()
    except Exception as e:
        return {"error": str(e)}, 503

    context = {"status": "success!"}
    return jsonify(**context)
Ejemplo n.º 25
0
    def put(self, name):
        data = Item.parser.parse_args()
        item = ItemModel.find_by_name(name)

        updated_item = ItemModel(name,data['price'])

        if item is None:
            try:
                updated_item.insert()
            except:
                return {"message": "An error occurred inserting the item."}
        else:
            try:
                updated_item.update()
            except:
                raise
                return {"message": "An error occurred updating the item."}
        return updated_item.json()
Ejemplo n.º 26
0
    def put(cls, name):
        """
        The async function that handles PUT requests.
        :param name: item name to create or update.
        :return:
        """
        # Load and parse data
        request_data = cls.parser.parse_args()

        # Check whether name already exists
        item = ItemModel.find_by_name(name)

        # If name doesn't exist, create. Otherwise, update.
        if item is None:
            item = ItemModel(name, **request_data)
        else:
            item.price = request_data['price']

        # In either case: insert or update we need to save to db ==> save_to_db()
        item.save_to_db()
        # Return item.
        return item.json()
Ejemplo n.º 27
0
def update(event, context):
    logger.debug(f'Event received: {json.dumps(event)}')
    id = event['pathParameters']['id']
    data = json.loads(event.get('body'))

    item = ItemModel.get(id)

    item.crit_chance = data['crit_chance']
    item.damage = data['damage']
    item.stamina = data['stamina']

    item.save()

    response = {
        'statusCode': 200,
        'body': json.dumps(item, cls=ModelEncoder),
        'headers': {
            'Access-Control-Allow-Origin': '*'
        }
    }

    logger.debug(f'Response: {json.dumps(response)}')

    return response
Ejemplo n.º 28
0
	def save_item (self,title,typeof,release_date,location,available,id):
		if id>0:
			# make new key if there is no key
			item_k = ndb.Key('ItemModel',long(id))
			item = item_k.get()
		else:
			item = ItemModel()
		# get key
		location_k = ndb.Key('LocationModel',long(location))
		item.title = title
		item.typeof = typeof
		item.release_date = datetime.date(year=int(release_date[6:10]), month=int(release_date[3:5]), day=int(release_date[0:2]))
		item.location = location_k
		item.locationName = item.item_location
		item.locationID = long(location)
		item.available = available
		item.username = users.get_current_user().email()
		item.put()
Ejemplo n.º 29
0
def insert_to_do(item_to_insert: ItemModel):
    """
    Returns the to-do list insert
    """
    return todo.insert(item_to_insert.dict())
Ejemplo n.º 30
0
 def mutate(self,info,cart_id,product_id):
     local_cart_id, local_product_id = from_global_id(cart_id)[1], from_global_id(product_id)[1] 
     item = ItemModel(cart_id=local_cart_id,product_id=local_product_id)
     db_session.add(item)
     db_session.commit()
     return CartAdd(cart=item.cart)
Ejemplo n.º 31
0
def new_todo(insert_item: ItemModel):
    """
    Insert a new To Do in a list
    """
    return todo.insert(insert_item.dict())
Ejemplo n.º 32
0
 def delete(self, name):
     item = ItemModel.find_by_name(name)
     if item:
         item.delete_from_db()     
         
     return {'message': 'Item deleted'}, 200