Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to return a raw response

This is what I want.

  1. Submit a POST request to a external site(i.e login information).
  2. Receive the response
  3. Return the raw response to my client's browser(containing the cookies for login
    validation).
  4. If the client tries to access the site in new tab he finds that he is already signed in.

I successfully completed steps 1 & 2 (submitted POST & received the response from the site).

request = urllib2.Request(url, formData, headers)
response = urllib2.urlopen(request)

But when I try to return it in the view

return response

I get the folllowing error

Django Version:     1.3.1
Exception Type:     AttributeError
Exception Value:    addinfourl instance has no attribute 'has_header'
Exception Location:D:\Python27\lib\site-packages\django\utils\cache.py in patch_vary_headers

note: I had a csrf error previosly,but i disabled csrf using decorator @csrf_exempt & the error was gone

like image 786
Jibin Avatar asked Oct 31 '11 10:10

Jibin


1 Answers

You shouldn't return the response from urlopen method directly. Instead your view should return an instance of django's HttpResponse, where body and the headers should be set to those from the original response:

from django.http import HttpResponse
import urllib2

def my_view(request):
    request = urllib2.Request(url, formData, headers)
    response = urllib2.urlopen(request)

    # set the body
    r = HttpResponse(response.read())

    # set the headers
    for header in response.info().keys():
        r[header] = response.info()[header]

    return r
like image 118
Sergey Golovchenko Avatar answered Sep 21 '22 15:09

Sergey Golovchenko