def post(self): catalog_data = CatalogSchema().load(request.json) catalog = Catalog(**catalog_data) try: catalog.save() except: return {"message": ERROR_INSERTING}, 500 return {'id': str(catalog.id)}, 201
def test_successful_inventory(self): address_data = { "street": "primera", "city": "segunda", "state": "tercero", "country": "cuarto", "name_code": "123abc" } address = Address(**address_data) address.save() shop_data = {"name": "un ejemplo mas", "address_id": address.id} shop = Shop(**shop_data) shop.save() catalog_data = {"name": "primavera verano", "shop_id": shop.id} catalog = Catalog(**catalog_data) catalog.save() product_data = { "title": "p2", "description": "un articulo de ropa", "price": 2.2, "is_featured": True, "sku": "abc12345678", "catalog_id": catalog.id, } product = Product(**product_data) product.save() inventory_data = { "product_id": product.id, "quantity": 10, "shop_id": shop.id } inventory = Inventory(**inventory_data) inventory.save() # Given payload = json.dumps({ "sku": "abc12345678", "quantity": 10, "shop_id": shop.id }) # When response = self.app.post('/api/v1/inventory/', headers={"Content-Type": "application/json"}, data=payload) # Then self.assertEqual(dict, type(response.json)) self.assertEqual(200, response.status_code)
def post(self): catalog = request.get_json() found_similar = Catalog.query.filter_by(name=catalog.get("name"), type=catalog.get("type")).first() if found_similar is not None: return {"message" : "Catalog found with name: {0} and type {1}".format(catalog.get("name"), catalog.get("type"))}, 400 else: newCatalog = Catalog() newCatalog.name = get("name") newCatalog.type = get("type") db.session.add(newCatalog) db.session.commit() return {"message" : "Catalog added"}, 200
def catalog_index(): search = False q = request.args.get('search') if q: search = True page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') if search: regex = re.compile('.*'+q+'.*') catalog = Catalog.objects(name = q,active=True).skip(offset).limit(per_page) else: catalog = Catalog.objects(active=True).skip(offset).limit(per_page) pagination = Pagination(page=page, total=catalog.count(), record_name='catalogs', css_framework='bootstrap4') return render_template('admin/catalog/index.html', catalogs=catalog, page=page,per_page=per_page, pagination=pagination)
async def update(self, catalog_dto: Catalog) -> Union[bool, UpdateResult]: self.date_sanitation(SanitationMode.rm_create_date, catalog_dto) # Update date sanitation catalog_dto.updatedAt = datetime.utcnow() try: q_result: UpdateResult = await self.collection.update_one( {'_id': catalog_dto.id}, {'$set': catalog_dto.dict(by_alias=True, exclude_none=True)}) except: return False return q_result
def edit_catalog(id): title = 'Edit catalog' catalog = Catalog.find_by_id(id) if not catalog: message = 'No catalog with id %s' % id return render_template('common/not-found.html', message=message) if catalog.user_id != login_session['user_id']: flash('Not authorized to edit this catalog') return redirect(url_for('show_catalogs')) if request.method == 'GET': return render_template('catalog/catalog-form.html', title=title, name=catalog.name, description=catalog.description) else: name = request.form['name'].strip() description = request.form['description'].strip() if name and description: catalog.name = name catalog.description = description catalog.save_to_db() flash('Catalog is successfully updated') return redirect(url_for('show_catalogs')) error = 'Name and description are required' return render_template('catalog/catalog-form.html', title=title, error=error)
def create_catalog(): title = 'Create new catalog' if request.method == 'GET': return render_template('catalog/catalog-form.html', title=title) else: name = request.form['name'].strip() description = request.form['description'].strip() if name and description: catalog = Catalog(bleach.clean(name), bleach.clean(description), user_id=login_session['user_id']) catalog.save_to_db() flash('%s is successfully Created' % catalog.name) return redirect(url_for('show_catalogs')) error = 'Name and description are required' return render_template('catalog/catalog-form.html', title=title, error=error)
def catalog_create(): name = request.values.get('name') catalog = Catalog(name = name).save() id = str(catalog.id) if id: flash('Success', 'success') else: flash('Error', 'error') return redirect('/admin/catalog/edit/' + id)
def catalog_update(): id = request.values.get('id') name = request.values.get('name') catalog = Catalog(id=id).update(name = name) if catalog: flash('Update Success', 'success') else: flash('Error', 'error') return redirect('/admin/catalog/edit/' + id)
def show_catalogs(): catalogs = Catalog.find_all() for catalog in catalogs: if len(catalog.name) > 20: catalog.name = catalog.name[:20] + '...' if len(catalog.description) > 32: catalog.description = catalog.description[:32] + '...' return render_template('catalog/catalog-list.html', catalogs=catalogs, session=login_session)
def create_catalog(user): if not user: return jsonify({'message': 'Unauthorized'}), 401 data = request.json if 'name' not in data or not data['name']: return jsonify({'message': 'No catalog name'}), 400 if 'description' not in data or not data['description']: data['description'] = '' name = data['name'].strip() description = data['description'].strip() if len(name) > MAX_NAME_LENGTH or len( description) > MAX_DESCRIPTION_LENGTH: return jsonify({'message': 'Bad request'}), 400 catalog = Catalog(name, description, user.id) catalog.save_to_db() return jsonify({ 'message': 'Catalog created', 'catalog': catalog.serializer }), 200
async def get(self, catalog_object_id: ObjectId) -> Union[None, Catalog]: """ Get a specific catalog from database :return: The catalog to find or None if the id is missing """ db_catalog = await self.collection.find_one({"_id": catalog_object_id}) if db_catalog: return Catalog(**db_catalog) else: return None
async def get_all(self) -> List[Catalog]: """ Retrieve all catalog from the database :return: List of catalogs """ catalogs: List = [] async for catalog in self.collection.find(): catalogs.append(Catalog(**catalog)) return catalogs
def delete_catalog(user, id): if not user: return jsonify({'message': 'Unauthorized'}), 401 catalog = Catalog.find_by_id(id) if not catalog: return jsonify({'message': 'Catalog not found'}), 404 if user.id != catalog.user_id: return jsonify({'message': 'No permission'}), 403 items = Item.find_by_catalog_id(id) for item in items: item.delete_from_db() catalog.delete_from_db() return jsonify({'message': 'Catalog deleted'}), 200
async def delete( self, catalog_object_id: ObjectId) -> Union[None, bool, Catalog]: catalog_db = await self.collection.find_one({'_id': catalog_object_id}) if catalog_db: try: await self.collection.delete_one({'_id': catalog_object_id}) except: return False # something was wrong else: return None # 404 return Catalog(**catalog_db)
async def create(self, catalog_dto: Catalog) -> Union[bool, InsertOneResult]: """ Created a new catalog in to the database :param catalog_dto: The Catalog to be added :return: The new added already catalog object """ catalog_dto.createdAt = datetime.utcnow() self.id_sanitation(catalog_dto) # if the dto has id, we remove it self.date_sanitation(SanitationMode.rm_update_date, catalog_dto) # Update date sanitation try: q_result: InsertOneResult = await self.collection.insert_one( catalog_dto.dict(by_alias=True)) except: return False return q_result
def delete_catalog(id): catalog = Catalog.find_by_id(id) if not catalog: message = 'No catalog with id %s' % id return render_template('common/not-found.html', message=message) if catalog.user_id != login_session['user_id']: flash('Not authorized to delete this catalog') return redirect(url_for('show_catalogs')) if request.method == 'GET': return render_template('catalog/catalog-delete.html', catalog=catalog) else: items = Item.find_by_catalog_id(id) for item in items: item.delete_from_db() catalog.delete_from_db() flash('Catalog is successfully deleted') return redirect(url_for('show_catalogs'))
async def get_parametrized( self, q: DQueryData) -> List[Catalog]: # qd means query data """ Gets the catalogs in a parametrized way with the query params """ # This kind of pagination have a very poor performance, but allows random navigation through pages. catalogs: List = [] if q['dir'] is None or q['field'] is None: # with sorting by field catalogs_db = self.collection.find().skip(q['skip']).limit(q['limit']) if q['search'] is None \ else self.collection.find({'name': {'$regex': '.*' + q['search'] + '.*'}}).limit(q['limit']) else: # without sorting catalogs_db = self.collection.find().skip(q['skip']).limit(q['limit']).sort(q['field'], q['dir']) if q['search'] is None \ else self.collection.find({'name': {'$regex': '.*' + q['search'] + '.*'}}).limit(q['limit']).sort(q['field'], q['dir']) async for catalog in catalogs_db: catalogs.append(Catalog(**catalog)) return catalogs
def create_item(user, catalog_id): if not user: return jsonify({'message': 'Unauthorized'}), 401 catalog = Catalog.find_by_id(catalog_id) if not catalog: return jsonify({'message': 'Catalog not found'}), 404 data = request.json if 'name' not in data or not data['name']: return jsonify({'message': 'No item name'}), 400 if 'description' not in data or not data['description']: data['description'] = '' name = data['name'].strip() description = data['description'].strip() if not name or len(name) > MAX_NAME_LENGTH or len( description) > MAX_DESCRIPTION_LENGTH: return jsonify({'message': 'Bad request'}), 400 item = Item(name, description, catalog_id, user.id) item.save_to_db() return jsonify({'message': 'Item created', 'item': item.serializer}), 200
def edit_catalog(user, id): if not user: return jsonify({'message': 'Unauthorized'}), 401 catalog = Catalog.find_by_id(id) if not catalog: return jsonify({'message': 'Catalog not found'}), 404 if user.id != catalog.user_id: return jsonify({'message': 'No permission'}), 403 data = request.json if 'name' in data and data['name']: name = data['name'].strip() if not name or len(name) > MAX_NAME_LENGTH: return jsonify({'message': 'Bad request'}), 400 catalog.name = name if 'description' in data and data['description']: description = data['description'].strip() if len(description) > MAX_DESCRIPTION_LENGTH: return jsonify({'message': 'Bad request'}), 400 catalog.description = description catalog.save_to_db() return jsonify({ 'message': 'Catalog edited', 'catalog': catalog.serializer }), 200
def catalog_delete(catalog_id): Catalog(id=catalog_id).update(active=False) return redirect('/admin/catalog')
def get_items(catalog_id): catalog = Catalog.find_by_id(catalog_id) if not catalog: return jsonify({'message': 'Catalog not found'}), 404 items = Item.find_by_catalog_id(catalog_id) return jsonify({'items': [item.serializer for item in items]}), 200
def get_catalogs(): catalogs = Catalog.find_all() return jsonify({'catalogs': [catalog.serializer for catalog in catalogs]}), 200
def get_catalog(id): catalog = Catalog.find_by_id(id) if not catalog: return jsonify({'message': 'Catalog not found'}), 404 return jsonify({'catalog': catalog.serializer}), 200
def load_catalog(): Catalog.load_nodes() Catalog.load_relations() Catalog.load_users()