How to get django-response on django-request
How to send a django.http.HttpRequest
object and receive a django.http.HttpResponse
object inside a view?
In other words, whats the analogue of python-requests-:
response = requests.request(**data)
using django.http.HttpRequest
and django.http.HttpResponse
accordingly
By the time a request
reaches your view, it'll have the form of a django.http.HttpRequest
object. It is constructed by Django's middleware, you don't have to craft it yourself.
Which is also to say that you can send normal request
objects to Django, and Django will wrap them in HttpRequest
before giving it to the view.
The case is sometimes similar for django.http.HttpResponse
, in that some pre-built views will construct the response object invisibly. But you can easily customize it or craft it yourself if you're building a view "from scratch".
If you need to intercept the response, kind of like a middleware would, you can do something like this:
# views.py
from django.http import HttpResponse
def other_view(request):
return HttpResponse("<div>Hello world</div>")
def proxy_view(request): # <-- Will be a `HttpRequest` object
# Fetch the response from the other view
# NB! Calling views like this bypasses the middleware stack
proxied_view = other_view(request)
proxied_content = proxied_view.response.content.decode('utf-8')
modified_response = "<h1>Hello world</h1>" + "<br>" + proxied_content
return HttpResponse(modified_response)
You can use the RequestFactory
class to create your own request, then call the view with it. Example:
from django.test import RequestFactory
new_request = RequestFactory().get(reverse('url_name', args=(an_arg,)))
# Depending on what you're doing you probably need to populate
# user and META, here I copy them from the current request, but if you
# can't do that you'll have to construct them.
new_request.user = request.user
new_request.META = request.META
# Now you can call your view.. here I am calling a class based view,
# getting the view method using `as_view()`
response = MyViewClass.as_view()(request=new_request)