Python rest_framework.request.Request() Examples

The following are 30 code examples of rest_framework.request.Request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.request , or try the search function .
Example #1
Source File: customer.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def put_customer(account: str, request: Request) -> Response:
    if account != request.data.get("account"):
        return render_error_response(
            "The account specified does not match authorization token", status_code=403
        )
    try:
        rci.put(
            {
                "account": request.data.get("account"),
                "memo": request.data.get("memo"),
                "memo_type": request.data.get("memo_type"),
                **extract_sep9_fields(request.data),
            }
        )
    except ValueError as e:
        return render_error_response(str(e), status_code=400)
    else:
        return Response({}, status=202) 
Example #2
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 6 votes vote down vote up
def delete_scan_list(request: Request, token: str) -> Response:
    """Update an existing list."""
    # TODO: Access control (Or is token sufficient)?
    try:
        scan_list = ScanList.objects.get(token=token)

        # all related objects CASCADE automatically.
        scan_list.delete()

        return Response({
            'type': 'success',
            'message': 'ok',
        })
    except KeyError as e:
        raise ParseError
    except ScanList.DoesNotExist:
        raise NotFound


# TODO: Why POST?
# TODO: Add a filter option to get_lists and get rid of this search method 
Example #3
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 6 votes vote down vote up
def save_scan_list(request: Request) -> Response:
    """Save a new list."""
    try:
        with transaction.atomic():
            scan_list = ScanList.objects.create(
                name=request.data['listname'],
                description=request.data['description'],
                private=bool(request.data['isprivate']),
                user=request.user if request.user.is_authenticated else None)

            scan_list.save_tags(request.data['tags'])

            # save columns
            scan_list.save_columns(request.data['columns'])

            return Response({
                'list_id': scan_list.pk,
                'token': scan_list.token
            }, status=201)
    except KeyError:
        raise ParseError 
Example #4
Source File: middlewares.py    From dingtalk-django-example with GNU General Public License v3.0 6 votes vote down vote up
def process_response(cls, request, response):
        if request.META.get('HTTP_ORIGIN'):
            response['Access-Control-Allow-Origin'] = request.META['HTTP_ORIGIN']
            response['Access-Control-Allow-Credentials'] = 'true'
        # setattr(response, 'Access-Control-Allow-Origin', "*")
        response['X-Frame-Options'] = 'ALLOW-FROM *.007.pub'

        from rest_framework.request import Request

        try:
            if isinstance(request, Request):
                request = request._request
            end = time.time()
            exectime = end - request.start

            logger.info("stat exectime: time: %fs  path:%s  querystring:%s" % (
                         exectime, request.path, request.META['QUERY_STRING']))

        except Exception as e:
            logging.error(e)

        return response 
