def patch(self, order_uuid):
""" Modify a specific order. """
res = request.get_json(force=True)
errors = Order.validate_input(res, partial=True)
if errors:
return errors, BAD_REQUEST
data = res['data']['relationships']
req_items = data.get('items', {})
req_address = data.get('delivery_address')
with database.atomic():
try:
order = Order.get(uuid=str(order_uuid))
except Order.DoesNotExist:
abort(NOT_FOUND)
address = None
if req_address:
try:
address = Address.get(Address.uuid == req_address['data']['id'])
except Address.DoesNotExist:
abort(BAD_REQUEST)
order.delivery_address = address
# get the user from the flask.g global object registered inside the
# auth.py::verify() function, called by @auth.login_required decorator
# and match it against the found user.
# This is to prevent uses from modify other users' order.
if auth.current_user != order.user and auth.current_user.admin is False:
return ({'message': "You can't delete another user's order"},
UNAUTHORIZED)
# Generate the dict of {<Item>: <int:quantity>} to call Order.update_items
items_uuids = [e['id'] for e in req_items.get('data', [])]
items = list(Item.select().where(Item.uuid << items_uuids))
if len(items) != len(items_uuids):
abort(BAD_REQUEST)
items_to_add = {
item: req_item['quantity']
for item in items for req_item in req_items.get('data', [])
if str(item.uuid) == req_item['id']
}
try:
order.update_items(items_to_add, new_address=address)
except InsufficientAvailabilityException:
abort(BAD_REQUEST)
return generate_response(order.json(), OK)
评论列表
文章目录