def shopping_cart(): try: # get the access token auth_header = request.headers.get('Authorization') if not auth_header: abort(make_response(jsonify(message="Bad Request."), 400)) access_token = auth_header.split(" ")[1] if access_token: user_id = User.decode_token(access_token) if not isinstance(user_id, str): # Go ahead and handle the request, the user is authed if request.method == "POST": schema_item_chart_data = { "type": "object", "properties": { "item_id": { "type": "number" }, "item_name": { "type": "string" }, "item_price": { "type": "number" }, "amount": { "type": "number" } }, } # Get country based on data user country_iso2 = User.get_user_country(user_id) cart_data = request.data.get('cart_data', '') # Validate the schema and type data input for cdata in cart_data: validate(cdata, schema_item_chart_data) cart = Cart() cart.save(user_id=user_id, country_iso2=country_iso2, cart_data=cart_data) response = {'message': 'Cart created successfully.'} data = { 'id': cart.id, 'date_created': cart.date_created, 'date_modified': cart.date_modified, 'created_by': cart.created_by, 'country_iso2': cart.country_iso2, 'status_id': cart.status_id } response['data'] = data return make_response(jsonify(response)), 201 else: # GET # get all the cart for this user carts = Cart.get_all(user_id) response = {'message': 'Request success.'} results = [] for cart in carts: obj = { 'id': cart.id, 'date_created': cart.date_created, 'date_modified': cart.date_modified, 'created_by': cart.created_by, 'country_iso2': cart.country_iso2, 'status_id': cart.status_id, 'items': [] } for item in cart.item_carts: icart = { 'id': item.id, 'cart_id': item.cart_id, 'item_id': item.item_id, 'item_name': item.item_name, 'item_price': item.item_price, 'amount': item.amount, } obj['items'].append(icart) results.append(obj) response['data'] = results return make_response(jsonify(response)), 200 else: # user is not legit, so the payload is an error message message = user_id response = {'message': message} return make_response(jsonify(response)), 401 except Exception as e: response = { 'message': 'Request / Input data is not valid. Error in ' + str(e) } return make_response(jsonify(response)), 500