Example #5
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ocpmemview_success(self, mock_handler):
        """Test OCP memory view report."""
        mock_handler.return_value.execute_query.return_value = self.report_ocp_mem
        params = {
            "group_by[node]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        if not django_request.META.get("HTTP_HOST"):
            django_request.META["HTTP_HOST"] = "testhost"

        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = OCPMemoryView().get(request)
        self.assertIsInstance(response, Response)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example #6
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ocpcpuview_success(self, mock_handler):
        """Test OCP cpu view report."""
        mock_handler.return_value.execute_query.return_value = self.report_ocp_cpu
        params = {
            "group_by[node]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        if not django_request.META.get("HTTP_HOST"):
            django_request.META["HTTP_HOST"] = "testhost"

        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = OCPCpuView().get(request)
        self.assertIsInstance(response, Response)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example #7
Source File: tests_views.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_costview_with_units_success(self, mock_handler):
        """Test unit conversion succeeds in AzureCostView."""
        mock_handler.return_value.execute_query.return_value = self.report
        params = {
            "group_by[subscription_guid]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
            "units": "byte",
            "SERVER_NAME": "",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = AzureCostView().get(request)
        self.assertIsInstance(response, Response) 
Example #8
Source File: user.py    From mangaki with GNU Affero General Public License v3.0 6 votes vote down vote up
def update_user_profile(request: Request):
    """
    Patch the profile settings of self or a given user when permitted.
    """
    if request.method == 'PUT':
        profile_serializer = UserProfileSettingsSerializer(request.user.profile,
                                                           data=request.data,
                                                           partial=True)

        profile_serializer.is_valid(raise_exception=True)
        profile = profile_serializer.save(user=request.user)
        return Response(UserProfileSettingsSerializer(profile).data)
    else:
        return Response(
            UserProfileSettingsSerializer(request.user.profile).data
        ) 
Example #9
Source File: views.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def confirm_email(request: Request) -> Response:
    if not (request.GET.get("token") and request.GET.get("email")):
        return render_error_response(
            "email and token arguments required.", content_type="text/html"
        )

    try:
        account = PolarisStellarAccount.objects.get(
            user__email=request.GET.get("email"),
            confirmation_token=request.GET.get("token"),
        )
    except PolarisStellarAccount.DoesNotExist:
        return render_error_response(
            "User with email and token does not exist", content_type="text/html"
        )

    account.confirmed = True
    account.save()

    return Response(template_name="email_confirmed.html") 
Example #10
Source File: transactions.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def interactive_url(
        self,
        request: Request,
        transaction: Transaction,
        asset: Asset,
        amount: Optional[Decimal],
        callback: Optional[str],
    ) -> Optional[str]:
        """
        Override this function to provide the wallet a non-Polaris endpoint
        to begin the interactive flow. If the `amount` or `callback` arguments
        are not ``None``, make sure you include them in the URL returned.

        :return: a URL to be used as the entry point for the interactive
            deposit flow
        """
        pass 
Example #11
Source File: deposit.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def complete_interactive_deposit(request: Request) -> Response:
    """
    GET /transactions/deposit/interactive/complete

    Updates the transaction status to pending_user_transfer_start and
    redirects to GET /more_info. A `callback` can be passed in the URL
    to be used by the more_info template javascript.
    """
    transaction_id = request.GET.get("transaction_id")
    callback = request.GET.get("callback")
    if not transaction_id:
        return render_error_response(
            _("Missing id parameter in URL"), content_type="text/html"
        )
    Transaction.objects.filter(id=transaction_id).update(
        status=Transaction.STATUS.pending_user_transfer_start
    )
    logger.info(f"Hands-off interactive flow complete for transaction {transaction_id}")
    url, args = (
        reverse("more_info"),
        urlencode({"id": transaction_id, "callback": callback}),
    )
    return redirect(f"{url}?{args}") 
Example #12
Source File: views.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def _generate_jwt(request: Request, envelope_xdr: str) -> str:
        """
        Generates the JSON web token from the challenge transaction XDR.

        See: https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md#token
        """
        issued_at = time.time()
        transaction_envelope, source_account = read_challenge_transaction(
            envelope_xdr, settings.SIGNING_KEY, settings.STELLAR_NETWORK_PASSPHRASE
        )
        logger.info(
            f"Challenge verified, generating SEP-10 token for account {source_account}"
        )
        hash_hex = binascii.hexlify(transaction_envelope.hash()).decode()
        jwt_dict = {
            "iss": os.path.join(settings.HOST_URL, "auth"),
            "sub": source_account,
            "iat": issued_at,
            "exp": issued_at + 24 * 60 * 60,
            "jti": hash_hex,
        }
        encoded_jwt = jwt.encode(jwt_dict, settings.SERVER_JWT_KEY, algorithm="HS256")
        return encoded_jwt.decode("ascii") 
Example #13
Source File: utils.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def check_authentication(content_type: str = "text/html") -> Callable:
    """
    Authentication decorator for POST /interactive endoints
    """

    def decorator(view) -> Callable:
        def wrapper(request: Request, *args, **kwargs) -> Response:
            try:
                check_authentication_helper(request)
            except ValueError as e:
                return render_error_response(
                    str(e), content_type=content_type, status_code=403
                )
            else:
                return view(request)

        return wrapper

    return decorator 
Example #14
Source File: utils.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def authenticate_session(content_type: str = "text/html") -> Callable:
    """
    Authentication decorator for GET /interactive endpoints
    """

    def decorator(view) -> Callable:
        def wrapper(request: Request, *args, **kwargs) -> Response:
            try:
                authenticate_session_helper(request)
            except ValueError as e:
                return render_error_response(
                    str(e), content_type=content_type, status_code=403
                )
            else:
                return view(request)

        return wrapper

    return decorator 
Example #15
Source File: utils.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def check_authentication_helper(r: Request):
    """
    Checks that the session associated with the request is authenticated
    """
    # Don't authenticate in local mode, since session cookies will not be
    # included in request/response headers without HTTPS
    if settings.LOCAL_MODE:
        return

    if not r.session.get("authenticated"):
        raise ValueError(_("Session is not authenticated"))

    transaction_qs = Transaction.objects.filter(
        id=r.GET.get("transaction_id"), stellar_account=r.session.get("account")
    )
    if not transaction_qs.exists():
        raise ValueError(_("Transaction for account not found")) 
Example #16
Source File: utils.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def generate_interactive_jwt(
    request: Request, transaction_id: str, account: str
) -> str:
    """
    Generates a 30-second JWT for the client to use in the GET URL for
    the interactive flow.
    """
    issued_at = time.time()
    payload = {
        "iss": request.build_absolute_uri(request.path),
        "iat": issued_at,
        "exp": issued_at + 30,
        "sub": account,
        "jti": transaction_id,
    }
    encoded_jwt = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256")
    return encoded_jwt.decode("ascii") 
Example #17
Source File: test_api_view_serializer_class_getter.py    From django-rest-registration with MIT License 6 votes vote down vote up
def test_browsable_renderer_put_render(input_put_view, decorator):
    """
    Test, that PUT method works with BrowsableAPIRenderer
    This was not working in the past, because of `_get_serializer`
    didn't allow `instance parameter.
    """
    data = {'blah': 'blah'}
    method = 'PUT'
    request = rest_request.Request(APIRequestFactory().get('blah'))
    output_view = decorator(input_put_view)
    wrapper_cls = _get_view_class(output_view)
    test_view_instance = wrapper_cls()

    renderer = renderers.BrowsableAPIRenderer()
    renderer.accepted_media_type = None
    renderer.renderer_context = {}
    response = renderer.get_raw_data_form(
        data, test_view_instance, method, request,
    )
    assert response.data == {} 
Example #18
Source File: test_pagination.py    From drf_tweaks with MIT License 5 votes vote down vote up
def test_middle_offset(self):
        request = Request(factory.get('/', {'limit': 5, 'offset': 10}))
        queryset = self.paginate_queryset(request)
        content = self.get_paginated_content(queryset)
        self.assertEqual(queryset, [11, 12, 13, 14, 15])
        self.assertEqual(content, {
            'results': [11, 12, 13, 14, 15],
            'previous': 'http://testserver/?limit=5&offset=5',
            'next': 'http://testserver/?limit=5&offset=15'
        }) 
Example #19
Source File: test_serializers.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_forward_relationship_not_loaded_when_not_included(self):
        to_representation_method = 'example.serializers.BlogSerializer.to_representation'
        with mock.patch(to_representation_method) as mocked_serializer:
            class EntrySerializer(ModelSerializer):
                blog = BlogSerializer()

                class Meta:
                    model = Entry
                    fields = '__all__'

            request_without_includes = Request(request_factory.get('/'))
            serializer = EntrySerializer(context={'request': request_without_includes})
            serializer.to_representation(self.entry)

            mocked_serializer.assert_not_called() 
Example #20
Source File: test_views.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_view(self, kwargs):
        factory = APIRequestFactory()
        request = Request(factory.get('', content_type='application/vnd.api+json'))
        return AuthorViewSet(request=request, kwargs=kwargs) 
Example #21
Source File: customer.py    From django-polaris with Apache License 2.0 5 votes vote down vote up
def delete_customer(account_from_auth: str, request: Request, account: str) -> Response:
    if account_from_auth != account:
        return render_error_response("account not found", status_code=404)
    try:
        rci.delete(account)
    except ValueError:
        return render_error_response("account not found", status_code=404)
    else:
        return Response({}, status=200) 
Example #22
Source File: test_rest.py    From scale with Apache License 2.0 5 votes vote down vote up
def test_check_bad_param_type(self):
        """Tests checking a white-list of invalid parameters allowed to be updated during a POST."""
        request = MagicMock(Request)
        request.data = QueryDict('', mutable=True)
        request.data.update({
            'test1': 'value1',
            'test2': 'value2',
        })
        self.assertRaises(AssertionError, rest_util.check_update, request, 'test1') 
Example #23
Source File: test_rest.py    From scale with Apache License 2.0 5 votes vote down vote up
def test_check_update(self):
        """Tests checking a white-list of parameters allowed to be updated during a POST."""
        request = MagicMock(Request)
        request.data = QueryDict('', mutable=True)
        request.data.update({
            'test': 'value1',
        })
        self.assertTrue(rest_util.check_update(request, ['test'])) 
Example #24
Source File: test_serializers.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_forward_relationship_optimization_correct_representation(self):
        class EntrySerializer(ModelSerializer):
            blog = BlogSerializer()

            class Meta:
                model = Entry
                fields = '__all__'

        request_without_includes = Request(request_factory.get('/'))
        serializer = EntrySerializer(context={'request': request_without_includes})
        result = serializer.to_representation(self.entry)

        # Remove non deterministic fields
        result.pop('created_at')
        result.pop('modified_at')

        expected = dict(
            [
                ('id', 1),
                ('blog', dict([('type', 'blogs'), ('id', 1)])),
                ('headline', 'headline'),
                ('body_text', 'body_text'),
                ('pub_date', DateField().to_representation(self.entry.pub_date)),
                ('mod_date', DateField().to_representation(self.entry.mod_date)),
                ('n_comments', 0),
                ('n_pingbacks', 0),
                ('rating', 3),
                ('authors',
                    [
                        dict([('type', 'authors'), ('id', '1')]),
                        dict([('type', 'authors'), ('id', '2')]),
                        dict([('type', 'authors'), ('id', '3')]),
                        dict([('type', 'authors'), ('id', '4')]),
                        dict([('type', 'authors'), ('id', '5')])])])

        self.assertDictEqual(expected, result) 
Example #25
Source File: test_serializers.py    From drf_tweaks with MIT License 5 votes vote down vote up
def test_control_over_serialization_fields(self):
        # w/o control
        serializer = SampleModelSerializer(instance=self.sample1)
        self.assertEqual(set(serializer.data.keys()), {"a", "b"})

        # pass through context
        serializer = SampleModelSerializer(instance=self.sample1, context={"fields": ("a", )})
        self.assertEqual(set(serializer.data.keys()), {"a"})

        # pass through request
        request = Request(factory.get("/", {"fields": "b,c"}))
        serializer = SampleModelSerializer(instance=self.sample1, context={"request": request})
        self.assertEqual(set(serializer.data.keys()), {"b"}) 
Example #26
Source File: test_pagination.py    From drf_tweaks with MIT License 5 votes vote down vote up
def test_no_offset(self):
        request = Request(factory.get('/', {'limit': 5}))
        queryset = self.paginate_queryset(request)
        content = self.get_paginated_content(queryset)
        self.assertEqual(queryset, [1, 2, 3, 4, 5])
        self.assertEqual(content, {
            'results': [1, 2, 3, 4, 5],
            'previous': None,
            'next': 'http://testserver/?limit=5&offset=5'
        }) 
Example #27
Source File: test_pagination.py    From drf_tweaks with MIT License 5 votes vote down vote up
def test_single_offset(self):
        request = Request(factory.get('/', {'limit': 5, 'offset': 1}))
        queryset = self.paginate_queryset(request)
        content = self.get_paginated_content(queryset)
        self.assertEqual(queryset, [2, 3, 4, 5, 6])
        self.assertEqual(content, {
            'results': [2, 3, 4, 5, 6],
            'previous': 'http://testserver/?limit=5',
            'next': 'http://testserver/?limit=5&offset=6'
        }) 
Example #28
Source File: cards.py    From mangaki with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_card(request: Request, category: str, slot_sort_type: str):
    """
    Fetch the work card from the `category` using the `slot_sort_type` as "sorting" method.
    """

    card_slot_query_serializer = CardSlotQuerySerializer(data={
        'category': category,
        'slot_type': slot_sort_type
    })

    if not card_slot_query_serializer.is_valid():
        return Response(
            card_slot_query_serializer.errors,
            status=400
        )

    card_slot_query = card_slot_query_serializer.data
    queryset = (
        Category.objects.get(slug=card_slot_query['category'])
            .work_set.all()
    )

    rated_works = current_user_ratings(request)
    slot_type_chosen = SlotCardTypes[card_slot_query['slot_type']]
    queryset = (
        slot_dispatchers[slot_type_chosen](queryset)
            .exclude(id__in=list(rated_works))
    )

    works = queryset[:POSTERS_PER_PAGE]

    return Response(
        CardSlotSerializer(works, many=True,
                           context={'request': request}).data
    ) 
Example #29
Source File: test_pagination.py    From drf_tweaks with MIT License 5 votes vote down vote up
def test_negative_offset(self):
        request = Request(factory.get('/', {'limit': 5, 'offset': -3}))
        queryset = self.paginate_queryset(request)
        content = self.get_paginated_content(queryset)
        self.assertEqual(queryset, [1, 2])
        self.assertEqual(content, {
            'results': [1, 2],
            'previous': None,
            'next': 'http://testserver/?limit=5&offset=2'
        }) 
Example #30
Source File: tasks.py    From mangaki with GNU Affero General Public License v3.0 5 votes vote down vote up
def user_tasks(request: Request) -> Response:
    return Response(UserBGTaskSerializer(request.user.background_tasks.all(), many=True).data)