Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add request header before redirection

I am retrofitting a Django web app for a new client. To this end I have added a url pattern that redirects requests from new client to old url patterns.

from:-

(('api/(?P<phone>\w+)/MessageA', handle_a_message),
 ('api/(?P<phone>\w+)/MessageB', handle_b_message),
  ...)

to:-

(('api/(?P<phone>\w+)/MessageA', handle_a_message),
 ('api/(?P<phone>\w+)/MessageB', handle_b_message),
 ('api/newclient', handle_newclient)
  ...)

views.handle_newclient

def handle_newclient(request):
    return redirect('/api/%(phone)s/%(msg)s' % request.GET)

This somewhat works. However the new client doesn't do basic auth which those url's need. Also the default output is json where the new client needs plain text. Is there a way I can tweak the headers before redirecting to the existing url's?

like image 309
Himanshu Avatar asked Aug 03 '15 10:08

Himanshu


1 Answers

Django FBV's should return an HTTPResponse object (or subclass thereof). The Django shorcut redirect returns HttpResponseRedirect which is a subclass of HTTPResponse. This means we can set the headers for redirect() the way we will set headers for a typical HTTPResponse object. We can do that like so:

def my_view(request):
    response = redirect('http://www.gamefaqs.com')
    # Set 'Test' header and then delete
    response['Test'] = 'Test'
    del response['Test']
    # Set 'Test Header' header
    response['Test Header'] = 'Test Header'
    return response

Relevant docs here and here.

like image 56
Wannabe Coder Avatar answered Oct 10 '22 15:10

Wannabe Coder