Пример #1
0
def product_insert(request):
    # Check if Request is POST
    if request.method != 'POST':
        raise Exception('Http Method is not POST')

    # Get JSON Data from request
    json_data = json.loads(request.body)

    # Check existence of fields
    if ('code' or 'name' or 'price') not in json_data:
        return JsonResponse({"message": "some fields are not given"},
                            status=400)

    # Check value type of fields
    if (type(json_data['code']) != str) or (type(json_data['name']) != str) or (type(json_data['price']) != int) \
            or (len(json_data['code']) > 10) or (len(json_data['name']) > 100):
        return JsonResponse({"message": "value of fields have problem"},
                            status=400)

    # Check if code is unique
    if Product.objects.all().filter(code=json_data['code']).exists():
        return JsonResponse({"message": "code must be unique"}, status=400)

    # Check if price is positive
    if json_data['price'] < 0:
        return JsonResponse({"message": "price value must be greater than 0"},
                            status=400)

    # Create a product
    product = Product()
    product.code = json_data['code']
    product.name = json_data['name']
    product.price = json_data['price']

    # Check if inventory filed is given and is positive
    if 'inventory' not in json_data:
        product.inventory = 0
    else:
        if json_data['inventory'] < 0:
            return JsonResponse(
                {"message": "value of inventory must be greater than 0"},
                status=400)
        product.inventory = json_data['inventory']

    # Save product
    product.save()
    return JsonResponse({"id": product.id}, status=201)
Пример #2
0
def product_insert(request):
    if request.method != 'POST':
        return JsonResponse(data={"message": "Wrong method"}, status=400)
    try:
        data = json.loads(request.body.decode('utf-8'))
    except:
        return JsonResponse(data={"message": "Can't read request's body"}, status=400)
    product = Product(code=data['code'], name=data['name'], price=data['price'])
    if 'inventory' in data:
        product.inventory = data['inventory']
    try:
        product.save()
    except IntegrityError:
        return JsonResponse(data={"message": "Duplicate code (or other messages)"}, status=400)
    return JsonResponse(data={"id": product.id}, status=201)