Advertisement
Guest User

Untitled

a guest
Dec 17th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. class AddItemSchema(Schema):  # схема для создания товара
  2.     title = fields.Str(validate=Length(1, 64), required=True)
  3.     description = fields.Str(validate=Length(1, 1024), required=True)
  4.     price = fields.Int(validate=Range(1, 1000000), required=True)
  5.  
  6.  
  7. @method_decorator(csrf_exempt, name='dispatch')
  8. class AddItemView(View):
  9.     """View для создания товара."""
  10.  
  11.     def post(self, request):
  12.         try:
  13.             document = json.loads(request.body)
  14.             schema = AddItemSchema(strict=True)
  15.             data = schema.load(document)  # получаем словарь с данными
  16.             new_item = Item.objects.create(**data.data)   # создаем объект в бд
  17.             new_item.save()
  18.             return JsonResponse({'id': new_item.id}, status=201)  
  19.         except json.JSONDecodeError:
  20.             return JsonResponse({'errors': 'Invalid JSON'}, status=400)
  21.         except MarshErr as exc:
  22.             return JsonResponse({'errors': exc.messages}, status=400)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement