Ejemplo n.º 1
0
    def test_parse(self):
        """ Make sure the `QueryDict` works OK """
        parser = FormParser()

        stream = io.StringIO(self.string)
        data = parser.parse(stream)

        assert Form(data).is_valid() is True
Ejemplo n.º 2
0
    def test_parse(self):
        """ Make sure the `QueryDict` works OK """
        parser = FormParser()

        stream = StringIO(self.string)
        data = parser.parse(stream)

        self.assertEqual(Form(data).is_valid(), True)
Ejemplo n.º 3
0
    def test_parse(self):
        """ Make sure the `QueryDict` works OK """
        parser = FormParser()

        stream = StringIO(self.string)
        data = parser.parse(stream)

        self.assertEqual(Form(data).is_valid(), True)
Ejemplo n.º 4
0
 def post(self, request, *kwargs):
     parser = FormParser()
     query_dict = parser.parse(request)
     contact = Contact.objects.filter(number=query_dict["From"]).first()
     if not contact:
         contact = Contact(number=query_dict["From"])
         contact.save()
     if contact.number != os.environ["TWILIO_NUMBER"]:
         sender = "them"
     else:
         sender = "you"
     text = Text(sender=sender, contact=contact, body=query_dict["Body"])
     text.save()
     return HttpResponse()
    def select_parser(self, request, parsers):
        if request.method == 'POST':
            parsers = [FormParser(), MultiPartParser()]

        return super(ConditionalContentNegotiation, self).select_parser(
            request, parsers
        )
Ejemplo n.º 6
0
def items_view(request):
    if request.method == 'GET':
        items = Item.objects.all()
        serializer = ItemSerializer(items, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = FormParser().parse(request)
        new_data = data.copy()
        #new_data['item_size'] = json.loads(data['item_size'])
        print(new_data)
        serializer = ItemSerializer(data=new_data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
Ejemplo n.º 7
0
 def test_form_POST_unicode(self):
     """
     JSON POST via default web interface with unicode data
     """
     # Note: environ and other variables here have simplified content compared to real Request
     CONTENT = b'_content_type=application%2Fjson&_content=%7B%22request%22%3A+4%2C+%22firm%22%3A+1%2C+%22text%22%3A+%22%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82%21%22%7D'
     environ = {
         'REQUEST_METHOD': 'POST',
         'CONTENT_TYPE': 'application/x-www-form-urlencoded',
         'CONTENT_LENGTH': len(CONTENT),
         'wsgi.input': BytesIO(CONTENT),
     }
     wsgi_request = WSGIRequest(environ=environ)
     wsgi_request._load_post_and_files()
     parsers = (JSONParser(), FormParser(), MultiPartParser())
     parser_context = {
         'encoding': 'utf-8',
         'kwargs': {},
         'args': (),
     }
     request = Request(wsgi_request,
                       parsers=parsers,
                       parser_context=parser_context)
     method = request.method
     self.assertEqual(method, 'POST')
     self.assertEqual(request._content_type, 'application/json')
     self.assertEqual(
         request._stream.getvalue(),
         b'{"request": 4, "firm": 1, "text": "\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!"}'
     )
     self.assertEqual(request._data, Empty)
     self.assertEqual(request._files, Empty)
 def test_post_accessed_in_put_method(self):
     django_request = self.factory.put('/', {'foo': 'bar'})
     request = Request(django_request,
                       parsers=[FormParser(),
                                MultiPartParser()])
     django_request.POST
     assert request.POST == {'foo': ['bar']}
     assert request.data == {'foo': ['bar']}
Ejemplo n.º 9
0
 def test_request_DATA_with_form_content(self):
     """
     Ensure request.DATA returns content for POST request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.post('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.DATA.items()), list(data.items()))
Ejemplo n.º 10
0
 def test_request_POST_with_form_content(self):
     """
     Ensure request.POST returns content for POST request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.post('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     assert list(request.POST.items()) == list(data.items())
Ejemplo n.º 11
0
 def test_standard_behaviour_determines_form_content_PUT(self):
     """
     Ensure request.data returns content for PUT request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.put('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     assert list(request.data.items()) == list(data.items())
Ejemplo n.º 12
0
def add_guide(request, format=None):
	"""
	Create a new Guide
	"""
	# if request.method == 'GET':
	#     customers = Launch_Customer.objects.all()
	#     serializer = Launch_Customer_Serializer(customers, many=True)
	#     return JSONResponse(serializer.data)

	if request.method == 'POST':
		data = FormParser().parse(request)
		# print(data)<QueryDict: {u'website': [u'mysite.com'], u'phone_number': [u'3172097889'], u'first_name': [u'nick'], u'last_name': [u'nick2'], u'sub_launch': [u'True'], u'email': [u'*****@*****.**']}>
		serializer = serializers.Guide_Serializer(data=data)
		if serializer.is_valid():
			serializer.save()
			#run agile crm script here
			tags = ["launch-leadform",]

			if(data["sub_launch"]):
				tags.append("launch-participateInterest")
			else:
				tags.append("launch-updates")
			contact_data = {
				"lead_score": "150",
				"tags": tags,
				"properties": [
					{
						"type": "SYSTEM",
						"name": "first_name",
						"value": data["first_name"],
					},
					{
						"type": "SYSTEM",
						"name": "last_name",
						"value": data["last_name"],
					},
					{
						"type": "SYSTEM",
						"name": "email",
						"subtype": "work",
						"value": data["email"],
					},
					{
						"type": "SYSTEM",
						"name": "phone",
						"value": data["phone_number"],
					},
					{
						"type": "CUSTOM",
						"name": "Website",
						"value": data["website"],
					},
				]
			}
			agileCRM("contacts","POST", contact_data,"application/json")
			return JSONResponse(serializer.data, status=201)
			# return redirect(request.META.get('HTTP_REFERER'))
		return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 13
0
 def test_request_POST_with_form_content_JSONField(self):
     data = b'-----------------------------20775962551482475149231161538\r\nContent-Disposition: form-data; name="json_field"\r\n\r\n{"a": true}\r\n-----------------------------20775962551482475149231161538--\r\n'
     content_type = 'multipart/form-data; boundary=---------------------------20775962551482475149231161538'
     wsgi_request = self.factory.generic('POST', '/', data, content_type)
     request = Request(wsgi_request)
     request.parsers = (FormParser(), MultiPartParser())
     serializer = self.Serializer(data=request.data)
     assert serializer.is_valid(raise_exception=True) == True
     assert dict(serializer.data)['json_field'] == {'a': True}
Ejemplo n.º 14
0
 def test_request_POST_with_files(self):
     """
     Ensure request.POST returns no content for POST request with file content.
     """
     upload = SimpleUploadedFile("file.txt", b"file_content")
     request = Request(factory.post('/', {'upload': upload}))
     request.parsers = (FormParser(), MultiPartParser())
     assert list(request.POST.keys()) == []
     assert list(request.FILES.keys()) == ['upload']
Ejemplo n.º 15
0
 def testupload(self):
     """
     Ensure request.POST returns no content for POST request with file content.
     """
     factory = APIRequestFactory()
     upload = SimpleUploadedFile("file.txt", b"file_content")
     request = Request(factory.post('App/upload', {'upload': upload}))
     request.parsers = (FormParser(), MultiPartParser())
     assert list(request.POST) == []
     assert list(request.FILES) == ['upload']
 def test_request_read_before_parsing(self):
     django_request = self.factory.put('/', {'foo': 'bar'})
     request = Request(django_request,
                       parsers=[FormParser(),
                                MultiPartParser()])
     django_request.read()
     with pytest.raises(RawPostDataException):
         request.POST
     with pytest.raises(RawPostDataException):
         request.POST
         request.data
Ejemplo n.º 17
0
def items_detail(request, id):
    try:
        item = Item.objects.get(pk=id)
    except Item.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = ItemSerializer(item)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = FormParser().parse(request)
        new_data = data.copy()
        #new_data['item_size'] = json.loads(data['item_size'])
        serializer = ItemSerializer(data=new_data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        item.delete()
        return HttpResponse(status=204)
Ejemplo n.º 18
0
def contact(request):
	if request.method == 'POST':
		data = FormParser().parse(request)
		serializer = serializers.Contact_Serializer(data=data)
		if serializer.is_valid():
			from django.core.mail import send_mail
			msg = {}
			msg['Subject'] = data["message"][:20]
			msg['From'] = '*****@*****.**'
			msg['To'] = ["*****@*****.**","*****@*****.**"]
			linebreak = "\n"
			msg["body"] = data["name"] + linebreak + data["email"] + linebreak + data["phone"] + linebreak + data["message"]
			send_mail(msg['Subject'],msg['body'],msg['From'], msg['To'],fail_silently=False)
			return JSONResponse(serializer.data, status=201)
		return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 19
0
def update_bottle_level(request, pk):

    try:
        bottle = Bottles.objects.get(pk=pk)
        update_bottle_stats(request, pk)
    except Bottles.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == "POST":
        data = FormParser().parse(request)
        serializer = BottleSerializer(bottle, data=data)
        if serializer.is_valid():
            serializer.save()
            #return JsonResponse(serializer.data)
            return redirect("get_patients_list")
        return JsonResponse(serializer.errors, status=400)
Ejemplo n.º 20
0
    def test_standard_behaviour_determines_form_content_PUT(self):
        """
        Ensure request.DATA returns content for PUT request with form content.
        """
        data = {'qwerty': 'uiop'}

        from django import VERSION

        if VERSION >= (1, 5):
            from django.test.client import MULTIPART_CONTENT, BOUNDARY, encode_multipart
            request = Request(factory.put('/', encode_multipart(BOUNDARY, data),
                                  content_type=MULTIPART_CONTENT))
        else:
            request = Request(factory.put('/', data))

        request.parsers = (FormParser(), MultiPartParser())
        self.assertEqual(list(request.DATA.items()), list(data.items()))
Ejemplo n.º 21
0
def create_user(request):
    if request.method == 'GET':
        serializer = UserSerializerSerializer()

        return render(request, 'registration/create_user.html',
                      {'serializer': serializer})

    elif request.method == 'POST':
        data = FormParser().parse(request)
        serializer = UserSerializerSerializer(data=data)
        if serializer.is_valid():
            try:
                serializer.save()
                messages.success(request,
                                 'User created successfully, please log in')
                return redirect('/account/login/')
            except IntegrityError as e:
                error = ['Username already taken. Please try again']
                return render_error(request, serializer, error)
        else:
            return render_error(request, serializer, serializer.errors)
Ejemplo n.º 22
0
 def to_internal_value(self, form_data):
     stream = BytesIO(form_data)
     data = FormParser().parse(stream)
     return super().to_internal_value(data)
Ejemplo n.º 23
0
    def check_request_body_for_id(self, request):
        """
        An Update (PUT/PATCH) request must contain the ID of the object
        to be updated. Later, we can allow Update of multiple objects, or the
        entire queryset.
        """
        id = None
        try:
            data = request.data
            id = data[self.lookup_field]
        except (AttributeError, MultiValueDictKeyError):
            try:
                if "application/json" in request.META['CONTENT_TYPE']:
                    str_data = request.body.decode('utf-8')
                    # Make this into a properly-formatted JSON string.
                    id = self.id_from_json(str_data)

                elif "multipart/form-data" in request.META['CONTENT_TYPE']:
                    if self.lookup_field is 'id' or self.lookup_field is 'pk':
                        lookup_field_string = "(?:id|pk)"
                    else:
                        lookup_field_string = self.lookup_field
                    expression = re.compile(
                        'name="{lookup_field}"\r\n\r\n([^\r]+)\r\n'.format(
                            lookup_field=lookup_field_string))

                    id_set = False
                    iterator = expression.finditer(
                        request.body.decode('utf-8'))
                    for match in iterator:
                        id = match.groups()[0]
                        id_set = True

                    if not id_set:
                        id = self.id_from_json(request.body.decode('utf-8'))
                elif "application/x-www-form-urlencoded" in request.META[
                        'CONTENT_TYPE']:
                    parser = FormParser()
                    stream = StringIO(request.body.decode('utf-8'))
                    data = parser.parse(stream)

                    if self.lookup_field is 'id' or self.lookup_field is 'pk':
                        if 'id' in data:
                            id = data['id']
                        elif 'pk' in data:
                            id = data['pk']
                    else:
                        id = data[self.lookup_field]

            except AttributeError:
                return False
            except KeyError:
                logger.exception("Missing lookup field {} on view {} ".format(
                    self.lookup_field, self))
                raise CRUDException(
                    "Missing {lookup_field}".format(
                        lookup_field=self.lookup_field), 400)
            except ValueError:
                logger.exception("CRUDFilters received improper json.")
                raise CRUDException("Improper json", 400)
        try:
            if id is None:
                logger.exception("Missing lookup field {} on view {} ".format(
                    self.lookup_field, self))
                raise CRUDException(
                    "Missing {lookup_field}".format(
                        lookup_field=self.lookup_field), 400)

            self.obj_id = id

            return self.obj_id
        except KeyError:
            logger.exception(
                "Update Operations must include {} in the request body.".
                format(self.lookup_field))
            raise CRUDException("Update operations must include " +
                                self.lookup_field + " in the request body.",
                                status_code=400)
Ejemplo n.º 24
0
    def check_request_body_for_id(self, request):
        """
        An Update (PUT/PATCH) request must contain the ID of the object
        to be updated. Later, we can allow Update of multiple objects, or the
        entire queryset.
        """
        id = None
        try:
            data = request.data
            id = data[self.lookup_field]
        except (AttributeError, MultiValueDictKeyError):
            try:
                if "application/json" in request.META['CONTENT_TYPE']:
                    str_data = request.body.decode('utf-8')
                    # Make this into a properly-formatted JSON string.
                    id = self.id_from_json(str_data)

                elif "multipart/form-data" in request.META['CONTENT_TYPE']:
                    if self.lookup_field is 'id' or self.lookup_field is 'pk':
                        lookup_field_string = "(?:id|pk)"
                    else:
                        lookup_field_string = self.lookup_field
                    expression = re.compile('name="{lookup_field}"\r\n\r\n([^\r]+)\r\n'.format(lookup_field=lookup_field_string))

                    id_set = False
                    iterator = expression.finditer(request.body.decode('utf-8'))
                    for match in iterator:
                        id = match.groups()[0]
                        id_set = True

                    if not id_set:
                        id = self.id_from_json(request.body.decode('utf-8'))
                elif "application/x-www-form-urlencoded" in request.META['CONTENT_TYPE']:
                    parser = FormParser()
                    stream = StringIO(request.body.decode('utf-8'))
                    data = parser.parse(stream)

                    if self.lookup_field is 'id' or self.lookup_field is 'pk':
                        if 'id' in data:
                            id = data['id']
                        elif 'pk' in data:
                            id = data['pk']
                    else:
                        id = data[self.lookup_field]

            except AttributeError:
                return False
            except KeyError:
                logger.exception("Missing lookup field {} on view {} ".format(self.lookup_field, self))
                raise CRUDException("Missing {lookup_field}".format(lookup_field=self.lookup_field), 400)
            except ValueError:
                logger.exception("CRUDFilters received improper json.")
                raise CRUDException("Improper json", 400)
        try:
            if id is None:
                logger.exception("Missing lookup field {} on view {} ".format(self.lookup_field, self))
                raise CRUDException("Missing {lookup_field}".format(lookup_field=self.lookup_field), 400)

            self.obj_id = id

            return self.obj_id
        except KeyError:
            logger.exception("Update Operations must include {} in the request body.".format(self.lookup_field))
            raise CRUDException("Update operations must include " + self.lookup_field + " in the request body.", status_code=400)