def recognizerApi(request, id=0): if request.method == 'GET': if id != 0: recognized_object = RecognizedObject.objects.get(id=id) serializer_class = RecognizedObjectSerializer(recognized_object) return JsonResponse(serializer_class.data, safe=False) else: recognized_objects = RecognizedObject.objects.all() serializer_class = RecognizedObjectSerializer(recognized_objects, many=True) return JsonResponse(serializer_class.data, safe=False) elif request.method == 'POST': received_data = JSONParser.parse(JSONParser(), request) serializer_class = RecognizedObjectSerializer(data=received_data) if serializer_class.is_valid(): serializer_class.save() return JsonResponse("Added successfully", safe=False) return JsonResponse("Failed to add", safe=False) elif request.method == 'PUT': received_data = JSONParser.parse(JSONParser(), request) single_recognized_object = RecognizedObject.objects.get( id=received_data['id']) serializer_class = RecognizedObjectSerializer(single_recognized_object, data=received_data) if serializer_class.is_valid(): serializer_class.save() return JsonResponse("Updated successfully", safe=False) return JsonResponse("Failed to update", safe=False) elif request.method == 'DELETE': single_recognized_object = RecognizedObject.objects.get(id=id) single_recognized_object.delete() return JsonResponse("Deleted successfully", safe=False)
def timesheet_details(request,id): try: instance = Timesheet.objects.get(id=id) except Timesheet.DoesNotExist as e: return JsonResponse({"error":"Given timesheet object not found"},status=404) if request.method == "GET": serialized = TimesheetSerializer(instance) return JsonResponse(serialized.data) elif request.method == "POST": obj_parser=JSONParser() data = obj_parser.parse(request) serializer =TimesheetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201) return JsonResponse(serializer.errors,status=400) elif request.method == "PUT": obj_parser = JSONParser() data = obj_parser.parse(request) serializer = TimesheetSerializer(instance,data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) return JsonResponse(serializer.errors, status=400) elif request.method == "DELETE": instance.delete() return HttpResponse(status=204)
class UsersTest(TestCase): """Test querying of users and developers """ def setUp(self): logger.debug('UsersTest.setUp') self.parser = JSONParser() self.client = APIClient() dev_group = Group.objects.get(name='Developer') ply_group = Group.objects.get(name='Player') for i in range(3): user = User.objects.create(username='******'.format(i)) user.save() dev_group.user_set.add(user) for i in range(5): user = User.objects.create(username='******'.format(i)) user.save() ply_group.user_set.add(user) def testUserList(self): response = self.client.get( reverse('api:user-list', args=['v1']), None, format='json' ) self.assertEquals(response.status_code, 200) content = self.parser.parse(BytesIO(response.content)) got_users = {user['username'] for user in content['results']} has_users = {user.username for user in User.objects.all()} self.assertTrue(got_users == has_users) def testDeveloperList(self): response = self.client.get( reverse('api:developer-list', args=['v1']), None, format='json' ) self.assertEquals(response.status_code, 200) content = self.parser.parse(BytesIO(response.content)) got_users = {user['username'] for user in content['results']} has_users = {user.username for user in Group.objects.get(name='Developer').user_set.all() } self.assertTrue(got_users == has_users)
def test_float_strictness(self): parser = JSONParser() # Default to strict for value in ['Infinity', '-Infinity', 'NaN']: with pytest.raises(ParseError): parser.parse(self.bytes(value)) parser.strict = False assert parser.parse(self.bytes('Infinity')) == float('inf') assert parser.parse(self.bytes('-Infinity')) == float('-inf') assert math.isnan(parser.parse(self.bytes('NaN')))
def createUser(self, request): data = JSONParser.parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def post(self, request, format=None): data = JSONParser.parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def user_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: user_ = UserData.objects.get(pk=pk) print (user_) except user_.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = UserProfileSerializer(user_) return JSONResponse(serializer.data) elif request.method =='PUT': data = JSONParser.parse(request) serializer = UserProfileSerializer(user_, data = data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': user_.delete() return HttpResponse(status=204)
def snippet_list(request): # # List of all code snippets, or create a new snippet (Obviously) # if request.method == 'GET': # # snippets store all the objects corresponding to the Snippet Object snippets = Snippet.objects.all() # # Serializer serializers the data coming into snippets serializer = SnippetSerializer(snippets, many=True) # # returns the serializer data in the form of a JSON return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': # # If the data is getting posted by the user, we'd want to parse it # Obviously! data = JSONParser.parse(request) serializer = SnippetSerializer(data=data) # # How will it check if the serailizer is valid? if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) # Status 201 why? # # Incase the serializer isn't valid, return erros return JsonResponse(serializer.errors, status=400)
def post(self, request, format=json): print '----------------------------------------' data = JSONParser.parse(request) serializer = QuestionSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=200)
def UserViewSet(request, format=None): if request.method == "POST": json_parser = JSONParser() data = json_parser.parse(request) #check if phone number is provided #check id name is given #check if a valid email id is provided #check if date of birth is given #if all the above condition are valid check phone number exists in the myuser table or not #if phone number exists you are all ready registered please login or go to forget password # if phone number does not exists then send the otp and varification link to the email address and redirct the user to the varification page # Check if varification is success full # check if phone varification is ok # check if email varification is ok # if both the varification is ok then register the user and redirect to the login page # this will happen only when the phone otp and mail id varification will be done serializer = MyUserSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def post(self, request, format=json): print '----------------------------------------' data=JSONParser.parse(request) serializer=QuestionSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=200)
def item_detail(request, pk): """ show all item :param request: :method PUT | DELETE: :return Json-response: """ try: instance = get_object_or_404(Item.objects.all(), pk=pk) except Item.DoesNotExists as not_exist: return JsonResponse({"error": "Given item not found"}, status=400) if request.method == "GET": serializer = AllItemSerializer(instance) return JsonResponse(serializer.data) if request.method == "PUT": json_parser = JSONParser() data = json_parser.parse(request) serializer = AllItemSerializer(instance, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) return JsonResponse(serializer.errors, status=400) if request.method == "DELETE": instance.delete() return JsonResponse( {"success": "Propper item successfull deleted"}, status=204)
def poll_details(request, id): try: instance = Question.objects.get(id=id) print(instance) print(type(instance)) except Question.DoesnotExist as e: return JsonResponse({"error": "Given Question does not found"}, status=400) if request.method == 'GET': serializer = QuestionSerializer(instance) return JsonResponse(serializer.data) elif request.method == 'PUT': json_parser = JSONParser() data = json_parser.parse(request) serializer = QuestionSerializer(instance, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': instance.delete() return JsonResponse(status=204)
def view_api_serializer(request, pk=None): renderer = JSONRenderer() parser = JSONParser() if pk is None: if request.method == 'GET': books = ModelBookForRest.objects.all() serializer = SerializerBook(books, many=True) rendered = renderer.render(serializer.data) return HttpResponse(rendered, content_type='application/json') elif request.method == 'POST': data = parser.parse(request) unserializer = SerializerBook(data=data) if unserializer.is_valid(): unserializer.save() return HttpResponse(renderer.render(unserializer.data), content_type='application/json') else: return HttpResponse(renderer.render(unserializer.errors), content_type='application/json', status=status.HTTP_400_BAD_REQUEST) else: try: book = ModelBookForRest.objects.get(pk=pk) except ModelBookForRest.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = SerializerBook(book) rendered = JSONRenderer().render(serializer.data) return HttpResponse(rendered, content_type='application/json') if request.method == 'PUT': parsed = parser.parse(request) unserializer = SerializerBook(book, data=parsed) if unserializer.is_valid(): unserializer.save() rendered = renderer.render(unserializer.data) return HttpResponse(rendered, content_type='application/json') else: return HttpResponse(renderer.render(unserializer.errors), content_type='application/json', status=status.HTTP_400_BAD_REQUEST) if request.method == 'DELETE': unserializer = SerializerBook(book) json = unserializer.data rendered = renderer.render(json) book.delete() return HttpResponse(rendered, content_type='application/json')
def test_json_parse(self): json_bytes_for_new_toy = bytes(self.json_string_for_new_toy, encoding="UTF-8") stream_for_new_toy = BytesIO(json_bytes_for_new_toy) parser = JSONParser() parsed_new_toy = parser.parse(stream_for_new_toy) self.assertDictEqual(parsed_new_toy, json.loads(self.json_string_for_new_toy))
def post_profile(self, request, *args, **kwargs): json_parser = JSONParser() data = json_parser.parse(request) serializer = UserProfileSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) else: return JsonResponse(serializer.errors, status=400)
def post(self, request): json_parser = JSONParser() data = json_parser.parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_create_from_json(self): json_bytes_for_new_toy = bytes(self.json_string_for_new_toy, encoding="UTF-8") stream_for_new_toy = BytesIO(json_bytes_for_new_toy) parser = JSONParser() parsed_new_toy = parser.parse(stream_for_new_toy) new_toy_serializer = ToySerializer(data=parsed_new_toy) if new_toy_serializer.is_valid(): toy3 = new_toy_serializer.save() self.assertEqual(toy3.name, 'Clash Royale play set')
def post(self, request): data = JSONParser.parse(request) newForumUser = ForumUser() newUser = User() try: newForumUser.save() newUser.save() except: # i think this is the wrong order and except is in the failure case? return Response({"success": True}, status=400) return Response({"success": False}, status=201)
def post_subscription(self, request, *args, **kwargs): json_parser = JSONParser() data = json_parser.parse(request) print('ok') serializer = SubscriptionSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) else: return JsonResponse(serializer.errors, status=400)
def userAdd(request): try: data = JSONParser.parse(request.body) serializer = UserSerializer(data=data) serializer.validated_data if (request.method == "POST"): serializer.save() except: return HttpResponse(status=404)
def put(self, request, pk, format=None): snippet = self._snippet_exist(pk) if type(snippet) == HttpResponse.__class__: return snippet data = JSONParser.parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def add_contact(request): try: data = JSONParser.parse(request) friend = User.objects.get(email=data.get('friend')) contacts, _ = Contact.objects.get_or_create(user=request.user) contacts.contacts.add(friend) contacts.save() Room.objects.get_or_create(first_user=request.user, second_user=friend) return Response({'status': 'success', 'data': 'Added'}, status=200) except Exception as e: return Response({'status': 'error', 'message': str(e)}, status=400)
def postlist(request): if request.method == 'GET': queryset = Post.objects.all() serializer = PostSerializer(queryset, many=True) return Response(serializer.data) elif request.method == "POST": data = JSONParser.parse(request) serializer = PostSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.data, status=400)
def travel_list(request): travel = Travel.objects.all() serializer = TravelSerializer(travel, may=True) if request.method == 'GET': return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser.parse(request) serializer = TravelSerializer(data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) return JsonResponse(serializer.errors, status=400)
def idc_list(request, *args, **kwargs): if request.method == 'GET': queryset = Idcs.objects.all() serializer = IdcSerializer(queryset, many=True) content = JSONRenderer().render(serializer.data) return HttpResponse(content, content_type='application/json') elif request.method == 'POST': content = JSONParser.parse(request) serializer = IdcSerializer(data=content) if serializer.is_valid(): content = JSONRenderer().render(serializer.data) return HttpResponse(content, content_type='application/json')
def candidate_list(request): if request.method == 'GET': candidates = Candidate.objects.all() serializer = CandidateSerializer(candidates, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser.parse(request) serializer = CandidateSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.data, status=400)
def snippet_list(request): if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many = True) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser.parse(request) serializer = SnippetSerializer(data = data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status = 201) return JSONResponse(serializer.errors,status = 400)
def review_list(request): #review = Review.get(pk=pk) if request.method == 'GET': reviews = Review.objects.all() serializer = ReviewSerializer(reviews, many = True) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser.parse(request) serializer = CourseSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def post_list(request): if request.method == "GET": posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return JSONResponse(serializer.data) elif request.method == "POST": data = JSONParser.parse(request) serializer = PostSerializer(data=data) if serializer.is_valid(): serializer.save(author=request.user) return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def article_list(request): if request.method == 'GET': article = Article.objects.all() serializer = ArticleSerializer(article,many=True) return JsonResponse(serializer.data,safe=False) elif request.method == 'POST': data = JSONParser.parse(request) serializer = ArticleSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors,status=400)
def additioninfo_list(request): #info = AdditionInfo.get(pk=pk) if request.method == 'GET': infos = AdditionInfo.objects.all() serializer = AdditionInfoSerializer(infos, many = True) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser.parse(request) serializer = AdditionInfoSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def tweets(request): if request.method == 'GET': tweets_list = Tweet.objects.all()[:10] serializer = TweetSerializer(tweets_list, many = True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser.parse(request) serializer = TweetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def timesheet_api(request): if request.method == "GET": q=Timesheet.objects.all() serialized = TimesheetSerializer(q,many=True) return JsonResponse(serialized.data,safe=False) elif request.method == "POST": obj_parser=JSONParser() data = obj_parser.parse(request) serializer =TimesheetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201) return JsonResponse(serializer.errors,status=400)
def application_list(request): #applications = Application.get(pk=pk) if request.method == 'GET': messages = Application.objects.all() serializer = ApplicationSerializer(messages, many = True) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser.parse(request) serializer = ApplicationSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def post_list(request): if request.method == 'GET': queryset = Post.objects.all() serializer = PostSerializer(queryset, many=True) return JsonResponse(serializer.data, safe=False) if request.method == 'POST': data = JSONParser.parse(request) serializer = PostSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def userInPartyAPI(request): if request.method == 'GET': partys_of_user = UserInParty.objects.all().filter(user = request.user) serializer = UserInPartySerializer(partys_of_user, many = True) return JSONResponse(serializer.data) elif reuqest.method == 'POST': raw_data = JSONParser.parse(request) serializer = UserInPartySerializer(data = raw_data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data , status = 201 ) return JSONResponse(serializer.errors, status = 400)
class NoiseBoxParser(BaseParser): # by the way, MIME type registration is free: http://www.iana.org/form/media-types media_type = 'application/vnd.qabel.noisebox+json' upper_media_type = 'application/json' def __init__(self): super().__init__() self.upper_parser = JSONParser() def parse(self, stream, media_type=None, parser_context=None): box = stream.read() key_pair = KeyPair(settings.SERVER_PRIVATE_KEY) try: public_key, contents = decrypt_box(key_pair, box) except NoiseError as noise_error: logger.exception('decrypt_box() exception, public_key=' + key_pair.public_key.hex()) raise ParseError from noise_error return public_key, self.upper_parser.parse(io.BytesIO(contents.encode()), self.upper_media_type)
def product_details(request, pk): try: product = Product.objects.get(pk=pk) except Product.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ProductSerializer(product) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser.parse(request) serializer = ProductSerializer(product, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': Product.delete() return HttpResponse(status=204)
def emp_visa_delete(request,slno): try: empvisa = EmpVisa.objects.get(slno=slno) except EmpVisa.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = EmpVisaSerializer(empvisa) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser.parse(request) serializer = EmpVisaSerializer(empvisa, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': empvisa.delete() return HttpResponse(status=204)
def emp_experience_delete(request, slno): try: empexp = EmployeeExperience.objects.get(slno=slno) #print 'hi hari ' . empexp except EmployeeExperience.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = EmpExperienceSerializer(empexp) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser.parse(request) serializer = EmpExperienceSerializer(empexp, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': empexp.delete() return HttpResponse(status=204)