From a8fb8ed6ac5959bc11c5d7955aac12b69acd8a50 Mon Sep 17 00:00:00 2001 From: Ian Stapleton Cordasco Date: Thu, 4 Jan 2018 14:31:30 -0600 Subject: [PATCH] Allow rest_framework.request.Request instances Instead of flat-out erroring (which can cause unhandled exceptions) let's perhaps be nicer to users who are considerately and carefully reusing ViewSets in other ViewSets. This means accessing the private attribute for them and then (and only then) raising an AssertionError if it isn't a Django HttpResponse instance. See also #5618 --- rest_framework/request.py | 6 ++++++ tests/test_request.py | 7 +++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/rest_framework/request.py b/rest_framework/request.py index 7e4daf274..5cd1ceaa8 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -153,6 +153,12 @@ class Request(object): def __init__(self, request, parsers=None, authenticators=None, negotiator=None, parser_context=None): + # If we're being passed our own Request object, unwrap the underlying + # HttpRequest. This allows for some backwards compatibilty to 3.7.3 + # for select users who carefully reuse ViewSets. + if isinstance(request, Request): + request = request._request + assert isinstance(request, HttpRequest), ( 'The `request` argument must be an instance of ' '`django.http.HttpRequest`, not `{}.{}`.' diff --git a/tests/test_request.py b/tests/test_request.py index 76589a440..6071e5877 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -33,10 +33,13 @@ class TestInitializer(TestCase): message = ( 'The `request` argument must be an instance of ' - '`django.http.HttpRequest`, not `rest_framework.request.Request`.' + '`django.http.HttpRequest`, not `NoneType`.' ) with self.assertRaisesMessage(AssertionError, message): - Request(request) + Request(None) + + other_request = Request(request) + assert other_request._request is request._request class PlainTextParser(BaseParser):