def create_product(product): productName = PRODUCTS.get("productName") productDesc = PRODUCTS.get("productDesc") productCost = PRODUCTS.get("productCost") productCurrentSale = PRODUCTS.get("productCurrentSale") productStock = PRODUCTS.get("productStock") existing_product = (Products.query.filter( Products.productName == productName).filter( Products.productDesc == productDesc).filter( Products.productCost == productCost).filter( Products.productCurrentSale == productCurrentSale).filter( Products.productStock == productStock).one_or_none()) if existing_product is None: schema = ProductSchema() new_product = schema.load(product, session=db.session).data db.session.add(new_product) data = schema.dump(new_product).data return data, 201 else: abort( 409, "{productName} already exists".format(productName=productName), )
def update(product_id, product): """ This function updates an esixting product in database """ # Get the products requested from the db into session update_product = Product.query.filter( Product.product_id == product_id ).one_or_none() # Did we find an existing product? if update_product is not None: schema = ProductSchema() update = schema.load(product, session=db.session) update.product_id = update_product.product_id db.session.merge(update) db.session.commit() return schema.dump(update_product), 200 else: abort(404, f"Product is not found for the id: {product_id}")
def read_one(product_id): """ This function responds to a request for /api/products/{product_id} with one matching product from products :param product_id: Id of product to find :return: product matching id """ # Get the product requested product = Product.query.filter( Product.product_id == product_id).one_or_none() # Did we find a product? if product is not None: # Serialize the data for the response product_schema = ProductSchema() data = product_schema.dump(product) return data # Otherwise, nope, didn't find that product else: abort( 404, "Product not found for Id: {product_id}".format( product_id=product_id), )
def read_one(asin): """ This function responds to a request for /api/product/{product_asin} with one matching product from products :param asin: Asin of product to find :return: product matching id """ product = Product.query.filter(Product.asin == asin).one_or_none() if product is not None: # Serialize the data for the response product_schema = ProductSchema() product_data = product_schema.dump(product) reviews = Review.query.filter(Review.product_asin == asin).all() review_schema = ReviewSchema() # combine product description and reviews data = { 'product': product_data, 'reviews': [review_schema.dump(r) for r in reviews], } return data else: abort( 404, "Product not found for Id: {asin}".format(asin=asin), )
def update(product_id, product): """ This function updates an existing product in the products structure Throws an error if a product with the name we want to update to already exists in the database. :param product_id: Id of the product to update in the products structure :param product: product to update :return: updated product structure """ # Get the product requested from the db into session update_product = Product.query.filter( Product.product_id == product_id).one_or_none() # Try to find an existing product with the same name as the update name = product.get("name") inventory_level = product.get("inventory_level") existing_product = (Product.query.filter(Product.name == name).filter( Product.inventory_level == inventory_level).one_or_none()) # Are we trying to find a product that does not exist? if update_product is None: abort( 404, "product not found for Id: {product_id}".format( product_id=product_id), ) # Would our update create a duplicate of another product already existing? elif (existing_product is not None and existing_product.product_id != product_id): abort( 409, "Product {name} {inventory_level} exists already".format( name=name, inventory_level=inventory_level), ) # Otherwise go ahead and update! else: # turn the passed in product into a db object schema = ProductSchema() update = schema.load(product, session=db.session) # Set the id to the product we want to update update.product_id = update_product.product_id # merge the new object into the old and commit it to the db db.session.merge(update) db.session.commit() # return updated product in the response data = schema.dump(update_product) return data, 200
def index(): """ This function responds to a request for /products with the complete lists of products """ products = Product.query.order_by(Product.product_id).all() product_schema = ProductSchema(many=True) return product_schema.dump(products)
def parse_data(): cat = request.args.get('category') prod_schema = ProductSchema(many=True) if cat == 'All': products = Product.query.all() else: products = Product.query.filter_by(category=Category.query.filter_by( name=cat).first()).all() result = prod_schema.dump(products) return jsonify(data=result.data)
def read_all(): """ This function responds to a request for /api/product with the complete lists of product :return: json string of list of products """ people = Product.query.order_by(Product.asin).all() # Serialize the data for the response product_schema = ProductSchema(many=True) data = product_schema.dump(people) return data
def read_all(): """ This function responds to a request for /api/product with the complete list of inventory levels for all products :return: json string of list of products """ # Create the list of products from our data, newest dates first. products = Product.query.order_by(Product.id, Product.timestamp.desc()).all() # Serialize the data for the response product_schema = ProductSchema(many=True) data = product_schema.dump(products) return data
def create(product): """ This function creates a new product in the product structure based on the passed in product data :param product: product to create in products structure :return: 201 on success, 406 on product exists """ name = product.get("name") inventory_level = product.get("inventory_level") # we aren't this kind of database... # existing_product = ( # Product.query.filter(Product.name == name) # .filter(Product.inventory_level == inventory_level) # .one_or_none() # ) existing_product = None # Can we insert this product? if existing_product is None: # Create a new product id based on max value if there isn't an id already # this allows us to add a new inventory_level for an existing product. # Or create an entirely new product by leaving out the id. if "id" not in product: product["id"] = db.session.query(func.max(Product.id)).scalar() + 1 # Create a product instance using the schema and the passed in product schema = ProductSchema() new_product = schema.load(product, session=db.session) # Add the product to the database db.session.add(new_product) db.session.commit() # Serialize and return the newly created product in the response data = schema.dump(new_product) return data, 201 # Otherwise, nope, product exists already else: abort( 409, "Product {name} {inventory_level} exists already".format( name=name, inventory_level=inventory_level), )
def create(products): """ This function responds to a post request for /products """ schema = ProductSchema(many=True) new_products = schema.load(products, session=db.session) if not new_products: abort(400, "No products for creation are specified") db.session.add_all(new_products) db.session.commit() return schema.dump(new_products), 201
def read_one_products(productID): product = Product.query.filter( Product.productID == productID).one_or_none() if product is not None: product_schema = ProductSchema() data = product_schema.dump(product).data return data else: abort( 404, "Product not found for ID: {productID}".format( productID=productID), )
def get_product(product_id): """ This function responds to a request for /products/{product_id} with one matching product """ product = Product.query.filter( Product.product_id == product_id).one_or_none() if product is not None: product_schema = ProductSchema() data = product_schema.dump(product) return data else: abort( 404, "Product is not found for id: {product_id}".format( product_id=product_id), )
def update_product(productID, productName): update_products = Product.query.filter( Product.productID == productID).one_or_none() if update_products is not None: schema = ProductSchema() update = schema.load(productName, session=db.session).data update.productID = update_products.productID db.session.merge(update) db.session.commit() data = schema.dump(update_products).data return data, 200 else: abort( 404, "Product not found for ID: {productID}".format( productID=productID), )
""" The main Flask application file that bootstraps and starts the app. """ import os from bootstrap import app_factory from marshmallow import ValidationError from flask import request from helpers import data_required, validate_schema from models import Product, ProductSchema, Message, MessageSchema, SendMessageSchema, db app = app_factory() twilio = app.twilio # Using schemas to serialize and make sure payloads are ok product_schema = ProductSchema() products_schema = ProductSchema(many=True, only=("id", "name")) message_schema = MessageSchema() send_message_schema = SendMessageSchema() ##### API ##### @app.route("/products") def get_products(): products = Product.query.all() # Serialize the queryset result = products_schema.dump(products) return {"data": result}
from app import app, db from flask import jsonify, redirect from models import Product, ProductSchema from functions import extract # Init schema product_schema = ProductSchema() products_schema = ProductSchema(many=True) # Redirect to /product @app.route('/') def root(): return redirect('/product') # Create a Product @app.route('/product', methods=['POST']) def add_product(): name = extract('name') description = extract('description') price = extract('price') qty = extract('qty') new_product = Product(name, description, price, qty) db.session.add(new_product) db.session.commit() return product_schema.jsonify(new_product)
from flask import Blueprint, request, jsonify, make_response from flask_restful import Api, Resource from http_status import HttpStatus from models import orm, Product, ProductSchema from sqlalchemy.exc import SQLAlchemyError from flask import current_app as app from sqlalchemy import func import re from collections import OrderedDict service_blueprint = Blueprint('service', __name__) # validate, serialize, and deserialize products. product_schema = ProductSchema() # link Api to Blueprint service = Api(service_blueprint) class ProductResource(Resource): def get(self, keyword): result = OrderedDict() result['keyword'] = keyword keyword = "%{}%".format(keyword) date_pattern = r"(\d{4}-\d{1,2}-\d{1,2})" product = Product.query.filter(Product.name.like(keyword)) #app.logger.info(result) dumped_product = product_schema.dump(product, many=True).data for product in dumped_product: timestamp = product['timestamp'] mat = re.search(date_pattern, timestamp) timestamp = mat.group(0) product = product['data']['item']
def read_all_products(): product = Product.query.order_by(Product.productName).all() products_schema = ProductSchema(many=True) data = products_schema.dump(product).data return data
def serialize(products): ps = ProductSchema() return list(map(lambda prod: ps.dump(prod), products))
token = jwt.encode({ 'public_id': user.public_id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, # The token is valid for 30 minutes app.config['SECRET_KEY']) # key used to encode the token return jsonify({'token': token.decode('UTF 8')}) else: return make_response('Wrong password', 401, # Unauthorized {'WWW-Authenticate': 'Basic realm="Login required!"'}) # Init Schema product_schema = ProductSchema() products_schema = ProductSchema(many=True) # Signaling we're dealing with multiple objects # Create a Product # Note: postman -> post -> headers: key Content-Type value key application/json # body -> raww ''' { "name": "product1", "description": "this is product1", "price": 3.75, "qty": 6 } '''